Initial load
diff --git a/test/java/nio/Buffer/AllocateDirectInit.java b/test/java/nio/Buffer/AllocateDirectInit.java
new file mode 100644
index 0000000..e30882d
--- /dev/null
+++ b/test/java/nio/Buffer/AllocateDirectInit.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2001-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4490253 6535542
+ * @summary Verify that newly allocated direct buffers are initialized.
+ */
+
+import java.nio.ByteBuffer;
+
+public class AllocateDirectInit {
+ public static void main(String [] args){
+ for (int i = 0; i < 1024; i++) {
+ ByteBuffer bb = ByteBuffer.allocateDirect(1024);
+// printByteBuffer(bb);
+ for (bb.position(0); bb.position() < bb.limit(); ) {
+ if ((bb.get() & 0xff) != 0)
+ throw new RuntimeException("uninitialized buffer, position = "
+ + bb.position());
+ }
+ }
+ }
+
+ private static void printByteBuffer(ByteBuffer bb) {
+ System.out.print("byte [");
+ for (bb.position(0); bb.position() < bb.limit(); )
+ System.out.print(" " + Integer.toHexString(bb.get() & 0xff));
+ System.out.println(" ]");
+ }
+}
diff --git a/test/java/nio/Buffer/Basic-X.java b/test/java/nio/Buffer/Basic-X.java
new file mode 100644
index 0000000..a28793c
--- /dev/null
+++ b/test/java/nio/Buffer/Basic-X.java
@@ -0,0 +1,828 @@
+/*
+ * Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* Type-specific source code for unit test
+ *
+ * Regenerate the BasicX classes via genBasic.sh whenever this file changes.
+ * We check in the generated source files so that the test tree can be used
+ * independently of the rest of the source tree.
+ */
+
+#warn This file is preprocessed before being compiled
+
+import java.nio.*;
+
+
+public class Basic$Type$
+ extends Basic
+{
+
+ private static void relGet($Type$Buffer b) {
+ int n = b.capacity();
+ $type$ v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)(($type$)ic(i)));
+ b.rewind();
+ }
+
+ private static void relGet($Type$Buffer b, int start) {
+ int n = b.remaining();
+ $type$ v;
+ for (int i = start; i < n; i++)
+ ck(b, (long)b.get(), (long)(($type$)ic(i)));
+ b.rewind();
+ }
+
+ private static void absGet($Type$Buffer b) {
+ int n = b.capacity();
+ $type$ v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)(($type$)ic(i)));
+ b.rewind();
+ }
+
+ private static void bulkGet($Type$Buffer b) {
+ int n = b.capacity();
+ $type$[] a = new $type$[n + 7];
+ b.get(a, 7, n);
+ for (int i = 0; i < n; i++)
+ ck(b, (long)a[i + 7], (long)(($type$)ic(i)));
+ }
+
+ private static void relPut($Type$Buffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(($type$)ic(i));
+ b.flip();
+ }
+
+ private static void absPut($Type$Buffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, ($type$)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void bulkPutArray($Type$Buffer b) {
+ int n = b.capacity();
+ b.clear();
+ $type$[] a = new $type$[n + 7];
+ for (int i = 0; i < n; i++)
+ a[i + 7] = ($type$)ic(i);
+ b.put(a, 7, n);
+ b.flip();
+ }
+
+ private static void bulkPutBuffer($Type$Buffer b) {
+ int n = b.capacity();
+ b.clear();
+ $Type$Buffer c = $Type$Buffer.allocate(n + 7);
+ c.position(7);
+ for (int i = 0; i < n; i++)
+ c.put(($type$)ic(i));
+ c.flip();
+ c.position(7);
+ b.put(c);
+ b.flip();
+ }
+
+ //6231529
+ private static void callReset($Type$Buffer b) {
+ b.position(0);
+ b.mark();
+
+ b.duplicate().reset();
+ b.asReadOnlyBuffer().reset();
+ }
+
+#if[byte]
+#else[byte]
+ // 6221101-6234263
+
+ private static void putBuffer() {
+ final int cap = 10;
+
+ $Type$Buffer direct1 = ByteBuffer.allocateDirect(cap).as$Type$Buffer();
+ $Type$Buffer nondirect1 = ByteBuffer.allocate(cap).as$Type$Buffer();
+ direct1.put(nondirect1);
+
+ $Type$Buffer direct2 = ByteBuffer.allocateDirect(cap).as$Type$Buffer();
+ $Type$Buffer nondirect2 = ByteBuffer.allocate(cap).as$Type$Buffer();
+ nondirect2.put(direct2);
+
+ $Type$Buffer direct3 = ByteBuffer.allocateDirect(cap).as$Type$Buffer();
+ $Type$Buffer direct4 = ByteBuffer.allocateDirect(cap).as$Type$Buffer();
+ direct3.put(direct4);
+
+ $Type$Buffer nondirect3 = ByteBuffer.allocate(cap).as$Type$Buffer();
+ $Type$Buffer nondirect4 = ByteBuffer.allocate(cap).as$Type$Buffer();
+ nondirect3.put(nondirect4);
+ }
+#end[byte]
+
+#if[char]
+
+ private static void bulkPutString($Type$Buffer b) {
+ int n = b.capacity();
+ b.clear();
+ StringBuffer sb = new StringBuffer(n + 7);
+ sb.append("1234567");
+ for (int i = 0; i < n; i++)
+ sb.append((char)ic(i));
+ b.put(sb.toString(), 7, 7 + n);
+ b.flip();
+ }
+
+#end[char]
+
+ private static void checkSlice($Type$Buffer b, $Type$Buffer slice) {
+ ck(slice, 0, slice.position());
+ ck(slice, b.remaining(), slice.limit());
+ ck(slice, b.remaining(), slice.capacity());
+ if (b.isDirect() != slice.isDirect())
+ fail("Lost direction", slice);
+ if (b.isReadOnly() != slice.isReadOnly())
+ fail("Lost read-only", slice);
+ }
+
+#if[byte]
+
+ private static void checkBytes(ByteBuffer b, byte[] bs) {
+ int n = bs.length;
+ int p = b.position();
+ byte v;
+ if (b.order() == ByteOrder.BIG_ENDIAN) {
+ for (int i = 0; i < n; i++)
+ ck(b, b.get(), bs[i]);
+ } else {
+ for (int i = n - 1; i >= 0; i--)
+ ck(b, b.get(), bs[i]);
+ }
+ b.position(p);
+ }
+
+ private static void testViews(int level, ByteBuffer b, boolean direct) {
+
+ ShortBuffer sb = b.asShortBuffer();
+ BasicShort.test(level, sb, direct);
+ checkBytes(b, new byte[] { 0, (byte)ic(0) });
+
+ CharBuffer cb = b.asCharBuffer();
+ BasicChar.test(level, cb, direct);
+ checkBytes(b, new byte[] { 0, (byte)ic(0) });
+
+ IntBuffer ib = b.asIntBuffer();
+ BasicInt.test(level, ib, direct);
+ checkBytes(b, new byte[] { 0, 0, 0, (byte)ic(0) });
+
+ LongBuffer lb = b.asLongBuffer();
+ BasicLong.test(level, lb, direct);
+ checkBytes(b, new byte[] { 0, 0, 0, 0, 0, 0, 0, (byte)ic(0) });
+
+ FloatBuffer fb = b.asFloatBuffer();
+ BasicFloat.test(level, fb, direct);
+ checkBytes(b, new byte[] { 0x42, (byte)0xc2, 0, 0 });
+
+ DoubleBuffer db = b.asDoubleBuffer();
+ BasicDouble.test(level, db, direct);
+ checkBytes(b, new byte[] { 0x40, 0x58, 0x40, 0, 0, 0, 0, 0 });
+
+ }
+
+ private static void testHet(int level, ByteBuffer b) {
+
+ int p = b.position();
+ b.limit(b.capacity());
+ show(level, b);
+ out.print(" put:");
+
+ b.putChar((char)1);
+ b.putChar((char)Character.MAX_VALUE);
+ out.print(" char");
+
+ b.putShort((short)1);
+ b.putShort((short)Short.MAX_VALUE);
+ out.print(" short");
+
+ b.putInt(1);
+ b.putInt(Integer.MAX_VALUE);
+ out.print(" int");
+
+ b.putLong((long)1);
+ b.putLong((long)Long.MAX_VALUE);
+ out.print(" long");
+
+ b.putFloat((float)1);
+ b.putFloat((float)Float.MIN_VALUE);
+ b.putFloat((float)Float.MAX_VALUE);
+ out.print(" float");
+
+ b.putDouble((double)1);
+ b.putDouble((double)Double.MIN_VALUE);
+ b.putDouble((double)Double.MAX_VALUE);
+ out.print(" double");
+
+ out.println();
+ b.limit(b.position());
+ b.position(p);
+ show(level, b);
+ out.print(" get:");
+
+ ck(b, b.getChar(), 1);
+ ck(b, b.getChar(), Character.MAX_VALUE);
+ out.print(" char");
+
+ ck(b, b.getShort(), 1);
+ ck(b, b.getShort(), Short.MAX_VALUE);
+ out.print(" short");
+
+ ck(b, b.getInt(), 1);
+ ck(b, b.getInt(), Integer.MAX_VALUE);
+ out.print(" int");
+
+ ck(b, b.getLong(), 1);
+ ck(b, b.getLong(), Long.MAX_VALUE);
+ out.print(" long");
+
+ ck(b, (long)b.getFloat(), 1);
+ ck(b, (long)b.getFloat(), (long)Float.MIN_VALUE);
+ ck(b, (long)b.getFloat(), (long)Float.MAX_VALUE);
+ out.print(" float");
+
+ ck(b, (long)b.getDouble(), 1);
+ ck(b, (long)b.getDouble(), (long)Double.MIN_VALUE);
+ ck(b, (long)b.getDouble(), (long)Double.MAX_VALUE);
+ out.print(" double");
+
+ out.println();
+
+ }
+
+#end[byte]
+
+ private static void tryCatch(Buffer b, Class ex, Runnable thunk) {
+ boolean caught = false;
+ try {
+ thunk.run();
+ } catch (Throwable x) {
+ if (ex.isAssignableFrom(x.getClass()))
+ caught = true;
+ }
+ if (!caught)
+ fail(ex.getName() + " not thrown", b);
+ }
+
+ private static void tryCatch($type$ [] t, Class ex, Runnable thunk) {
+ tryCatch($Type$Buffer.wrap(t), ex, thunk);
+ }
+
+ public static void test(int level, final $Type$Buffer b, boolean direct) {
+
+ show(level, b);
+
+ if (direct != b.isDirect())
+ fail("Wrong direction", b);
+
+ // Gets and puts
+
+ relPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ absPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ bulkPutArray(b);
+ relGet(b);
+
+ bulkPutBuffer(b);
+ relGet(b);
+
+#if[char]
+
+ bulkPutString(b);
+ relGet(b);
+ b.position(1);
+ b.limit(7);
+ ck(b, b.toString().equals("bcdefg"));
+
+ // CharSequence ops
+
+ b.position(2);
+ ck(b, b.charAt(1), 'd');
+ CharBuffer c = (CharBuffer)b.subSequence(1, 4);
+ ck(b, b.subSequence(1, 4).toString().equals("def"));
+
+ // 4938424
+ b.position(4);
+ ck(b, b.charAt(1), 'f');
+ ck(b, b.subSequence(1, 3).toString().equals("fg"));
+
+#end[char]
+
+ // Compact
+
+ relPut(b);
+ b.position(13);
+ b.compact();
+ b.flip();
+ relGet(b, 13);
+
+ // Exceptions
+
+ boolean caught = false;
+ relPut(b);
+ b.limit(b.capacity() / 2);
+ b.position(b.limit());
+
+ tryCatch(b, BufferUnderflowException.class, new Runnable() {
+ public void run() {
+ b.get();
+ }});
+
+ tryCatch(b, BufferOverflowException.class, new Runnable() {
+ public void run() {
+ b.put(($type$)42);
+ }});
+
+ // The index must be non-negative and lesss than the buffer's limit.
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(b.limit());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(-1);
+ }});
+
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.put(b.limit(), ($type$)42);
+ }});
+
+ // Values
+
+ b.clear();
+ b.put(($type$)0);
+ b.put(($type$)-1);
+ b.put(($type$)1);
+ b.put($Fulltype$.MAX_VALUE);
+ b.put($Fulltype$.MIN_VALUE);
+#if[float]
+ b.put(-Float.MAX_VALUE);
+ b.put(-Float.MIN_VALUE);
+ b.put(Float.NEGATIVE_INFINITY);
+ b.put(Float.POSITIVE_INFINITY);
+ b.put(Float.NaN);
+ b.put(0.91697687f); // Changes value if incorrectly swapped
+#end[float]
+#if[double]
+ b.put(-Double.MAX_VALUE);
+ b.put(-Double.MIN_VALUE);
+ b.put(Double.NEGATIVE_INFINITY);
+ b.put(Double.POSITIVE_INFINITY);
+ b.put(Double.NaN);
+ b.put(0.5121609353879392); // Changes value if incorrectly swapped
+#end[double]
+
+ $type$ v;
+ b.flip();
+ ck(b, b.get(), 0);
+ ck(b, b.get(), ($type$)-1);
+ ck(b, b.get(), 1);
+ ck(b, b.get(), $Fulltype$.MAX_VALUE);
+ ck(b, b.get(), $Fulltype$.MIN_VALUE);
+
+#if[float]
+ ck(b, b.get(), -Float.MAX_VALUE);
+ ck(b, b.get(), -Float.MIN_VALUE);
+ ck(b, b.get(), Float.NEGATIVE_INFINITY);
+ ck(b, b.get(), Float.POSITIVE_INFINITY);
+ if (Float.floatToRawIntBits(v = b.get()) != Float.floatToRawIntBits(Float.NaN))
+ fail(b, (long)Float.NaN, (long)v);
+ ck(b, b.get(), 0.91697687f);
+#end[float]
+#if[double]
+ ck(b, b.get(), -Double.MAX_VALUE);
+ ck(b, b.get(), -Double.MIN_VALUE);
+ ck(b, b.get(), Double.NEGATIVE_INFINITY);
+ ck(b, b.get(), Double.POSITIVE_INFINITY);
+ if (Double.doubleToRawLongBits(v = b.get())
+ != Double.doubleToRawLongBits(Double.NaN))
+ fail(b, (long)Double.NaN, (long)v);
+ ck(b, b.get(), 0.5121609353879392);
+#end[double]
+
+
+ // Comparison
+ b.rewind();
+ $Type$Buffer b2 = $Type$Buffer.allocate(b.capacity());
+ b2.put(b);
+ b2.flip();
+ b.position(2);
+ b2.position(2);
+ if (!b.equals(b2)) {
+ for (int i = 2; i < b.limit(); i++) {
+ $type$ x = b.get(i);
+ $type$ y = b2.get(i);
+ if (x != y
+#if[double]
+ || Double.compare(x, y) != 0
+#end[double]
+#if[float]
+ || Float.compare(x, y) != 0
+#end[float]
+ )
+ out.println("[" + i + "] " + x + " != " + y);
+ }
+ fail("Identical buffers not equal", b, b2);
+ }
+ if (b.compareTo(b2) != 0)
+ fail("Comparison to identical buffer != 0", b, b2);
+
+ b.limit(b.limit() + 1);
+ b.position(b.limit() - 1);
+ b.put(($type$)99);
+ b.rewind();
+ b2.rewind();
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to shorter buffer <= 0", b, b2);
+ b.limit(b.limit() - 1);
+
+ b.put(2, ($type$)42);
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to lesser buffer <= 0", b, b2);
+
+ // Sub, dup
+
+ relPut(b);
+ relGet(b.duplicate());
+ b.position(13);
+ relGet(b.duplicate(), 13);
+ relGet(b.duplicate().slice(), 13);
+ relGet(b.slice(), 13);
+ relGet(b.slice().duplicate(), 13);
+
+ // Slice
+
+ b.position(5);
+ $Type$Buffer sb = b.slice();
+ checkSlice(b, sb);
+ b.position(0);
+ $Type$Buffer sb2 = sb.slice();
+ checkSlice(sb, sb2);
+
+ if (!sb.equals(sb2))
+ fail("Sliced slices do not match", sb, sb2);
+ if ((sb.hasArray()) && (sb.arrayOffset() != sb2.arrayOffset()))
+ fail("Array offsets do not match: "
+ + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2);
+
+#if[byte]
+
+ // Views
+
+ b.clear();
+ b.order(ByteOrder.BIG_ENDIAN);
+ testViews(level + 1, b, direct);
+
+ for (int i = 1; i <= 9; i++) {
+ b.position(i);
+ show(level + 1, b);
+ testViews(level + 2, b, direct);
+ }
+
+ b.position(0);
+ b.order(ByteOrder.LITTLE_ENDIAN);
+ testViews(level + 1, b, direct);
+
+ // Heterogeneous accessors
+
+ b.order(ByteOrder.BIG_ENDIAN);
+ for (int i = 0; i <= 9; i++) {
+ b.position(i);
+ testHet(level + 1, b);
+ }
+ b.order(ByteOrder.LITTLE_ENDIAN);
+ b.position(3);
+ testHet(level + 1, b);
+
+#end[byte]
+
+ // Read-only views
+
+ b.rewind();
+ final $Type$Buffer rb = b.asReadOnlyBuffer();
+ if (!b.equals(rb))
+ fail("Buffer not equal to read-only view", b, rb);
+ show(level + 1, rb);
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ relPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ absPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutArray(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutBuffer(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.compact();
+ }});
+
+#if[byte]
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putChar((char)1);
+ }});
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putChar(0, (char)1);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putShort((short)1);
+ }});
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putShort(0, (short)1);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putInt(1);
+ }});
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putInt(0, 1);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putLong((long)1);
+ }});
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putLong(0, (long)1);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putFloat((float)1);
+ }});
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putFloat(0, (float)1);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putDouble((double)1);
+ }});
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putDouble(0, (double)1);
+ }});
+
+#end[byte]
+
+ if (rb.getClass().getName().startsWith("java.nio.Heap")) {
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.array();
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.arrayOffset();
+ }});
+
+ if (rb.hasArray())
+ fail("Read-only heap buffer's backing array is accessible",
+ rb);
+
+ }
+
+ // Bulk puts from read-only buffers
+
+ b.clear();
+ rb.rewind();
+ b.put(rb);
+
+#if[byte]
+ // For byte buffers, test both the direct and non-direct cases
+ $Type$Buffer ob
+ = (b.isDirect()
+ ? $Type$Buffer.allocate(rb.capacity())
+ : $Type$Buffer.allocateDirect(rb.capacity()));
+ rb.rewind();
+ ob.put(rb);
+#end[byte]
+
+ relPut(b); // Required by testViews
+
+ }
+
+#if[char]
+
+ private static void testStr() {
+ final String s = "abcdefghijklm";
+ int start = 3;
+ int end = 9;
+ final CharBuffer b = CharBuffer.wrap(s, start, end);
+ show(0, b);
+ ck(b, b.toString().equals(s.substring(start, end)));
+ ck(b, b.toString().equals("defghi"));
+ ck(b, b.isReadOnly());
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ b.put('x');
+ }});
+ ck(b, start, b.position());
+ ck(b, end, b.limit());
+ ck(b, s.length(), b.capacity());
+
+ // The index, relative to the position, must be non-negative and
+ // smaller than remaining().
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.charAt(-1);
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.charAt(b.remaining());
+ }});
+
+ // The index must be non-negative and less than the buffer's limit.
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(b.limit());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(-1);
+ }});
+
+ // The start must be non-negative and no larger than remaining().
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.subSequence(-1, b.remaining());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.subSequence(b.remaining() + 1, b.remaining());
+ }});
+
+ // The end must be no smaller than start and no larger than
+ // remaining().
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.subSequence(2, 1);
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.subSequence(0, b.remaining() + 1);
+ }});
+
+ // The offset must be non-negative and no larger than <array.length>.
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ $Type$Buffer.wrap(s, -1, s.length());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ $Type$Buffer.wrap(s, s.length() + 1, s.length());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ $Type$Buffer.wrap(s, 1, 0);
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ $Type$Buffer.wrap(s, 0, s.length() + 1);
+ }});
+ }
+
+#end[char]
+
+ public static void test(final $type$ [] ba) {
+ int offset = 47;
+ int length = 900;
+ final $Type$Buffer b = $Type$Buffer.wrap(ba, offset, length);
+ show(0, b);
+ ck(b, b.capacity(), ba.length);
+ ck(b, b.position(), offset);
+ ck(b, b.limit(), offset + length);
+
+ // The offset must be non-negative and no larger than <array.length>.
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ $Type$Buffer.wrap(ba, -1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ $Type$Buffer.wrap(ba, ba.length + 1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ $Type$Buffer.wrap(ba, 0, -1);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ $Type$Buffer.wrap(ba, 0, ba.length + 1);
+ }});
+
+ // A NullPointerException will be thrown if the array is null.
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ $Type$Buffer.wrap(($type$ []) null, 0, 5);
+ }});
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ $Type$Buffer.wrap(($type$ []) null);
+ }});
+ }
+
+ private static void testAllocate() {
+ // An IllegalArgumentException will be thrown for negative capacities.
+ tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() {
+ public void run() {
+ $Type$Buffer.allocate(-1);
+ }});
+#if[byte]
+ tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() {
+ public void run() {
+ $Type$Buffer.allocateDirect(-1);
+ }});
+#end[byte]
+ }
+
+ public static void test() {
+ testAllocate();
+ test(0, $Type$Buffer.allocate(7 * 1024), false);
+ test(0, $Type$Buffer.wrap(new $type$[7 * 1024], 0, 7 * 1024), false);
+ test(new $type$[1024]);
+#if[byte]
+ $Type$Buffer b = $Type$Buffer.allocateDirect(7 * 1024);
+ for (b.position(0); b.position() < b.limit(); )
+ ck(b, b.get(), 0);
+ test(0, b, true);
+#end[byte]
+#if[char]
+ testStr();
+#end[char]
+
+ callReset($Type$Buffer.allocate(10));
+
+#if[byte]
+#else[byte]
+ putBuffer();
+#end[byte]
+ }
+
+}
diff --git a/test/java/nio/Buffer/Basic.java b/test/java/nio/Buffer/Basic.java
new file mode 100644
index 0000000..0716a5b
--- /dev/null
+++ b/test/java/nio/Buffer/Basic.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Unit test for buffers
+ * @bug 4413135 4414911 4416536 4416562 4418782 4471053 4472779 4490253 4523725
+ * 4526177 4463011 4660660 4661219 4663521 4782970 4804304 4938424 6231529
+ * 6221101 6234263 6535542 6591971
+ * @author Mark Reinhold
+ */
+
+
+import java.io.PrintStream;
+
+import java.nio.Buffer;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+
+
+public class Basic {
+
+ static PrintStream out = System.err;
+
+ static long ic(int i) {
+ int j = i % 54;
+ return j + 'a' + ((j > 26) ? 128 : 0);
+ }
+
+ static String toString(Buffer b) {
+ return (b.getClass().getName()
+ + "[pos=" + b.position()
+ + " lim=" + b.limit()
+ + " cap=" + b.capacity()
+ + "]");
+ }
+
+ static void show(int level, Buffer b) {
+ for (int i = 0; i < level; i++)
+ out.print(" ");
+ out.println(toString(b) + " " + Integer.toHexString(b.hashCode()));
+ }
+
+ static void fail(String s) {
+ throw new RuntimeException(s);
+ }
+
+ static void fail(String s, Buffer b) {
+ throw new RuntimeException(s + ": " + toString(b));
+ }
+
+ static void fail(String s, Buffer b, Buffer b2) {
+ throw new RuntimeException(s + ": "
+ + toString(b) + ", " + toString(b2));
+ }
+
+ static void fail(Buffer b,
+ String expected, char expectedChar,
+ String got, char gotChar)
+ {
+ if (b instanceof ByteBuffer) {
+ ByteBuffer bb = (ByteBuffer)b;
+ int n = Math.min(16, bb.limit());
+ for (int i = 0; i < n; i++)
+ out.print(" " + Integer.toHexString(bb.get(i) & 0xff));
+ out.println();
+ }
+ if (b instanceof CharBuffer) {
+ CharBuffer bb = (CharBuffer)b;
+ int n = Math.min(16, bb.limit());
+ for (int i = 0; i < n; i++)
+ out.print(" " + Integer.toHexString(bb.get(i) & 0xffff));
+ out.println();
+ }
+ throw new RuntimeException(toString(b)
+ + ": Expected '" + expectedChar + "'=0x"
+ + expected
+ + ", got '" + gotChar + "'=0x"
+ + got);
+ }
+
+ static void fail(Buffer b, long expected, long got) {
+ fail(b,
+ Long.toHexString(expected), (char)expected,
+ Long.toHexString(got), (char)got);
+ }
+
+ static void ck(Buffer b, boolean cond) {
+ if (!cond)
+ fail("Condition failed", b);
+ }
+
+ static void ck(Buffer b, long got, long expected) {
+ if (expected != got)
+ fail(b, expected, got);
+ }
+
+ static void ck(Buffer b, float got, float expected) {
+ if (expected != got)
+ fail(b,
+ Float.toString(expected), (char)expected,
+ Float.toString(got), (char)got);
+ }
+
+ static void ck(Buffer b, double got, double expected) {
+ if (expected != got)
+ fail(b,
+ Double.toString(expected), (char)expected,
+ Double.toString(got), (char)got);
+ }
+
+ public static void main(String[] args) {
+ BasicByte.test();
+ BasicChar.test();
+ BasicShort.test();
+ BasicInt.test();
+ BasicLong.test();
+ BasicFloat.test();
+ BasicDouble.test();
+ }
+
+}
diff --git a/test/java/nio/Buffer/BasicByte.java b/test/java/nio/Buffer/BasicByte.java
new file mode 100644
index 0000000..539af2c
--- /dev/null
+++ b/test/java/nio/Buffer/BasicByte.java
@@ -0,0 +1,828 @@
+/*
+ * Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* Type-specific source code for unit test
+ *
+ * Regenerate the BasicX classes via genBasic.sh whenever this file changes.
+ * We check in the generated source files so that the test tree can be used
+ * independently of the rest of the source tree.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+
+public class BasicByte
+ extends Basic
+{
+
+ private static void relGet(ByteBuffer b) {
+ int n = b.capacity();
+ byte v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((byte)ic(i)));
+ b.rewind();
+ }
+
+ private static void relGet(ByteBuffer b, int start) {
+ int n = b.remaining();
+ byte v;
+ for (int i = start; i < n; i++)
+ ck(b, (long)b.get(), (long)((byte)ic(i)));
+ b.rewind();
+ }
+
+ private static void absGet(ByteBuffer b) {
+ int n = b.capacity();
+ byte v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((byte)ic(i)));
+ b.rewind();
+ }
+
+ private static void bulkGet(ByteBuffer b) {
+ int n = b.capacity();
+ byte[] a = new byte[n + 7];
+ b.get(a, 7, n);
+ for (int i = 0; i < n; i++)
+ ck(b, (long)a[i + 7], (long)((byte)ic(i)));
+ }
+
+ private static void relPut(ByteBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put((byte)ic(i));
+ b.flip();
+ }
+
+ private static void absPut(ByteBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (byte)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void bulkPutArray(ByteBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ byte[] a = new byte[n + 7];
+ for (int i = 0; i < n; i++)
+ a[i + 7] = (byte)ic(i);
+ b.put(a, 7, n);
+ b.flip();
+ }
+
+ private static void bulkPutBuffer(ByteBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ ByteBuffer c = ByteBuffer.allocate(n + 7);
+ c.position(7);
+ for (int i = 0; i < n; i++)
+ c.put((byte)ic(i));
+ c.flip();
+ c.position(7);
+ b.put(c);
+ b.flip();
+ }
+
+ //6231529
+ private static void callReset(ByteBuffer b) {
+ b.position(0);
+ b.mark();
+
+ b.duplicate().reset();
+ b.asReadOnlyBuffer().reset();
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ private static void checkSlice(ByteBuffer b, ByteBuffer slice) {
+ ck(slice, 0, slice.position());
+ ck(slice, b.remaining(), slice.limit());
+ ck(slice, b.remaining(), slice.capacity());
+ if (b.isDirect() != slice.isDirect())
+ fail("Lost direction", slice);
+ if (b.isReadOnly() != slice.isReadOnly())
+ fail("Lost read-only", slice);
+ }
+
+
+
+ private static void checkBytes(ByteBuffer b, byte[] bs) {
+ int n = bs.length;
+ int p = b.position();
+ byte v;
+ if (b.order() == ByteOrder.BIG_ENDIAN) {
+ for (int i = 0; i < n; i++)
+ ck(b, b.get(), bs[i]);
+ } else {
+ for (int i = n - 1; i >= 0; i--)
+ ck(b, b.get(), bs[i]);
+ }
+ b.position(p);
+ }
+
+ private static void testViews(int level, ByteBuffer b, boolean direct) {
+
+ ShortBuffer sb = b.asShortBuffer();
+ BasicShort.test(level, sb, direct);
+ checkBytes(b, new byte[] { 0, (byte)ic(0) });
+
+ CharBuffer cb = b.asCharBuffer();
+ BasicChar.test(level, cb, direct);
+ checkBytes(b, new byte[] { 0, (byte)ic(0) });
+
+ IntBuffer ib = b.asIntBuffer();
+ BasicInt.test(level, ib, direct);
+ checkBytes(b, new byte[] { 0, 0, 0, (byte)ic(0) });
+
+ LongBuffer lb = b.asLongBuffer();
+ BasicLong.test(level, lb, direct);
+ checkBytes(b, new byte[] { 0, 0, 0, 0, 0, 0, 0, (byte)ic(0) });
+
+ FloatBuffer fb = b.asFloatBuffer();
+ BasicFloat.test(level, fb, direct);
+ checkBytes(b, new byte[] { 0x42, (byte)0xc2, 0, 0 });
+
+ DoubleBuffer db = b.asDoubleBuffer();
+ BasicDouble.test(level, db, direct);
+ checkBytes(b, new byte[] { 0x40, 0x58, 0x40, 0, 0, 0, 0, 0 });
+
+ }
+
+ private static void testHet(int level, ByteBuffer b) {
+
+ int p = b.position();
+ b.limit(b.capacity());
+ show(level, b);
+ out.print(" put:");
+
+ b.putChar((char)1);
+ b.putChar((char)Character.MAX_VALUE);
+ out.print(" char");
+
+ b.putShort((short)1);
+ b.putShort((short)Short.MAX_VALUE);
+ out.print(" short");
+
+ b.putInt(1);
+ b.putInt(Integer.MAX_VALUE);
+ out.print(" int");
+
+ b.putLong((long)1);
+ b.putLong((long)Long.MAX_VALUE);
+ out.print(" long");
+
+ b.putFloat((float)1);
+ b.putFloat((float)Float.MIN_VALUE);
+ b.putFloat((float)Float.MAX_VALUE);
+ out.print(" float");
+
+ b.putDouble((double)1);
+ b.putDouble((double)Double.MIN_VALUE);
+ b.putDouble((double)Double.MAX_VALUE);
+ out.print(" double");
+
+ out.println();
+ b.limit(b.position());
+ b.position(p);
+ show(level, b);
+ out.print(" get:");
+
+ ck(b, b.getChar(), 1);
+ ck(b, b.getChar(), Character.MAX_VALUE);
+ out.print(" char");
+
+ ck(b, b.getShort(), 1);
+ ck(b, b.getShort(), Short.MAX_VALUE);
+ out.print(" short");
+
+ ck(b, b.getInt(), 1);
+ ck(b, b.getInt(), Integer.MAX_VALUE);
+ out.print(" int");
+
+ ck(b, b.getLong(), 1);
+ ck(b, b.getLong(), Long.MAX_VALUE);
+ out.print(" long");
+
+ ck(b, (long)b.getFloat(), 1);
+ ck(b, (long)b.getFloat(), (long)Float.MIN_VALUE);
+ ck(b, (long)b.getFloat(), (long)Float.MAX_VALUE);
+ out.print(" float");
+
+ ck(b, (long)b.getDouble(), 1);
+ ck(b, (long)b.getDouble(), (long)Double.MIN_VALUE);
+ ck(b, (long)b.getDouble(), (long)Double.MAX_VALUE);
+ out.print(" double");
+
+ out.println();
+
+ }
+
+
+
+ private static void tryCatch(Buffer b, Class ex, Runnable thunk) {
+ boolean caught = false;
+ try {
+ thunk.run();
+ } catch (Throwable x) {
+ if (ex.isAssignableFrom(x.getClass()))
+ caught = true;
+ }
+ if (!caught)
+ fail(ex.getName() + " not thrown", b);
+ }
+
+ private static void tryCatch(byte [] t, Class ex, Runnable thunk) {
+ tryCatch(ByteBuffer.wrap(t), ex, thunk);
+ }
+
+ public static void test(int level, final ByteBuffer b, boolean direct) {
+
+ show(level, b);
+
+ if (direct != b.isDirect())
+ fail("Wrong direction", b);
+
+ // Gets and puts
+
+ relPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ absPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ bulkPutArray(b);
+ relGet(b);
+
+ bulkPutBuffer(b);
+ relGet(b);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Compact
+
+ relPut(b);
+ b.position(13);
+ b.compact();
+ b.flip();
+ relGet(b, 13);
+
+ // Exceptions
+
+ boolean caught = false;
+ relPut(b);
+ b.limit(b.capacity() / 2);
+ b.position(b.limit());
+
+ tryCatch(b, BufferUnderflowException.class, new Runnable() {
+ public void run() {
+ b.get();
+ }});
+
+ tryCatch(b, BufferOverflowException.class, new Runnable() {
+ public void run() {
+ b.put((byte)42);
+ }});
+
+ // The index must be non-negative and lesss than the buffer's limit.
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(b.limit());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(-1);
+ }});
+
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.put(b.limit(), (byte)42);
+ }});
+
+ // Values
+
+ b.clear();
+ b.put((byte)0);
+ b.put((byte)-1);
+ b.put((byte)1);
+ b.put(Byte.MAX_VALUE);
+ b.put(Byte.MIN_VALUE);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ byte v;
+ b.flip();
+ ck(b, b.get(), 0);
+ ck(b, b.get(), (byte)-1);
+ ck(b, b.get(), 1);
+ ck(b, b.get(), Byte.MAX_VALUE);
+ ck(b, b.get(), Byte.MIN_VALUE);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Comparison
+ b.rewind();
+ ByteBuffer b2 = ByteBuffer.allocate(b.capacity());
+ b2.put(b);
+ b2.flip();
+ b.position(2);
+ b2.position(2);
+ if (!b.equals(b2)) {
+ for (int i = 2; i < b.limit(); i++) {
+ byte x = b.get(i);
+ byte y = b2.get(i);
+ if (x != y
+
+
+
+
+
+
+ )
+ out.println("[" + i + "] " + x + " != " + y);
+ }
+ fail("Identical buffers not equal", b, b2);
+ }
+ if (b.compareTo(b2) != 0)
+ fail("Comparison to identical buffer != 0", b, b2);
+
+ b.limit(b.limit() + 1);
+ b.position(b.limit() - 1);
+ b.put((byte)99);
+ b.rewind();
+ b2.rewind();
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to shorter buffer <= 0", b, b2);
+ b.limit(b.limit() - 1);
+
+ b.put(2, (byte)42);
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to lesser buffer <= 0", b, b2);
+
+ // Sub, dup
+
+ relPut(b);
+ relGet(b.duplicate());
+ b.position(13);
+ relGet(b.duplicate(), 13);
+ relGet(b.duplicate().slice(), 13);
+ relGet(b.slice(), 13);
+ relGet(b.slice().duplicate(), 13);
+
+ // Slice
+
+ b.position(5);
+ ByteBuffer sb = b.slice();
+ checkSlice(b, sb);
+ b.position(0);
+ ByteBuffer sb2 = sb.slice();
+ checkSlice(sb, sb2);
+
+ if (!sb.equals(sb2))
+ fail("Sliced slices do not match", sb, sb2);
+ if ((sb.hasArray()) && (sb.arrayOffset() != sb2.arrayOffset()))
+ fail("Array offsets do not match: "
+ + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2);
+
+
+
+ // Views
+
+ b.clear();
+ b.order(ByteOrder.BIG_ENDIAN);
+ testViews(level + 1, b, direct);
+
+ for (int i = 1; i <= 9; i++) {
+ b.position(i);
+ show(level + 1, b);
+ testViews(level + 2, b, direct);
+ }
+
+ b.position(0);
+ b.order(ByteOrder.LITTLE_ENDIAN);
+ testViews(level + 1, b, direct);
+
+ // Heterogeneous accessors
+
+ b.order(ByteOrder.BIG_ENDIAN);
+ for (int i = 0; i <= 9; i++) {
+ b.position(i);
+ testHet(level + 1, b);
+ }
+ b.order(ByteOrder.LITTLE_ENDIAN);
+ b.position(3);
+ testHet(level + 1, b);
+
+
+
+ // Read-only views
+
+ b.rewind();
+ final ByteBuffer rb = b.asReadOnlyBuffer();
+ if (!b.equals(rb))
+ fail("Buffer not equal to read-only view", b, rb);
+ show(level + 1, rb);
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ relPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ absPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutArray(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutBuffer(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.compact();
+ }});
+
+
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putChar((char)1);
+ }});
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putChar(0, (char)1);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putShort((short)1);
+ }});
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putShort(0, (short)1);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putInt(1);
+ }});
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putInt(0, 1);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putLong((long)1);
+ }});
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putLong(0, (long)1);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putFloat((float)1);
+ }});
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putFloat(0, (float)1);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putDouble((double)1);
+ }});
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.putDouble(0, (double)1);
+ }});
+
+
+
+ if (rb.getClass().getName().startsWith("java.nio.Heap")) {
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.array();
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.arrayOffset();
+ }});
+
+ if (rb.hasArray())
+ fail("Read-only heap buffer's backing array is accessible",
+ rb);
+
+ }
+
+ // Bulk puts from read-only buffers
+
+ b.clear();
+ rb.rewind();
+ b.put(rb);
+
+
+ // For byte buffers, test both the direct and non-direct cases
+ ByteBuffer ob
+ = (b.isDirect()
+ ? ByteBuffer.allocate(rb.capacity())
+ : ByteBuffer.allocateDirect(rb.capacity()));
+ rb.rewind();
+ ob.put(rb);
+
+
+ relPut(b); // Required by testViews
+
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ public static void test(final byte [] ba) {
+ int offset = 47;
+ int length = 900;
+ final ByteBuffer b = ByteBuffer.wrap(ba, offset, length);
+ show(0, b);
+ ck(b, b.capacity(), ba.length);
+ ck(b, b.position(), offset);
+ ck(b, b.limit(), offset + length);
+
+ // The offset must be non-negative and no larger than <array.length>.
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ ByteBuffer.wrap(ba, -1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ ByteBuffer.wrap(ba, ba.length + 1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ ByteBuffer.wrap(ba, 0, -1);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ ByteBuffer.wrap(ba, 0, ba.length + 1);
+ }});
+
+ // A NullPointerException will be thrown if the array is null.
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ ByteBuffer.wrap((byte []) null, 0, 5);
+ }});
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ ByteBuffer.wrap((byte []) null);
+ }});
+ }
+
+ private static void testAllocate() {
+ // An IllegalArgumentException will be thrown for negative capacities.
+ tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() {
+ public void run() {
+ ByteBuffer.allocate(-1);
+ }});
+
+ tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() {
+ public void run() {
+ ByteBuffer.allocateDirect(-1);
+ }});
+
+ }
+
+ public static void test() {
+ testAllocate();
+ test(0, ByteBuffer.allocate(7 * 1024), false);
+ test(0, ByteBuffer.wrap(new byte[7 * 1024], 0, 7 * 1024), false);
+ test(new byte[1024]);
+
+ ByteBuffer b = ByteBuffer.allocateDirect(7 * 1024);
+ for (b.position(0); b.position() < b.limit(); )
+ ck(b, b.get(), 0);
+ test(0, b, true);
+
+
+
+
+
+ callReset(ByteBuffer.allocate(10));
+
+
+
+
+
+ }
+
+}
diff --git a/test/java/nio/Buffer/BasicChar.java b/test/java/nio/Buffer/BasicChar.java
new file mode 100644
index 0000000..10111cc
--- /dev/null
+++ b/test/java/nio/Buffer/BasicChar.java
@@ -0,0 +1,828 @@
+/*
+ * Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* Type-specific source code for unit test
+ *
+ * Regenerate the BasicX classes via genBasic.sh whenever this file changes.
+ * We check in the generated source files so that the test tree can be used
+ * independently of the rest of the source tree.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+
+public class BasicChar
+ extends Basic
+{
+
+ private static void relGet(CharBuffer b) {
+ int n = b.capacity();
+ char v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((char)ic(i)));
+ b.rewind();
+ }
+
+ private static void relGet(CharBuffer b, int start) {
+ int n = b.remaining();
+ char v;
+ for (int i = start; i < n; i++)
+ ck(b, (long)b.get(), (long)((char)ic(i)));
+ b.rewind();
+ }
+
+ private static void absGet(CharBuffer b) {
+ int n = b.capacity();
+ char v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((char)ic(i)));
+ b.rewind();
+ }
+
+ private static void bulkGet(CharBuffer b) {
+ int n = b.capacity();
+ char[] a = new char[n + 7];
+ b.get(a, 7, n);
+ for (int i = 0; i < n; i++)
+ ck(b, (long)a[i + 7], (long)((char)ic(i)));
+ }
+
+ private static void relPut(CharBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put((char)ic(i));
+ b.flip();
+ }
+
+ private static void absPut(CharBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (char)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void bulkPutArray(CharBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ char[] a = new char[n + 7];
+ for (int i = 0; i < n; i++)
+ a[i + 7] = (char)ic(i);
+ b.put(a, 7, n);
+ b.flip();
+ }
+
+ private static void bulkPutBuffer(CharBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ CharBuffer c = CharBuffer.allocate(n + 7);
+ c.position(7);
+ for (int i = 0; i < n; i++)
+ c.put((char)ic(i));
+ c.flip();
+ c.position(7);
+ b.put(c);
+ b.flip();
+ }
+
+ //6231529
+ private static void callReset(CharBuffer b) {
+ b.position(0);
+ b.mark();
+
+ b.duplicate().reset();
+ b.asReadOnlyBuffer().reset();
+ }
+
+
+
+ // 6221101-6234263
+
+ private static void putBuffer() {
+ final int cap = 10;
+
+ CharBuffer direct1 = ByteBuffer.allocateDirect(cap).asCharBuffer();
+ CharBuffer nondirect1 = ByteBuffer.allocate(cap).asCharBuffer();
+ direct1.put(nondirect1);
+
+ CharBuffer direct2 = ByteBuffer.allocateDirect(cap).asCharBuffer();
+ CharBuffer nondirect2 = ByteBuffer.allocate(cap).asCharBuffer();
+ nondirect2.put(direct2);
+
+ CharBuffer direct3 = ByteBuffer.allocateDirect(cap).asCharBuffer();
+ CharBuffer direct4 = ByteBuffer.allocateDirect(cap).asCharBuffer();
+ direct3.put(direct4);
+
+ CharBuffer nondirect3 = ByteBuffer.allocate(cap).asCharBuffer();
+ CharBuffer nondirect4 = ByteBuffer.allocate(cap).asCharBuffer();
+ nondirect3.put(nondirect4);
+ }
+
+
+
+
+ private static void bulkPutString(CharBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ StringBuffer sb = new StringBuffer(n + 7);
+ sb.append("1234567");
+ for (int i = 0; i < n; i++)
+ sb.append((char)ic(i));
+ b.put(sb.toString(), 7, 7 + n);
+ b.flip();
+ }
+
+
+
+ private static void checkSlice(CharBuffer b, CharBuffer slice) {
+ ck(slice, 0, slice.position());
+ ck(slice, b.remaining(), slice.limit());
+ ck(slice, b.remaining(), slice.capacity());
+ if (b.isDirect() != slice.isDirect())
+ fail("Lost direction", slice);
+ if (b.isReadOnly() != slice.isReadOnly())
+ fail("Lost read-only", slice);
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ private static void tryCatch(Buffer b, Class ex, Runnable thunk) {
+ boolean caught = false;
+ try {
+ thunk.run();
+ } catch (Throwable x) {
+ if (ex.isAssignableFrom(x.getClass()))
+ caught = true;
+ }
+ if (!caught)
+ fail(ex.getName() + " not thrown", b);
+ }
+
+ private static void tryCatch(char [] t, Class ex, Runnable thunk) {
+ tryCatch(CharBuffer.wrap(t), ex, thunk);
+ }
+
+ public static void test(int level, final CharBuffer b, boolean direct) {
+
+ show(level, b);
+
+ if (direct != b.isDirect())
+ fail("Wrong direction", b);
+
+ // Gets and puts
+
+ relPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ absPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ bulkPutArray(b);
+ relGet(b);
+
+ bulkPutBuffer(b);
+ relGet(b);
+
+
+
+ bulkPutString(b);
+ relGet(b);
+ b.position(1);
+ b.limit(7);
+ ck(b, b.toString().equals("bcdefg"));
+
+ // CharSequence ops
+
+ b.position(2);
+ ck(b, b.charAt(1), 'd');
+ CharBuffer c = (CharBuffer)b.subSequence(1, 4);
+ ck(b, b.subSequence(1, 4).toString().equals("def"));
+
+ // 4938424
+ b.position(4);
+ ck(b, b.charAt(1), 'f');
+ ck(b, b.subSequence(1, 3).toString().equals("fg"));
+
+
+
+ // Compact
+
+ relPut(b);
+ b.position(13);
+ b.compact();
+ b.flip();
+ relGet(b, 13);
+
+ // Exceptions
+
+ boolean caught = false;
+ relPut(b);
+ b.limit(b.capacity() / 2);
+ b.position(b.limit());
+
+ tryCatch(b, BufferUnderflowException.class, new Runnable() {
+ public void run() {
+ b.get();
+ }});
+
+ tryCatch(b, BufferOverflowException.class, new Runnable() {
+ public void run() {
+ b.put((char)42);
+ }});
+
+ // The index must be non-negative and lesss than the buffer's limit.
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(b.limit());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(-1);
+ }});
+
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.put(b.limit(), (char)42);
+ }});
+
+ // Values
+
+ b.clear();
+ b.put((char)0);
+ b.put((char)-1);
+ b.put((char)1);
+ b.put(Character.MAX_VALUE);
+ b.put(Character.MIN_VALUE);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ char v;
+ b.flip();
+ ck(b, b.get(), 0);
+ ck(b, b.get(), (char)-1);
+ ck(b, b.get(), 1);
+ ck(b, b.get(), Character.MAX_VALUE);
+ ck(b, b.get(), Character.MIN_VALUE);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Comparison
+ b.rewind();
+ CharBuffer b2 = CharBuffer.allocate(b.capacity());
+ b2.put(b);
+ b2.flip();
+ b.position(2);
+ b2.position(2);
+ if (!b.equals(b2)) {
+ for (int i = 2; i < b.limit(); i++) {
+ char x = b.get(i);
+ char y = b2.get(i);
+ if (x != y
+
+
+
+
+
+
+ )
+ out.println("[" + i + "] " + x + " != " + y);
+ }
+ fail("Identical buffers not equal", b, b2);
+ }
+ if (b.compareTo(b2) != 0)
+ fail("Comparison to identical buffer != 0", b, b2);
+
+ b.limit(b.limit() + 1);
+ b.position(b.limit() - 1);
+ b.put((char)99);
+ b.rewind();
+ b2.rewind();
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to shorter buffer <= 0", b, b2);
+ b.limit(b.limit() - 1);
+
+ b.put(2, (char)42);
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to lesser buffer <= 0", b, b2);
+
+ // Sub, dup
+
+ relPut(b);
+ relGet(b.duplicate());
+ b.position(13);
+ relGet(b.duplicate(), 13);
+ relGet(b.duplicate().slice(), 13);
+ relGet(b.slice(), 13);
+ relGet(b.slice().duplicate(), 13);
+
+ // Slice
+
+ b.position(5);
+ CharBuffer sb = b.slice();
+ checkSlice(b, sb);
+ b.position(0);
+ CharBuffer sb2 = sb.slice();
+ checkSlice(sb, sb2);
+
+ if (!sb.equals(sb2))
+ fail("Sliced slices do not match", sb, sb2);
+ if ((sb.hasArray()) && (sb.arrayOffset() != sb2.arrayOffset()))
+ fail("Array offsets do not match: "
+ + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Read-only views
+
+ b.rewind();
+ final CharBuffer rb = b.asReadOnlyBuffer();
+ if (!b.equals(rb))
+ fail("Buffer not equal to read-only view", b, rb);
+ show(level + 1, rb);
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ relPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ absPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutArray(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutBuffer(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.compact();
+ }});
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ if (rb.getClass().getName().startsWith("java.nio.Heap")) {
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.array();
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.arrayOffset();
+ }});
+
+ if (rb.hasArray())
+ fail("Read-only heap buffer's backing array is accessible",
+ rb);
+
+ }
+
+ // Bulk puts from read-only buffers
+
+ b.clear();
+ rb.rewind();
+ b.put(rb);
+
+
+
+
+
+
+
+
+
+
+
+ relPut(b); // Required by testViews
+
+ }
+
+
+
+ private static void testStr() {
+ final String s = "abcdefghijklm";
+ int start = 3;
+ int end = 9;
+ final CharBuffer b = CharBuffer.wrap(s, start, end);
+ show(0, b);
+ ck(b, b.toString().equals(s.substring(start, end)));
+ ck(b, b.toString().equals("defghi"));
+ ck(b, b.isReadOnly());
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ b.put('x');
+ }});
+ ck(b, start, b.position());
+ ck(b, end, b.limit());
+ ck(b, s.length(), b.capacity());
+
+ // The index, relative to the position, must be non-negative and
+ // smaller than remaining().
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.charAt(-1);
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.charAt(b.remaining());
+ }});
+
+ // The index must be non-negative and less than the buffer's limit.
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(b.limit());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(-1);
+ }});
+
+ // The start must be non-negative and no larger than remaining().
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.subSequence(-1, b.remaining());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.subSequence(b.remaining() + 1, b.remaining());
+ }});
+
+ // The end must be no smaller than start and no larger than
+ // remaining().
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.subSequence(2, 1);
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.subSequence(0, b.remaining() + 1);
+ }});
+
+ // The offset must be non-negative and no larger than <array.length>.
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ CharBuffer.wrap(s, -1, s.length());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ CharBuffer.wrap(s, s.length() + 1, s.length());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ CharBuffer.wrap(s, 1, 0);
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ CharBuffer.wrap(s, 0, s.length() + 1);
+ }});
+ }
+
+
+
+ public static void test(final char [] ba) {
+ int offset = 47;
+ int length = 900;
+ final CharBuffer b = CharBuffer.wrap(ba, offset, length);
+ show(0, b);
+ ck(b, b.capacity(), ba.length);
+ ck(b, b.position(), offset);
+ ck(b, b.limit(), offset + length);
+
+ // The offset must be non-negative and no larger than <array.length>.
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ CharBuffer.wrap(ba, -1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ CharBuffer.wrap(ba, ba.length + 1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ CharBuffer.wrap(ba, 0, -1);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ CharBuffer.wrap(ba, 0, ba.length + 1);
+ }});
+
+ // A NullPointerException will be thrown if the array is null.
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ CharBuffer.wrap((char []) null, 0, 5);
+ }});
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ CharBuffer.wrap((char []) null);
+ }});
+ }
+
+ private static void testAllocate() {
+ // An IllegalArgumentException will be thrown for negative capacities.
+ tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() {
+ public void run() {
+ CharBuffer.allocate(-1);
+ }});
+
+
+
+
+
+
+ }
+
+ public static void test() {
+ testAllocate();
+ test(0, CharBuffer.allocate(7 * 1024), false);
+ test(0, CharBuffer.wrap(new char[7 * 1024], 0, 7 * 1024), false);
+ test(new char[1024]);
+
+
+
+
+
+
+
+ testStr();
+
+
+ callReset(CharBuffer.allocate(10));
+
+
+
+ putBuffer();
+
+ }
+
+}
diff --git a/test/java/nio/Buffer/BasicDouble.java b/test/java/nio/Buffer/BasicDouble.java
new file mode 100644
index 0000000..3da2396
--- /dev/null
+++ b/test/java/nio/Buffer/BasicDouble.java
@@ -0,0 +1,828 @@
+/*
+ * Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* Type-specific source code for unit test
+ *
+ * Regenerate the BasicX classes via genBasic.sh whenever this file changes.
+ * We check in the generated source files so that the test tree can be used
+ * independently of the rest of the source tree.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+
+public class BasicDouble
+ extends Basic
+{
+
+ private static void relGet(DoubleBuffer b) {
+ int n = b.capacity();
+ double v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((double)ic(i)));
+ b.rewind();
+ }
+
+ private static void relGet(DoubleBuffer b, int start) {
+ int n = b.remaining();
+ double v;
+ for (int i = start; i < n; i++)
+ ck(b, (long)b.get(), (long)((double)ic(i)));
+ b.rewind();
+ }
+
+ private static void absGet(DoubleBuffer b) {
+ int n = b.capacity();
+ double v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((double)ic(i)));
+ b.rewind();
+ }
+
+ private static void bulkGet(DoubleBuffer b) {
+ int n = b.capacity();
+ double[] a = new double[n + 7];
+ b.get(a, 7, n);
+ for (int i = 0; i < n; i++)
+ ck(b, (long)a[i + 7], (long)((double)ic(i)));
+ }
+
+ private static void relPut(DoubleBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put((double)ic(i));
+ b.flip();
+ }
+
+ private static void absPut(DoubleBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (double)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void bulkPutArray(DoubleBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ double[] a = new double[n + 7];
+ for (int i = 0; i < n; i++)
+ a[i + 7] = (double)ic(i);
+ b.put(a, 7, n);
+ b.flip();
+ }
+
+ private static void bulkPutBuffer(DoubleBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ DoubleBuffer c = DoubleBuffer.allocate(n + 7);
+ c.position(7);
+ for (int i = 0; i < n; i++)
+ c.put((double)ic(i));
+ c.flip();
+ c.position(7);
+ b.put(c);
+ b.flip();
+ }
+
+ //6231529
+ private static void callReset(DoubleBuffer b) {
+ b.position(0);
+ b.mark();
+
+ b.duplicate().reset();
+ b.asReadOnlyBuffer().reset();
+ }
+
+
+
+ // 6221101-6234263
+
+ private static void putBuffer() {
+ final int cap = 10;
+
+ DoubleBuffer direct1 = ByteBuffer.allocateDirect(cap).asDoubleBuffer();
+ DoubleBuffer nondirect1 = ByteBuffer.allocate(cap).asDoubleBuffer();
+ direct1.put(nondirect1);
+
+ DoubleBuffer direct2 = ByteBuffer.allocateDirect(cap).asDoubleBuffer();
+ DoubleBuffer nondirect2 = ByteBuffer.allocate(cap).asDoubleBuffer();
+ nondirect2.put(direct2);
+
+ DoubleBuffer direct3 = ByteBuffer.allocateDirect(cap).asDoubleBuffer();
+ DoubleBuffer direct4 = ByteBuffer.allocateDirect(cap).asDoubleBuffer();
+ direct3.put(direct4);
+
+ DoubleBuffer nondirect3 = ByteBuffer.allocate(cap).asDoubleBuffer();
+ DoubleBuffer nondirect4 = ByteBuffer.allocate(cap).asDoubleBuffer();
+ nondirect3.put(nondirect4);
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ private static void checkSlice(DoubleBuffer b, DoubleBuffer slice) {
+ ck(slice, 0, slice.position());
+ ck(slice, b.remaining(), slice.limit());
+ ck(slice, b.remaining(), slice.capacity());
+ if (b.isDirect() != slice.isDirect())
+ fail("Lost direction", slice);
+ if (b.isReadOnly() != slice.isReadOnly())
+ fail("Lost read-only", slice);
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ private static void tryCatch(Buffer b, Class ex, Runnable thunk) {
+ boolean caught = false;
+ try {
+ thunk.run();
+ } catch (Throwable x) {
+ if (ex.isAssignableFrom(x.getClass()))
+ caught = true;
+ }
+ if (!caught)
+ fail(ex.getName() + " not thrown", b);
+ }
+
+ private static void tryCatch(double [] t, Class ex, Runnable thunk) {
+ tryCatch(DoubleBuffer.wrap(t), ex, thunk);
+ }
+
+ public static void test(int level, final DoubleBuffer b, boolean direct) {
+
+ show(level, b);
+
+ if (direct != b.isDirect())
+ fail("Wrong direction", b);
+
+ // Gets and puts
+
+ relPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ absPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ bulkPutArray(b);
+ relGet(b);
+
+ bulkPutBuffer(b);
+ relGet(b);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Compact
+
+ relPut(b);
+ b.position(13);
+ b.compact();
+ b.flip();
+ relGet(b, 13);
+
+ // Exceptions
+
+ boolean caught = false;
+ relPut(b);
+ b.limit(b.capacity() / 2);
+ b.position(b.limit());
+
+ tryCatch(b, BufferUnderflowException.class, new Runnable() {
+ public void run() {
+ b.get();
+ }});
+
+ tryCatch(b, BufferOverflowException.class, new Runnable() {
+ public void run() {
+ b.put((double)42);
+ }});
+
+ // The index must be non-negative and lesss than the buffer's limit.
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(b.limit());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(-1);
+ }});
+
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.put(b.limit(), (double)42);
+ }});
+
+ // Values
+
+ b.clear();
+ b.put((double)0);
+ b.put((double)-1);
+ b.put((double)1);
+ b.put(Double.MAX_VALUE);
+ b.put(Double.MIN_VALUE);
+
+
+
+
+
+
+
+
+
+ b.put(-Double.MAX_VALUE);
+ b.put(-Double.MIN_VALUE);
+ b.put(Double.NEGATIVE_INFINITY);
+ b.put(Double.POSITIVE_INFINITY);
+ b.put(Double.NaN);
+ b.put(0.5121609353879392); // Changes value if incorrectly swapped
+
+
+ double v;
+ b.flip();
+ ck(b, b.get(), 0);
+ ck(b, b.get(), (double)-1);
+ ck(b, b.get(), 1);
+ ck(b, b.get(), Double.MAX_VALUE);
+ ck(b, b.get(), Double.MIN_VALUE);
+
+
+
+
+
+
+
+
+
+
+
+ ck(b, b.get(), -Double.MAX_VALUE);
+ ck(b, b.get(), -Double.MIN_VALUE);
+ ck(b, b.get(), Double.NEGATIVE_INFINITY);
+ ck(b, b.get(), Double.POSITIVE_INFINITY);
+ if (Double.doubleToRawLongBits(v = b.get())
+ != Double.doubleToRawLongBits(Double.NaN))
+ fail(b, (long)Double.NaN, (long)v);
+ ck(b, b.get(), 0.5121609353879392);
+
+
+
+ // Comparison
+ b.rewind();
+ DoubleBuffer b2 = DoubleBuffer.allocate(b.capacity());
+ b2.put(b);
+ b2.flip();
+ b.position(2);
+ b2.position(2);
+ if (!b.equals(b2)) {
+ for (int i = 2; i < b.limit(); i++) {
+ double x = b.get(i);
+ double y = b2.get(i);
+ if (x != y
+
+ || Double.compare(x, y) != 0
+
+
+
+
+ )
+ out.println("[" + i + "] " + x + " != " + y);
+ }
+ fail("Identical buffers not equal", b, b2);
+ }
+ if (b.compareTo(b2) != 0)
+ fail("Comparison to identical buffer != 0", b, b2);
+
+ b.limit(b.limit() + 1);
+ b.position(b.limit() - 1);
+ b.put((double)99);
+ b.rewind();
+ b2.rewind();
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to shorter buffer <= 0", b, b2);
+ b.limit(b.limit() - 1);
+
+ b.put(2, (double)42);
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to lesser buffer <= 0", b, b2);
+
+ // Sub, dup
+
+ relPut(b);
+ relGet(b.duplicate());
+ b.position(13);
+ relGet(b.duplicate(), 13);
+ relGet(b.duplicate().slice(), 13);
+ relGet(b.slice(), 13);
+ relGet(b.slice().duplicate(), 13);
+
+ // Slice
+
+ b.position(5);
+ DoubleBuffer sb = b.slice();
+ checkSlice(b, sb);
+ b.position(0);
+ DoubleBuffer sb2 = sb.slice();
+ checkSlice(sb, sb2);
+
+ if (!sb.equals(sb2))
+ fail("Sliced slices do not match", sb, sb2);
+ if ((sb.hasArray()) && (sb.arrayOffset() != sb2.arrayOffset()))
+ fail("Array offsets do not match: "
+ + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Read-only views
+
+ b.rewind();
+ final DoubleBuffer rb = b.asReadOnlyBuffer();
+ if (!b.equals(rb))
+ fail("Buffer not equal to read-only view", b, rb);
+ show(level + 1, rb);
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ relPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ absPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutArray(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutBuffer(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.compact();
+ }});
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ if (rb.getClass().getName().startsWith("java.nio.Heap")) {
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.array();
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.arrayOffset();
+ }});
+
+ if (rb.hasArray())
+ fail("Read-only heap buffer's backing array is accessible",
+ rb);
+
+ }
+
+ // Bulk puts from read-only buffers
+
+ b.clear();
+ rb.rewind();
+ b.put(rb);
+
+
+
+
+
+
+
+
+
+
+
+ relPut(b); // Required by testViews
+
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ public static void test(final double [] ba) {
+ int offset = 47;
+ int length = 900;
+ final DoubleBuffer b = DoubleBuffer.wrap(ba, offset, length);
+ show(0, b);
+ ck(b, b.capacity(), ba.length);
+ ck(b, b.position(), offset);
+ ck(b, b.limit(), offset + length);
+
+ // The offset must be non-negative and no larger than <array.length>.
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ DoubleBuffer.wrap(ba, -1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ DoubleBuffer.wrap(ba, ba.length + 1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ DoubleBuffer.wrap(ba, 0, -1);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ DoubleBuffer.wrap(ba, 0, ba.length + 1);
+ }});
+
+ // A NullPointerException will be thrown if the array is null.
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ DoubleBuffer.wrap((double []) null, 0, 5);
+ }});
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ DoubleBuffer.wrap((double []) null);
+ }});
+ }
+
+ private static void testAllocate() {
+ // An IllegalArgumentException will be thrown for negative capacities.
+ tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() {
+ public void run() {
+ DoubleBuffer.allocate(-1);
+ }});
+
+
+
+
+
+
+ }
+
+ public static void test() {
+ testAllocate();
+ test(0, DoubleBuffer.allocate(7 * 1024), false);
+ test(0, DoubleBuffer.wrap(new double[7 * 1024], 0, 7 * 1024), false);
+ test(new double[1024]);
+
+
+
+
+
+
+
+
+
+
+ callReset(DoubleBuffer.allocate(10));
+
+
+
+ putBuffer();
+
+ }
+
+}
diff --git a/test/java/nio/Buffer/BasicFloat.java b/test/java/nio/Buffer/BasicFloat.java
new file mode 100644
index 0000000..9bd702b
--- /dev/null
+++ b/test/java/nio/Buffer/BasicFloat.java
@@ -0,0 +1,828 @@
+/*
+ * Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* Type-specific source code for unit test
+ *
+ * Regenerate the BasicX classes via genBasic.sh whenever this file changes.
+ * We check in the generated source files so that the test tree can be used
+ * independently of the rest of the source tree.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+
+public class BasicFloat
+ extends Basic
+{
+
+ private static void relGet(FloatBuffer b) {
+ int n = b.capacity();
+ float v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((float)ic(i)));
+ b.rewind();
+ }
+
+ private static void relGet(FloatBuffer b, int start) {
+ int n = b.remaining();
+ float v;
+ for (int i = start; i < n; i++)
+ ck(b, (long)b.get(), (long)((float)ic(i)));
+ b.rewind();
+ }
+
+ private static void absGet(FloatBuffer b) {
+ int n = b.capacity();
+ float v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((float)ic(i)));
+ b.rewind();
+ }
+
+ private static void bulkGet(FloatBuffer b) {
+ int n = b.capacity();
+ float[] a = new float[n + 7];
+ b.get(a, 7, n);
+ for (int i = 0; i < n; i++)
+ ck(b, (long)a[i + 7], (long)((float)ic(i)));
+ }
+
+ private static void relPut(FloatBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put((float)ic(i));
+ b.flip();
+ }
+
+ private static void absPut(FloatBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (float)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void bulkPutArray(FloatBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ float[] a = new float[n + 7];
+ for (int i = 0; i < n; i++)
+ a[i + 7] = (float)ic(i);
+ b.put(a, 7, n);
+ b.flip();
+ }
+
+ private static void bulkPutBuffer(FloatBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ FloatBuffer c = FloatBuffer.allocate(n + 7);
+ c.position(7);
+ for (int i = 0; i < n; i++)
+ c.put((float)ic(i));
+ c.flip();
+ c.position(7);
+ b.put(c);
+ b.flip();
+ }
+
+ //6231529
+ private static void callReset(FloatBuffer b) {
+ b.position(0);
+ b.mark();
+
+ b.duplicate().reset();
+ b.asReadOnlyBuffer().reset();
+ }
+
+
+
+ // 6221101-6234263
+
+ private static void putBuffer() {
+ final int cap = 10;
+
+ FloatBuffer direct1 = ByteBuffer.allocateDirect(cap).asFloatBuffer();
+ FloatBuffer nondirect1 = ByteBuffer.allocate(cap).asFloatBuffer();
+ direct1.put(nondirect1);
+
+ FloatBuffer direct2 = ByteBuffer.allocateDirect(cap).asFloatBuffer();
+ FloatBuffer nondirect2 = ByteBuffer.allocate(cap).asFloatBuffer();
+ nondirect2.put(direct2);
+
+ FloatBuffer direct3 = ByteBuffer.allocateDirect(cap).asFloatBuffer();
+ FloatBuffer direct4 = ByteBuffer.allocateDirect(cap).asFloatBuffer();
+ direct3.put(direct4);
+
+ FloatBuffer nondirect3 = ByteBuffer.allocate(cap).asFloatBuffer();
+ FloatBuffer nondirect4 = ByteBuffer.allocate(cap).asFloatBuffer();
+ nondirect3.put(nondirect4);
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ private static void checkSlice(FloatBuffer b, FloatBuffer slice) {
+ ck(slice, 0, slice.position());
+ ck(slice, b.remaining(), slice.limit());
+ ck(slice, b.remaining(), slice.capacity());
+ if (b.isDirect() != slice.isDirect())
+ fail("Lost direction", slice);
+ if (b.isReadOnly() != slice.isReadOnly())
+ fail("Lost read-only", slice);
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ private static void tryCatch(Buffer b, Class ex, Runnable thunk) {
+ boolean caught = false;
+ try {
+ thunk.run();
+ } catch (Throwable x) {
+ if (ex.isAssignableFrom(x.getClass()))
+ caught = true;
+ }
+ if (!caught)
+ fail(ex.getName() + " not thrown", b);
+ }
+
+ private static void tryCatch(float [] t, Class ex, Runnable thunk) {
+ tryCatch(FloatBuffer.wrap(t), ex, thunk);
+ }
+
+ public static void test(int level, final FloatBuffer b, boolean direct) {
+
+ show(level, b);
+
+ if (direct != b.isDirect())
+ fail("Wrong direction", b);
+
+ // Gets and puts
+
+ relPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ absPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ bulkPutArray(b);
+ relGet(b);
+
+ bulkPutBuffer(b);
+ relGet(b);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Compact
+
+ relPut(b);
+ b.position(13);
+ b.compact();
+ b.flip();
+ relGet(b, 13);
+
+ // Exceptions
+
+ boolean caught = false;
+ relPut(b);
+ b.limit(b.capacity() / 2);
+ b.position(b.limit());
+
+ tryCatch(b, BufferUnderflowException.class, new Runnable() {
+ public void run() {
+ b.get();
+ }});
+
+ tryCatch(b, BufferOverflowException.class, new Runnable() {
+ public void run() {
+ b.put((float)42);
+ }});
+
+ // The index must be non-negative and lesss than the buffer's limit.
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(b.limit());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(-1);
+ }});
+
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.put(b.limit(), (float)42);
+ }});
+
+ // Values
+
+ b.clear();
+ b.put((float)0);
+ b.put((float)-1);
+ b.put((float)1);
+ b.put(Float.MAX_VALUE);
+ b.put(Float.MIN_VALUE);
+
+ b.put(-Float.MAX_VALUE);
+ b.put(-Float.MIN_VALUE);
+ b.put(Float.NEGATIVE_INFINITY);
+ b.put(Float.POSITIVE_INFINITY);
+ b.put(Float.NaN);
+ b.put(0.91697687f); // Changes value if incorrectly swapped
+
+
+
+
+
+
+
+
+
+
+ float v;
+ b.flip();
+ ck(b, b.get(), 0);
+ ck(b, b.get(), (float)-1);
+ ck(b, b.get(), 1);
+ ck(b, b.get(), Float.MAX_VALUE);
+ ck(b, b.get(), Float.MIN_VALUE);
+
+
+ ck(b, b.get(), -Float.MAX_VALUE);
+ ck(b, b.get(), -Float.MIN_VALUE);
+ ck(b, b.get(), Float.NEGATIVE_INFINITY);
+ ck(b, b.get(), Float.POSITIVE_INFINITY);
+ if (Float.floatToRawIntBits(v = b.get()) != Float.floatToRawIntBits(Float.NaN))
+ fail(b, (long)Float.NaN, (long)v);
+ ck(b, b.get(), 0.91697687f);
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Comparison
+ b.rewind();
+ FloatBuffer b2 = FloatBuffer.allocate(b.capacity());
+ b2.put(b);
+ b2.flip();
+ b.position(2);
+ b2.position(2);
+ if (!b.equals(b2)) {
+ for (int i = 2; i < b.limit(); i++) {
+ float x = b.get(i);
+ float y = b2.get(i);
+ if (x != y
+
+
+
+
+ || Float.compare(x, y) != 0
+
+ )
+ out.println("[" + i + "] " + x + " != " + y);
+ }
+ fail("Identical buffers not equal", b, b2);
+ }
+ if (b.compareTo(b2) != 0)
+ fail("Comparison to identical buffer != 0", b, b2);
+
+ b.limit(b.limit() + 1);
+ b.position(b.limit() - 1);
+ b.put((float)99);
+ b.rewind();
+ b2.rewind();
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to shorter buffer <= 0", b, b2);
+ b.limit(b.limit() - 1);
+
+ b.put(2, (float)42);
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to lesser buffer <= 0", b, b2);
+
+ // Sub, dup
+
+ relPut(b);
+ relGet(b.duplicate());
+ b.position(13);
+ relGet(b.duplicate(), 13);
+ relGet(b.duplicate().slice(), 13);
+ relGet(b.slice(), 13);
+ relGet(b.slice().duplicate(), 13);
+
+ // Slice
+
+ b.position(5);
+ FloatBuffer sb = b.slice();
+ checkSlice(b, sb);
+ b.position(0);
+ FloatBuffer sb2 = sb.slice();
+ checkSlice(sb, sb2);
+
+ if (!sb.equals(sb2))
+ fail("Sliced slices do not match", sb, sb2);
+ if ((sb.hasArray()) && (sb.arrayOffset() != sb2.arrayOffset()))
+ fail("Array offsets do not match: "
+ + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Read-only views
+
+ b.rewind();
+ final FloatBuffer rb = b.asReadOnlyBuffer();
+ if (!b.equals(rb))
+ fail("Buffer not equal to read-only view", b, rb);
+ show(level + 1, rb);
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ relPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ absPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutArray(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutBuffer(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.compact();
+ }});
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ if (rb.getClass().getName().startsWith("java.nio.Heap")) {
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.array();
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.arrayOffset();
+ }});
+
+ if (rb.hasArray())
+ fail("Read-only heap buffer's backing array is accessible",
+ rb);
+
+ }
+
+ // Bulk puts from read-only buffers
+
+ b.clear();
+ rb.rewind();
+ b.put(rb);
+
+
+
+
+
+
+
+
+
+
+
+ relPut(b); // Required by testViews
+
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ public static void test(final float [] ba) {
+ int offset = 47;
+ int length = 900;
+ final FloatBuffer b = FloatBuffer.wrap(ba, offset, length);
+ show(0, b);
+ ck(b, b.capacity(), ba.length);
+ ck(b, b.position(), offset);
+ ck(b, b.limit(), offset + length);
+
+ // The offset must be non-negative and no larger than <array.length>.
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ FloatBuffer.wrap(ba, -1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ FloatBuffer.wrap(ba, ba.length + 1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ FloatBuffer.wrap(ba, 0, -1);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ FloatBuffer.wrap(ba, 0, ba.length + 1);
+ }});
+
+ // A NullPointerException will be thrown if the array is null.
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ FloatBuffer.wrap((float []) null, 0, 5);
+ }});
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ FloatBuffer.wrap((float []) null);
+ }});
+ }
+
+ private static void testAllocate() {
+ // An IllegalArgumentException will be thrown for negative capacities.
+ tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() {
+ public void run() {
+ FloatBuffer.allocate(-1);
+ }});
+
+
+
+
+
+
+ }
+
+ public static void test() {
+ testAllocate();
+ test(0, FloatBuffer.allocate(7 * 1024), false);
+ test(0, FloatBuffer.wrap(new float[7 * 1024], 0, 7 * 1024), false);
+ test(new float[1024]);
+
+
+
+
+
+
+
+
+
+
+ callReset(FloatBuffer.allocate(10));
+
+
+
+ putBuffer();
+
+ }
+
+}
diff --git a/test/java/nio/Buffer/BasicInt.java b/test/java/nio/Buffer/BasicInt.java
new file mode 100644
index 0000000..4a58871
--- /dev/null
+++ b/test/java/nio/Buffer/BasicInt.java
@@ -0,0 +1,828 @@
+/*
+ * Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* Type-specific source code for unit test
+ *
+ * Regenerate the BasicX classes via genBasic.sh whenever this file changes.
+ * We check in the generated source files so that the test tree can be used
+ * independently of the rest of the source tree.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+
+public class BasicInt
+ extends Basic
+{
+
+ private static void relGet(IntBuffer b) {
+ int n = b.capacity();
+ int v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((int)ic(i)));
+ b.rewind();
+ }
+
+ private static void relGet(IntBuffer b, int start) {
+ int n = b.remaining();
+ int v;
+ for (int i = start; i < n; i++)
+ ck(b, (long)b.get(), (long)((int)ic(i)));
+ b.rewind();
+ }
+
+ private static void absGet(IntBuffer b) {
+ int n = b.capacity();
+ int v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((int)ic(i)));
+ b.rewind();
+ }
+
+ private static void bulkGet(IntBuffer b) {
+ int n = b.capacity();
+ int[] a = new int[n + 7];
+ b.get(a, 7, n);
+ for (int i = 0; i < n; i++)
+ ck(b, (long)a[i + 7], (long)((int)ic(i)));
+ }
+
+ private static void relPut(IntBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put((int)ic(i));
+ b.flip();
+ }
+
+ private static void absPut(IntBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (int)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void bulkPutArray(IntBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ int[] a = new int[n + 7];
+ for (int i = 0; i < n; i++)
+ a[i + 7] = (int)ic(i);
+ b.put(a, 7, n);
+ b.flip();
+ }
+
+ private static void bulkPutBuffer(IntBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ IntBuffer c = IntBuffer.allocate(n + 7);
+ c.position(7);
+ for (int i = 0; i < n; i++)
+ c.put((int)ic(i));
+ c.flip();
+ c.position(7);
+ b.put(c);
+ b.flip();
+ }
+
+ //6231529
+ private static void callReset(IntBuffer b) {
+ b.position(0);
+ b.mark();
+
+ b.duplicate().reset();
+ b.asReadOnlyBuffer().reset();
+ }
+
+
+
+ // 6221101-6234263
+
+ private static void putBuffer() {
+ final int cap = 10;
+
+ IntBuffer direct1 = ByteBuffer.allocateDirect(cap).asIntBuffer();
+ IntBuffer nondirect1 = ByteBuffer.allocate(cap).asIntBuffer();
+ direct1.put(nondirect1);
+
+ IntBuffer direct2 = ByteBuffer.allocateDirect(cap).asIntBuffer();
+ IntBuffer nondirect2 = ByteBuffer.allocate(cap).asIntBuffer();
+ nondirect2.put(direct2);
+
+ IntBuffer direct3 = ByteBuffer.allocateDirect(cap).asIntBuffer();
+ IntBuffer direct4 = ByteBuffer.allocateDirect(cap).asIntBuffer();
+ direct3.put(direct4);
+
+ IntBuffer nondirect3 = ByteBuffer.allocate(cap).asIntBuffer();
+ IntBuffer nondirect4 = ByteBuffer.allocate(cap).asIntBuffer();
+ nondirect3.put(nondirect4);
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ private static void checkSlice(IntBuffer b, IntBuffer slice) {
+ ck(slice, 0, slice.position());
+ ck(slice, b.remaining(), slice.limit());
+ ck(slice, b.remaining(), slice.capacity());
+ if (b.isDirect() != slice.isDirect())
+ fail("Lost direction", slice);
+ if (b.isReadOnly() != slice.isReadOnly())
+ fail("Lost read-only", slice);
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ private static void tryCatch(Buffer b, Class ex, Runnable thunk) {
+ boolean caught = false;
+ try {
+ thunk.run();
+ } catch (Throwable x) {
+ if (ex.isAssignableFrom(x.getClass()))
+ caught = true;
+ }
+ if (!caught)
+ fail(ex.getName() + " not thrown", b);
+ }
+
+ private static void tryCatch(int [] t, Class ex, Runnable thunk) {
+ tryCatch(IntBuffer.wrap(t), ex, thunk);
+ }
+
+ public static void test(int level, final IntBuffer b, boolean direct) {
+
+ show(level, b);
+
+ if (direct != b.isDirect())
+ fail("Wrong direction", b);
+
+ // Gets and puts
+
+ relPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ absPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ bulkPutArray(b);
+ relGet(b);
+
+ bulkPutBuffer(b);
+ relGet(b);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Compact
+
+ relPut(b);
+ b.position(13);
+ b.compact();
+ b.flip();
+ relGet(b, 13);
+
+ // Exceptions
+
+ boolean caught = false;
+ relPut(b);
+ b.limit(b.capacity() / 2);
+ b.position(b.limit());
+
+ tryCatch(b, BufferUnderflowException.class, new Runnable() {
+ public void run() {
+ b.get();
+ }});
+
+ tryCatch(b, BufferOverflowException.class, new Runnable() {
+ public void run() {
+ b.put((int)42);
+ }});
+
+ // The index must be non-negative and lesss than the buffer's limit.
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(b.limit());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(-1);
+ }});
+
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.put(b.limit(), (int)42);
+ }});
+
+ // Values
+
+ b.clear();
+ b.put((int)0);
+ b.put((int)-1);
+ b.put((int)1);
+ b.put(Integer.MAX_VALUE);
+ b.put(Integer.MIN_VALUE);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ int v;
+ b.flip();
+ ck(b, b.get(), 0);
+ ck(b, b.get(), (int)-1);
+ ck(b, b.get(), 1);
+ ck(b, b.get(), Integer.MAX_VALUE);
+ ck(b, b.get(), Integer.MIN_VALUE);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Comparison
+ b.rewind();
+ IntBuffer b2 = IntBuffer.allocate(b.capacity());
+ b2.put(b);
+ b2.flip();
+ b.position(2);
+ b2.position(2);
+ if (!b.equals(b2)) {
+ for (int i = 2; i < b.limit(); i++) {
+ int x = b.get(i);
+ int y = b2.get(i);
+ if (x != y
+
+
+
+
+
+
+ )
+ out.println("[" + i + "] " + x + " != " + y);
+ }
+ fail("Identical buffers not equal", b, b2);
+ }
+ if (b.compareTo(b2) != 0)
+ fail("Comparison to identical buffer != 0", b, b2);
+
+ b.limit(b.limit() + 1);
+ b.position(b.limit() - 1);
+ b.put((int)99);
+ b.rewind();
+ b2.rewind();
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to shorter buffer <= 0", b, b2);
+ b.limit(b.limit() - 1);
+
+ b.put(2, (int)42);
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to lesser buffer <= 0", b, b2);
+
+ // Sub, dup
+
+ relPut(b);
+ relGet(b.duplicate());
+ b.position(13);
+ relGet(b.duplicate(), 13);
+ relGet(b.duplicate().slice(), 13);
+ relGet(b.slice(), 13);
+ relGet(b.slice().duplicate(), 13);
+
+ // Slice
+
+ b.position(5);
+ IntBuffer sb = b.slice();
+ checkSlice(b, sb);
+ b.position(0);
+ IntBuffer sb2 = sb.slice();
+ checkSlice(sb, sb2);
+
+ if (!sb.equals(sb2))
+ fail("Sliced slices do not match", sb, sb2);
+ if ((sb.hasArray()) && (sb.arrayOffset() != sb2.arrayOffset()))
+ fail("Array offsets do not match: "
+ + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Read-only views
+
+ b.rewind();
+ final IntBuffer rb = b.asReadOnlyBuffer();
+ if (!b.equals(rb))
+ fail("Buffer not equal to read-only view", b, rb);
+ show(level + 1, rb);
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ relPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ absPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutArray(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutBuffer(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.compact();
+ }});
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ if (rb.getClass().getName().startsWith("java.nio.Heap")) {
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.array();
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.arrayOffset();
+ }});
+
+ if (rb.hasArray())
+ fail("Read-only heap buffer's backing array is accessible",
+ rb);
+
+ }
+
+ // Bulk puts from read-only buffers
+
+ b.clear();
+ rb.rewind();
+ b.put(rb);
+
+
+
+
+
+
+
+
+
+
+
+ relPut(b); // Required by testViews
+
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ public static void test(final int [] ba) {
+ int offset = 47;
+ int length = 900;
+ final IntBuffer b = IntBuffer.wrap(ba, offset, length);
+ show(0, b);
+ ck(b, b.capacity(), ba.length);
+ ck(b, b.position(), offset);
+ ck(b, b.limit(), offset + length);
+
+ // The offset must be non-negative and no larger than <array.length>.
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ IntBuffer.wrap(ba, -1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ IntBuffer.wrap(ba, ba.length + 1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ IntBuffer.wrap(ba, 0, -1);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ IntBuffer.wrap(ba, 0, ba.length + 1);
+ }});
+
+ // A NullPointerException will be thrown if the array is null.
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ IntBuffer.wrap((int []) null, 0, 5);
+ }});
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ IntBuffer.wrap((int []) null);
+ }});
+ }
+
+ private static void testAllocate() {
+ // An IllegalArgumentException will be thrown for negative capacities.
+ tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() {
+ public void run() {
+ IntBuffer.allocate(-1);
+ }});
+
+
+
+
+
+
+ }
+
+ public static void test() {
+ testAllocate();
+ test(0, IntBuffer.allocate(7 * 1024), false);
+ test(0, IntBuffer.wrap(new int[7 * 1024], 0, 7 * 1024), false);
+ test(new int[1024]);
+
+
+
+
+
+
+
+
+
+
+ callReset(IntBuffer.allocate(10));
+
+
+
+ putBuffer();
+
+ }
+
+}
diff --git a/test/java/nio/Buffer/BasicLong.java b/test/java/nio/Buffer/BasicLong.java
new file mode 100644
index 0000000..0ef145c
--- /dev/null
+++ b/test/java/nio/Buffer/BasicLong.java
@@ -0,0 +1,828 @@
+/*
+ * Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* Type-specific source code for unit test
+ *
+ * Regenerate the BasicX classes via genBasic.sh whenever this file changes.
+ * We check in the generated source files so that the test tree can be used
+ * independently of the rest of the source tree.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+
+public class BasicLong
+ extends Basic
+{
+
+ private static void relGet(LongBuffer b) {
+ int n = b.capacity();
+ long v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((long)ic(i)));
+ b.rewind();
+ }
+
+ private static void relGet(LongBuffer b, int start) {
+ int n = b.remaining();
+ long v;
+ for (int i = start; i < n; i++)
+ ck(b, (long)b.get(), (long)((long)ic(i)));
+ b.rewind();
+ }
+
+ private static void absGet(LongBuffer b) {
+ int n = b.capacity();
+ long v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((long)ic(i)));
+ b.rewind();
+ }
+
+ private static void bulkGet(LongBuffer b) {
+ int n = b.capacity();
+ long[] a = new long[n + 7];
+ b.get(a, 7, n);
+ for (int i = 0; i < n; i++)
+ ck(b, (long)a[i + 7], (long)((long)ic(i)));
+ }
+
+ private static void relPut(LongBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put((long)ic(i));
+ b.flip();
+ }
+
+ private static void absPut(LongBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (long)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void bulkPutArray(LongBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ long[] a = new long[n + 7];
+ for (int i = 0; i < n; i++)
+ a[i + 7] = (long)ic(i);
+ b.put(a, 7, n);
+ b.flip();
+ }
+
+ private static void bulkPutBuffer(LongBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ LongBuffer c = LongBuffer.allocate(n + 7);
+ c.position(7);
+ for (int i = 0; i < n; i++)
+ c.put((long)ic(i));
+ c.flip();
+ c.position(7);
+ b.put(c);
+ b.flip();
+ }
+
+ //6231529
+ private static void callReset(LongBuffer b) {
+ b.position(0);
+ b.mark();
+
+ b.duplicate().reset();
+ b.asReadOnlyBuffer().reset();
+ }
+
+
+
+ // 6221101-6234263
+
+ private static void putBuffer() {
+ final int cap = 10;
+
+ LongBuffer direct1 = ByteBuffer.allocateDirect(cap).asLongBuffer();
+ LongBuffer nondirect1 = ByteBuffer.allocate(cap).asLongBuffer();
+ direct1.put(nondirect1);
+
+ LongBuffer direct2 = ByteBuffer.allocateDirect(cap).asLongBuffer();
+ LongBuffer nondirect2 = ByteBuffer.allocate(cap).asLongBuffer();
+ nondirect2.put(direct2);
+
+ LongBuffer direct3 = ByteBuffer.allocateDirect(cap).asLongBuffer();
+ LongBuffer direct4 = ByteBuffer.allocateDirect(cap).asLongBuffer();
+ direct3.put(direct4);
+
+ LongBuffer nondirect3 = ByteBuffer.allocate(cap).asLongBuffer();
+ LongBuffer nondirect4 = ByteBuffer.allocate(cap).asLongBuffer();
+ nondirect3.put(nondirect4);
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ private static void checkSlice(LongBuffer b, LongBuffer slice) {
+ ck(slice, 0, slice.position());
+ ck(slice, b.remaining(), slice.limit());
+ ck(slice, b.remaining(), slice.capacity());
+ if (b.isDirect() != slice.isDirect())
+ fail("Lost direction", slice);
+ if (b.isReadOnly() != slice.isReadOnly())
+ fail("Lost read-only", slice);
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ private static void tryCatch(Buffer b, Class ex, Runnable thunk) {
+ boolean caught = false;
+ try {
+ thunk.run();
+ } catch (Throwable x) {
+ if (ex.isAssignableFrom(x.getClass()))
+ caught = true;
+ }
+ if (!caught)
+ fail(ex.getName() + " not thrown", b);
+ }
+
+ private static void tryCatch(long [] t, Class ex, Runnable thunk) {
+ tryCatch(LongBuffer.wrap(t), ex, thunk);
+ }
+
+ public static void test(int level, final LongBuffer b, boolean direct) {
+
+ show(level, b);
+
+ if (direct != b.isDirect())
+ fail("Wrong direction", b);
+
+ // Gets and puts
+
+ relPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ absPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ bulkPutArray(b);
+ relGet(b);
+
+ bulkPutBuffer(b);
+ relGet(b);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Compact
+
+ relPut(b);
+ b.position(13);
+ b.compact();
+ b.flip();
+ relGet(b, 13);
+
+ // Exceptions
+
+ boolean caught = false;
+ relPut(b);
+ b.limit(b.capacity() / 2);
+ b.position(b.limit());
+
+ tryCatch(b, BufferUnderflowException.class, new Runnable() {
+ public void run() {
+ b.get();
+ }});
+
+ tryCatch(b, BufferOverflowException.class, new Runnable() {
+ public void run() {
+ b.put((long)42);
+ }});
+
+ // The index must be non-negative and lesss than the buffer's limit.
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(b.limit());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(-1);
+ }});
+
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.put(b.limit(), (long)42);
+ }});
+
+ // Values
+
+ b.clear();
+ b.put((long)0);
+ b.put((long)-1);
+ b.put((long)1);
+ b.put(Long.MAX_VALUE);
+ b.put(Long.MIN_VALUE);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ long v;
+ b.flip();
+ ck(b, b.get(), 0);
+ ck(b, b.get(), (long)-1);
+ ck(b, b.get(), 1);
+ ck(b, b.get(), Long.MAX_VALUE);
+ ck(b, b.get(), Long.MIN_VALUE);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Comparison
+ b.rewind();
+ LongBuffer b2 = LongBuffer.allocate(b.capacity());
+ b2.put(b);
+ b2.flip();
+ b.position(2);
+ b2.position(2);
+ if (!b.equals(b2)) {
+ for (int i = 2; i < b.limit(); i++) {
+ long x = b.get(i);
+ long y = b2.get(i);
+ if (x != y
+
+
+
+
+
+
+ )
+ out.println("[" + i + "] " + x + " != " + y);
+ }
+ fail("Identical buffers not equal", b, b2);
+ }
+ if (b.compareTo(b2) != 0)
+ fail("Comparison to identical buffer != 0", b, b2);
+
+ b.limit(b.limit() + 1);
+ b.position(b.limit() - 1);
+ b.put((long)99);
+ b.rewind();
+ b2.rewind();
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to shorter buffer <= 0", b, b2);
+ b.limit(b.limit() - 1);
+
+ b.put(2, (long)42);
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to lesser buffer <= 0", b, b2);
+
+ // Sub, dup
+
+ relPut(b);
+ relGet(b.duplicate());
+ b.position(13);
+ relGet(b.duplicate(), 13);
+ relGet(b.duplicate().slice(), 13);
+ relGet(b.slice(), 13);
+ relGet(b.slice().duplicate(), 13);
+
+ // Slice
+
+ b.position(5);
+ LongBuffer sb = b.slice();
+ checkSlice(b, sb);
+ b.position(0);
+ LongBuffer sb2 = sb.slice();
+ checkSlice(sb, sb2);
+
+ if (!sb.equals(sb2))
+ fail("Sliced slices do not match", sb, sb2);
+ if ((sb.hasArray()) && (sb.arrayOffset() != sb2.arrayOffset()))
+ fail("Array offsets do not match: "
+ + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Read-only views
+
+ b.rewind();
+ final LongBuffer rb = b.asReadOnlyBuffer();
+ if (!b.equals(rb))
+ fail("Buffer not equal to read-only view", b, rb);
+ show(level + 1, rb);
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ relPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ absPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutArray(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutBuffer(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.compact();
+ }});
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ if (rb.getClass().getName().startsWith("java.nio.Heap")) {
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.array();
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.arrayOffset();
+ }});
+
+ if (rb.hasArray())
+ fail("Read-only heap buffer's backing array is accessible",
+ rb);
+
+ }
+
+ // Bulk puts from read-only buffers
+
+ b.clear();
+ rb.rewind();
+ b.put(rb);
+
+
+
+
+
+
+
+
+
+
+
+ relPut(b); // Required by testViews
+
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ public static void test(final long [] ba) {
+ int offset = 47;
+ int length = 900;
+ final LongBuffer b = LongBuffer.wrap(ba, offset, length);
+ show(0, b);
+ ck(b, b.capacity(), ba.length);
+ ck(b, b.position(), offset);
+ ck(b, b.limit(), offset + length);
+
+ // The offset must be non-negative and no larger than <array.length>.
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ LongBuffer.wrap(ba, -1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ LongBuffer.wrap(ba, ba.length + 1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ LongBuffer.wrap(ba, 0, -1);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ LongBuffer.wrap(ba, 0, ba.length + 1);
+ }});
+
+ // A NullPointerException will be thrown if the array is null.
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ LongBuffer.wrap((long []) null, 0, 5);
+ }});
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ LongBuffer.wrap((long []) null);
+ }});
+ }
+
+ private static void testAllocate() {
+ // An IllegalArgumentException will be thrown for negative capacities.
+ tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() {
+ public void run() {
+ LongBuffer.allocate(-1);
+ }});
+
+
+
+
+
+
+ }
+
+ public static void test() {
+ testAllocate();
+ test(0, LongBuffer.allocate(7 * 1024), false);
+ test(0, LongBuffer.wrap(new long[7 * 1024], 0, 7 * 1024), false);
+ test(new long[1024]);
+
+
+
+
+
+
+
+
+
+
+ callReset(LongBuffer.allocate(10));
+
+
+
+ putBuffer();
+
+ }
+
+}
diff --git a/test/java/nio/Buffer/BasicShort.java b/test/java/nio/Buffer/BasicShort.java
new file mode 100644
index 0000000..42fe98b
--- /dev/null
+++ b/test/java/nio/Buffer/BasicShort.java
@@ -0,0 +1,828 @@
+/*
+ * Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* Type-specific source code for unit test
+ *
+ * Regenerate the BasicX classes via genBasic.sh whenever this file changes.
+ * We check in the generated source files so that the test tree can be used
+ * independently of the rest of the source tree.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+
+public class BasicShort
+ extends Basic
+{
+
+ private static void relGet(ShortBuffer b) {
+ int n = b.capacity();
+ short v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((short)ic(i)));
+ b.rewind();
+ }
+
+ private static void relGet(ShortBuffer b, int start) {
+ int n = b.remaining();
+ short v;
+ for (int i = start; i < n; i++)
+ ck(b, (long)b.get(), (long)((short)ic(i)));
+ b.rewind();
+ }
+
+ private static void absGet(ShortBuffer b) {
+ int n = b.capacity();
+ short v;
+ for (int i = 0; i < n; i++)
+ ck(b, (long)b.get(), (long)((short)ic(i)));
+ b.rewind();
+ }
+
+ private static void bulkGet(ShortBuffer b) {
+ int n = b.capacity();
+ short[] a = new short[n + 7];
+ b.get(a, 7, n);
+ for (int i = 0; i < n; i++)
+ ck(b, (long)a[i + 7], (long)((short)ic(i)));
+ }
+
+ private static void relPut(ShortBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put((short)ic(i));
+ b.flip();
+ }
+
+ private static void absPut(ShortBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (short)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void bulkPutArray(ShortBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ short[] a = new short[n + 7];
+ for (int i = 0; i < n; i++)
+ a[i + 7] = (short)ic(i);
+ b.put(a, 7, n);
+ b.flip();
+ }
+
+ private static void bulkPutBuffer(ShortBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ ShortBuffer c = ShortBuffer.allocate(n + 7);
+ c.position(7);
+ for (int i = 0; i < n; i++)
+ c.put((short)ic(i));
+ c.flip();
+ c.position(7);
+ b.put(c);
+ b.flip();
+ }
+
+ //6231529
+ private static void callReset(ShortBuffer b) {
+ b.position(0);
+ b.mark();
+
+ b.duplicate().reset();
+ b.asReadOnlyBuffer().reset();
+ }
+
+
+
+ // 6221101-6234263
+
+ private static void putBuffer() {
+ final int cap = 10;
+
+ ShortBuffer direct1 = ByteBuffer.allocateDirect(cap).asShortBuffer();
+ ShortBuffer nondirect1 = ByteBuffer.allocate(cap).asShortBuffer();
+ direct1.put(nondirect1);
+
+ ShortBuffer direct2 = ByteBuffer.allocateDirect(cap).asShortBuffer();
+ ShortBuffer nondirect2 = ByteBuffer.allocate(cap).asShortBuffer();
+ nondirect2.put(direct2);
+
+ ShortBuffer direct3 = ByteBuffer.allocateDirect(cap).asShortBuffer();
+ ShortBuffer direct4 = ByteBuffer.allocateDirect(cap).asShortBuffer();
+ direct3.put(direct4);
+
+ ShortBuffer nondirect3 = ByteBuffer.allocate(cap).asShortBuffer();
+ ShortBuffer nondirect4 = ByteBuffer.allocate(cap).asShortBuffer();
+ nondirect3.put(nondirect4);
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ private static void checkSlice(ShortBuffer b, ShortBuffer slice) {
+ ck(slice, 0, slice.position());
+ ck(slice, b.remaining(), slice.limit());
+ ck(slice, b.remaining(), slice.capacity());
+ if (b.isDirect() != slice.isDirect())
+ fail("Lost direction", slice);
+ if (b.isReadOnly() != slice.isReadOnly())
+ fail("Lost read-only", slice);
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ private static void tryCatch(Buffer b, Class ex, Runnable thunk) {
+ boolean caught = false;
+ try {
+ thunk.run();
+ } catch (Throwable x) {
+ if (ex.isAssignableFrom(x.getClass()))
+ caught = true;
+ }
+ if (!caught)
+ fail(ex.getName() + " not thrown", b);
+ }
+
+ private static void tryCatch(short [] t, Class ex, Runnable thunk) {
+ tryCatch(ShortBuffer.wrap(t), ex, thunk);
+ }
+
+ public static void test(int level, final ShortBuffer b, boolean direct) {
+
+ show(level, b);
+
+ if (direct != b.isDirect())
+ fail("Wrong direction", b);
+
+ // Gets and puts
+
+ relPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ absPut(b);
+ relGet(b);
+ absGet(b);
+ bulkGet(b);
+
+ bulkPutArray(b);
+ relGet(b);
+
+ bulkPutBuffer(b);
+ relGet(b);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Compact
+
+ relPut(b);
+ b.position(13);
+ b.compact();
+ b.flip();
+ relGet(b, 13);
+
+ // Exceptions
+
+ boolean caught = false;
+ relPut(b);
+ b.limit(b.capacity() / 2);
+ b.position(b.limit());
+
+ tryCatch(b, BufferUnderflowException.class, new Runnable() {
+ public void run() {
+ b.get();
+ }});
+
+ tryCatch(b, BufferOverflowException.class, new Runnable() {
+ public void run() {
+ b.put((short)42);
+ }});
+
+ // The index must be non-negative and lesss than the buffer's limit.
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(b.limit());
+ }});
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.get(-1);
+ }});
+
+ tryCatch(b, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ b.put(b.limit(), (short)42);
+ }});
+
+ // Values
+
+ b.clear();
+ b.put((short)0);
+ b.put((short)-1);
+ b.put((short)1);
+ b.put(Short.MAX_VALUE);
+ b.put(Short.MIN_VALUE);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ short v;
+ b.flip();
+ ck(b, b.get(), 0);
+ ck(b, b.get(), (short)-1);
+ ck(b, b.get(), 1);
+ ck(b, b.get(), Short.MAX_VALUE);
+ ck(b, b.get(), Short.MIN_VALUE);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Comparison
+ b.rewind();
+ ShortBuffer b2 = ShortBuffer.allocate(b.capacity());
+ b2.put(b);
+ b2.flip();
+ b.position(2);
+ b2.position(2);
+ if (!b.equals(b2)) {
+ for (int i = 2; i < b.limit(); i++) {
+ short x = b.get(i);
+ short y = b2.get(i);
+ if (x != y
+
+
+
+
+
+
+ )
+ out.println("[" + i + "] " + x + " != " + y);
+ }
+ fail("Identical buffers not equal", b, b2);
+ }
+ if (b.compareTo(b2) != 0)
+ fail("Comparison to identical buffer != 0", b, b2);
+
+ b.limit(b.limit() + 1);
+ b.position(b.limit() - 1);
+ b.put((short)99);
+ b.rewind();
+ b2.rewind();
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to shorter buffer <= 0", b, b2);
+ b.limit(b.limit() - 1);
+
+ b.put(2, (short)42);
+ if (b.equals(b2))
+ fail("Non-identical buffers equal", b, b2);
+ if (b.compareTo(b2) <= 0)
+ fail("Comparison to lesser buffer <= 0", b, b2);
+
+ // Sub, dup
+
+ relPut(b);
+ relGet(b.duplicate());
+ b.position(13);
+ relGet(b.duplicate(), 13);
+ relGet(b.duplicate().slice(), 13);
+ relGet(b.slice(), 13);
+ relGet(b.slice().duplicate(), 13);
+
+ // Slice
+
+ b.position(5);
+ ShortBuffer sb = b.slice();
+ checkSlice(b, sb);
+ b.position(0);
+ ShortBuffer sb2 = sb.slice();
+ checkSlice(sb, sb2);
+
+ if (!sb.equals(sb2))
+ fail("Sliced slices do not match", sb, sb2);
+ if ((sb.hasArray()) && (sb.arrayOffset() != sb2.arrayOffset()))
+ fail("Array offsets do not match: "
+ + sb.arrayOffset() + " != " + sb2.arrayOffset(), sb, sb2);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ // Read-only views
+
+ b.rewind();
+ final ShortBuffer rb = b.asReadOnlyBuffer();
+ if (!b.equals(rb))
+ fail("Buffer not equal to read-only view", b, rb);
+ show(level + 1, rb);
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ relPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ absPut(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutArray(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ bulkPutBuffer(rb);
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.compact();
+ }});
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ if (rb.getClass().getName().startsWith("java.nio.Heap")) {
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.array();
+ }});
+
+ tryCatch(b, ReadOnlyBufferException.class, new Runnable() {
+ public void run() {
+ rb.arrayOffset();
+ }});
+
+ if (rb.hasArray())
+ fail("Read-only heap buffer's backing array is accessible",
+ rb);
+
+ }
+
+ // Bulk puts from read-only buffers
+
+ b.clear();
+ rb.rewind();
+ b.put(rb);
+
+
+
+
+
+
+
+
+
+
+
+ relPut(b); // Required by testViews
+
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ public static void test(final short [] ba) {
+ int offset = 47;
+ int length = 900;
+ final ShortBuffer b = ShortBuffer.wrap(ba, offset, length);
+ show(0, b);
+ ck(b, b.capacity(), ba.length);
+ ck(b, b.position(), offset);
+ ck(b, b.limit(), offset + length);
+
+ // The offset must be non-negative and no larger than <array.length>.
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ ShortBuffer.wrap(ba, -1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ ShortBuffer.wrap(ba, ba.length + 1, ba.length);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ ShortBuffer.wrap(ba, 0, -1);
+ }});
+ tryCatch(ba, IndexOutOfBoundsException.class, new Runnable() {
+ public void run() {
+ ShortBuffer.wrap(ba, 0, ba.length + 1);
+ }});
+
+ // A NullPointerException will be thrown if the array is null.
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ ShortBuffer.wrap((short []) null, 0, 5);
+ }});
+ tryCatch(ba, NullPointerException.class, new Runnable() {
+ public void run() {
+ ShortBuffer.wrap((short []) null);
+ }});
+ }
+
+ private static void testAllocate() {
+ // An IllegalArgumentException will be thrown for negative capacities.
+ tryCatch((Buffer) null, IllegalArgumentException.class, new Runnable() {
+ public void run() {
+ ShortBuffer.allocate(-1);
+ }});
+
+
+
+
+
+
+ }
+
+ public static void test() {
+ testAllocate();
+ test(0, ShortBuffer.allocate(7 * 1024), false);
+ test(0, ShortBuffer.wrap(new short[7 * 1024], 0, 7 * 1024), false);
+ test(new short[1024]);
+
+
+
+
+
+
+
+
+
+
+ callReset(ShortBuffer.allocate(10));
+
+
+
+ putBuffer();
+
+ }
+
+}
diff --git a/test/java/nio/Buffer/CharAt.java b/test/java/nio/Buffer/CharAt.java
new file mode 100644
index 0000000..245fb7e
--- /dev/null
+++ b/test/java/nio/Buffer/CharAt.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test charAt index checking
+ * @bug 4510323
+ */
+
+import java.nio.*;
+
+public class CharAt {
+ public static void main (String[] args) {
+ CharSequence cs = CharBuffer.wrap("foo");
+ for (int i = 0; i < cs.length(); i++)
+ System.err.print(cs.charAt(i));
+ System.err.println();
+ }
+}
diff --git a/test/java/nio/Buffer/Chew.java b/test/java/nio/Buffer/Chew.java
new file mode 100644
index 0000000..605097c
--- /dev/null
+++ b/test/java/nio/Buffer/Chew.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 5046110
+ * @summary Ensure that direct memory can be unreserved
+ * as the reserving thread sleeps
+ *
+ * @run main/othervm -mx16M Chew
+ */
+
+import java.nio.*;
+
+
+public class Chew {
+
+ public static void main(String[] args) {
+ for (int i = 0; i < 64; i++)
+ ByteBuffer.allocateDirect(1 << 20);
+ }
+
+}
diff --git a/test/java/nio/Buffer/CopyDirect-X-Memory.java b/test/java/nio/Buffer/CopyDirect-X-Memory.java
new file mode 100644
index 0000000..802ca55
--- /dev/null
+++ b/test/java/nio/Buffer/CopyDirect-X-Memory.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+#warn This file is preprocessed before being compiled
+
+import java.nio.*;
+
+public class CopyDirect$Type$Memory
+ extends CopyDirectMemory
+{
+ private static void init($Type$Buffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, ($type$)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void init($type$ [] a) {
+ for (int i = 0; i < a.length; i++)
+ a[i] = ($type$)ic(i + 1);
+ }
+
+ public static void test() {
+#if[byte]
+ ByteBuffer b = ByteBuffer.allocateDirect(1024 * 1024 + 1024);
+#else[byte]
+ ByteBuffer bb = ByteBuffer.allocateDirect(1024 * 1024 + 1024);
+ $Type$Buffer b = bb.as$Type$Buffer();
+#end[byte]
+ init(b);
+ $type$ [] a = new $type$[b.capacity()];
+ init(a);
+
+ // copyFrom$Type$Array (a -> b)
+ b.put(a);
+ for (int i = 0; i < a.length; i++)
+ ck(b, b.get(i), ($type$)ic(i + 1));
+
+ // copyTo$Type$Array (b -> a)
+ init(b);
+ init(a);
+ b.get(a);
+ for (int i = 0; i < a.length; i++)
+ if (a[i] != b.get(i))
+ fail("Copy failed at " + i + ": '"
+ + a[i] + "' != '" + b.get(i) + "'");
+ }
+}
diff --git a/test/java/nio/Buffer/CopyDirectByteMemory.java b/test/java/nio/Buffer/CopyDirectByteMemory.java
new file mode 100644
index 0000000..686fc90
--- /dev/null
+++ b/test/java/nio/Buffer/CopyDirectByteMemory.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+public class CopyDirectByteMemory
+ extends CopyDirectMemory
+{
+ private static void init(ByteBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (byte)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void init(byte [] a) {
+ for (int i = 0; i < a.length; i++)
+ a[i] = (byte)ic(i + 1);
+ }
+
+ public static void test() {
+
+ ByteBuffer b = ByteBuffer.allocateDirect(1024 * 1024 + 1024);
+
+
+
+
+ init(b);
+ byte [] a = new byte[b.capacity()];
+ init(a);
+
+ // copyFromByteArray (a -> b)
+ b.put(a);
+ for (int i = 0; i < a.length; i++)
+ ck(b, b.get(i), (byte)ic(i + 1));
+
+ // copyToByteArray (b -> a)
+ init(b);
+ init(a);
+ b.get(a);
+ for (int i = 0; i < a.length; i++)
+ if (a[i] != b.get(i))
+ fail("Copy failed at " + i + ": '"
+ + a[i] + "' != '" + b.get(i) + "'");
+ }
+}
diff --git a/test/java/nio/Buffer/CopyDirectCharMemory.java b/test/java/nio/Buffer/CopyDirectCharMemory.java
new file mode 100644
index 0000000..db134b2
--- /dev/null
+++ b/test/java/nio/Buffer/CopyDirectCharMemory.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+public class CopyDirectCharMemory
+ extends CopyDirectMemory
+{
+ private static void init(CharBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (char)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void init(char [] a) {
+ for (int i = 0; i < a.length; i++)
+ a[i] = (char)ic(i + 1);
+ }
+
+ public static void test() {
+
+
+
+ ByteBuffer bb = ByteBuffer.allocateDirect(1024 * 1024 + 1024);
+ CharBuffer b = bb.asCharBuffer();
+
+ init(b);
+ char [] a = new char[b.capacity()];
+ init(a);
+
+ // copyFromCharArray (a -> b)
+ b.put(a);
+ for (int i = 0; i < a.length; i++)
+ ck(b, b.get(i), (char)ic(i + 1));
+
+ // copyToCharArray (b -> a)
+ init(b);
+ init(a);
+ b.get(a);
+ for (int i = 0; i < a.length; i++)
+ if (a[i] != b.get(i))
+ fail("Copy failed at " + i + ": '"
+ + a[i] + "' != '" + b.get(i) + "'");
+ }
+}
diff --git a/test/java/nio/Buffer/CopyDirectDoubleMemory.java b/test/java/nio/Buffer/CopyDirectDoubleMemory.java
new file mode 100644
index 0000000..1ed65d7
--- /dev/null
+++ b/test/java/nio/Buffer/CopyDirectDoubleMemory.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+public class CopyDirectDoubleMemory
+ extends CopyDirectMemory
+{
+ private static void init(DoubleBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (double)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void init(double [] a) {
+ for (int i = 0; i < a.length; i++)
+ a[i] = (double)ic(i + 1);
+ }
+
+ public static void test() {
+
+
+
+ ByteBuffer bb = ByteBuffer.allocateDirect(1024 * 1024 + 1024);
+ DoubleBuffer b = bb.asDoubleBuffer();
+
+ init(b);
+ double [] a = new double[b.capacity()];
+ init(a);
+
+ // copyFromDoubleArray (a -> b)
+ b.put(a);
+ for (int i = 0; i < a.length; i++)
+ ck(b, b.get(i), (double)ic(i + 1));
+
+ // copyToDoubleArray (b -> a)
+ init(b);
+ init(a);
+ b.get(a);
+ for (int i = 0; i < a.length; i++)
+ if (a[i] != b.get(i))
+ fail("Copy failed at " + i + ": '"
+ + a[i] + "' != '" + b.get(i) + "'");
+ }
+}
diff --git a/test/java/nio/Buffer/CopyDirectFloatMemory.java b/test/java/nio/Buffer/CopyDirectFloatMemory.java
new file mode 100644
index 0000000..79ddb5c
--- /dev/null
+++ b/test/java/nio/Buffer/CopyDirectFloatMemory.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+public class CopyDirectFloatMemory
+ extends CopyDirectMemory
+{
+ private static void init(FloatBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (float)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void init(float [] a) {
+ for (int i = 0; i < a.length; i++)
+ a[i] = (float)ic(i + 1);
+ }
+
+ public static void test() {
+
+
+
+ ByteBuffer bb = ByteBuffer.allocateDirect(1024 * 1024 + 1024);
+ FloatBuffer b = bb.asFloatBuffer();
+
+ init(b);
+ float [] a = new float[b.capacity()];
+ init(a);
+
+ // copyFromFloatArray (a -> b)
+ b.put(a);
+ for (int i = 0; i < a.length; i++)
+ ck(b, b.get(i), (float)ic(i + 1));
+
+ // copyToFloatArray (b -> a)
+ init(b);
+ init(a);
+ b.get(a);
+ for (int i = 0; i < a.length; i++)
+ if (a[i] != b.get(i))
+ fail("Copy failed at " + i + ": '"
+ + a[i] + "' != '" + b.get(i) + "'");
+ }
+}
diff --git a/test/java/nio/Buffer/CopyDirectIntMemory.java b/test/java/nio/Buffer/CopyDirectIntMemory.java
new file mode 100644
index 0000000..da06bc0
--- /dev/null
+++ b/test/java/nio/Buffer/CopyDirectIntMemory.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+public class CopyDirectIntMemory
+ extends CopyDirectMemory
+{
+ private static void init(IntBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (int)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void init(int [] a) {
+ for (int i = 0; i < a.length; i++)
+ a[i] = (int)ic(i + 1);
+ }
+
+ public static void test() {
+
+
+
+ ByteBuffer bb = ByteBuffer.allocateDirect(1024 * 1024 + 1024);
+ IntBuffer b = bb.asIntBuffer();
+
+ init(b);
+ int [] a = new int[b.capacity()];
+ init(a);
+
+ // copyFromIntArray (a -> b)
+ b.put(a);
+ for (int i = 0; i < a.length; i++)
+ ck(b, b.get(i), (int)ic(i + 1));
+
+ // copyToIntArray (b -> a)
+ init(b);
+ init(a);
+ b.get(a);
+ for (int i = 0; i < a.length; i++)
+ if (a[i] != b.get(i))
+ fail("Copy failed at " + i + ": '"
+ + a[i] + "' != '" + b.get(i) + "'");
+ }
+}
diff --git a/test/java/nio/Buffer/CopyDirectLongMemory.java b/test/java/nio/Buffer/CopyDirectLongMemory.java
new file mode 100644
index 0000000..97caa21
--- /dev/null
+++ b/test/java/nio/Buffer/CopyDirectLongMemory.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+public class CopyDirectLongMemory
+ extends CopyDirectMemory
+{
+ private static void init(LongBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (long)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void init(long [] a) {
+ for (int i = 0; i < a.length; i++)
+ a[i] = (long)ic(i + 1);
+ }
+
+ public static void test() {
+
+
+
+ ByteBuffer bb = ByteBuffer.allocateDirect(1024 * 1024 + 1024);
+ LongBuffer b = bb.asLongBuffer();
+
+ init(b);
+ long [] a = new long[b.capacity()];
+ init(a);
+
+ // copyFromLongArray (a -> b)
+ b.put(a);
+ for (int i = 0; i < a.length; i++)
+ ck(b, b.get(i), (long)ic(i + 1));
+
+ // copyToLongArray (b -> a)
+ init(b);
+ init(a);
+ b.get(a);
+ for (int i = 0; i < a.length; i++)
+ if (a[i] != b.get(i))
+ fail("Copy failed at " + i + ": '"
+ + a[i] + "' != '" + b.get(i) + "'");
+ }
+}
diff --git a/test/java/nio/Buffer/CopyDirectMemory.java b/test/java/nio/Buffer/CopyDirectMemory.java
new file mode 100644
index 0000000..4ab33f6
--- /dev/null
+++ b/test/java/nio/Buffer/CopyDirectMemory.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test view buffer bulk operations for large buffers.
+ * @bug 4463011
+ *
+ * @build Basic
+ * @run main CopyDirectMemory
+ */
+
+import java.nio.*;
+
+public class CopyDirectMemory
+ extends Basic
+{
+ public static void main(String [] args) {
+ CopyDirectByteMemory.test();
+ CopyDirectCharMemory.test();
+ CopyDirectShortMemory.test();
+ CopyDirectIntMemory.test();
+ CopyDirectLongMemory.test();
+ CopyDirectFloatMemory.test();
+ CopyDirectDoubleMemory.test();
+ }
+}
diff --git a/test/java/nio/Buffer/CopyDirectShortMemory.java b/test/java/nio/Buffer/CopyDirectShortMemory.java
new file mode 100644
index 0000000..fab996a
--- /dev/null
+++ b/test/java/nio/Buffer/CopyDirectShortMemory.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+// -- This file was mechanically generated: Do not edit! -- //
+
+import java.nio.*;
+
+public class CopyDirectShortMemory
+ extends CopyDirectMemory
+{
+ private static void init(ShortBuffer b) {
+ int n = b.capacity();
+ b.clear();
+ for (int i = 0; i < n; i++)
+ b.put(i, (short)ic(i));
+ b.limit(n);
+ b.position(0);
+ }
+
+ private static void init(short [] a) {
+ for (int i = 0; i < a.length; i++)
+ a[i] = (short)ic(i + 1);
+ }
+
+ public static void test() {
+
+
+
+ ByteBuffer bb = ByteBuffer.allocateDirect(1024 * 1024 + 1024);
+ ShortBuffer b = bb.asShortBuffer();
+
+ init(b);
+ short [] a = new short[b.capacity()];
+ init(a);
+
+ // copyFromShortArray (a -> b)
+ b.put(a);
+ for (int i = 0; i < a.length; i++)
+ ck(b, b.get(i), (short)ic(i + 1));
+
+ // copyToShortArray (b -> a)
+ init(b);
+ init(a);
+ b.get(a);
+ for (int i = 0; i < a.length; i++)
+ if (a[i] != b.get(i))
+ fail("Copy failed at " + i + ": '"
+ + a[i] + "' != '" + b.get(i) + "'");
+ }
+}
diff --git a/test/java/nio/Buffer/Order.java b/test/java/nio/Buffer/Order.java
new file mode 100644
index 0000000..3ce57c5
--- /dev/null
+++ b/test/java/nio/Buffer/Order.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Unit test for X-Buffer.order methods
+ */
+
+import java.io.*;
+import java.nio.*;
+
+
+public class Order {
+
+ static final ByteOrder be = ByteOrder.BIG_ENDIAN;
+ static final ByteOrder le = ByteOrder.LITTLE_ENDIAN;
+ static final ByteOrder nord = ByteOrder.nativeOrder();
+
+ static void ck(ByteOrder ord, ByteOrder expected) {
+ if (ord != expected)
+ throw new RuntimeException("Got " + ord
+ + ", expected " + expected);
+ }
+
+ static void ckViews(ByteBuffer bb, ByteOrder ord) {
+ ck(bb.asCharBuffer().order(), bb.order());
+ ck(bb.asIntBuffer().order(), bb.order());
+ ck(bb.asLongBuffer().order(), bb.order());
+ ck(bb.asFloatBuffer().order(), bb.order());
+ ck(bb.asDoubleBuffer().order(), bb.order());
+ }
+
+ static void ckByteBuffer(ByteBuffer bb) {
+ ckViews(bb, bb.order());
+ bb.order(be);
+ ckViews(bb, be);
+ bb.order(le);
+ ckViews(bb, le);
+ }
+
+ public static void main(String args[]) throws Exception {
+
+ ck(ByteBuffer.allocate(10).order(), be);
+ ck(ByteBuffer.allocateDirect(10).order(), be);
+ ck(ByteBuffer.allocate(10).order(be).order(), be);
+ ck(ByteBuffer.allocate(10).order(le).order(), le);
+
+ ckByteBuffer(ByteBuffer.allocate(10));
+ ckByteBuffer(ByteBuffer.allocateDirect(10));
+
+ }
+
+}
diff --git a/test/java/nio/Buffer/StringCharBufferSliceTest.java b/test/java/nio/Buffer/StringCharBufferSliceTest.java
new file mode 100644
index 0000000..5677002
--- /dev/null
+++ b/test/java/nio/Buffer/StringCharBufferSliceTest.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4997655
+ * @summary (bf) CharBuffer.slice() on wrapped CharSequence results in wrong position
+ */
+
+import java.nio.*;
+
+public class StringCharBufferSliceTest {
+ public static void main( String[] args) throws Exception {
+ System.out.println(
+ ">>> StringCharBufferSliceTest-main: testing the slice method...");
+
+ final String in = "for testing";
+
+ System.out.println(
+ ">>> StringCharBufferSliceTest-main: testing with the position 0.");
+
+ CharBuffer buff = CharBuffer.wrap(in);
+ test(buff, buff.slice());
+
+ System.out.println(
+ ">>> StringCharBufferSliceTest-main: testing with new position.");
+
+ buff.position(2);
+ test(buff, buff.slice());
+
+ System.out.println(
+ ">>> StringCharBufferSliceTest-main: testing with non zero initial position.");
+
+ buff = CharBuffer.wrap(in, 3, in.length());
+ test(buff, buff.slice());
+
+ System.out.println(">>> StringCharBufferSliceTest-main: done!");
+ }
+
+ public static void test(CharBuffer buff, CharBuffer slice) throws RuntimeException {
+ boolean marked = false;
+
+ try {
+ slice.reset();
+
+ marked = true;
+ } catch (InvalidMarkException ime) {
+ // expected
+ }
+
+ if (marked ||
+ slice.position() != 0 ||
+ buff.remaining() != slice.limit() ||
+ buff.remaining() != slice.capacity()) {
+
+ throw new RuntimeException(
+ "Calling the CharBuffer.slice method failed.");
+ }
+ }
+}
diff --git a/test/java/nio/Buffer/SwapMicroBenchmark.java b/test/java/nio/Buffer/SwapMicroBenchmark.java
new file mode 100644
index 0000000..cb5fcd1
--- /dev/null
+++ b/test/java/nio/Buffer/SwapMicroBenchmark.java
@@ -0,0 +1,247 @@
+/*
+ * Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * This is not a regression test, but a micro-benchmark.
+ * To exercise swap, run with filter=LITTLE_ENDIAN on sparc,
+ * filter=BIG_ENDIAN on x86.
+ *
+ * I have run this as follows:
+ *
+ * for f in -client -server; do mergeBench dolphin . jr -dsa -da $f SwapMicroBenchmark.java filter=LITTLE_ENDIAN; done
+ *
+ * @author Martin Buchholz
+ */
+
+import java.util.*;
+import java.nio.*;
+import java.util.concurrent.*;
+import java.util.regex.Pattern;
+
+public class SwapMicroBenchmark {
+ abstract static class Job {
+ private final String name;
+ public Job(String name) { this.name = name; }
+ public String name() { return name; }
+ public abstract void work() throws Throwable;
+ }
+
+ private static void collectAllGarbage() {
+ final java.util.concurrent.CountDownLatch drained
+ = new java.util.concurrent.CountDownLatch(1);
+ try {
+ System.gc(); // enqueue finalizable objects
+ new Object() { protected void finalize() {
+ drained.countDown(); }};
+ System.gc(); // enqueue detector
+ drained.await(); // wait for finalizer queue to drain
+ System.gc(); // cleanup finalized objects
+ } catch (InterruptedException e) { throw new Error(e); }
+ }
+
+ /**
+ * Runs each job for long enough that all the runtime compilers
+ * have had plenty of time to warm up, i.e. get around to
+ * compiling everything worth compiling.
+ * Returns array of average times per job per run.
+ */
+ private static long[] time0(Job ... jobs) throws Throwable {
+ final long warmupNanos = 10L * 1000L * 1000L * 1000L;
+ long[] nanoss = new long[jobs.length];
+ for (int i = 0; i < jobs.length; i++) {
+ collectAllGarbage();
+ long t0 = System.nanoTime();
+ long t;
+ int j = 0;
+ do { jobs[i].work(); j++; }
+ while ((t = System.nanoTime() - t0) < warmupNanos);
+ nanoss[i] = t/j;
+ }
+ return nanoss;
+ }
+
+ private static void time(Job ... jobs) throws Throwable {
+
+ long[] warmup = time0(jobs); // Warm up run
+ long[] nanoss = time0(jobs); // Real timing run
+ long[] milliss = new long[jobs.length];
+ double[] ratios = new double[jobs.length];
+
+ final String nameHeader = "Method";
+ final String millisHeader = "Millis";
+ final String ratioHeader = "Ratio";
+
+ int nameWidth = nameHeader.length();
+ int millisWidth = millisHeader.length();
+ int ratioWidth = ratioHeader.length();
+
+ for (int i = 0; i < jobs.length; i++) {
+ nameWidth = Math.max(nameWidth, jobs[i].name().length());
+
+ milliss[i] = nanoss[i]/(1000L * 1000L);
+ millisWidth = Math.max(millisWidth,
+ String.format("%d", milliss[i]).length());
+
+ ratios[i] = (double) nanoss[i] / (double) nanoss[0];
+ ratioWidth = Math.max(ratioWidth,
+ String.format("%.3f", ratios[i]).length());
+ }
+
+ String format = String.format("%%-%ds %%%dd %%%d.3f%%n",
+ nameWidth, millisWidth, ratioWidth);
+ String headerFormat = String.format("%%-%ds %%%ds %%%ds%%n",
+ nameWidth, millisWidth, ratioWidth);
+ System.out.printf(headerFormat, "Method", "Millis", "Ratio");
+
+ // Print out absolute and relative times, calibrated against first job
+ for (int i = 0; i < jobs.length; i++)
+ System.out.printf(format, jobs[i].name(), milliss[i], ratios[i]);
+ }
+
+ private static String keywordValue(String[] args, String keyword) {
+ for (String arg : args)
+ if (arg.startsWith(keyword))
+ return arg.substring(keyword.length() + 1);
+ return null;
+ }
+
+ private static int intArg(String[] args, String keyword, int defaultValue) {
+ String val = keywordValue(args, keyword);
+ return val == null ? defaultValue : Integer.parseInt(val);
+ }
+
+ private static Pattern patternArg(String[] args, String keyword) {
+ String val = keywordValue(args, keyword);
+ return val == null ? null : Pattern.compile(val);
+ }
+
+ private static Job[] filter(Pattern filter, Job[] jobs) {
+ if (filter == null) return jobs;
+ Job[] newJobs = new Job[jobs.length];
+ int n = 0;
+ for (Job job : jobs)
+ if (filter.matcher(job.name()).find())
+ newJobs[n++] = job;
+ // Arrays.copyOf not available in JDK 5
+ Job[] ret = new Job[n];
+ System.arraycopy(newJobs, 0, ret, 0, n);
+ return ret;
+ }
+
+ private static void deoptimize(int sum) {
+ if (sum == 42)
+ System.out.println("the answer");
+ }
+
+ /**
+ * Usage: [iterations=N] [size=N] [filter=REGEXP]
+ */
+ public static void main(String[] args) throws Throwable {
+ final int iterations = intArg(args, "iterations", 10000);
+ final int size = intArg(args, "size", 1024);
+ final Pattern filter = patternArg(args, "filter");
+
+ final Random rnd = new Random();
+
+ final ByteBuffer b = ByteBuffer.allocateDirect(8*size);
+ for (int i = 0; i < b.limit(); i++)
+ b.put(i, (byte) rnd.nextInt());
+
+ Job[] jobs = {
+ new Job("swap char BIG_ENDIAN") {
+ public void work() throws Throwable {
+ b.order(ByteOrder.BIG_ENDIAN);
+ CharBuffer x = b.asCharBuffer();
+ for (int i = 0; i < iterations; i++) {
+ int sum = 0;
+ for (int j = 0, end = x.limit(); j < end; j++)
+ sum += x.get(j);
+ deoptimize(sum);}}},
+ new Job("swap char LITTLE_ENDIAN") {
+ public void work() throws Throwable {
+ b.order(ByteOrder.LITTLE_ENDIAN);
+ CharBuffer x = b.asCharBuffer();
+ for (int i = 0; i < iterations; i++) {
+ int sum = 0;
+ for (int j = 0, end = x.limit(); j < end; j++)
+ sum += x.get(j);
+ deoptimize(sum);}}},
+ new Job("swap short BIG_ENDIAN") {
+ public void work() throws Throwable {
+ b.order(ByteOrder.BIG_ENDIAN);
+ ShortBuffer x = b.asShortBuffer();
+ for (int i = 0; i < iterations; i++) {
+ int sum = 0;
+ for (int j = 0, end = x.limit(); j < end; j++)
+ sum += x.get(j);
+ deoptimize(sum);}}},
+ new Job("swap short LITTLE_ENDIAN") {
+ public void work() throws Throwable {
+ b.order(ByteOrder.LITTLE_ENDIAN);
+ ShortBuffer x = b.asShortBuffer();
+ for (int i = 0; i < iterations; i++) {
+ int sum = 0;
+ for (int j = 0, end = x.limit(); j < end; j++)
+ sum += x.get(j);
+ deoptimize(sum);}}},
+ new Job("swap int BIG_ENDIAN") {
+ public void work() throws Throwable {
+ b.order(ByteOrder.BIG_ENDIAN);
+ IntBuffer x = b.asIntBuffer();
+ for (int i = 0; i < iterations; i++) {
+ int sum = 0;
+ for (int j = 0, end = x.limit(); j < end; j++)
+ sum += x.get(j);
+ deoptimize(sum);}}},
+ new Job("swap int LITTLE_ENDIAN") {
+ public void work() throws Throwable {
+ b.order(ByteOrder.LITTLE_ENDIAN);
+ IntBuffer x = b.asIntBuffer();
+ for (int i = 0; i < iterations; i++) {
+ int sum = 0;
+ for (int j = 0, end = x.limit(); j < end; j++)
+ sum += x.get(j);
+ deoptimize(sum);}}},
+ new Job("swap long BIG_ENDIAN") {
+ public void work() throws Throwable {
+ b.order(ByteOrder.BIG_ENDIAN);
+ LongBuffer x = b.asLongBuffer();
+ for (int i = 0; i < iterations; i++) {
+ int sum = 0;
+ for (int j = 0, end = x.limit(); j < end; j++)
+ sum += x.get(j);
+ deoptimize(sum);}}},
+ new Job("swap long LITTLE_ENDIAN") {
+ public void work() throws Throwable {
+ b.order(ByteOrder.LITTLE_ENDIAN);
+ LongBuffer x = b.asLongBuffer();
+ for (int i = 0; i < iterations; i++) {
+ int sum = 0;
+ for (int j = 0, end = x.limit(); j < end; j++)
+ sum += x.get(j);
+ deoptimize(sum);}}}
+ };
+
+ time(filter(filter, jobs));
+ }
+}
diff --git a/test/java/nio/Buffer/genBasic.sh b/test/java/nio/Buffer/genBasic.sh
new file mode 100644
index 0000000..b045567
--- /dev/null
+++ b/test/java/nio/Buffer/genBasic.sh
@@ -0,0 +1,38 @@
+#! /bin/sh
+
+#
+# Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+SPP='sh ../../../../make/java/nio/spp.sh'
+
+gen() {
+ $SPP -K$1 -Dtype=$1 -DType=$2 -DFulltype=$3 <Basic-X.java >Basic$2.java
+}
+
+gen byte Byte Byte
+gen char Char Character
+gen short Short Short
+gen int Int Integer
+gen long Long Long
+gen float Float Float
+gen double Double Double
diff --git a/test/java/nio/Buffer/genCopyDirectMemory.sh b/test/java/nio/Buffer/genCopyDirectMemory.sh
new file mode 100644
index 0000000..588a179
--- /dev/null
+++ b/test/java/nio/Buffer/genCopyDirectMemory.sh
@@ -0,0 +1,39 @@
+#! /bin/sh
+
+#
+# Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+SPP='sh ../../../../make/java/nio/spp.sh'
+
+gen() {
+ $SPP -K$1 -Dtype=$1 -DType=$2 -DFulltype=$3<CopyDirect-X-Memory.java >CopyDirect$2Memory.java
+}
+
+gen byte Byte Byte
+gen char Char Character
+gen short Short Short
+gen int Int Integer
+gen long Long Long
+gen float Float Float
+gen double Double Double
+
diff --git a/test/java/nio/ByteOrder/NativeOrder.java b/test/java/nio/ByteOrder/NativeOrder.java
new file mode 100644
index 0000000..7d264c5
--- /dev/null
+++ b/test/java/nio/ByteOrder/NativeOrder.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Unit test for ByteOrder.nativeOrder()
+ */
+
+import java.nio.*;
+
+
+public class NativeOrder {
+
+ public static void main(String[] args) throws Exception {
+ ByteOrder bo = ByteOrder.nativeOrder();
+ System.err.println(bo);
+ String arch = System.getProperty("os.arch");
+ if (((arch.equals("i386") && (bo != ByteOrder.LITTLE_ENDIAN))) ||
+ ((arch.equals("sparc") && (bo != ByteOrder.BIG_ENDIAN)))) {
+ throw new Exception("Wrong byte order");
+ }
+ }
+
+}
diff --git a/test/java/nio/MappedByteBuffer/Basic.java b/test/java/nio/MappedByteBuffer/Basic.java
new file mode 100644
index 0000000..8d7f9bd
--- /dev/null
+++ b/test/java/nio/MappedByteBuffer/Basic.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4462336
+ * @summary Simple MappedByteBuffer tests
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class Basic {
+ public static void main(String[] args) throws Exception {
+ byte[] srcData = new byte[20];
+ for (int i=0; i<20; i++)
+ srcData[i] = 3;
+ File blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(blah);
+ FileChannel fc = fos.getChannel();
+ fc.write(ByteBuffer.wrap(srcData));
+ fc.close();
+ fos.close();
+
+ FileInputStream fis = new FileInputStream(blah);
+ fc = fis.getChannel();
+ MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, 10);
+ mbb.load();
+ mbb.isLoaded();
+ mbb.force();
+ if (!mbb.isReadOnly())
+ throw new RuntimeException("Incorrect isReadOnly");
+ fc.close();
+ fis.close();
+
+ RandomAccessFile raf = new RandomAccessFile(blah, "r");
+ fc = raf.getChannel();
+ mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, 10);
+ if (!mbb.isReadOnly())
+ throw new RuntimeException("Incorrect isReadOnly");
+ fc.close();
+ raf.close();
+
+ raf = new RandomAccessFile(blah, "rw");
+ fc = raf.getChannel();
+ mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, 10);
+ if (mbb.isReadOnly())
+ throw new RuntimeException("Incorrect isReadOnly");
+ fc.close();
+ raf.close();
+ }
+}
diff --git a/test/java/nio/MappedByteBuffer/Force.java b/test/java/nio/MappedByteBuffer/Force.java
new file mode 100644
index 0000000..2c44fb4
--- /dev/null
+++ b/test/java/nio/MappedByteBuffer/Force.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4625907
+ * @summary Testing force()
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.util.*;
+import java.nio.channels.*;
+
+public class Force {
+ public static void main(String[] args) throws Exception {
+ Random random = new Random();
+ long filesize = random.nextInt(3*1024*1024);
+ int cut = random.nextInt((int)filesize);
+ File file = new File("Blah");
+ RandomAccessFile raf = new RandomAccessFile(file, "rw");
+ raf.setLength(filesize);
+ FileChannel fc = raf.getChannel();
+ MappedByteBuffer buf1 = fc.map(
+ FileChannel.MapMode.READ_WRITE, cut, filesize-cut);
+ buf1.force();
+ fc.close();
+ raf.close();
+ }
+}
diff --git a/test/java/nio/MappedByteBuffer/ZeroMap.java b/test/java/nio/MappedByteBuffer/ZeroMap.java
new file mode 100644
index 0000000..d806777
--- /dev/null
+++ b/test/java/nio/MappedByteBuffer/ZeroMap.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4802340
+ * @summary Testing force(), load() isLoaded() of zero len MBB
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.util.*;
+import java.nio.channels.*;
+
+public class ZeroMap {
+ public static void main(String[] args) throws Exception {
+ Random random = new Random();
+ long filesize = random.nextInt(1024*1024);
+ int cut = random.nextInt((int)filesize);
+ File file = new File("Blah");
+ RandomAccessFile raf = new RandomAccessFile(file, "rw");
+ raf.setLength(filesize);
+ FileChannel fc = raf.getChannel();
+ MappedByteBuffer buf1 = fc.map(
+ FileChannel.MapMode.READ_WRITE, cut, 0);
+ buf1.force();
+ buf1.load();
+ buf1.isLoaded();
+ fc.close();
+ raf.close();
+ }
+}
diff --git a/test/java/nio/channels/AsyncCloseAndInterrupt.java b/test/java/nio/channels/AsyncCloseAndInterrupt.java
new file mode 100644
index 0000000..8ec350c
--- /dev/null
+++ b/test/java/nio/channels/AsyncCloseAndInterrupt.java
@@ -0,0 +1,670 @@
+/*
+ * Copyright 2002-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4460583 4470470 4840199 6419424
+ * @summary Comprehensive test of asynchronous closing and interruption
+ * @author Mark Reinhold
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.util.*;
+
+
+public class AsyncCloseAndInterrupt {
+
+ static PrintStream log = System.err;
+
+ static void sleep(int ms) {
+ try {
+ Thread.sleep(ms);
+ } catch (InterruptedException x) { }
+ }
+
+ // Wildcard address localized to this machine -- Windoze doesn't allow
+ // connecting to a server socket that was previously bound to a true
+ // wildcard, namely new InetSocketAddress((InetAddress)null, 0).
+ //
+ private static InetSocketAddress wildcardAddress;
+
+
+ // Server socket that blindly accepts all connections
+
+ static ServerSocketChannel acceptor;
+
+ private static void initAcceptor() throws IOException {
+ acceptor = ServerSocketChannel.open();
+ acceptor.socket().bind(wildcardAddress);
+
+ Thread th = new Thread("Acceptor") {
+ public void run() {
+ try {
+ for (;;) {
+ SocketChannel sc = acceptor.accept();
+ }
+ } catch (IOException x) {
+ x.printStackTrace();
+ }
+ }
+ };
+
+ th.setDaemon(true);
+ th.start();
+ }
+
+
+ // Server socket that refuses all connections
+
+ static ServerSocketChannel refuser;
+ static List refuserClients = new ArrayList();
+
+ private static void initRefuser() throws IOException {
+ refuser = ServerSocketChannel.open();
+ refuser.socket().bind(wildcardAddress);
+ pumpRefuser("Initializing refuser...");
+ }
+
+ private static void pumpRefuser(String msg) throws IOException {
+ log.print(msg);
+ int n = refuserClients.size();
+
+ // Saturate the refuser's connection backlog so that further connection
+ // attempts will block
+ //
+ outer:
+ for (;;) {
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ if (!sc.connect(refuser.socket().getLocalSocketAddress())) {
+ for (int i = 0; i < 20; i++) {
+ Thread.yield();
+ if (sc.finishConnect())
+ break;
+ if (i >= 19)
+ break outer;
+ }
+ }
+ // Retain so that finalizer doesn't close
+ refuserClients.add(sc);
+ }
+
+ log.println(" " + (refuserClients.size() - n) + " connections");
+ }
+
+
+ // Dead pipe source and sink
+
+ static Pipe.SourceChannel deadSource;
+ static Pipe.SinkChannel deadSink;
+
+ private static void initPipes() throws IOException {
+ if (deadSource != null)
+ deadSource.close();
+ deadSource = Pipe.open().source();
+ if (deadSink != null)
+ deadSink.close();
+ deadSink = Pipe.open().sink();
+ }
+
+
+ // Files
+
+ private static File fifoFile = null; // File that blocks on reads and writes
+ private static File diskFile = null; // Disk file
+
+ private static void initFile() throws Exception {
+
+ diskFile = File.createTempFile("aci", ".tmp");
+ diskFile.deleteOnExit();
+ FileChannel fc = new FileOutputStream(diskFile).getChannel();
+ buffer.clear();
+ if (fc.write(buffer) != buffer.capacity())
+ throw new RuntimeException("Cannot create disk file");
+ fc.close();
+
+ if (TestUtil.onWindows()) {
+ log.println("WARNING: Cannot completely test FileChannels on Windows");
+ return;
+ }
+ fifoFile = new File("x.fifo");
+ if (fifoFile.exists()) {
+ if (!fifoFile.delete())
+ throw new IOException("Cannot delete existing fifo " + fifoFile);
+ }
+ Process p = Runtime.getRuntime().exec("mkfifo " + fifoFile);
+ if (p.waitFor() != 0)
+ throw new IOException("Error creating fifo");
+ new RandomAccessFile(fifoFile, "rw").close();
+
+ }
+
+
+ // Channel factories
+
+ static abstract class ChannelFactory {
+ private final String name;
+ ChannelFactory(String name) {
+ this.name = name;
+ }
+ public String toString() {
+ return name;
+ }
+ abstract InterruptibleChannel create() throws IOException;
+ }
+
+ static ChannelFactory socketChannelFactory
+ = new ChannelFactory("SocketChannel") {
+ InterruptibleChannel create() throws IOException {
+ return SocketChannel.open();
+ }
+ };
+
+ static ChannelFactory connectedSocketChannelFactory
+ = new ChannelFactory("SocketChannel") {
+ InterruptibleChannel create() throws IOException {
+ SocketAddress sa = acceptor.socket().getLocalSocketAddress();
+ return SocketChannel.open(sa);
+ }
+ };
+
+ static ChannelFactory serverSocketChannelFactory
+ = new ChannelFactory("ServerSocketChannel") {
+ InterruptibleChannel create() throws IOException {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(wildcardAddress);
+ return ssc;
+ }
+ };
+
+ static ChannelFactory datagramChannelFactory
+ = new ChannelFactory("DatagramChannel") {
+ InterruptibleChannel create() throws IOException {
+ DatagramChannel dc = DatagramChannel.open();
+ dc.socket().bind(wildcardAddress);
+ InetAddress ia = InetAddress.getByName("127.0.0.1");
+ dc.connect(new InetSocketAddress(ia, 80));
+ return dc;
+ }
+ };
+
+ static ChannelFactory pipeSourceChannelFactory
+ = new ChannelFactory("Pipe.SourceChannel") {
+ InterruptibleChannel create() throws IOException {
+ // ## arrange to close sink
+ return Pipe.open().source();
+ }
+ };
+
+ static ChannelFactory pipeSinkChannelFactory
+ = new ChannelFactory("Pipe.SinkChannel") {
+ InterruptibleChannel create() throws IOException {
+ // ## arrange to close source
+ return Pipe.open().sink();
+ }
+ };
+
+ static ChannelFactory fifoFileChannelFactory
+ = new ChannelFactory("FileChannel") {
+ InterruptibleChannel create() throws IOException {
+ return new RandomAccessFile(fifoFile, "rw").getChannel();
+ }
+ };
+
+ static ChannelFactory diskFileChannelFactory
+ = new ChannelFactory("FileChannel") {
+ InterruptibleChannel create() throws IOException {
+ return new RandomAccessFile(diskFile, "rw").getChannel();
+ }
+ };
+
+
+ // I/O operations
+
+ static abstract class Op {
+ private final String name;
+ protected Op(String name) {
+ this.name = name;
+ }
+ abstract void doIO(InterruptibleChannel ich) throws IOException;
+ void setup() throws IOException { }
+ public String toString() { return name; }
+ }
+
+ static ByteBuffer buffer = ByteBuffer.allocateDirect(1 << 20);
+
+ static ByteBuffer[] buffers = new ByteBuffer[] {
+ ByteBuffer.allocateDirect(1 << 19),
+ ByteBuffer.allocateDirect(1 << 19)
+ };
+
+ static void clearBuffers() {
+ buffers[0].clear();
+ buffers[1].clear();
+ }
+
+ static void show(Channel ch) {
+ log.print("Channel " + (ch.isOpen() ? "open" : "closed"));
+ if (ch.isOpen() && (ch instanceof SocketChannel)) {
+ SocketChannel sc = (SocketChannel)ch;
+ if (sc.socket().isInputShutdown())
+ log.print(", input shutdown");
+ if (sc.socket().isOutputShutdown())
+ log.print(", output shutdown");
+ }
+ log.println();
+ }
+
+ static final Op READ = new Op("read") {
+ void doIO(InterruptibleChannel ich) throws IOException {
+ ReadableByteChannel rbc = (ReadableByteChannel)ich;
+ buffer.clear();
+ int n = rbc.read(buffer);
+ log.println("Read returned " + n);
+ show(rbc);
+ if (rbc.isOpen()
+ && (n == -1)
+ && (rbc instanceof SocketChannel)
+ && ((SocketChannel)rbc).socket().isInputShutdown()) {
+ return;
+ }
+ throw new RuntimeException("Read succeeded");
+ }
+ };
+
+ static final Op READV = new Op("readv") {
+ void doIO(InterruptibleChannel ich) throws IOException {
+ ScatteringByteChannel sbc = (ScatteringByteChannel)ich;
+ clearBuffers();
+ int n = (int)sbc.read(buffers);
+ log.println("Read returned " + n);
+ show(sbc);
+ if (sbc.isOpen()
+ && (n == -1)
+ && (sbc instanceof SocketChannel)
+ && ((SocketChannel)sbc).socket().isInputShutdown()) {
+ return;
+ }
+ throw new RuntimeException("Read succeeded");
+ }
+ };
+
+ static final Op RECEIVE = new Op("receive") {
+ void doIO(InterruptibleChannel ich) throws IOException {
+ DatagramChannel dc = (DatagramChannel)ich;
+ buffer.clear();
+ dc.receive(buffer);
+ show(dc);
+ throw new RuntimeException("Read succeeded");
+ }
+ };
+
+ static final Op WRITE = new Op("write") {
+ void doIO(InterruptibleChannel ich) throws IOException {
+
+ WritableByteChannel wbc = (WritableByteChannel)ich;
+
+ SocketChannel sc = null;
+ if (wbc instanceof SocketChannel)
+ sc = (SocketChannel)wbc;
+
+ int n = 0;
+ for (;;) {
+ buffer.clear();
+ int d = wbc.write(buffer);
+ n += d;
+ if (!wbc.isOpen())
+ break;
+ if ((sc != null) && sc.socket().isOutputShutdown())
+ break;
+ }
+ log.println("Wrote " + n + " bytes");
+ show(wbc);
+ }
+ };
+
+ static final Op WRITEV = new Op("writev") {
+ void doIO(InterruptibleChannel ich) throws IOException {
+
+ GatheringByteChannel gbc = (GatheringByteChannel)ich;
+
+ SocketChannel sc = null;
+ if (gbc instanceof SocketChannel)
+ sc = (SocketChannel)gbc;
+
+ int n = 0;
+ for (;;) {
+ clearBuffers();
+ int d = (int)gbc.write(buffers);
+ n += d;
+ if (!gbc.isOpen())
+ break;
+ if ((sc != null) && sc.socket().isOutputShutdown())
+ break;
+ }
+ log.println("Wrote " + n + " bytes");
+ show(gbc);
+
+ }
+ };
+
+ static final Op CONNECT = new Op("connect") {
+ void setup() throws IOException {
+ pumpRefuser("Pumping refuser ...");
+ }
+ void doIO(InterruptibleChannel ich) throws IOException {
+ SocketChannel sc = (SocketChannel)ich;
+ if (sc.connect(refuser.socket().getLocalSocketAddress()))
+ throw new RuntimeException("Connection succeeded");
+ throw new RuntimeException("Connection did not block");
+ }
+ };
+
+ static final Op FINISH_CONNECT = new Op("finishConnect") {
+ void setup() throws IOException {
+ pumpRefuser("Pumping refuser ...");
+ }
+ void doIO(InterruptibleChannel ich) throws IOException {
+ SocketChannel sc = (SocketChannel)ich;
+ sc.configureBlocking(false);
+ SocketAddress sa = refuser.socket().getLocalSocketAddress();
+ if (sc.connect(sa))
+ throw new RuntimeException("Connection succeeded");
+ sc.configureBlocking(true);
+ if (sc.finishConnect())
+ throw new RuntimeException("Connection succeeded");
+ throw new RuntimeException("Connection did not block");
+ }
+ };
+
+ static final Op ACCEPT = new Op("accept") {
+ void doIO(InterruptibleChannel ich) throws IOException {
+ ServerSocketChannel ssc = (ServerSocketChannel)ich;
+ ssc.accept();
+ throw new RuntimeException("Accept succeeded");
+ }
+ };
+
+ // Use only with diskFileChannelFactory
+ static final Op TRANSFER_TO = new Op("transferTo") {
+ void doIO(InterruptibleChannel ich) throws IOException {
+ FileChannel fc = (FileChannel)ich;
+ long n = fc.transferTo(0, fc.size(), deadSink);
+ log.println("Transferred " + n + " bytes");
+ show(fc);
+ }
+ };
+
+ // Use only with diskFileChannelFactory
+ static final Op TRANSFER_FROM = new Op("transferFrom") {
+ void doIO(InterruptibleChannel ich) throws IOException {
+ FileChannel fc = (FileChannel)ich;
+ long n = fc.transferFrom(deadSource, 0, 1 << 20);
+ log.println("Transferred " + n + " bytes");
+ show(fc);
+ }
+ };
+
+
+
+ // Test modes
+
+ static final int TEST_PREINTR = 0; // Interrupt thread before I/O
+ static final int TEST_INTR = 1; // Interrupt thread during I/O
+ static final int TEST_CLOSE = 2; // Close channel during I/O
+ static final int TEST_SHUTI = 3; // Shutdown input during I/O
+ static final int TEST_SHUTO = 4; // Shutdown output during I/O
+
+ static final String[] testName = new String[] {
+ "pre-interrupt", "interrupt", "close",
+ "shutdown-input", "shutdown-output"
+ };
+
+
+ static class Tester extends TestThread {
+
+ private InterruptibleChannel ch;
+ private Op op;
+ private int test;
+ volatile boolean ready = false;
+
+ protected Tester(ChannelFactory cf, InterruptibleChannel ch,
+ Op op, int test)
+ {
+ super(cf + "/" + op + "/" + testName[test]);
+ this.ch = ch;
+ this.op = op;
+ this.test = test;
+ }
+
+ private void caught(Channel ch, IOException x) {
+ String xn = x.getClass().getName();
+ switch (test) {
+
+ case TEST_PREINTR:
+ case TEST_INTR:
+ if (!xn.equals("java.nio.channels.ClosedByInterruptException"))
+ throw new RuntimeException("Wrong exception thrown: " + x);
+ break;
+
+ case TEST_CLOSE:
+ case TEST_SHUTO:
+ if (!xn.equals("java.nio.channels.AsynchronousCloseException"))
+ throw new RuntimeException("Wrong exception thrown: " + x);
+ break;
+
+ case TEST_SHUTI:
+ if (TestUtil.onWindows())
+ break;
+ // FALL THROUGH
+
+ default:
+ throw new Error(x);
+ }
+
+ if (ch.isOpen()) {
+ if (test == TEST_SHUTO) {
+ SocketChannel sc = (SocketChannel)ch;
+ if (!sc.socket().isOutputShutdown())
+ throw new RuntimeException("Output not shutdown");
+ } else if ((test == TEST_INTR) && (op == TRANSFER_FROM)) {
+ // Let this case pass -- CBIE applies to other channel
+ } else {
+ throw new RuntimeException("Channel still open");
+ }
+ }
+
+ log.println("Thrown as expected: " + x);
+ }
+
+ final void go() throws Exception {
+ if (test == TEST_PREINTR)
+ Thread.currentThread().interrupt();
+ ready = true;
+ try {
+ op.doIO(ch);
+ } catch (ClosedByInterruptException x) {
+ caught(ch, x);
+ } catch (AsynchronousCloseException x) {
+ caught(ch, x);
+ } finally {
+ ch.close();
+ }
+ }
+
+ }
+
+
+ // Tests
+
+ static void test(ChannelFactory cf, Op op, int test)
+ throws Exception
+ {
+ log.println();
+ initPipes();
+ InterruptibleChannel ch = cf.create();
+ Tester t = new Tester(cf, ch, op, test);
+ log.println(t);
+ op.setup();
+ t.start();
+ do {
+ sleep(50);
+ } while (!t.ready);
+
+ sleep(100);
+
+ switch (test) {
+
+ case TEST_INTR:
+ t.interrupt();
+ break;
+
+ case TEST_CLOSE:
+ ch.close();
+ break;
+
+ case TEST_SHUTI:
+ if (TestUtil.onWindows()) {
+ log.println("WARNING: Asynchronous shutdown not working on Windows");
+ ch.close();
+ } else {
+ ((SocketChannel)ch).socket().shutdownInput();
+ }
+ break;
+
+ case TEST_SHUTO:
+ if (TestUtil.onWindows()) {
+ log.println("WARNING: Asynchronous shutdown not working on Windows");
+ ch.close();
+ } else {
+ ((SocketChannel)ch).socket().shutdownOutput();
+ }
+ break;
+
+ default:
+ break;
+ }
+
+ t.finishAndThrow(500);
+ }
+
+
+ static void test(ChannelFactory cf, Op op) throws Exception {
+ // Test INTR cases before PREINTER cases since sometimes
+ // interrupted threads can't load classes
+ test(cf, op, TEST_INTR);
+ test(cf, op, TEST_PREINTR);
+
+ // Bugs, see FileChannelImpl for details
+ if (op == TRANSFER_FROM) {
+ log.println("WARNING: transferFrom/close not tested");
+ return;
+ }
+ if ((op == TRANSFER_TO) && TestUtil.onSolaris()) {
+ log.println("WARNING: transferTo/close not tested");
+ return;
+ }
+
+ test(cf, op, TEST_CLOSE);
+ }
+
+ static void test(ChannelFactory cf)
+ throws Exception
+ {
+ InterruptibleChannel ch = cf.create(); // Sample channel
+ ch.close();
+
+ if (ch instanceof ReadableByteChannel) {
+ test(cf, READ);
+ if (ch instanceof SocketChannel)
+ test(cf, READ, TEST_SHUTI);
+ }
+
+ if (ch instanceof ScatteringByteChannel) {
+ test(cf, READV);
+ if (ch instanceof SocketChannel)
+ test(cf, READV, TEST_SHUTI);
+ }
+
+ if (ch instanceof DatagramChannel) {
+ test(cf, RECEIVE);
+
+ // Return here: We can't effectively test writes since, if they
+ // block, they do so only for a fleeting moment unless the network
+ // interface is overloaded.
+ return;
+
+ }
+
+ if (ch instanceof WritableByteChannel) {
+ test(cf, WRITE);
+ if (ch instanceof SocketChannel)
+ test(cf, WRITE, TEST_SHUTO);
+ }
+
+ if (ch instanceof GatheringByteChannel) {
+ test(cf, WRITEV);
+ if (ch instanceof SocketChannel)
+ test(cf, WRITEV, TEST_SHUTO);
+ }
+
+ }
+
+ public static void main(String[] args) throws Exception {
+
+ wildcardAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
+ initAcceptor();
+ initRefuser();
+ initPipes();
+ initFile();
+
+ if (TestUtil.onME()) {
+ log.println("WARNING: Cannot test FileChannel transfer operations"
+ + " on Windows 95/98/ME");
+ } else {
+ test(diskFileChannelFactory, TRANSFER_TO);
+ test(diskFileChannelFactory, TRANSFER_FROM);
+ }
+ if (fifoFile != null)
+ test(fifoFileChannelFactory);
+
+ // Testing positional file reads and writes is impractical: It requires
+ // access to a large file soft-mounted via NFS, and even then isn't
+ // completely guaranteed to work.
+ //
+ // Testing map is impractical and arguably unnecessary: It's
+ // unclear under what conditions mmap(2) will actually block.
+
+ test(connectedSocketChannelFactory);
+ test(socketChannelFactory, CONNECT);
+ test(socketChannelFactory, FINISH_CONNECT);
+ test(serverSocketChannelFactory, ACCEPT);
+ test(datagramChannelFactory);
+ test(pipeSourceChannelFactory);
+ test(pipeSinkChannelFactory);
+
+ }
+
+}
diff --git a/test/java/nio/channels/Channels/Basic.java b/test/java/nio/channels/Channels/Basic.java
new file mode 100644
index 0000000..9d1a5dc
--- /dev/null
+++ b/test/java/nio/channels/Channels/Basic.java
@@ -0,0 +1,268 @@
+/*
+ * Copyright 2001-2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4417152 4481572 6248930
+ * @summary Test Channels basic functionality
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+
+public class Basic {
+
+ static String message;
+
+ static String encoding;
+
+ static File blah;
+
+ static int ITERATIONS = 500;
+
+ public static void main(String[] args) throws Exception {
+ message = "ascii data for a test";
+ encoding = "ISO-8859-1";
+ test();
+ message = "\ucafe\ubabe\ucafe\ubabe\ucafe\ubabe";
+ encoding = "UTF-8";
+ test();
+ }
+
+ private static void test() throws Exception {
+ try {
+ ReadableByteChannel channel = Channels.newChannel((InputStream)null);
+
+ throw new RuntimeException("Did not get the expected NullPointerException.");
+ } catch (NullPointerException ne) {
+ // OK. As expected.
+ }
+
+ try {
+ WritableByteChannel channel = Channels.newChannel((OutputStream)null);
+
+ throw new RuntimeException("Did not get the expected NullPointerException.");
+ } catch (NullPointerException ne) {
+ // OK. As expected.
+ }
+
+ try {
+ blah = File.createTempFile("blah", null);
+
+ testNewOutputStream(blah);
+ readAndCheck(blah);
+ blah.delete();
+
+ writeOut(blah, ITERATIONS);
+ testNewInputStream(blah);
+ blah.delete();
+
+ testNewChannelOut(blah);
+ readAndCheck(blah);
+ blah.delete();
+
+ writeOut(blah, ITERATIONS);
+ testNewChannelIn(blah);
+ test4481572(blah);
+ blah.delete();
+
+ testNewWriter(blah);
+ readAndCheck(blah);
+ blah.delete();
+
+ writeOut(blah, ITERATIONS);
+ testNewReader(blah);
+
+ } finally {
+ blah.delete();
+ }
+ }
+
+ private static void readAndCheck(File blah) throws Exception {
+ FileInputStream fis = new FileInputStream(blah);
+ int messageSize = message.length() * ITERATIONS * 3 + 1;
+ byte bb[] = new byte[messageSize];
+ int bytesRead = 0;
+ int totalRead = 0;
+ while (bytesRead != -1) {
+ totalRead += bytesRead;
+ bytesRead = fis.read(bb, totalRead, messageSize - totalRead);
+ }
+ String result = new String(bb, 0, totalRead, encoding);
+ int len = message.length();
+ for (int i=0; i<ITERATIONS; i++) {
+ String segment = result.substring(i++ * len, i * len);
+ if (!segment.equals(message))
+ throw new RuntimeException("Test failed");
+ }
+ fis.close();
+ }
+
+ private static void writeOut(File blah, int limit) throws Exception {
+ FileOutputStream fos = new FileOutputStream(blah);
+ for (int i=0; i<limit; i++)
+ fos.write(message.getBytes(encoding));
+ fos.close();
+ }
+
+ private static void testNewOutputStream(File blah) throws Exception {
+ FileOutputStream fos = new FileOutputStream(blah);
+ FileChannel fc = fos.getChannel();
+ WritableByteChannel wbc = (WritableByteChannel)fc;
+ OutputStream os = Channels.newOutputStream(wbc);
+ for (int i=0; i<ITERATIONS; i++)
+ os.write(message.getBytes(encoding));
+ os.close();
+ fos.close();
+ }
+
+ private static void testNewInputStream(File blah) throws Exception {
+ FileInputStream fis = new FileInputStream(blah);
+ FileChannel fc = fis.getChannel();
+ ReadableByteChannel rbc = (ReadableByteChannel)fc;
+ InputStream is = Channels.newInputStream(rbc);
+ int messageSize = message.length() * ITERATIONS * 3 + 1;
+ byte bb[] = new byte[messageSize];
+
+ int bytesRead = 0;
+ int totalRead = 0;
+ while (bytesRead != -1) {
+ totalRead += bytesRead;
+ bytesRead = is.read(bb, totalRead, messageSize - totalRead);
+ }
+
+ String result = new String(bb, 0, totalRead, encoding);
+ int len = message.length();
+ for (int i=0; i<ITERATIONS; i++) {
+ String segment = result.substring(i++ * len, i * len);
+ if (!segment.equals(message))
+ throw new RuntimeException("Test failed");
+ }
+ is.close();
+ fis.close();
+ }
+
+ private static void testNewChannelOut(File blah) throws Exception {
+ ExtendedFileOutputStream fos = new ExtendedFileOutputStream(blah);
+ WritableByteChannel wbc = Channels.newChannel(fos);
+ for (int i=0; i<ITERATIONS; i++)
+ wbc.write(ByteBuffer.wrap(message.getBytes(encoding)));
+ wbc.close();
+ fos.close();
+ }
+
+ private static void testNewChannelIn(File blah) throws Exception {
+ ExtendedFileInputStream fis = new ExtendedFileInputStream(blah);
+ ReadableByteChannel rbc = Channels.newChannel(fis);
+
+ int messageSize = message.length() * ITERATIONS * 3;
+ byte data[] = new byte[messageSize+1];
+ ByteBuffer bb = ByteBuffer.wrap(data);
+
+ int bytesRead = 0;
+ int totalRead = 0;
+ while (bytesRead != -1) {
+ totalRead += bytesRead;
+ bytesRead = rbc.read(bb);
+ }
+
+ String result = new String(data, 0, totalRead, encoding);
+ int len = message.length();
+ for (int i=0; i<ITERATIONS; i++) {
+ String segment = result.substring(i++ * len, i * len);
+ if (!segment.equals(message))
+ throw new RuntimeException("Test failed");
+ }
+ rbc.close();
+ fis.close();
+ }
+
+ // Causes BufferOverflowException if bug 4481572 is present.
+ private static void test4481572(File blah) throws Exception {
+ ExtendedFileInputStream fis = new ExtendedFileInputStream(blah);
+ ReadableByteChannel rbc = Channels.newChannel(fis);
+
+ byte data[] = new byte[9000];
+ ByteBuffer bb = ByteBuffer.wrap(data);
+
+ int bytesRead = 1;
+ int totalRead = 0;
+ while (bytesRead > 0) {
+ totalRead += bytesRead;
+ bytesRead = rbc.read(bb);
+ }
+ rbc.close();
+ fis.close();
+ }
+
+ private static void testNewWriter(File blah) throws Exception {
+ FileOutputStream fos = new FileOutputStream(blah);
+ WritableByteChannel wbc = (WritableByteChannel)fos.getChannel();
+ Writer w = Channels.newWriter(wbc, encoding);
+ char data[] = new char[40];
+ message.getChars(0, message.length(), data, 0);
+ for (int i=0; i<ITERATIONS; i++)
+ w.write(data, 0, message.length());
+ w.flush();
+ w.close();
+ fos.close();
+ }
+
+ private static void testNewReader(File blah) throws Exception {
+ FileInputStream fis = new FileInputStream(blah);
+ ReadableByteChannel rbc = (ReadableByteChannel)fis.getChannel();
+ Reader r = Channels.newReader(rbc, encoding);
+
+ int messageSize = message.length() * ITERATIONS;
+ char data[] = new char[messageSize];
+
+ int totalRead = 0;
+ int charsRead = 0;
+ while (totalRead < messageSize) {
+ totalRead += charsRead;
+ charsRead = r.read(data, totalRead, messageSize - totalRead);
+ }
+ String result = new String(data, 0, totalRead);
+ int len = message.length();
+ for (int i=0; i<ITERATIONS; i++) {
+ String segment = result.substring(i++ * len, i * len);
+ if (!segment.equals(message))
+ throw new RuntimeException("Test failed");
+ }
+ r.close();
+ fis.close();
+ }
+}
+
+class ExtendedFileInputStream extends java.io.FileInputStream {
+ ExtendedFileInputStream(File file) throws FileNotFoundException {
+ super(file);
+ }
+}
+
+class ExtendedFileOutputStream extends java.io.FileOutputStream {
+ ExtendedFileOutputStream(File file) throws FileNotFoundException {
+ super(file);
+ }
+}
diff --git a/test/java/nio/channels/Channels/ReadByte.java b/test/java/nio/channels/Channels/ReadByte.java
new file mode 100644
index 0000000..dee9098
--- /dev/null
+++ b/test/java/nio/channels/Channels/ReadByte.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4773447
+ * @summary Test Channels.newInputStream.read() method
+ */
+
+import java.nio.ByteBuffer;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.Channels;
+import java.io.InputStream;
+import java.io.IOException;
+
+public class ReadByte {
+ public static void main(String[] args) throws IOException {
+ ReadableByteChannel channel = new ReadableByteChannel() {
+ public int read(ByteBuffer dst) {
+ dst.put((byte) 129);
+ return 1;
+ }
+
+ public boolean isOpen() {
+ return true;
+ }
+
+ public void close() {
+ }
+ };
+
+ InputStream in = Channels.newInputStream(channel);
+ int data = in.read();
+ if (data < 0)
+ throw new RuntimeException(
+ "InputStream.read() spec'd to return 0-255");
+ }
+}
diff --git a/test/java/nio/channels/Channels/ReadOffset.java b/test/java/nio/channels/Channels/ReadOffset.java
new file mode 100644
index 0000000..e1b4dff
--- /dev/null
+++ b/test/java/nio/channels/Channels/ReadOffset.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 6545054
+ * @summary Channels.newInputStream.read throws IAE when invoked with
+ * different offsets.
+ */
+
+import java.nio.ByteBuffer;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.Channels;
+import java.io.InputStream;
+import java.io.IOException;
+
+public class ReadOffset {
+ public static void main(String[] args) throws IOException {
+ ReadableByteChannel rbc = new ReadableByteChannel() {
+ public int read(ByteBuffer dst) {
+ dst.put((byte)0);
+ return 1;
+ }
+ public boolean isOpen() {
+ return true;
+ }
+ public void close() {
+ }
+ };
+
+ InputStream in = Channels.newInputStream(rbc);
+
+ byte[] b = new byte[3];
+ in.read(b, 0, 1);
+ in.read(b, 2, 1); // throws IAE
+ }
+}
diff --git a/test/java/nio/channels/Channels/TinyBuffers.java b/test/java/nio/channels/Channels/TinyBuffers.java
new file mode 100644
index 0000000..022f71d
--- /dev/null
+++ b/test/java/nio/channels/Channels/TinyBuffers.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4654722
+ * @summary Ensure that ridiculously tiny buffers work with
+ * Channels.newReader
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+
+
+public class TinyBuffers {
+
+ private static Charset cs = Charset.forName("UTF-16");
+
+ private static void test(int sz) throws Exception {
+ ByteArrayInputStream bis = new ByteArrayInputStream(new byte[100]);
+ ReadableByteChannel ch = Channels.newChannel(bis);
+ Reader r = Channels.newReader(ch, cs.newDecoder(), sz);
+ char [] arr = new char[100];
+ System.out.println(r.read(arr, 0, arr.length));
+ }
+
+ public static void main(String[] args) throws Exception {
+ for (int i = -2; i < 10; i++)
+ test(i);
+ }
+
+}
diff --git a/test/java/nio/channels/Channels/Write.java b/test/java/nio/channels/Channels/Write.java
new file mode 100644
index 0000000..0f9a669
--- /dev/null
+++ b/test/java/nio/channels/Channels/Write.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4712766
+ * @summary Test Channels.newOutputStream.write
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class Write {
+
+ public static void main(String[] args) throws Exception {
+ byte[] bb = new byte[3];
+ File testFile = File.createTempFile("test1", null);
+ testFile.deleteOnExit();
+
+ FileOutputStream fos = new FileOutputStream(testFile);
+ FileChannel fc = fos.getChannel();
+ OutputStream out = Channels.newOutputStream(fc);
+
+ out.write(bb,0,1);
+ out.write(bb,2,1);
+
+ out.close();
+ fc.close();
+ fos.close();
+ }
+}
diff --git a/test/java/nio/channels/ConfigureBlocking.java b/test/java/nio/channels/ConfigureBlocking.java
new file mode 100644
index 0000000..d174355
--- /dev/null
+++ b/test/java/nio/channels/ConfigureBlocking.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4797768
+ * @summary test configureBlocking on closed channels
+ */
+
+import java.io.*;
+import java.nio.channels.*;
+
+public class ConfigureBlocking {
+ public static void main (String [] str) throws Exception {
+ SelectableChannel [] channels = null;
+ channels = new SelectableChannel [] {
+ DatagramChannel.open(),
+ SocketChannel.open(),
+ ServerSocketChannel.open()};
+ for (int i = 0; i < channels.length; i++) {
+ SelectableChannel channel = channels[i];
+ channel.close();
+ try {
+ channel.configureBlocking(true);
+ throw new RuntimeException("expected exception not thrown");
+ } catch (ClosedChannelException e) {
+ // Correct result
+ }
+ }
+ }
+}
diff --git a/test/java/nio/channels/DatagramChannel/AdaptDatagramSocket.java b/test/java/nio/channels/DatagramChannel/AdaptDatagramSocket.java
new file mode 100644
index 0000000..5bcb031
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/AdaptDatagramSocket.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Unit test for datagram-socket-channel adaptors
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+import java.util.*;
+
+
+public class AdaptDatagramSocket {
+
+ static java.io.PrintStream out = System.out;
+
+ static Random rand = new Random();
+
+ static final int ECHO_PORT = 7;
+ static final int DISCARD_PORT = 9;
+ static final String REMOTE_HOST = TestUtil.HOST;
+
+ static final InetSocketAddress echoAddress
+ = new InetSocketAddress(REMOTE_HOST, ECHO_PORT);
+ static final InetSocketAddress discardAddress
+ = new InetSocketAddress(REMOTE_HOST, DISCARD_PORT);
+
+ static String toString(DatagramPacket dp) {
+ return ("DatagramPacket[off=" + dp.getOffset()
+ + ", len=" + dp.getLength()
+ + "]");
+ }
+
+ static void test(DatagramSocket ds, InetSocketAddress dst,
+ boolean shouldTimeout)
+ throws Exception
+ {
+ DatagramPacket op = new DatagramPacket(new byte[100], 13, 42, dst);
+ rand.nextBytes(op.getData());
+ DatagramPacket ip = new DatagramPacket(new byte[100], 19, 100 - 19);
+ out.println("pre op: " + toString(op) + " ip: " + toString(ip));
+
+ long start = System.currentTimeMillis();
+ ds.send(op);
+
+ for (;;) {
+ try {
+ ds.receive(ip);
+ if (ip.getLength() == 0) { // ## Not sure why this happens
+ ip.setLength(100 - 19);
+ continue;
+ }
+ } catch (SocketTimeoutException x) {
+ if (shouldTimeout) {
+ out.println("Receive timed out, as expected");
+ return;
+ }
+ throw x;
+ }
+ if (shouldTimeout)
+ throw new Exception("Receive did not time out");
+ break;
+ }
+
+ out.println("rtt: " + (System.currentTimeMillis() - start));
+ out.println("post op: " + toString(op) + " ip: " + toString(ip));
+
+ for (int i = 0; i < ip.getLength(); i++)
+ if (ip.getData()[ip.getOffset() + i]
+ != op.getData()[op.getOffset() + i])
+ throw new Exception("Incorrect data received");
+ }
+
+ static void test(InetSocketAddress dst,
+ int timeout, boolean shouldTimeout,
+ boolean connect)
+ throws Exception
+ {
+ out.println();
+ out.println("dst: " + dst);
+
+ DatagramSocket ds;
+ if (false) {
+ // Original
+ ds = new DatagramSocket();
+ } else {
+ DatagramChannel dc = DatagramChannel.open();
+ ds = dc.socket();
+ ds.bind(new InetSocketAddress(0));
+ }
+
+ out.println("socket: " + ds);
+ if (connect) {
+ ds.connect(dst);
+ out.println("connect: " + ds);
+ }
+ InetSocketAddress src = new InetSocketAddress(ds.getLocalAddress(),
+ ds.getLocalPort());
+ out.println("src: " + src);
+
+ if (timeout > 0)
+ ds.setSoTimeout(timeout);
+ out.println("timeout: " + ds.getSoTimeout());
+
+ for (int i = 0; i < 5; i++)
+ test(ds, dst, shouldTimeout);
+
+ // Leave the socket open so that we don't reuse the old src address
+ //ds.close();
+
+ }
+
+ public static void main(String[] args) throws Exception {
+ test(echoAddress, 0, false, false);
+ test(echoAddress, 0, false, true);
+ test(echoAddress, 5000, false, false);
+ test(discardAddress, 10, true, false);
+ }
+
+}
diff --git a/test/java/nio/channels/DatagramChannel/Connect.java b/test/java/nio/channels/DatagramChannel/Connect.java
new file mode 100644
index 0000000..d9b9199
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/Connect.java
@@ -0,0 +1,165 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test DatagramChannel's send and receive methods
+ * @author Mike McCloskey
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+
+
+public class Connect {
+
+ static PrintStream log = System.err;
+
+ public static void main(String[] args) throws Exception {
+ test();
+ }
+
+ static void test() throws Exception {
+ invoke(new Actor(), new Reactor());
+ }
+
+ static void invoke(Sprintable reader, Sprintable writer) throws Exception {
+
+ Thread writerThread = new Thread(writer);
+ writerThread.start();
+ while (!writer.ready())
+ Thread.sleep(50);
+
+ Thread readerThread = new Thread(reader);
+ readerThread.start();
+
+ writerThread.join();
+ readerThread.join();
+
+ reader.throwException();
+ writer.throwException();
+ }
+
+ public interface Sprintable extends Runnable {
+ public void throwException() throws Exception;
+ public boolean ready();
+ }
+
+ public static class Actor implements Sprintable {
+ Exception e = null;
+
+ public void throwException() throws Exception {
+ if (e != null)
+ throw e;
+ }
+
+ private volatile boolean ready = false;
+
+ public boolean ready() {
+ return ready;
+ }
+
+ public void run() {
+ try {
+ DatagramChannel dc = DatagramChannel.open();
+ ready = true;
+
+ // Send a message
+ ByteBuffer bb = ByteBuffer.allocateDirect(256);
+ bb.put("hello".getBytes());
+ bb.flip();
+ InetAddress address = InetAddress.getLocalHost();
+ InetSocketAddress isa = new InetSocketAddress(address, 8888);
+ dc.connect(isa);
+ dc.write(bb);
+
+ // Try to send to some other address
+ address = InetAddress.getLocalHost();
+ InetSocketAddress bogus = new InetSocketAddress(address, 3333);
+ try {
+ dc.send(bb, bogus);
+ throw new RuntimeException("Allowed bogus send while connected");
+ } catch (IllegalArgumentException iae) {
+ // Correct behavior
+ }
+
+ // Read a reply
+ bb.flip();
+ dc.read(bb);
+ bb.flip();
+ CharBuffer cb = Charset.forName("US-ASCII").
+ newDecoder().decode(bb);
+ log.println("From Reactor: "+isa+ " said " +cb);
+
+ // Clean up
+ dc.disconnect();
+ dc.close();
+ } catch (Exception ex) {
+ e = ex;
+ }
+ }
+ }
+
+ public static class Reactor implements Sprintable {
+ Exception e = null;
+
+ public void throwException() throws Exception {
+ if (e != null)
+ throw e;
+ }
+
+ private volatile boolean ready = false;
+
+ public boolean ready() {
+ return ready;
+ }
+
+ public void run() {
+ try {
+ // Listen for a message
+ DatagramChannel dc = DatagramChannel.open();
+ dc.socket().bind(new InetSocketAddress(8888));
+ ByteBuffer bb = ByteBuffer.allocateDirect(100);
+ ready = true;
+ SocketAddress sa = dc.receive(bb);
+ bb.flip();
+ CharBuffer cb = Charset.forName("US-ASCII").
+ newDecoder().decode(bb);
+ log.println("From Actor: "+sa+ " said " +cb);
+
+ // Reply to sender
+ dc.connect(sa);
+ bb.flip();
+ dc.write(bb);
+
+ // Clean up
+ dc.disconnect();
+ dc.close();
+ } catch (Exception ex) {
+ e = ex;
+ }
+ }
+ }
+}
diff --git a/test/java/nio/channels/DatagramChannel/ConnectedSend.java b/test/java/nio/channels/DatagramChannel/ConnectedSend.java
new file mode 100644
index 0000000..d53c801
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/ConnectedSend.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4849277
+ * @summary Test DatagramChannel send while connected
+ * @author Mike McCloskey
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+
+public class ConnectedSend {
+
+ public static void main(String[] args) throws Exception {
+ test1();
+ test2();
+ }
+
+ // Check if DatagramChannel.send while connected can include
+ // address without throwing
+ private static void test1() throws Exception {
+
+ DatagramChannel sndChannel = DatagramChannel.open();
+ sndChannel.socket().bind(null);
+ InetSocketAddress sender = new InetSocketAddress(
+ InetAddress.getLocalHost(),
+ sndChannel.socket().getLocalPort());
+
+ DatagramChannel rcvChannel = DatagramChannel.open();
+ rcvChannel.socket().bind(null);
+ InetSocketAddress receiver = new InetSocketAddress(
+ InetAddress.getLocalHost(),
+ rcvChannel.socket().getLocalPort());
+
+ rcvChannel.connect(sender);
+ sndChannel.connect(receiver);
+
+ ByteBuffer bb = ByteBuffer.allocate(256);
+ bb.put("hello".getBytes());
+ bb.flip();
+ int sent = sndChannel.send(bb, receiver);
+ bb.clear();
+ rcvChannel.receive(bb);
+ bb.flip();
+ CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
+ if (!cb.toString().startsWith("h"))
+ throw new RuntimeException("Test failed");
+
+ rcvChannel.close();
+ sndChannel.close();
+ }
+
+ // Check if the datagramsocket adaptor can send with a packet
+ // that has not been initialized with an address; the legacy
+ // datagram socket will send in this case
+ private static void test2() throws Exception {
+ DatagramChannel sndChannel = DatagramChannel.open();
+ sndChannel.socket().bind(null);
+ InetSocketAddress sender = new InetSocketAddress(
+ InetAddress.getLocalHost(),
+ sndChannel.socket().getLocalPort());
+
+ DatagramChannel rcvChannel = DatagramChannel.open();
+ rcvChannel.socket().bind(null);
+ InetSocketAddress receiver = new InetSocketAddress(
+ InetAddress.getLocalHost(),
+ rcvChannel.socket().getLocalPort());
+
+ rcvChannel.connect(sender);
+ sndChannel.connect(receiver);
+
+ byte b[] = "hello".getBytes("UTF-8");
+ DatagramPacket pkt = new DatagramPacket(b, b.length);
+ sndChannel.socket().send(pkt);
+
+ ByteBuffer bb = ByteBuffer.allocate(256);
+ rcvChannel.receive(bb);
+ bb.flip();
+ CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
+ if (!cb.toString().startsWith("h"))
+ throw new RuntimeException("Test failed");
+
+ // Check that the pkt got set with the target address;
+ // This is legacy behavior
+ if (!pkt.getSocketAddress().equals(receiver))
+ throw new RuntimeException("Test failed");
+
+ rcvChannel.close();
+ sndChannel.close();
+ }
+}
diff --git a/test/java/nio/channels/DatagramChannel/EmptyBuffer.java b/test/java/nio/channels/DatagramChannel/EmptyBuffer.java
new file mode 100644
index 0000000..ecbf0ba
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/EmptyBuffer.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4669040
+ * @summary Test DatagramChannel receive with empty buffer
+ * @author Mike McCloskey
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+
+public class EmptyBuffer {
+
+ static PrintStream log = System.err;
+
+ public static void main(String[] args) throws Exception {
+ test();
+ }
+
+ static void test() throws Exception {
+ Sprintable server = new Server();
+ Thread serverThread = new Thread(server);
+ serverThread.start();
+ while (!server.ready())
+ Thread.sleep(50);
+ DatagramChannel dc = DatagramChannel.open();
+ ByteBuffer bb = ByteBuffer.allocateDirect(12);
+ bb.order(ByteOrder.BIG_ENDIAN);
+ bb.putInt(1).putLong(1);
+ bb.flip();
+ InetAddress address = InetAddress.getLocalHost();
+ InetSocketAddress isa = new InetSocketAddress(address, 8888);
+ dc.connect(isa);
+ dc.write(bb);
+ bb.rewind();
+ dc.write(bb);
+ bb.rewind();
+ dc.write(bb);
+ Thread.sleep(2000);
+ serverThread.interrupt();
+ server.throwException();
+ }
+
+ public interface Sprintable extends Runnable {
+ public void throwException() throws Exception;
+ public boolean ready();
+ }
+
+ public static class Server implements Sprintable {
+ Exception e = null;
+ private volatile boolean ready = false;
+
+ public void throwException() throws Exception {
+ if (e != null)
+ throw e;
+ }
+
+ public boolean ready() {
+ return ready;
+ }
+
+ void showBuffer(String s, ByteBuffer bb) {
+ log.println(s);
+ bb.rewind();
+ for (int i=0; i<bb.limit(); i++) {
+ byte element = bb.get();
+ log.print(element);
+ }
+ log.println();
+ }
+
+ public void run() {
+ SocketAddress sa = null;
+ int numberReceived = 0;
+ try {
+ DatagramChannel dc = DatagramChannel.open();
+ dc.socket().bind(new InetSocketAddress(8888));
+ ready = true;
+ ByteBuffer bb = ByteBuffer.allocateDirect(12);
+ bb.clear();
+ // Only one clear. The buffer will be full after
+ // the first receive, but it should still block
+ // and receive and discard the next two
+ while (!Thread.interrupted()) {
+ try {
+ sa = dc.receive(bb);
+ } catch (ClosedByInterruptException cbie) {
+ // Expected
+ log.println("Took expected exit");
+ break;
+ }
+ if (sa != null) {
+ log.println("Client: " + sa);
+ showBuffer("RECV", bb);
+ sa = null;
+ numberReceived++;
+ if (numberReceived > 3)
+ throw new RuntimeException("Test failed");
+ }
+ }
+ } catch (Exception ex) {
+ e = ex;
+ }
+ }
+ }
+
+}
diff --git a/test/java/nio/channels/DatagramChannel/IsBound.java b/test/java/nio/channels/DatagramChannel/IsBound.java
new file mode 100644
index 0000000..ba237ac
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/IsBound.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4468875
+ * @summary Simple test of DatagramChannel isBound
+ * @library ..
+ */
+
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+
+public class IsBound {
+ public static void main(String argv[]) throws Exception {
+ InetSocketAddress isa = new InetSocketAddress(
+ InetAddress.getByName(TestUtil.HOST), 13);
+ ByteBuffer bb = ByteBuffer.allocateDirect(256);
+ bb.put("hello".getBytes());
+ bb.flip();
+
+ DatagramChannel dc = DatagramChannel.open();
+ dc.send(bb, isa);
+ if(!dc.socket().isBound())
+ throw new Exception("Test failed");
+ dc.close();
+
+ dc = DatagramChannel.open();
+ if(dc.socket().isBound())
+ throw new Exception("Test failed");
+ dc.close();
+ }
+}
diff --git a/test/java/nio/channels/DatagramChannel/IsConnected.java b/test/java/nio/channels/DatagramChannel/IsConnected.java
new file mode 100644
index 0000000..5ef08e3
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/IsConnected.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4446035
+ * @summary Simple test of DatagramSocket connection consistency
+ * @library ..
+ */
+
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+
+public class IsConnected {
+ public static void main(String argv[]) throws Exception {
+ InetSocketAddress isa = new InetSocketAddress(
+ InetAddress.getByName(TestUtil.HOST), 13);
+ DatagramChannel dc = DatagramChannel.open();
+ dc.configureBlocking(true);
+ dc.connect(isa);
+ if (!dc.isConnected())
+ throw new RuntimeException("channel.isConnected inconsistent");
+ if (!dc.socket().isConnected())
+ throw new RuntimeException("socket.isConnected inconsistent");
+ dc.close();
+ }
+}
diff --git a/test/java/nio/channels/DatagramChannel/NoSender.java b/test/java/nio/channels/DatagramChannel/NoSender.java
new file mode 100644
index 0000000..d268cbb
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/NoSender.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4487193
+ * @summary Test nonblocking receive with no sender
+ */
+
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class NoSender {
+ public static void main(String argv[]) throws Exception {
+ DatagramChannel dc = DatagramChannel.open();
+ dc.socket().bind(new InetSocketAddress(5441));
+ dc.configureBlocking(false);
+ ByteBuffer buf1 = ByteBuffer.allocateDirect(256);
+ SocketAddress sa1 = dc.receive(buf1);
+ if (sa1 != null)
+ throw new RuntimeException("Test failed");
+ dc.close();
+ }
+}
diff --git a/test/java/nio/channels/DatagramChannel/NotBound.java b/test/java/nio/channels/DatagramChannel/NotBound.java
new file mode 100644
index 0000000..9a58fe6
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/NotBound.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4512723
+ * @summary Unit test for datagram-socket-channel adaptors
+ */
+
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+class NotBound {
+ public static void main(String[] args) throws Exception {
+ test1(false);
+ test1(true);
+ }
+
+ static void test1(boolean blocking) throws Exception {
+ ByteBuffer bb = ByteBuffer.allocateDirect(256);
+ DatagramChannel dc1 = DatagramChannel.open();
+ dc1.configureBlocking(false);
+ SocketAddress isa = dc1.receive(bb);
+ if (isa != null)
+ throw new Exception("Unbound dc returned non-null");
+ dc1.close();
+ }
+}
diff --git a/test/java/nio/channels/DatagramChannel/Receive.java b/test/java/nio/channels/DatagramChannel/Receive.java
new file mode 100644
index 0000000..abb446b
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/Receive.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4660944
+ * @summary Test DatagramChannel's receive after close
+ */
+
+import java.nio.*;
+import java.nio.channels.*;
+import java.net.*;
+
+public class Receive {
+ public static void main(String args[]) throws Exception {
+ ByteBuffer bb = ByteBuffer.allocate(10);
+ DatagramChannel dc1 = DatagramChannel.open();
+ dc1.close();
+ try {
+ dc1.receive(bb);
+ throw new Exception("Receive on closed DC did not throw");
+ } catch (ClosedChannelException cce) {
+ // Correct result
+ }
+ }
+}
diff --git a/test/java/nio/channels/DatagramChannel/ReceiveISA.java b/test/java/nio/channels/DatagramChannel/ReceiveISA.java
new file mode 100644
index 0000000..f492c66
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/ReceiveISA.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4503641
+ * @summary Check that DatagramChannel.receive returns a new SocketAddress
+ * when it receives a packet from the same source address but
+ * different endpoint.
+ */
+import java.nio.*;
+import java.nio.channels.*;
+import java.net.*;
+
+public class ReceiveISA {
+
+ public static void main(String args[]) throws Exception {
+
+ // clients
+ DatagramChannel dc1 = DatagramChannel.open();
+ DatagramChannel dc2 = DatagramChannel.open();
+
+ // bind server to any port
+ DatagramChannel dc3 = DatagramChannel.open();
+ dc3.socket().bind((SocketAddress)null);
+
+ // get server address
+ InetAddress lh = InetAddress.getLocalHost();
+ InetSocketAddress isa
+ = new InetSocketAddress( lh, dc3.socket().getLocalPort() );
+
+ ByteBuffer bb = ByteBuffer.allocateDirect(100);
+ bb.put("Dia duit!".getBytes());
+ bb.flip();
+
+ dc1.send(bb, isa); // packet 1 from dc1
+ dc1.send(bb, isa); // packet 2 from dc1
+ dc2.send(bb, isa); // packet 3 from dc1
+
+ // receive 3 packets
+ dc3.socket().setSoTimeout(1000);
+ ByteBuffer rb = ByteBuffer.allocateDirect(100);
+ SocketAddress sa[] = new SocketAddress[3];
+ for (int i=0; i<3; i++) {
+ sa[i] = dc3.receive(rb);
+ rb.clear();
+ }
+
+ /*
+ * Check that sa[0] equals sa[1] (both from dc1)
+ * Check that sa[1] not equal to sa[2] (one from dc1, one from dc2)
+ */
+
+ if (!sa[0].equals(sa[1])) {
+ throw new Exception("Source address for packets 1 & 2 should be equal");
+ }
+
+ if (sa[1].equals(sa[2])) {
+ throw new Exception("Source address for packets 2 & 3 should be different");
+ }
+ }
+
+}
diff --git a/test/java/nio/channels/DatagramChannel/Refused.java b/test/java/nio/channels/DatagramChannel/Refused.java
new file mode 100644
index 0000000..70c5d2c
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/Refused.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright 2002-2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test DatagramChannel's receive when port unreachable
+ * @author Mike McCloskey
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class Refused {
+
+ static ByteBuffer outBuf = ByteBuffer.allocateDirect(100);
+ static ByteBuffer inBuf = ByteBuffer.allocateDirect(100);
+ static DatagramChannel client;
+ static DatagramChannel server;
+ static InetSocketAddress isa;
+
+ public static void main(String[] args) throws Exception {
+ outBuf.put("Blah Blah".getBytes());
+ outBuf.flip();
+ test1();
+
+ // This test has been disabled because there are many circumstances
+ // under which no ICMP port unreachable packets are received
+ // See http://java.sun.com/j2se/1.4/networking-relnotes.html
+ if ((args.length > 0) && (args[0].equals("test2"))) {
+ outBuf.rewind();
+ test2();
+ }
+ }
+
+ public static void setup() throws Exception {
+ client = DatagramChannel.open();
+ server = DatagramChannel.open();
+
+ client.socket().bind((SocketAddress)null);
+ server.socket().bind((SocketAddress)null);
+
+ client.configureBlocking(false);
+ server.configureBlocking(false);
+
+ InetAddress address = InetAddress.getLocalHost();
+ int port = client.socket().getLocalPort();
+ isa = new InetSocketAddress(address, port);
+ }
+
+ // Since this is not connected no PortUnreachableException should be thrown
+ public static void test1() throws Exception {
+ setup();
+
+ server.send(outBuf, isa);
+ server.receive(inBuf);
+
+ client.close();
+
+ outBuf.rewind();
+ server.send(outBuf, isa);
+ server.receive(inBuf);
+
+ server.close();
+ }
+
+ // Test the connected case to see if PUE is thrown
+ public static void test2() throws Exception {
+
+ setup();
+ server.configureBlocking(true);
+ server.connect(isa);
+ server.configureBlocking(false);
+ outBuf.rewind();
+ server.write(outBuf);
+ server.receive(inBuf);
+
+ client.close();
+ Thread.sleep(2000);
+ outBuf.rewind();
+
+ try {
+ server.write(outBuf);
+ Thread.sleep(2000);
+ inBuf.clear();
+ server.read(inBuf);
+ if (onSolarisOrLinux())
+ throw new Exception("Expected PUE not thrown");
+ } catch (PortUnreachableException pue) {
+ System.err.println("received PUE");
+ }
+ server.close();
+ }
+
+ static boolean onSolarisOrLinux() {
+ String osName = System.getProperty("os.name");
+ return osName.startsWith("SunOS") || osName.startsWith("Linux");
+ }
+}
diff --git a/test/java/nio/channels/DatagramChannel/SRTest.java b/test/java/nio/channels/DatagramChannel/SRTest.java
new file mode 100644
index 0000000..1688e07
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/SRTest.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test DatagramChannel's send and receive methods
+ * @author Mike McCloskey
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+
+
+public class SRTest {
+
+ static PrintStream log = System.err;
+
+ public static void main(String[] args) throws Exception {
+ test();
+ }
+
+ static void test() throws Exception {
+ invoke(new ClassicReader(), new ClassicWriter());
+ log.println("Classic RW: OK");
+
+ invoke(new ClassicReader(), new NioWriter());
+ log.println("Classic R, Nio W: OK");
+
+ invoke(new NioReader(), new ClassicWriter());
+ log.println("Classic W, Nio R: OK");
+
+ invoke(new NioReader(), new NioWriter());
+ log.println("Nio RW: OK");
+ }
+
+ static void invoke(Sprintable reader, Sprintable writer) throws Exception {
+ Thread readerThread = new Thread(reader);
+ readerThread.start();
+ Thread.sleep(50);
+
+ Thread writerThread = new Thread(writer);
+ writerThread.start();
+
+ writerThread.join();
+ readerThread.join();
+
+ reader.throwException();
+ writer.throwException();
+ }
+
+ public interface Sprintable extends Runnable {
+ public void throwException() throws Exception;
+ }
+
+ public static class ClassicWriter implements Sprintable {
+ Exception e = null;
+
+ public void throwException() throws Exception {
+ if (e != null)
+ throw e;
+ }
+
+ public void run() {
+ try {
+ DatagramSocket ds = new DatagramSocket();
+ String dataString = "hello";
+ byte[] data = dataString.getBytes();
+ InetAddress address = InetAddress.getLocalHost();
+ DatagramPacket dp = new DatagramPacket(data, data.length,
+ address, 8888);
+ ds.send(dp);
+ Thread.sleep(50);
+ ds.send(dp);
+ } catch (Exception ex) {
+ e = ex;
+ }
+ }
+ }
+
+ public static class NioWriter implements Sprintable {
+ Exception e = null;
+
+ public void throwException() throws Exception {
+ if (e != null)
+ throw e;
+ }
+
+ public void run() {
+ try {
+ DatagramChannel dc = DatagramChannel.open();
+ ByteBuffer bb = ByteBuffer.allocateDirect(256);
+ bb.put("hello".getBytes());
+ bb.flip();
+ InetAddress address = InetAddress.getLocalHost();
+ InetSocketAddress isa = new InetSocketAddress(address, 8888);
+ dc.send(bb, isa);
+ Thread.sleep(50);
+ dc.send(bb, isa);
+ } catch (Exception ex) {
+ e = ex;
+ }
+ }
+ }
+
+ public static class ClassicReader implements Sprintable {
+ Exception e = null;
+
+ public void throwException() throws Exception {
+ if (e != null)
+ throw e;
+ }
+
+ public void run() {
+ try {
+ byte[] buf = new byte[256];
+ DatagramPacket dp = new DatagramPacket(buf, buf.length);
+ DatagramSocket ds = new DatagramSocket(8888);
+ ds.receive(dp);
+ String received = new String(dp.getData());
+ log.println(received);
+ ds.close();
+ } catch (Exception ex) {
+ e = ex;
+ }
+ }
+ }
+
+ public static class NioReader implements Sprintable {
+ Exception e = null;
+
+ public void throwException() throws Exception {
+ if (e != null)
+ throw e;
+ }
+
+ public void run() {
+ try {
+ DatagramChannel dc = DatagramChannel.open();
+ dc.socket().bind(new InetSocketAddress(8888));
+ ByteBuffer bb = ByteBuffer.allocateDirect(100);
+ SocketAddress sa = dc.receive(bb);
+ bb.flip();
+ CharBuffer cb = Charset.forName("US-ASCII").
+ newDecoder().decode(bb);
+ log.println("From: "+sa+ " said " +cb);
+ dc.close();
+ } catch (Exception ex) {
+ e = ex;
+ }
+ }
+ }
+
+}
diff --git a/test/java/nio/channels/DatagramChannel/SendToUnresolved.java b/test/java/nio/channels/DatagramChannel/SendToUnresolved.java
new file mode 100644
index 0000000..ecdf3ae
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/SendToUnresolved.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4675045
+ * @summary Test DatagramChannel send to unresolved address
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class SendToUnresolved {
+ public static void main(String [] argv) throws Exception {
+ String host = TestUtil.UNRESOLVABLE_HOST;
+ DatagramChannel dc = DatagramChannel.open();
+ ByteBuffer bb = ByteBuffer.allocate(4);
+ InetSocketAddress sa = new InetSocketAddress (host, 37);
+ InetAddress inetaddr = sa.getAddress();
+ try {
+ dc.send(bb, sa);
+ throw new RuntimeException("Expected exception not thrown");
+ } catch (IOException e) {
+ // Correct result
+ }
+ dc.close();
+ }
+}
diff --git a/test/java/nio/channels/DatagramChannel/Sender.java b/test/java/nio/channels/DatagramChannel/Sender.java
new file mode 100644
index 0000000..32706f3
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/Sender.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4669040
+ * @summary Test DatagramChannel subsequent receives with no datagram ready
+ * @author Mike McCloskey
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+
+public class Sender {
+
+ static PrintStream log = System.err;
+
+ public static void main(String[] args) throws Exception {
+ test();
+ }
+
+ static void test() throws Exception {
+ Sprintable server = new Server();
+ Sprintable client = new Client();
+
+ Thread serverThread = new Thread(server);
+ serverThread.start();
+ while (!server.ready())
+ Thread.sleep(50);
+
+ Thread clientThread = new Thread(client);
+ clientThread.start();
+
+ serverThread.join();
+ clientThread.join();
+
+ server.throwException();
+ client.throwException();
+ }
+
+ public interface Sprintable extends Runnable {
+ public void throwException() throws Exception;
+ public boolean ready();
+ }
+
+ public static class Client implements Sprintable {
+ Exception e = null;
+
+ public void throwException() throws Exception {
+ if (e != null)
+ throw e;
+ }
+
+ private volatile boolean ready = false;
+
+ public boolean ready() {
+ return ready;
+ }
+
+ public void run() {
+ try {
+ DatagramChannel dc = DatagramChannel.open();
+ ByteBuffer bb = ByteBuffer.allocateDirect(12);
+ bb.order(ByteOrder.BIG_ENDIAN);
+ bb.putInt(1).putLong(1);
+ bb.flip();
+ InetAddress address = InetAddress.getLocalHost();
+ InetSocketAddress isa = new InetSocketAddress(address, 8888);
+ dc.connect(isa);
+ dc.write(bb);
+ } catch (Exception ex) {
+ e = ex;
+ }
+ }
+ }
+
+ public static class Server implements Sprintable {
+ Exception e = null;
+ private volatile boolean ready = false;
+
+ public void throwException() throws Exception {
+ if (e != null)
+ throw e;
+ }
+
+ public boolean ready() {
+ return ready;
+ }
+
+ void showBuffer(String s, ByteBuffer bb) {
+ log.println(s);
+ bb.rewind();
+ for (int i=0; i<bb.limit(); i++) {
+ byte element = bb.get();
+ log.print(element);
+ }
+ log.println();
+ }
+
+ public void run() {
+ SocketAddress sa = null;
+
+ try {
+ DatagramChannel dc = DatagramChannel.open();
+ dc.socket().bind(new InetSocketAddress(8888));
+ dc.configureBlocking(false);
+ ready = true;
+ ByteBuffer bb = ByteBuffer.allocateDirect(12);
+ bb.clear();
+ // Get the one valid datagram
+ while (sa == null)
+ sa = dc.receive(bb);
+ sa = null;
+ for (int i=0; i<100; i++) {
+ bb.clear();
+ sa = dc.receive(bb);
+ if (sa != null)
+ throw new RuntimeException("Test failed");
+ }
+ dc.close();
+ } catch (Exception ex) {
+ e = ex;
+ }
+ }
+ }
+
+}
diff --git a/test/java/nio/channels/DatagramChannel/ThereCanBeOnlyOne.java b/test/java/nio/channels/DatagramChannel/ThereCanBeOnlyOne.java
new file mode 100644
index 0000000..0955fb0
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/ThereCanBeOnlyOne.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4630914
+ * @summary Should only be one PUE even if multiple ICMPs were received
+ */
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class ThereCanBeOnlyOne {
+
+ static void doTest(InetAddress ia, boolean testSend) throws Exception {
+ DatagramChannel dc1 = DatagramChannel.open();
+ dc1.socket().bind((SocketAddress)null);
+ int port = dc1.socket().getLocalPort();
+ InetSocketAddress isa = new InetSocketAddress(ia, port);
+ dc1.connect(isa);
+
+ ByteBuffer bb = ByteBuffer.allocateDirect(512);
+ bb.put("hello".getBytes());
+ bb.flip();
+
+ /*
+ * Send a bunch of packets to the destination
+ */
+ int outstanding = 0;
+ for (int i=0; i<20; i++) {
+ try {
+ bb.rewind();
+ dc1.write(bb);
+ outstanding++;
+ } catch (PortUnreachableException e) {
+ /* PUE throw => assume none outstanding now */
+ outstanding = 0;
+ }
+ if (outstanding > 1) {
+ break;
+ }
+ }
+ if (outstanding < 1) {
+ System.err.println("Insufficient exceptions outstanding - Test Skipped (Passed).");
+ dc1.close();
+ return;
+ }
+
+ /*
+ * Give time for ICMP port unreachables to return
+ */
+ Thread.currentThread().sleep(5000);
+
+ /*
+ * The next send or receive should cause a PUE to be thrown
+ */
+ boolean gotPUE = false;
+ boolean gotTimeout = false;
+ dc1.configureBlocking(false);
+
+ try {
+ if (testSend) {
+ bb.rewind();
+ dc1.write(bb);
+ } else {
+ bb.clear();
+ dc1.receive(bb);
+ }
+ } catch (PortUnreachableException pue) {
+ System.err.println("Got one PUE...");
+ gotPUE = true;
+ }
+
+ /*
+ * The next receive should not get another PUE
+ */
+ if (gotPUE) {
+ try {
+ dc1.receive(bb);
+ } catch (PortUnreachableException pue) {
+ throw new Exception("PUs should have been consumed");
+ }
+ } else {
+ // packets discarded. Okay
+ }
+
+ dc1.close();
+ }
+
+
+ public static void main(String args[]) throws Exception {
+ InetAddress ia = InetAddress.getLocalHost();
+ doTest(ia, true);
+ doTest(ia, false);
+ }
+
+}
diff --git a/test/java/nio/channels/DatagramChannel/UseDGWithIPv6.java b/test/java/nio/channels/DatagramChannel/UseDGWithIPv6.java
new file mode 100644
index 0000000..164d024
--- /dev/null
+++ b/test/java/nio/channels/DatagramChannel/UseDGWithIPv6.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 6435300
+ * @summary Check using IPv6 address does not crash the VM
+ */
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.DatagramChannel;
+
+public class UseDGWithIPv6 {
+ static String[] targets = {
+ "3ffe:e00:811:b::21:5",
+ "15.70.186.80"
+ };
+ static int BUFFER_LEN = 10;
+ static int port = 12345;
+
+ public static void main(String[] args) throws IOException
+ {
+ ByteBuffer data = ByteBuffer.wrap("TESTING DATA".getBytes());
+ DatagramChannel dgChannel = DatagramChannel.open();
+
+ for(int i = 0; i < targets.length; i++){
+ data.rewind();
+ SocketAddress sa = new InetSocketAddress(targets[i], port);
+ System.out.println("-------------\nDG_Sending data:" +
+ "\n remaining:" + data.remaining() +
+ "\n position:" + data.position() +
+ "\n limit:" + data.limit() +
+ "\n capacity:" + data.capacity() +
+ " bytes on DG channel to " + sa);
+ try {
+ int n = dgChannel.send(data, sa);
+ System.out.println("DG_Sent " + n + " bytes");
+ } catch (IOException e) {
+ //This regression test is to check vm crash only, so ioe is OK.
+ e.printStackTrace();
+ }
+ }
+ dgChannel.close();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/Args.java b/test/java/nio/channels/FileChannel/Args.java
new file mode 100644
index 0000000..416bc34
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Args.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4470017
+ * @summary Ensure that illegal arguments cause appropriate exceptions
+ * to be thrown
+ */
+
+import java.io.*;
+import java.nio.channels.*;
+
+
+public class Args {
+
+ static void fail(String s) {
+ throw new RuntimeException(s);
+ }
+
+ static interface Thunk {
+ public void run() throws Exception;
+ }
+
+ private static void tryCatch(Class ex, Thunk thunk) {
+ boolean caught = false;
+ try {
+ thunk.run();
+ } catch (Throwable x) {
+ if (ex.isAssignableFrom(x.getClass())) {
+ caught = true;
+ System.err.println("Thrown as expected: " + x);
+ }
+ }
+ if (!caught)
+ fail(ex.getName() + " not thrown");
+ }
+
+ public static void main(String[] args) throws Exception {
+
+ File f = File.createTempFile("foo", null);
+ f.deleteOnExit();
+ final FileChannel fc = new RandomAccessFile(f, "rw").getChannel();
+
+ tryCatch(IllegalArgumentException.class, new Thunk() {
+ public void run() throws Exception {
+ fc.transferFrom(fc, -1, 1);
+ }});
+
+ tryCatch(IllegalArgumentException.class, new Thunk() {
+ public void run() throws Exception {
+ fc.transferFrom(fc, 0, -1);
+ }});
+
+ tryCatch(IllegalArgumentException.class, new Thunk() {
+ public void run() throws Exception {
+ fc.transferTo(-1, 1, fc);
+ }});
+
+ tryCatch(IllegalArgumentException.class, new Thunk() {
+ public void run() throws Exception {
+ fc.transferTo(0, -1, fc);
+ }});
+
+ tryCatch(IllegalArgumentException.class, new Thunk() {
+ public void run() throws Exception {
+ fc.map(FileChannel.MapMode.READ_ONLY, -1, 0);
+ }});
+
+ tryCatch(IllegalArgumentException.class, new Thunk() {
+ public void run() throws Exception {
+ fc.map(FileChannel.MapMode.READ_ONLY, 0, -1);
+ }});
+
+ tryCatch(IllegalArgumentException.class, new Thunk() {
+ public void run() throws Exception {
+ fc.map(FileChannel.MapMode.READ_ONLY, 0,
+ (long)Integer.MAX_VALUE << 3);
+ }});
+
+ }
+
+}
diff --git a/test/java/nio/channels/FileChannel/ClosedChannelTransfer.java b/test/java/nio/channels/FileChannel/ClosedChannelTransfer.java
new file mode 100644
index 0000000..65e43c3
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/ClosedChannelTransfer.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4659408 4659410
+ * @summary Verify transfers with closed channels throws ClosedChannelException
+ */
+
+import java.nio.*;
+import java.nio.channels.*;
+import java.io.*;
+
+public class ClosedChannelTransfer {
+ public static void main (String args []) throws Exception {
+ File file = File.createTempFile("test1", null);
+ file.deleteOnExit();
+ FileChannel channel = (new RandomAccessFile("aaa","rw")).getChannel();
+ test1(channel);
+ test2(channel);
+ channel.close();
+ }
+
+ static void test1(FileChannel channel) throws Exception {
+ ByteArrayInputStream istr = new ByteArrayInputStream(
+ new byte [] {1, 2, 3, 4}
+ );
+ ReadableByteChannel rbc = Channels.newChannel(istr);
+ rbc.close();
+ try {
+ channel.transferFrom(rbc, 0, 2);
+ throw new Exception("Test1: No ClosedChannelException was thrown");
+ } catch (ClosedChannelException cce) {
+ // Correct result
+ }
+ }
+
+ static void test2(FileChannel channel) throws Exception {
+ ByteArrayOutputStream istr = new ByteArrayOutputStream(4);
+ WritableByteChannel wbc = Channels.newChannel(istr);
+ wbc.close();
+ try {
+ channel.transferTo(0, 2, wbc);
+ throw new Exception("Test2: No ClosedChannelException was thrown");
+ } catch (ClosedChannelException cce) {
+ // Correct result
+ }
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/ExpandingMap.java b/test/java/nio/channels/FileChannel/ExpandingMap.java
new file mode 100644
index 0000000..23ef97a
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/ExpandingMap.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4938372
+ * @summary Flushing dirty pages prior to unmap can cause Cleaner thread to
+ * abort VM if memory system has pages locked
+ */
+import java.io.File;
+import java.io.RandomAccessFile;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.util.ArrayList;
+
+/**
+ * Test case provided by submitter of 4938372.
+ */
+
+public class ExpandingMap {
+
+ public static void main(String[] args) throws IOException {
+
+ int initialSize = 20480*1024;
+ int maximumMapSize = 16*1024*1024;
+ int maximumFileSize = 300000000;
+
+ File file = File.createTempFile("exp", "tmp");
+ file.deleteOnExit();
+ RandomAccessFile f = new RandomAccessFile(file, "rw");
+ f.setLength(initialSize);
+
+ FileChannel fc = f.getChannel();
+
+ ByteBuffer[] buffers = new ByteBuffer[128];
+
+ System.out.format("map %d -> %d\n", 0, initialSize);
+ buffers[0] = fc.map(FileChannel.MapMode.READ_WRITE, 0, initialSize);
+
+ int currentBuffer = 0;
+ int currentSize = initialSize;
+ int currentPosition = 0;
+
+ ArrayList<String> junk = new ArrayList<String>();
+
+ while (currentPosition+currentSize < maximumFileSize) {
+ int inc = Math.max(1000*1024, (currentPosition+currentSize)/8);
+
+ int size = currentPosition+currentSize+inc;
+ f.setLength(size);
+
+ while (currentSize+inc > maximumMapSize) {
+ if (currentSize < maximumMapSize) {
+ System.out.format("map %d -> %d\n", currentPosition,
+ (currentPosition + maximumMapSize));
+ buffers[currentBuffer] = fc.map(FileChannel.MapMode.READ_WRITE,
+ currentPosition, maximumMapSize);
+ fillBuffer(buffers[currentBuffer], currentSize);
+ }
+ currentPosition += maximumMapSize;
+ inc = currentSize+inc-maximumMapSize;
+ currentSize = 0;
+ currentBuffer++;
+ if (currentBuffer == buffers.length) {
+ ByteBuffer[] old = buffers;
+ buffers = new ByteBuffer[currentBuffer+currentBuffer/2];
+ System.arraycopy(old, 0, buffers, 0, currentBuffer); }
+ }
+ currentSize += inc;
+ if (currentSize > 0) {
+ System.out.format("map %d -> %d\n", currentPosition,
+ (currentPosition + currentSize));
+ buffers[currentBuffer] = fc.map(FileChannel.MapMode.READ_WRITE,
+ currentPosition, currentSize);
+ fillBuffer(buffers[currentBuffer], currentSize-inc);
+ }
+
+ // busy loop needed to reproduce issue
+ long t = System.currentTimeMillis();
+ while (System.currentTimeMillis() < t+500) {
+ junk.add(String.valueOf(t));
+ if (junk.size() > 100000) junk.clear();
+ }
+ }
+
+ System.out.println("TEST PASSED");
+ }
+
+ static void fillBuffer(ByteBuffer buf, int from) {
+ int limit = buf.limit();
+ for (int i=from; i<limit; i++) {
+ buf.put(i, (byte)i);
+ }
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/Force.java b/test/java/nio/channels/FileChannel/Force.java
new file mode 100644
index 0000000..44991c8
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Force.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2001-2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ @bug 4434115 4802789
+ * @summary Check for regressions in FileChannel.force
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+
+public class Force {
+ public static void main(String[] args) throws Exception {
+ writeAfterForce();
+ forceReadableOnly();
+ }
+
+ // 4434115: FileChannel.write() fails when preceded by force() operation
+ private static void writeAfterForce() throws Exception {
+ byte[] srcData = new byte[20];
+ File blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+ FileOutputStream fis = new FileOutputStream(blah);
+ FileChannel fc = fis.getChannel();
+ fc.write(ByteBuffer.wrap(srcData));
+ fc.force(false);
+ fc.write(ByteBuffer.wrap(srcData));
+ fc.close();
+ }
+
+ // 4802789: FileChannel.force(true) throws IOException (windows)
+ private static void forceReadableOnly() throws Exception {
+ File f = File.createTempFile("blah", null);
+ f.deleteOnExit();
+ FileInputStream fis = new FileInputStream(f);
+ FileChannel fc = fis.getChannel();
+ fc.force(true);
+ fc.close();
+ fis.close();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/Lock.java b/test/java/nio/channels/FileChannel/Lock.java
new file mode 100644
index 0000000..b33db97
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Lock.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2001-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4429043 4493595 6332756
+ * @summary The FileChannel file locking
+ */
+
+import java.io.*;
+import java.nio.channels.*;
+import java.nio.*;
+
+/**
+ * Testing FileChannel's lock method.
+ */
+
+public class Lock {
+
+ public static void main(String[] args) throws Exception {
+ if (args.length > 0) {
+ if(args[0].equals("1")) {
+ MadWriter mw = new MadWriter(args[1], false);
+ } else {
+ MadWriter mw = new MadWriter(args[1], true);
+ }
+ return;
+ }
+ File blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+ RandomAccessFile raf = new RandomAccessFile(blah, "rw");
+ raf.write(1);
+ raf.close();
+ test1(blah, "1");
+ test1(blah, "2");
+ test2(blah, true);
+ test2(blah, false);
+ test3(blah);
+ }
+
+ private static void test2(File blah, boolean b) throws Exception {
+ RandomAccessFile raf = new RandomAccessFile(blah, "rw");
+ FileChannel channel = raf.getChannel();
+ FileLock lock;
+ if (b)
+ lock = channel.lock();
+ else
+ lock = channel.tryLock();
+ lock.release();
+ channel.close();
+ }
+
+ static void test1(File blah, String str) throws Exception {
+
+ // Grab the lock
+ RandomAccessFile fis = new RandomAccessFile(blah, "rw");
+ FileChannel fc = fis.getChannel();
+ FileLock lock = null;
+
+ if (str.equals("1")) {
+ lock = fc.lock(0, 10, false);
+ if (lock == null)
+ throw new RuntimeException("Lock should not return null");
+ try {
+ FileLock lock2 = fc.lock(5, 10, false);
+ throw new RuntimeException("Overlapping locks allowed");
+ } catch (OverlappingFileLockException e) {
+ // Correct result
+ }
+ }
+
+ // Exec the tamperer
+ String command = System.getProperty("java.home") +
+ File.separator + "bin" + File.separator + "java Lock " + str + " " + blah;
+ Process p = Runtime.getRuntime().exec(command);
+
+ BufferedReader in = new BufferedReader
+ (new InputStreamReader(p.getInputStream()));
+
+ String s;
+ int count = 0;
+ while ((s = in.readLine()) != null) {
+ if (!s.equals("good")) {
+ if (File.separatorChar == '/') {
+ // Fails on windows over NFS...
+ throw new RuntimeException("Failed: "+s);
+ }
+ }
+ count++;
+ }
+
+ if (count == 0) {
+ in = new BufferedReader(new InputStreamReader(p.getErrorStream()));
+ while ((s = in.readLine()) != null) {
+ System.err.println("Error output: " + s);
+ }
+ throw new RuntimeException("Failed, no output");
+ }
+
+ // Clean up
+ if (lock != null) {
+ /* Check multiple releases */
+ lock.release();
+ lock.release();
+ }
+ fc.close();
+ fis.close();
+ }
+
+ // The overlap check for file locks should be JVM-wide
+ private static void test3(File blah) throws Exception {
+ FileChannel fc1 = new RandomAccessFile(blah, "rw").getChannel();
+ FileChannel fc2 = new RandomAccessFile(blah, "rw").getChannel();
+
+ // lock via one channel, and then attempt to lock the same file
+ // using a second channel
+ FileLock fl1 = fc1.lock();
+ try {
+ fc2.tryLock();
+ throw new RuntimeException("Overlapping locks allowed");
+ } catch (OverlappingFileLockException x) {
+ }
+ try {
+ fc2.lock();
+ throw new RuntimeException("Overlapping locks allowed");
+ } catch (OverlappingFileLockException x) {
+ }
+
+ // release lock and the attempt to lock with the second channel
+ // should succeed.
+ fl1.release();
+ FileLock fl2 = fc2.lock();
+ try {
+ fc1.lock();
+ throw new RuntimeException("Overlapping locks allowed");
+ } catch (OverlappingFileLockException x) {
+ }
+
+ fc1.close();
+ fc2.close();
+ }
+}
+
+class MadWriter {
+ public MadWriter(String s, boolean b) throws Exception {
+ File f = new File(s);
+ RandomAccessFile fos = new RandomAccessFile(f, "rw");
+ FileChannel fc = fos.getChannel();
+ if (fc.tryLock(10, 10, false) == null) {
+ System.out.println("bad: Failed to grab adjacent lock");
+ }
+ FileLock lock = fc.tryLock(0, 10, false);
+ if (lock == null) {
+ if (b)
+ System.out.println("bad");
+ else
+ System.out.println("good");
+ } else {
+ if (b)
+ System.out.println("good");
+ else
+ System.out.println("bad");
+ }
+ fc.close();
+ fos.close();
+ }
+
+}
diff --git a/test/java/nio/channels/FileChannel/LongTransferTest.java b/test/java/nio/channels/FileChannel/LongTransferTest.java
new file mode 100644
index 0000000..068e6d0
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/LongTransferTest.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ @bug 5105464 6269047
+ * @summary Test to transfer bytes with a size bigger than Integer.MAX_VALUE
+ */
+
+
+import java.io.*;
+import java.net.*;
+import java.nio.channels.*;
+
+public class LongTransferTest {
+ public static void main(String[] args) throws Exception {
+ System.out.println("LongTransferTest-main: "+
+ "Test to transfer bytes with a size bigger than Integer.MAX_VALUE.");
+
+ System.out.println("LongTransferTest-main: Test at first "+
+ "the private method transferFromFileChannel with files...");
+
+ final String dir = (String)System.getProperty("java.io.tmpdir");
+ System.out.println(
+ "LongTransferTest-main: using the temp dir (java.io.tmpdir) "+dir);
+
+ File inFile = new File(dir, "LongTransferTest_channelTestInFile_tmp");
+ if (!inFile.exists()) {
+ inFile.createNewFile();
+ }
+
+ File outFile = new File(dir, "LongTransferTest_channelTestOutFile_tmp");
+ if (!outFile.exists()) {
+ outFile.createNewFile();
+ }
+
+ FileInputStream inStream = new FileInputStream(inFile);
+ FileChannel inChannel = inStream.getChannel();
+
+ FileOutputStream outStream = new FileOutputStream(outFile);
+ FileChannel outChannel = outStream.getChannel();
+
+ outChannel.transferFrom(inChannel, 0, (long)Integer.MAX_VALUE+1L);
+
+ System.out.println("LongTransferTest-main: Test the method transferTo with files.");
+
+ inChannel.transferTo(0, (long)Integer.MAX_VALUE+1L, outChannel);
+
+
+ System.out.println("LongTransferTest-main: Test the "+
+ "private method transferFromArbitraryChannel with sockets ...");
+
+ ServerSocket server = new ServerSocket(0);
+ MyJob job = new MyJob(server);
+ job.start();
+
+ SocketChannel socket = SocketChannel.open();
+ socket.socket().connect(new InetSocketAddress(server.getInetAddress(), server.getLocalPort()));
+
+ outChannel.transferFrom(socket, 0, (long)Integer.MAX_VALUE + 1L);
+
+ System.out.println("LongTransferTest-main: OK!");
+
+ socket.close();
+
+ server.close();
+
+ inFile.delete();
+ outFile.delete();
+ }
+
+ private static class MyJob extends Thread {
+ public MyJob(ServerSocket server) {
+ setDaemon(true);
+ this.server = server;
+ }
+
+ public void run() {
+ try {
+ Socket s = server.accept();
+ System.out.println("MyJob-run: client connected: "+s);
+
+ byte[] bs = new byte[10];
+ System.out.println("MyJob-run: write some bytes to client.");
+
+ s.getOutputStream().write(bs);
+ s.getOutputStream().flush();
+
+ // no need to write all Integer.MAX_VALUE + 1 bytes
+ // it will take too much time
+ System.out.println("MyJob-run: close the client socket.");
+ s.close();
+ } catch (Exception e) {
+ // unexpected
+ e.printStackTrace();
+
+ System.exit(1);
+ }
+ }
+
+ private ServerSocket server;
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/MapAssertions.java b/test/java/nio/channels/FileChannel/MapAssertions.java
new file mode 100644
index 0000000..cd77ec7
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/MapAssertions.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4896666
+ * @run main/othervm -esa MapAssertions
+ * @summary Check for assertion failures in FileChannel.map
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class MapAssertions {
+ public static void main(String[] args) throws Exception {
+ File blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+ RandomAccessFile raf = new RandomAccessFile(blah, "r");
+ FileChannel fc = raf.getChannel();
+ long fileSize = fc.size();
+ MappedByteBuffer mapBuf =
+ fc.map(FileChannel.MapMode.READ_ONLY, 0l, fileSize);
+ fc.close();
+ raf.close();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/MapOverEnd.java b/test/java/nio/channels/FileChannel/MapOverEnd.java
new file mode 100644
index 0000000..de34dc5
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/MapOverEnd.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4463036
+ * @summary Check if file mapping extends beyond end of file
+ */
+
+import java.nio.*;
+import java.nio.channels.*;
+import java.io.*;
+
+public class MapOverEnd {
+ public static void main (String [] args) throws Exception {
+ File blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+ RandomAccessFile raf = new RandomAccessFile (blah, "rw");
+ FileChannel fc = raf.getChannel();
+ MappedByteBuffer map = fc.map(FileChannel.MapMode.READ_WRITE, 0, 2048);
+ fc.close();
+ double current = map.getDouble (50);
+ map.putDouble (50, current+0.1d);
+ map.force();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/MapReadOnly.java b/test/java/nio/channels/FileChannel/MapReadOnly.java
new file mode 100644
index 0000000..4541129
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/MapReadOnly.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4510489
+ * @summary Verify IOUtil.java reads to buffer limits
+ */
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class MapReadOnly {
+ public static void main (String args[]) throws Exception {
+ File testFile = File.createTempFile("test2", null);
+ testFile.deleteOnExit();
+ RandomAccessFile raf = new RandomAccessFile(testFile, "rw");
+ FileChannel fc = raf.getChannel();
+ MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0L,
+ (int) fc.size());
+ mbb.load();
+ try {
+ mbb.put((byte)3);
+ throw new Exception("Test failed");
+ } catch (ReadOnlyBufferException robe) {
+ // Correct result
+ }
+ fc.close();
+ raf.close();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/MapTest.java b/test/java/nio/channels/FileChannel/MapTest.java
new file mode 100644
index 0000000..9b64787
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/MapTest.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test file mapping with FileChannel
+ */
+
+import java.io.*;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.*;
+import java.nio.channels.FileChannel;
+import java.util.Random;
+
+
+/**
+ * Testing FileChannel's mapping capabilities.
+ */
+
+public class MapTest {
+
+ private static PrintStream err = System.err;
+
+ private static Random generator = new Random();
+
+ private static int CHARS_PER_LINE = File.separatorChar == '/' ? 5 : 6;
+
+ private static File blah;
+
+ public static void main(String[] args) throws Exception {
+ blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+ initTestFile(blah);
+ err.println("Test file " + blah + " initialized");
+ testZero();
+ err.println("Zero size: OK");
+ testRead();
+ err.println("Read: OK");
+ testWrite();
+ err.println("Write: OK");
+ testHighOffset();
+ err.println("High offset: OK");
+ }
+
+ /**
+ * Creates file blah:
+ * 0000
+ * 0001
+ * 0002
+ * 0003
+ * .
+ * .
+ * .
+ * 3999
+ *
+ * Blah extends beyond a single page of memory so that the
+ * ability to index into a file of multiple pages is tested.
+ */
+ private static void initTestFile(File blah) throws Exception {
+ FileOutputStream fos = new FileOutputStream(blah);
+ BufferedWriter awriter
+ = new BufferedWriter(new OutputStreamWriter(fos, "8859_1"));
+
+ for(int i=0; i<4000; i++) {
+ String number = new Integer(i).toString();
+ for (int h=0; h<4-number.length(); h++)
+ awriter.write("0");
+ awriter.write(""+i);
+ awriter.newLine();
+ }
+ awriter.flush();
+ awriter.close();
+ }
+
+ /**
+ * Tests zero size file mapping
+ */
+ private static void testZero() throws Exception {
+ FileInputStream fis = new FileInputStream(blah);
+ FileChannel c = fis.getChannel();
+ MappedByteBuffer b = c.map(FileChannel.MapMode.READ_ONLY, 0, 0);
+ c.close();
+ fis.close();
+ }
+
+ /**
+ * Maps blah file with a random offset and checks to see if read
+ * from the ByteBuffer gets the right line number
+ */
+ private static void testRead() throws Exception {
+ StringBuffer sb = new StringBuffer();
+ sb.setLength(4);
+
+ for (int x=0; x<1000; x++) {
+ FileInputStream fis = new FileInputStream(blah);
+ FileChannel c = fis.getChannel();
+
+ long offset = generator.nextInt(10000);
+ long expectedResult = offset / CHARS_PER_LINE;
+ offset = expectedResult * CHARS_PER_LINE;
+
+ MappedByteBuffer b = c.map(FileChannel.MapMode.READ_ONLY,
+ offset, 100);
+
+ for (int i=0; i<4; i++) {
+ byte aByte = b.get(i);
+ sb.setCharAt(i, (char)aByte);
+ }
+
+ int result = Integer.parseInt(sb.toString());
+ if (result != expectedResult) {
+ err.println("I expected "+expectedResult);
+ err.println("I got "+result);
+ throw new Exception("Read test failed");
+ }
+ c.close();
+ fis.close();
+ }
+ }
+
+ /**
+ * Maps blah file with a random offset and checks to see if data
+ * written out to the file can be read back in
+ */
+ private static void testWrite() throws Exception {
+ StringBuffer sb = new StringBuffer();
+ sb.setLength(4);
+
+ for (int x=0; x<1000; x++) {
+ RandomAccessFile raf = new RandomAccessFile(blah, "rw");
+ FileChannel c = raf.getChannel();
+
+ long offset = generator.nextInt(1000);
+ MappedByteBuffer b = c.map(FileChannel.MapMode.READ_WRITE,
+ offset, 100);
+
+ for (int i=0; i<4; i++) {
+ b.put(i, (byte)('0' + i));
+ }
+
+ for (int i=0; i<4; i++) {
+ byte aByte = b.get(i);
+ sb.setCharAt(i, (char)aByte);
+ }
+ if (!sb.toString().equals("0123"))
+ throw new Exception("Write test failed");
+ c.close();
+ raf.close();
+ }
+ }
+
+ private static void testHighOffset() throws Exception {
+ StringBuffer sb = new StringBuffer();
+ sb.setLength(4);
+
+ for (int x=0; x<1000; x++) {
+ RandomAccessFile raf = new RandomAccessFile(blah, "rw");
+ FileChannel fc = raf.getChannel();
+ long offset = 66000;
+ MappedByteBuffer b = fc.map(FileChannel.MapMode.READ_WRITE,
+ offset, 100);
+
+ fc.close();
+ raf.close();
+ }
+ }
+
+}
diff --git a/test/java/nio/channels/FileChannel/Mode.java b/test/java/nio/channels/FileChannel/Mode.java
new file mode 100644
index 0000000..90aa945
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Mode.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ @bug 4462298
+ * @summary Test FileChannel maps with different accesses
+ */
+
+import java.nio.channels.*;
+import java.nio.MappedByteBuffer;
+import java.io.*;
+
+
+public class Mode {
+ private static File testFile;
+
+ public static void main(String[] args) throws Exception {
+ testFile = File.createTempFile("testFile", null);
+ testFile.deleteOnExit();
+ testReadable();
+ testWritable();
+ }
+
+ private static void testReadable() throws IOException {
+ FileInputStream is = new FileInputStream(testFile);
+ FileChannel channel = is.getChannel();
+ try {
+ MappedByteBuffer buff = channel.map(FileChannel.MapMode.READ_WRITE,
+ 0, 8);
+ throw new RuntimeException("Exception expected, none thrown");
+ } catch (NonWritableChannelException e) {
+ // correct result
+ }
+ is.close();
+ }
+
+ private static void testWritable() throws IOException {
+ FileOutputStream is = new FileOutputStream(testFile);
+ FileChannel channel = is.getChannel();
+ try {
+ MappedByteBuffer buff = channel.map(FileChannel.MapMode.READ_ONLY,
+ 0, 8);
+ throw new RuntimeException("Exception expected, none thrown");
+ } catch (NonReadableChannelException e) {
+ // correct result
+ }
+ is.close();
+ }
+
+}
diff --git a/test/java/nio/channels/FileChannel/Position.java b/test/java/nio/channels/FileChannel/Position.java
new file mode 100644
index 0000000..4b60b09
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Position.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test position method of FileChannel
+ */
+
+import java.io.*;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.*;
+import java.nio.channels.FileChannel;
+import java.util.Random;
+
+
+/**
+ * Testing FileChannel's position method.
+ */
+
+public class Position {
+
+ private static PrintStream err = System.err;
+
+ private static Random generator = new Random();
+
+ private static int CHARS_PER_LINE = File.separatorChar == '/' ? 5 : 6;
+
+ private static File blah;
+
+ public static void main(String[] args) throws Exception {
+ blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+ initTestFile(blah);
+
+ FileInputStream fis = new FileInputStream(blah);
+ FileChannel c = fis.getChannel();
+
+ for(int i=0; i<100; i++) {
+ long newPos = generator.nextInt(1000);
+ c.position(newPos);
+ if (c.position() != newPos)
+ throw new RuntimeException("Position failed");
+ }
+
+ c.close();
+ fis.close();
+ }
+
+ /**
+ * Creates file blah:
+ * 0000
+ * 0001
+ * 0002
+ * 0003
+ * .
+ * .
+ * .
+ * 3999
+ *
+ */
+ private static void initTestFile(File blah) throws Exception {
+ FileOutputStream fos = new FileOutputStream(blah);
+ BufferedWriter awriter
+ = new BufferedWriter(new OutputStreamWriter(fos, "8859_1"));
+
+ for(int i=0; i<4000; i++) {
+ String number = new Integer(i).toString();
+ for (int h=0; h<4-number.length(); h++)
+ awriter.write("0");
+ awriter.write(""+i);
+ awriter.newLine();
+ }
+ awriter.flush();
+ awriter.close();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/Pread.java b/test/java/nio/channels/FileChannel/Pread.java
new file mode 100644
index 0000000..acc2766
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Pread.java
@@ -0,0 +1,164 @@
+/*
+ * Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4862382 4862408
+ * @summary Test positional read method of FileChannel
+ */
+
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.channels.*;
+import java.nio.channels.FileChannel;
+import java.util.Random;
+
+
+/**
+ * Testing FileChannel's positional read method.
+ */
+
+public class Pread {
+
+ private static PrintStream err = System.err;
+
+ private static Random generator = new Random();
+
+ private static int CHARS_PER_LINE = File.separatorChar == '/' ? 5 : 6;
+
+ public static void main(String[] args) throws Exception {
+ genericTest();
+ testNegativePosition(); // This test for bug 4862382
+ testUnreadableChannel();// This test for bug 4862408
+ }
+
+ // This test for bug 4862382
+ private static void testNegativePosition() throws Exception {
+ File blah = File.createTempFile("blah1", null);
+ blah.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(blah);
+ fos.write(new byte[128]);
+ fos.close();
+ FileChannel fc = (new FileInputStream(blah)).getChannel();
+ try {
+ fc.read(ByteBuffer.allocate(256), -1L);
+ throw new RuntimeException("Expected exception not thrown");
+ } catch(IllegalArgumentException e) {
+ // Correct result
+ }
+ }
+
+ // This test for bug 4862408
+ private static void testUnreadableChannel() throws Exception {
+ File blah = File.createTempFile("blah2", null);
+ blah.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(blah);
+ fos.write(new byte[128]);
+ FileChannel fc = fos.getChannel();
+ try {
+ fc.read(ByteBuffer.allocate(256),1);
+ throw new RuntimeException("Expected exception not thrown");
+ } catch(NonReadableChannelException e) {
+ // Correct result
+ }
+ }
+
+ private static void genericTest() throws Exception {
+ StringBuffer sb = new StringBuffer();
+ sb.setLength(4);
+
+ File blah = File.createTempFile("blah3", null);
+ blah.deleteOnExit();
+ initTestFile(blah);
+
+ FileInputStream fis = new FileInputStream(blah);
+ FileChannel c = fis.getChannel();
+
+ for (int x=0; x<100; x++) {
+ long offset = generator.nextInt(1000);
+ long expectedResult = offset / CHARS_PER_LINE;
+ offset = expectedResult * CHARS_PER_LINE;
+ ByteBuffer bleck = ByteBuffer.allocateDirect(4);
+
+ long originalPosition = c.position();
+
+ int totalRead = 0;
+ while (totalRead < 4) {
+ int read = c.read(bleck, offset);
+ if (read < 0)
+ throw new Exception("Read failed");
+ totalRead += read;
+ }
+
+ long newPosition = c.position();
+
+ for (int i=0; i<4; i++) {
+ byte aByte = bleck.get(i);
+ sb.setCharAt(i, (char)aByte);
+ }
+ int result = Integer.parseInt(sb.toString());
+ if (result != expectedResult) {
+ err.println("I expected "+ expectedResult);
+ err.println("I got "+ result);
+ throw new Exception("Read test failed");
+ }
+
+ // Ensure that file pointer position has not changed
+ if (originalPosition != newPosition)
+ throw new Exception("File position modified");
+ }
+
+ c.close();
+ fis.close();
+ }
+
+ /**
+ * Creates file blah:
+ * 0000
+ * 0001
+ * 0002
+ * 0003
+ * .
+ * .
+ * .
+ * 3999
+ *
+ * Blah extends beyond a single page of memory so that the
+ * ability to index into a file of multiple pages is tested.
+ */
+ private static void initTestFile(File blah) throws Exception {
+ FileOutputStream fos = new FileOutputStream(blah);
+ BufferedWriter awriter
+ = new BufferedWriter(new OutputStreamWriter(fos, "8859_1"));
+
+ for(int i=0; i<4000; i++) {
+ String number = new Integer(i).toString();
+ for (int h=0; h<4-number.length(); h++)
+ awriter.write("0");
+ awriter.write(""+i);
+ awriter.newLine();
+ }
+ awriter.flush();
+ awriter.close();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/Pwrite.java b/test/java/nio/channels/FileChannel/Pwrite.java
new file mode 100644
index 0000000..00ecb73
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Pwrite.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright 2000-2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4862411
+ * @summary Test positional write method of FileChannel
+ */
+
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.channels.*;
+import java.nio.channels.FileChannel;
+import java.util.Random;
+
+
+/**
+ * Testing FileChannel's positional write method.
+ */
+public class Pwrite {
+
+ private static Random generator = new Random();
+
+ private static File blah;
+
+ public static void main(String[] args) throws Exception {
+ genericTest();
+ testUnwritableChannel();
+ }
+
+ // This test for bug 4862411
+ private static void testUnwritableChannel() throws Exception {
+ File blah = File.createTempFile("blah2", null);
+ blah.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(blah);
+ fos.write(new byte[128]);
+ fos.close();
+ FileInputStream fis = new FileInputStream(blah);
+ FileChannel fc = fis.getChannel();
+ try {
+ fc.write(ByteBuffer.allocate(256),1);
+ throw new RuntimeException("Expected exception not thrown");
+ } catch(NonWritableChannelException e) {
+ // Correct result
+ }
+ }
+
+ private static void genericTest() throws Exception {
+ StringBuffer sb = new StringBuffer();
+ sb.setLength(4);
+
+ blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+ initTestFile(blah);
+
+ RandomAccessFile raf = new RandomAccessFile(blah, "rw");
+ FileChannel c = raf.getChannel();
+
+ for (int x=0; x<100; x++) {
+ long offset = generator.nextInt(1000);
+ ByteBuffer bleck = ByteBuffer.allocateDirect(4);
+
+ // Write known sequence out
+ for (byte i=0; i<4; i++) {
+ bleck.put(i);
+ }
+ bleck.flip();
+ long originalPosition = c.position();
+ int totalWritten = 0;
+ while (totalWritten < 4) {
+ int written = c.write(bleck, offset);
+ if (written < 0)
+ throw new Exception("Read failed");
+ totalWritten += written;
+ }
+
+ long newPosition = c.position();
+
+ // Ensure that file pointer position has not changed
+ if (originalPosition != newPosition)
+ throw new Exception("File position modified");
+
+ // Attempt to read sequence back in
+ bleck = ByteBuffer.allocateDirect(4);
+ originalPosition = c.position();
+ int totalRead = 0;
+ while (totalRead < 4) {
+ int read = c.read(bleck, offset);
+ if (read < 0)
+ throw new Exception("Read failed");
+ totalRead += read;
+ }
+ newPosition = c.position();
+
+ // Ensure that file pointer position has not changed
+ if (originalPosition != newPosition)
+ throw new Exception("File position modified");
+
+ for (byte i=0; i<4; i++) {
+ if (bleck.get(i) != i)
+ throw new Exception("Write test failed");
+ }
+ }
+ c.close();
+ raf.close();
+ }
+
+ /**
+ * Creates file blah:
+ * 0000
+ * 0001
+ * 0002
+ * 0003
+ * .
+ * .
+ * .
+ * 3999
+ *
+ * Blah extends beyond a single page of memory so that the
+ * ability to index into a file of multiple pages is tested.
+ */
+ private static void initTestFile(File blah) throws Exception {
+ FileOutputStream fos = new FileOutputStream(blah);
+ BufferedWriter awriter
+ = new BufferedWriter(new OutputStreamWriter(fos, "8859_1"));
+
+ for(int i=0; i<4000; i++) {
+ String number = new Integer(i).toString();
+ for (int h=0; h<4-number.length(); h++)
+ awriter.write("0");
+ awriter.write(""+i);
+ awriter.newLine();
+ }
+ awriter.flush();
+ awriter.close();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/Read.java b/test/java/nio/channels/FileChannel/Read.java
new file mode 100644
index 0000000..6637863
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Read.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test read method of FileChannel
+ */
+
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.channels.*;
+import java.nio.channels.FileChannel;
+import java.util.Random;
+
+
+/**
+ * Testing FileChannel's mapping capabilities.
+ */
+
+public class Read {
+
+ private static PrintStream err = System.err;
+
+ private static Random generator = new Random();
+
+ private static int CHARS_PER_LINE = File.separatorChar == '/' ? 5 : 6;
+
+ private static File blah;
+
+ public static void main(String[] args) throws Exception {
+ StringBuffer sb = new StringBuffer();
+ sb.setLength(4);
+
+ blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+ initTestFile(blah);
+
+ FileInputStream fis = new FileInputStream(blah);
+ FileChannel c = fis.getChannel();
+
+ for (int x=0; x<1000; x++) {
+ long offset = x * CHARS_PER_LINE;
+ long expectedResult = offset / CHARS_PER_LINE;
+ offset = expectedResult * CHARS_PER_LINE;
+ ByteBuffer bleck = ByteBuffer.allocateDirect(CHARS_PER_LINE);
+
+ c.read(bleck);
+
+ for (int i=0; i<4; i++) {
+ byte aByte = bleck.get(i);
+ sb.setCharAt(i, (char)aByte);
+ }
+ int result = Integer.parseInt(sb.toString());
+ if (result != expectedResult) {
+ err.println("I expected "+expectedResult);
+ err.println("I got "+ result);
+ throw new Exception("Read test failed");
+ }
+ }
+
+ c.close();
+ fis.close();
+ }
+
+ /**
+ * Creates file blah:
+ * 0000
+ * 0001
+ * 0002
+ * 0003
+ * .
+ * .
+ * .
+ * 3999
+ *
+ * Blah extends beyond a single page of memory so that the
+ * ability to index into a file of multiple pages is tested.
+ */
+ private static void initTestFile(File blah) throws Exception {
+ FileOutputStream fos = new FileOutputStream(blah);
+ BufferedWriter awriter
+ = new BufferedWriter(new OutputStreamWriter(fos, "8859_1"));
+
+ for(int i=0; i<4000; i++) {
+ String number = new Integer(i).toString();
+ for (int h=0; h<4-number.length(); h++)
+ awriter.write("0");
+ awriter.write(""+i);
+ awriter.newLine();
+ }
+ awriter.flush();
+ awriter.close();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/ReadFull.java b/test/java/nio/channels/FileChannel/ReadFull.java
new file mode 100644
index 0000000..5cb7d95
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/ReadFull.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test read method of FileChannel
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+
+/**
+ * Testing a read into buffers that have no room.
+ */
+public class ReadFull {
+
+ public static void main(String[] args) throws Exception {
+
+ File blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+ ByteBuffer[] dstBuffers = new ByteBuffer[10];
+ for(int i=0; i<10; i++) {
+ dstBuffers[i] = ByteBuffer.allocateDirect(10);
+ dstBuffers[i].position(10);
+ }
+ FileInputStream fis = new FileInputStream(blah);
+ FileChannel fc = fis.getChannel();
+
+ // No space left in buffers, this should return 0
+ long bytesRead = fc.read(dstBuffers) ;
+ if (bytesRead != 0)
+ throw new RuntimeException("Nonzero return from read");
+
+ fc.close();
+ fis.close();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/ReadToLimit.java b/test/java/nio/channels/FileChannel/ReadToLimit.java
new file mode 100644
index 0000000..dfca92d
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/ReadToLimit.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ @bug 4526350
+ @summary Verify IOUtil.java reads to buffer limits
+ */
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class ReadToLimit {
+ public static void main(String[] args) throws Exception {
+ File blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+ initTestFile(blah);
+
+ ByteBuffer[] dstBuffers = new ByteBuffer[2];
+ for(int i=0; i<2; i++) {
+ dstBuffers[i] = ByteBuffer.allocateDirect(10);
+ dstBuffers[i].limit(5);
+ }
+ FileInputStream fis = new FileInputStream(blah);
+ FileChannel fc = fis.getChannel();
+ long bytesRead = fc.read(dstBuffers);
+ for(int i=0; i<2; i++)
+ if (dstBuffers[i].position() != 5)
+ throw new Exception("Test failed");
+ fc.close();
+ fis.close();
+ }
+
+ /**
+ * Creates file blah:
+ * 0000
+ * 0001
+ * 0002
+ * 0003
+ */
+ private static void initTestFile(File blah) throws Exception {
+ FileOutputStream fos = new FileOutputStream(blah);
+ BufferedWriter awriter
+ = new BufferedWriter(new OutputStreamWriter(fos, "8859_1"));
+
+ for(int i=0; i<4; i++) {
+ String number = new Integer(i).toString();
+ for (int h=0; h<4-number.length(); h++)
+ awriter.write("0");
+ awriter.write(""+i);
+ awriter.newLine();
+ }
+ awriter.flush();
+ awriter.close();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/Release.java b/test/java/nio/channels/FileChannel/Release.java
new file mode 100644
index 0000000..4daa51b
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Release.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4854056
+ * @summary Check release on closed channel
+ */
+
+import java.io.*;
+import java.nio.channels.*;
+
+public class Release {
+ public static void main(String[] args) throws Exception {
+ FileOutputStream fos = new FileOutputStream("testFile.tmp");
+ fos.write(new byte[128]);
+ FileChannel ch = fos.getChannel();
+ FileLock fl = ch.lock();
+ ch.close();
+ try {
+ fl.release();
+ throw new RuntimeException("Expected exception not thrown");
+ } catch (ClosedChannelException cce) {
+ // Correct result
+ }
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/ScatteringRead.java b/test/java/nio/channels/FileChannel/ScatteringRead.java
new file mode 100644
index 0000000..d064aee
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/ScatteringRead.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright 2001-2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ @bug 4452020 4629048 4638365 4869859
+ * @summary Test FileChannel scattering reads
+ */
+
+import java.nio.channels.*;
+import java.nio.*;
+import java.io.*;
+
+public class ScatteringRead {
+
+ private static final int NUM_BUFFERS = 3;
+
+ private static final int BUFFER_CAP = 3;
+
+ private static final int BIG_BUFFER_CAP = Integer.MAX_VALUE / 3 + 10;
+
+ public static void main(String[] args) throws Exception {
+ test1(); // for bug 4452020
+ test2(); // for bug 4629048
+ System.gc();
+
+ // Test 3 proves that the system is capable of reading
+ // more than MAX_INT bytes in one shot. But it is unsuitable
+ // for automated testing because oftentimes less bytes are
+ // read for various reasons, and this is allowed by the spec.
+ // test3(); // for bug 4638365
+ }
+
+ private static void test1() throws Exception {
+ ByteBuffer dstBuffers[] = new ByteBuffer[NUM_BUFFERS];
+ for (int i=0; i<NUM_BUFFERS; i++)
+ dstBuffers[i] = ByteBuffer.allocateDirect(BUFFER_CAP);
+ File blah = File.createTempFile("blah1", null);
+ blah.deleteOnExit();
+ createTestFile(blah);
+
+ FileInputStream fis = new FileInputStream(blah);
+ FileChannel fc = fis.getChannel();
+
+ byte expectedResult = -128;
+ for (int k=0; k<20; k++) {
+ long bytesRead = fc.read(dstBuffers);
+ for (int i=0; i<NUM_BUFFERS; i++) {
+ for (int j=0; j<BUFFER_CAP; j++) {
+ byte b = dstBuffers[i].get(j);
+ if (b != expectedResult++)
+ throw new RuntimeException("Test failed");
+ }
+ dstBuffers[i].flip();
+ }
+ }
+ fis.close();
+ }
+
+ private static void createTestFile(File blah) throws Exception {
+ FileOutputStream fos = new FileOutputStream(blah);
+ for(int i=-128; i<128; i++)
+ fos.write((byte)i);
+ fos.flush();
+ fos.close();
+ }
+
+ private static void test2() throws Exception {
+ ByteBuffer dstBuffers[] = new ByteBuffer[2];
+ for (int i=0; i<2; i++)
+ dstBuffers[i] = ByteBuffer.allocateDirect(10);
+ File blah = File.createTempFile("blah2", null);
+ blah.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(blah);
+ for(int i=0; i<15; i++)
+ fos.write((byte)92);
+ fos.flush();
+ fos.close();
+
+ FileInputStream fis = new FileInputStream(blah);
+ FileChannel fc = fis.getChannel();
+
+ long bytesRead = fc.read(dstBuffers);
+ if (dstBuffers[1].limit() != 10)
+ throw new Exception("Scattering read changed buf limit.");
+ fis.close();
+ }
+
+ private static void test3() throws Exception {
+ // Only works on 64 bit Solaris
+ String osName = System.getProperty("os.name");
+ if (!osName.startsWith("SunOS"))
+ return;
+ String dataModel = System.getProperty("sun.arch.data.model");
+ if (!dataModel.startsWith("64"))
+ return;
+
+ ByteBuffer dstBuffers[] = new ByteBuffer[NUM_BUFFERS];
+ File f = File.createTempFile("test3", null);
+ f.deleteOnExit();
+ prepTest3File(f, (long)BIG_BUFFER_CAP);
+ RandomAccessFile raf = new RandomAccessFile(f, "rw");
+ FileChannel fc = raf.getChannel();
+ MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0,
+ BIG_BUFFER_CAP);
+ for (int i=0; i<NUM_BUFFERS; i++) {
+ dstBuffers[i] = mbb;
+ }
+ fc.close();
+ raf.close();
+
+ // Source must be large
+ FileInputStream fis = new FileInputStream("/dev/zero");
+ fc = fis.getChannel();
+
+ long bytesRead = fc.read(dstBuffers);
+ if (bytesRead <= Integer.MAX_VALUE)
+ throw new RuntimeException("Test 3 failed "+bytesRead+" < "+Integer.MAX_VALUE);
+
+ fc.close();
+ fis.close();
+ }
+
+ static void prepTest3File(File blah, long testSize) throws Exception {
+ RandomAccessFile raf = new RandomAccessFile(blah, "rw");
+ FileChannel fc = raf.getChannel();
+ fc.write(ByteBuffer.wrap("Use the source!".getBytes()), testSize - 40);
+ fc.close();
+ raf.close();
+ }
+
+}
diff --git a/test/java/nio/channels/FileChannel/Size.java b/test/java/nio/channels/FileChannel/Size.java
new file mode 100644
index 0000000..3fc6a52
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Size.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4563125
+ * @summary Test size method of FileChannel
+ */
+
+import java.io.*;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.*;
+import java.util.Random;
+
+
+/**
+ * Testing FileChannel's size method.
+ */
+
+public class Size {
+
+ private static Random generator = new Random();
+
+ private static File blah;
+
+ public static void main(String[] args) throws Exception {
+ test1();
+ test2();
+ }
+
+ private static void test1() throws Exception {
+ blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+ for(int i=0; i<100; i++) {
+ long testSize = generator.nextInt(1000);
+ initTestFile(blah, testSize);
+ FileInputStream fis = new FileInputStream(blah);
+ FileChannel c = fis.getChannel();
+ if (c.size() != testSize)
+ throw new RuntimeException("Size failed");
+ c.close();
+ fis.close();
+ }
+ blah.delete();
+ }
+
+ // Test for bug 4563125
+ private static void test2() throws Exception {
+ // Windows and Linux can't handle the really large file sizes for a truncate
+ // or a positional write required by the test for 4563125
+ String osName = System.getProperty("os.name");
+ if (osName.startsWith("SunOS")) {
+ blah = File.createTempFile("blah", null);
+ long testSize = ((long)Integer.MAX_VALUE) * 2;
+ initTestFile(blah, 10);
+ RandomAccessFile raf = new RandomAccessFile(blah, "rw");
+ FileChannel fc = raf.getChannel();
+ fc.size();
+ fc.map(FileChannel.MapMode.READ_WRITE, testSize, 10);
+ if (fc.size() != testSize + 10)
+ throw new RuntimeException("Size failed " + fc.size());
+ fc.close();
+ raf.close();
+ blah.delete();
+ }
+ }
+
+ /**
+ * Creates file blah of specified size in bytes.
+ *
+ */
+ private static void initTestFile(File blah, long size) throws Exception {
+ if (blah.exists())
+ blah.delete();
+ FileOutputStream fos = new FileOutputStream(blah);
+ BufferedWriter awriter
+ = new BufferedWriter(new OutputStreamWriter(fos, "8859_1"));
+
+ for(int i=0; i<size; i++) {
+ awriter.write("e");
+ }
+ awriter.flush();
+ awriter.close();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/Transfer.java b/test/java/nio/channels/FileChannel/Transfer.java
new file mode 100644
index 0000000..15578c3
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Transfer.java
@@ -0,0 +1,529 @@
+/*
+ * Copyright 2001-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4434723 4482726 4559072 4638365 4795550 5081340 5103988 6253145
+ * @summary Test FileChannel.transferFrom and transferTo
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
+import java.util.Random;
+
+
+public class Transfer {
+
+ private static Random generator = new Random();
+
+ private static int[] testSizes = {
+ 0, 10, 1023, 1024, 1025, 2047, 2048, 2049 };
+
+ public static void main(String[] args) throws Exception {
+ testFileChannel();
+ for (int i=0; i<testSizes.length; i++)
+ testReadableByteChannel(testSizes[i]);
+ xferTest02(); // for bug 4482726
+ xferTest03(); // for bug 4559072
+ xferTest04(); // for bug 4638365
+ xferTest05(); // for bug 4638365
+ xferTest06(); // for bug 5081340
+ xferTest07(); // for bug 5103988
+ xferTest08(); // for bug 6253145
+ }
+
+ private static void testFileChannel() throws Exception {
+ File source = File.createTempFile("source", null);
+ source.deleteOnExit();
+ File sink = File.createTempFile("sink", null);
+ sink.deleteOnExit();
+
+ FileOutputStream fos = new FileOutputStream(source);
+ FileChannel sourceChannel = fos.getChannel();
+ sourceChannel.write(ByteBuffer.wrap(
+ "Use the source, Luke!".getBytes()));
+ sourceChannel.close();
+
+ FileInputStream fis = new FileInputStream(source);
+ sourceChannel = fis.getChannel();
+
+ RandomAccessFile raf = new RandomAccessFile(sink, "rw");
+ FileChannel sinkChannel = raf.getChannel();
+ long oldSinkPosition = sinkChannel.position();
+ long oldSourcePosition = sourceChannel.position();
+
+ long bytesWritten = sinkChannel.transferFrom(sourceChannel, 0, 10);
+ if (bytesWritten != 10)
+ throw new RuntimeException("Transfer failed");
+
+ if (sourceChannel.position() == oldSourcePosition)
+ throw new RuntimeException("Source position didn't change");
+
+ if (sinkChannel.position() != oldSinkPosition)
+ throw new RuntimeException("Sink position changed");
+
+ if (sinkChannel.size() != 10)
+ throw new RuntimeException("Unexpected sink size");
+
+ bytesWritten = sinkChannel.transferFrom(sourceChannel, 1000, 10);
+
+ if (bytesWritten > 0)
+ throw new RuntimeException("Wrote past file size");
+
+ sourceChannel.close();
+ sinkChannel.close();
+ }
+
+ private static void testReadableByteChannel(int size) throws Exception {
+ SelectorProvider sp = SelectorProvider.provider();
+ Pipe p = sp.openPipe();
+ Pipe.SinkChannel sink = p.sink();
+ Pipe.SourceChannel source = p.source();
+ sink.configureBlocking(false);
+
+ ByteBuffer outgoingdata = ByteBuffer.allocateDirect(size + 10);
+ byte[] someBytes = new byte[size + 10];
+ generator.nextBytes(someBytes);
+ outgoingdata.put(someBytes);
+ outgoingdata.flip();
+
+ int totalWritten = 0;
+ while (totalWritten < size + 10) {
+ int written = sink.write(outgoingdata);
+ if (written < 0)
+ throw new Exception("Write failed");
+ totalWritten += written;
+ }
+
+ File f = File.createTempFile("blah"+size, null);
+ f.deleteOnExit();
+ RandomAccessFile raf = new RandomAccessFile(f, "rw");
+ FileChannel fc = raf.getChannel();
+ long oldPosition = fc.position();
+
+ long bytesWritten = fc.transferFrom(source, 0, size);
+ fc.force(true);
+ if (bytesWritten != size)
+ throw new RuntimeException("Transfer failed");
+
+ if (fc.position() != oldPosition)
+ throw new RuntimeException("Position changed");
+
+ if (fc.size() != size)
+ throw new RuntimeException("Unexpected sink size "+ fc.size());
+
+ fc.close();
+ sink.close();
+ source.close();
+ }
+
+ public static void xferTest02() throws Exception {
+ byte[] srcData = new byte[5000];
+ for (int i=0; i<5000; i++)
+ srcData[i] = (byte)generator.nextInt();
+
+ // get filechannel for the source file.
+ File source = File.createTempFile("source", null);
+ source.deleteOnExit();
+ RandomAccessFile raf1 = new RandomAccessFile(source, "rw");
+ FileChannel fc1 = raf1.getChannel();
+
+ // write out data to the file channel
+ long bytesWritten = 0;
+ while (bytesWritten < 5000) {
+ bytesWritten = fc1.write(ByteBuffer.wrap(srcData));
+ }
+
+ // get filechannel for the dst file.
+ File dest = File.createTempFile("dest", null);
+ dest.deleteOnExit();
+ RandomAccessFile raf2 = new RandomAccessFile(dest, "rw");
+ FileChannel fc2 = raf2.getChannel();
+
+ int bytesToWrite = 3000;
+ int startPosition = 1000;
+
+ bytesWritten = fc1.transferTo(startPosition, bytesToWrite, fc2);
+
+ fc1.close();
+ fc2.close();
+ raf1.close();
+ raf2.close();
+ }
+
+ public static void xferTest03() throws Exception {
+ byte[] srcData = new byte[] {1,2,3,4} ;
+
+ // get filechannel for the source file.
+ File source = File.createTempFile("source", null);
+ source.deleteOnExit();
+ RandomAccessFile raf1 = new RandomAccessFile(source, "rw");
+ FileChannel fc1 = raf1.getChannel();
+ fc1.truncate(0);
+
+ // write out data to the file channel
+ int bytesWritten = 0;
+ while (bytesWritten < 4) {
+ bytesWritten = fc1.write(ByteBuffer.wrap(srcData));
+ }
+
+ // get filechannel for the dst file.
+ File dest = File.createTempFile("dest", null);
+ dest.deleteOnExit();
+ RandomAccessFile raf2 = new RandomAccessFile(dest, "rw");
+ FileChannel fc2 = raf2.getChannel();
+ fc2.truncate(0);
+
+ fc1.transferTo(0, srcData.length + 1, fc2);
+
+ if (fc2.size() > 4)
+ throw new Exception("xferTest03 failed");
+
+ fc1.close();
+ fc2.close();
+ raf1.close();
+ raf2.close();
+ }
+
+ // Test transferTo with large file
+ public static void xferTest04() throws Exception {
+ // Windows and Linux can't handle the really large file sizes for a
+ // truncate or a positional write required by the test for 4563125
+ String osName = System.getProperty("os.name");
+ if (!osName.startsWith("SunOS"))
+ return;
+
+ File source = File.createTempFile("blah", null);
+ source.deleteOnExit();
+ long testSize = ((long)Integer.MAX_VALUE) * 2;
+ initTestFile(source, 10);
+ RandomAccessFile raf = new RandomAccessFile(source, "rw");
+ FileChannel fc = raf.getChannel();
+ fc.write(ByteBuffer.wrap("Use the source!".getBytes()), testSize - 40);
+ fc.close();
+ raf.close();
+
+ File sink = File.createTempFile("sink", null);
+ sink.deleteOnExit();
+
+ FileInputStream fis = new FileInputStream(source);
+ FileChannel sourceChannel = fis.getChannel();
+
+ raf = new RandomAccessFile(sink, "rw");
+ FileChannel sinkChannel = raf.getChannel();
+
+ long bytesWritten = sourceChannel.transferTo(testSize -40, 10,
+ sinkChannel);
+ if (bytesWritten != 10) {
+ throw new RuntimeException("Transfer test 4 failed " +
+ bytesWritten);
+ }
+ sourceChannel.close();
+ sinkChannel.close();
+
+ }
+
+ // Test transferFrom with large file
+ public static void xferTest05() throws Exception {
+ // Linux can't handle the really large file sizes for a
+ // truncate or a positional write
+ String osName = System.getProperty("os.name");
+ if (osName.startsWith("Linux"))
+ return;
+
+ // Create a source file & large sink file for the test
+ File source = File.createTempFile("blech", null);
+ source.deleteOnExit();
+ initTestFile(source, 100);
+
+ File sink = File.createTempFile("sink", null);
+ sink.deleteOnExit();
+
+ long testSize = ((long)Integer.MAX_VALUE) * 2;
+ RandomAccessFile raf = new RandomAccessFile(sink, "rw");
+ FileChannel fc = raf.getChannel();
+ try {
+ fc.write(ByteBuffer.wrap("Use the source!".getBytes()),
+ testSize - 40);
+ } catch (IOException e) {
+ // Can't set up the test, abort it
+ System.err.println("xferTest05 was aborted.");
+ return;
+ } finally {
+ fc.close();
+ raf.close();
+ }
+
+ // Get new channels for the source and sink and attempt transfer
+ FileInputStream fis = new FileInputStream(source);
+ FileChannel sourceChannel = fis.getChannel();
+
+ raf = new RandomAccessFile(sink, "rw");
+ FileChannel sinkChannel = raf.getChannel();
+
+ long bytesWritten = sinkChannel.transferFrom(sourceChannel,
+ testSize - 40, 10);
+ if (bytesWritten != 10) {
+ throw new RuntimeException("Transfer test 5 failed " +
+ bytesWritten);
+ }
+ sourceChannel.close();
+ sinkChannel.close();
+ }
+
+ static void checkFileData(File file, String expected) throws Exception {
+ FileInputStream fis = new FileInputStream(file);
+ Reader r = new BufferedReader(new InputStreamReader(fis, "ASCII"));
+ StringBuilder sb = new StringBuilder();
+ int c;
+ while ((c = r.read()) != -1)
+ sb.append((char)c);
+ String contents = sb.toString();
+ if (! contents.equals(expected))
+ throw new Exception("expected: " + expected
+ + ", got: " + contents);
+ r.close();
+ }
+
+ // Test transferFrom asking for more bytes than remain in source
+ public static void xferTest06() throws Exception {
+ String data = "Use the source, Luke!";
+
+ File source = File.createTempFile("source", null);
+ source.deleteOnExit();
+ File sink = File.createTempFile("sink", null);
+ sink.deleteOnExit();
+
+ FileOutputStream fos = new FileOutputStream(source);
+ fos.write(data.getBytes("ASCII"));
+ fos.close();
+
+ FileChannel sourceChannel =
+ new RandomAccessFile(source, "rw").getChannel();
+ sourceChannel.position(7);
+ long remaining = sourceChannel.size() - sourceChannel.position();
+ FileChannel sinkChannel =
+ new RandomAccessFile(sink, "rw").getChannel();
+ long n = sinkChannel.transferFrom(sourceChannel, 0L,
+ sourceChannel.size()); // overflow
+ if (n != remaining)
+ throw new Exception("n == " + n + ", remaining == " + remaining);
+
+ sinkChannel.close();
+ sourceChannel.close();
+
+ checkFileData(source, data);
+ checkFileData(sink, data.substring(7,data.length()));
+ }
+
+ // Test transferTo to non-blocking socket channel
+ public static void xferTest07() throws Exception {
+ File source = File.createTempFile("source", null);
+ source.deleteOnExit();
+
+ FileChannel sourceChannel = new RandomAccessFile(source, "rw")
+ .getChannel();
+ sourceChannel.position(32000L)
+ .write(ByteBuffer.wrap("The End".getBytes()));
+
+ // The sink is a non-blocking socket channel
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(new InetSocketAddress(0));
+ InetSocketAddress sa = new InetSocketAddress(
+ InetAddress.getLocalHost(), ssc.socket().getLocalPort());
+ SocketChannel sink = SocketChannel.open(sa);
+ sink.configureBlocking(false);
+ SocketChannel other = ssc.accept();
+
+ long size = sourceChannel.size();
+
+ // keep sending until congested
+ long n;
+ do {
+ n = sourceChannel.transferTo(0, size, sink);
+ } while (n > 0);
+
+ sourceChannel.close();
+ sink.close();
+ other.close();
+ ssc.close();
+ }
+
+
+ // Test transferTo with file positions larger than 2 and 4GB
+ public static void xferTest08() throws Exception {
+ // Creating a sparse 6GB file on Windows takes too long
+ String osName = System.getProperty("os.name");
+ if (osName.startsWith("Windows"))
+ return;
+
+ final long G = 1024L * 1024L * 1024L;
+
+ // Create 6GB file
+
+ File file = File.createTempFile("source", null);
+ file.deleteOnExit();
+
+ RandomAccessFile raf = new RandomAccessFile(file, "rw");
+ FileChannel fc = raf.getChannel();
+
+ try {
+ fc.write(ByteBuffer.wrap("0123456789012345".getBytes("UTF-8")), 6*G);
+ } catch (IOException x) {
+ System.err.println("Unable to create test file:" + x);
+ fc.close();
+ return;
+ }
+
+ // Setup looback connection and echo server
+
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(new InetSocketAddress(0));
+
+ InetAddress lh = InetAddress.getLocalHost();
+ InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort());
+ SocketChannel source = SocketChannel.open(isa);
+ SocketChannel sink = ssc.accept();
+
+ Thread thr = new Thread(new EchoServer(sink));
+ thr.start();
+
+ // Test data is array of positions and counts
+
+ long testdata[][] = {
+ { 2*G-1, 1 },
+ { 2*G-1, 10 }, // across 2GB boundary
+ { 2*G, 1 },
+ { 2*G, 10 },
+ { 2*G+1, 1 },
+ { 4*G-1, 1 },
+ { 4*G-1, 10 }, // across 4GB boundary
+ { 4*G, 1 },
+ { 4*G, 10 },
+ { 4*G+1, 1 },
+ { 5*G-1, 1 },
+ { 5*G-1, 10 },
+ { 5*G, 1 },
+ { 5*G, 10 },
+ { 5*G+1, 1 },
+ { 6*G, 1 },
+ };
+
+ ByteBuffer sendbuf = ByteBuffer.allocateDirect(100);
+ ByteBuffer readbuf = ByteBuffer.allocateDirect(100);
+
+ try {
+ byte value = 0;
+ for (int i=0; i<testdata.length; i++) {
+ long position = testdata[(int)i][0];
+ long count = testdata[(int)i][1];
+
+ // generate bytes
+ for (long j=0; j<count; j++) {
+ sendbuf.put(++value);
+ }
+ sendbuf.flip();
+
+ // write to file and transfer to echo server
+ fc.write(sendbuf, position);
+ fc.transferTo(position, count, source);
+
+ // read from echo server
+ long nread = 0;
+ while (nread < count) {
+ int n = source.read(readbuf);
+ if (n < 0)
+ throw new RuntimeException("Premature EOF!");
+ nread += n;
+ }
+
+ // check reply from echo server
+ readbuf.flip();
+ sendbuf.flip();
+ if (!readbuf.equals(sendbuf))
+ throw new RuntimeException("Echo'ed bytes do not match!");
+ readbuf.clear();
+ sendbuf.clear();
+ }
+ } finally {
+ source.close();
+ ssc.close();
+ fc.close();
+ }
+ }
+
+ /**
+ * Creates file blah of specified size in bytes.
+ */
+ private static void initTestFile(File blah, long size) throws Exception {
+ if (blah.exists())
+ blah.delete();
+ FileOutputStream fos = new FileOutputStream(blah);
+ BufferedWriter awriter
+ = new BufferedWriter(new OutputStreamWriter(fos, "8859_1"));
+
+ for(int i=0; i<size; i++) {
+ awriter.write("e");
+ }
+ awriter.flush();
+ awriter.close();
+ }
+
+ /**
+ * Simple in-process server to echo bytes read by a given socket channel
+ */
+ static class EchoServer implements Runnable {
+ private SocketChannel sc;
+
+ public EchoServer(SocketChannel sc) {
+ this.sc = sc;
+ }
+
+ public void run() {
+ ByteBuffer bb = ByteBuffer.allocateDirect(1024);
+ try {
+ for (;;) {
+ int n = sc.read(bb);
+ if (n < 0)
+ break;
+
+ bb.flip();
+ while (bb.remaining() > 0) {
+ sc.write(bb);
+ }
+ bb.clear();
+ }
+ } catch (IOException x) {
+ x.printStackTrace();
+ } finally {
+ try {
+ sc.close();
+ } catch (IOException ignore) { }
+ }
+ }
+ }
+
+}
diff --git a/test/java/nio/channels/FileChannel/TransferToChannel.java b/test/java/nio/channels/FileChannel/TransferToChannel.java
new file mode 100644
index 0000000..506a259
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/TransferToChannel.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4652496
+ * @summary Test transferTo with different target channels
+ */
+
+import java.nio.channels.FileChannel;
+import java.nio.channels.WritableByteChannel;
+import java.nio.ByteBuffer;
+import java.io.*;
+import java.util.Random;
+
+public class TransferToChannel {
+
+ static File file;
+ static File outFile;
+ static FileChannel in;
+ // Chunk size should be larger than FileChannelImpl.TRANSFER_SIZE for good test
+ static int CHUNK_SIZE = 1024 * 9;
+
+ public static void main(String[] args) throws Exception {
+ file = File.createTempFile("readingin", null);
+ outFile = File.createTempFile("writingout", null);
+ file.deleteOnExit();
+ outFile.deleteOnExit();
+ generateBigFile(file);
+ FileInputStream fis = new FileInputStream(file);
+ in = fis.getChannel();
+ test1();
+ test2();
+ in.close();
+ }
+
+ static void test1() throws Exception {
+ for (int i=0; i<10; i++) {
+ transferFileToUserChannel();
+ System.gc();
+ System.err.println("Transferred file...");
+ }
+ }
+
+ static void test2() throws Exception {
+ for (int i=0; i<10; i++) {
+ transferFileToTrustedChannel();
+ System.gc();
+ System.err.println("Transferred file...");
+ }
+ }
+
+ static void transferFileToUserChannel() throws Exception {
+ long remainingBytes = in.size();
+ long size = remainingBytes;
+ WritableByteChannel wbc = new WritableByteChannel() {
+ Random rand = new Random(0);
+ public int write(ByteBuffer src) throws IOException {
+ int read = src.remaining();
+ byte[] incoming = new byte[read];
+ src.get(incoming);
+ checkData(incoming, read);
+ return read == 0 ? -1 : read;
+ }
+ public boolean isOpen() {
+ return true;
+ }
+ public void close() throws IOException {
+ }
+ void checkData(byte[] incoming, int size) {
+ byte[] expected = new byte[size];
+ rand.nextBytes(expected);
+ for (int i=0; i<size; i++)
+ if (incoming[i] != expected[i])
+ throw new RuntimeException("Data corrupted");
+ }
+ };
+ while (remainingBytes > 0) {
+ long bytesTransferred = in.transferTo(size - remainingBytes,
+ Math.min(CHUNK_SIZE, remainingBytes), wbc);
+ if (bytesTransferred >= 0)
+ remainingBytes -= bytesTransferred;
+ else
+ throw new Exception("transfer failed");
+ }
+ }
+
+ static void transferFileToTrustedChannel() throws Exception {
+ long remainingBytes = in.size();
+ long size = remainingBytes;
+ FileOutputStream fos = new FileOutputStream(outFile);
+ FileChannel out = fos.getChannel();
+ while (remainingBytes > 0) {
+ long bytesTransferred = in.transferTo(size - remainingBytes,
+ CHUNK_SIZE, out);
+ if (bytesTransferred >= 0)
+ remainingBytes -= bytesTransferred;
+ else
+ throw new Exception("transfer failed");
+ }
+ out.close();
+ }
+
+ static void generateBigFile(File file) throws Exception {
+ OutputStream out = new BufferedOutputStream(
+ new FileOutputStream(file));
+ byte[] randomBytes = new byte[1024];
+ Random rand = new Random(0);
+ for (int i = 0; i < 1000; i++) {
+ rand.nextBytes(randomBytes);
+ out.write(randomBytes);
+ }
+ out.flush();
+ out.close();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/TransferToNonWritable.java b/test/java/nio/channels/FileChannel/TransferToNonWritable.java
new file mode 100644
index 0000000..8f0ea34
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/TransferToNonWritable.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4732777
+ * @summary Test if transferTo throws right exceptions
+ */
+
+import java.io.*;
+import java.nio.channels.*;
+
+
+public class TransferToNonWritable {
+
+ public static void main(String args[]) throws Exception {
+ File blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+
+ FileInputStream fis = new FileInputStream(blah);
+ FileChannel channel = fis.getChannel();
+ try {
+ channel.transferTo((long)0, (long)2, channel);
+ throw new RuntimeException("Test failed");
+ } catch (NonWritableChannelException nwce) {
+ // Correct result
+ }
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/Transfers.java b/test/java/nio/channels/FileChannel/Transfers.java
new file mode 100644
index 0000000..e3b3286
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Transfers.java
@@ -0,0 +1,564 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Comprehensive test for FileChannel.transfer{From,To}
+ * @bug 4708120
+ * @author Mark Reinhold
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.util.*;
+
+
+public class Transfers {
+
+ static PrintStream out = System.out;
+
+ private static class Failure
+ extends RuntimeException
+ {
+
+ Failure(Exception x) {
+ super(x);
+ }
+
+ Failure(String s) {
+ super(s);
+ }
+
+ }
+
+
+ // -- Writing and reading random bytes --
+
+ private static void writeBytes(byte[] ba, FileChannel fc,
+ int off, int len)
+ throws IOException
+ {
+ fc.position(off);
+ if (fc.write(ByteBuffer.wrap(ba, 0, len)) != len)
+ throw new IOException("Incomplete write");
+ fc.position(0);
+ }
+
+ private static void writeRandomBytes(long seed,
+ FileChannel fc, int off, int len)
+ throws IOException
+ {
+ Random r = new Random(seed);
+ byte[] ba = new byte[len];
+ r.nextBytes(ba);
+ writeBytes(ba, fc, off, len);
+ }
+
+ private static void writeZeroBytes(FileChannel fc, int off, int len)
+ throws IOException
+ {
+ byte[] ba = new byte[len];
+ writeBytes(ba, fc, off, len);
+ }
+
+ private static void checkBytes(FileChannel fc, int off, int len,
+ byte[] bytes)
+ throws IOException
+ {
+ ByteBuffer bb = ByteBuffer.allocate(len);
+ fc.position(off);
+ if (fc.read(bb) != len)
+ throw new IOException("Incomplete read");
+ bb.flip();
+ ByteBuffer bab = ByteBuffer.wrap(bytes, 0, len);
+ if (!bb.equals(bab))
+ throw new Failure("Wrong data written");
+ }
+
+ private static void checkRandomBytes(FileChannel fc, int off, int len,
+ long seed)
+ throws IOException
+ {
+ byte[] ba = new byte[len];
+ Random r = new Random(seed);
+ r.nextBytes(ba);
+ checkBytes(fc, off, len, ba);
+ }
+
+ private static void checkZeroBytes(FileChannel fc, int off, int len)
+ throws IOException
+ {
+ byte[] ba = new byte[len];
+ checkBytes(fc, off, len, ba);
+ }
+
+ // For debugging
+ //
+ private static void dump(FileChannel fc)
+ throws IOException
+ {
+ int sz = (int)fc.size();
+ ByteBuffer bb = ByteBuffer.allocate(sz);
+ fc.position(0);
+ if (fc.read(bb) != sz)
+ throw new IOException("Incomplete read");
+ bb.flip();
+ byte prev = -1;
+ int r = 0; // Repeats
+ int n = 0;
+ while (bb.hasRemaining() && (n < 32)) {
+ byte b = bb.get();
+ if (b == prev) {
+ r++;
+ continue;
+ }
+ if (r > 0) {
+ int c = prev & 0xff;
+ if (c < 0x10)
+ out.print('0');
+ out.print(Integer.toHexString(c));
+ if (r > 1) {
+ out.print("[");
+ out.print(r);
+ out.print("]");
+ }
+ n++;
+ }
+ prev = b;
+ r = 1;
+ }
+ if (r > 0) {
+ int c = prev & 0xff;
+ if (c < 0x10)
+ out.print('0');
+ out.print(Integer.toHexString(c));
+ if (r > 1) {
+ out.print("[");
+ out.print(r);
+ out.print("]");
+ }
+ n++;
+ }
+ if (bb.hasRemaining())
+ out.print("...");
+ out.println();
+ }
+
+
+
+ static File sourceFile;
+ static File targetFile;
+
+ // -- Self-verifying sources and targets --
+
+ static abstract class Source {
+
+ protected final int size;
+ protected final long seed;
+ private final String name;
+
+ Source(int size, long seed, String name) {
+ this.size = size;
+ this.seed = seed;
+ this.name = name;
+ }
+
+ String name() {
+ return name;
+ }
+
+ abstract ReadableByteChannel channel();
+
+ abstract void verify() throws IOException;
+
+ }
+
+ static class FileSource
+ extends Source
+ {
+ private final File fn;
+ private final RandomAccessFile raf;
+ private final FileChannel fc;
+
+ FileSource(int size, long seed) throws IOException {
+ super(size, seed, "FileChannel");
+ fn = sourceFile;
+ raf = new RandomAccessFile(fn, "rw");
+ fc = raf.getChannel();
+ fc.position(0);
+ writeRandomBytes(seed, fc, 0, size);
+ }
+
+ ReadableByteChannel channel() {
+ return fc;
+ }
+
+ void verify() throws IOException {
+ if (fc.position() != size)
+ throw new Failure("Wrong position: "
+ + fc.position() + " (expected " + size +
+ ")");
+ checkRandomBytes(fc, 0, size, seed);
+ fc.close();
+ raf.close(); // Bug in 1.4.0
+ }
+
+ }
+
+ static class UserSource
+ extends Source
+ {
+ private ReadableByteChannel ch;
+ private final ByteBuffer src;
+
+ UserSource(int size, long seed) {
+ super(size, seed, "UserChannel");
+
+ final byte[] bytes = new byte[size + 1];
+ Random r = new Random(seed);
+ r.nextBytes(bytes);
+ src = ByteBuffer.wrap(bytes);
+
+ ch = new ReadableByteChannel() {
+ public int read(ByteBuffer dst) {
+ if (!src.hasRemaining())
+ return -1;
+ int nr = Math.min(src.remaining(), dst.remaining());
+ ByteBuffer s = src.duplicate();
+ s.limit(s.position() + nr);
+ dst.put(s);
+ src.position(src.position() + nr);
+ return nr;
+ }
+ public boolean isOpen() {
+ return true;
+ }
+ public void close() { }
+ };
+ }
+
+ ReadableByteChannel channel() {
+ return ch;
+ }
+
+ void verify() {
+ if (src.remaining() != 1)
+ throw new Failure("Source has " + src.remaining()
+ + " bytes remaining (expected 1)");
+ }
+
+ }
+
+ static abstract class Target {
+
+ protected final int size;
+ protected final long seed;
+ private final String name;
+
+ Target(int size, long seed, String name) {
+ this.size = size;
+ this.seed = seed;
+ this.name = name;
+ }
+
+ String name() {
+ return name;
+ }
+
+ abstract WritableByteChannel channel();
+
+ abstract void verify() throws IOException;
+
+ }
+
+ static class FileTarget
+ extends Target
+ {
+ private final File fn;
+ private final RandomAccessFile raf;
+ private final FileChannel fc;
+
+ FileTarget(int size, long seed) throws IOException {
+ super(size, seed, "FileChannel");
+ fn = targetFile;
+ raf = new RandomAccessFile(fn, "rw");
+ fc = raf.getChannel();
+ fc.position(0);
+ }
+
+ WritableByteChannel channel() {
+ return fc;
+ }
+
+ void verify() throws IOException {
+ if (fc.position() != size)
+ throw new Failure("Wrong position: "
+ + fc.position() + " (expected " + size + ")");
+ checkRandomBytes(fc, 0, size, seed);
+ fc.close();
+ raf.close(); // Bug in 1.4.0
+ }
+
+ }
+
+ static class UserTarget
+ extends Target
+ {
+ private WritableByteChannel ch;
+ private final ByteBuffer dst;
+
+ UserTarget(int size, long seed) {
+ super(size, seed, "UserChannel");
+ dst = ByteBuffer.wrap(new byte[size + 1]);
+
+ ch = new WritableByteChannel() {
+ public int write(ByteBuffer src) {
+ int nr = Math.min(src.remaining(), dst.remaining());
+ ByteBuffer s = src.duplicate();
+ s.limit(s.position() + nr);
+ dst.put(s);
+ src.position(src.position() + nr);
+ return nr;
+ }
+ public boolean isOpen() {
+ return true;
+ }
+ public void close() { }
+ };
+ }
+
+ WritableByteChannel channel() {
+ return ch;
+ }
+
+ void verify() {
+ if (dst.remaining() != 1)
+ throw new Failure("Destination has " + dst.remaining()
+ + " bytes remaining (expected 1)");
+ byte[] ba = new byte[size];
+ Random r = new Random(seed);
+ r.nextBytes(ba);
+ dst.flip();
+ ByteBuffer rbb = ByteBuffer.wrap(ba, 0, size);
+ if (!dst.equals(rbb))
+ throw new Failure("Wrong data written");
+ }
+
+ }
+
+
+ // Generates a sequence of ints of the form 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+ // 15, 16, 17, 31, 32, 33, ..., 2^i-1, 2^i, 2^i+1, ..., max.
+
+ static class IntGenerator {
+
+ private int max;
+ private int cur = -1;
+ private int p2 = 8;
+
+ IntGenerator(int max) {
+ this.max = max;
+ }
+
+ boolean hasNext() {
+ return cur < max;
+ }
+
+ int next() {
+ if (cur >= max)
+ throw new IllegalStateException();
+ if (cur < 6) {
+ cur++;
+ return cur;
+ }
+ if (cur == p2 + 1) {
+ p2 <<= 1;
+ cur = p2 - 1;
+ return cur;
+ }
+ cur++;
+ return cur;
+ }
+
+ }
+
+
+ // -- Tests --
+
+ private static final int MAX_XFER_SIZE = 1 << 14;
+ private static final int MAX_FILE_SIZE = MAX_XFER_SIZE << 1;
+
+ private static boolean debug = false;
+ private static boolean verbose = false;
+
+ static void show(String dir, String channelName, int off, int len) {
+ if (!verbose)
+ return;
+ out.println(dir + " " + channelName +
+ ": offset " + off + ", length " + len);
+ }
+
+ static void testTo(long seed, FileChannel fc, int off, int len, Target tgt)
+ throws IOException
+ {
+ show("To", tgt.name(), off, len);
+
+ // Clear source, then randomize just the source region
+ writeZeroBytes(fc, 0, MAX_FILE_SIZE);
+ writeRandomBytes(seed, fc, off, len);
+
+ // Randomize position
+ int pos = (int)seed & 0xfff;
+ fc.position(pos);
+
+ int n = (int)fc.transferTo(off, len, tgt.channel());
+ if (n != len)
+ throw new Failure("Incorrect transfer length: " + n
+ + " (expected " + len + ")");
+
+ // Check that source wasn't changed
+ if (fc.position() != pos)
+ throw new Failure("Position changed");
+ if (debug)
+ dump(fc);
+ checkRandomBytes(fc, off, len, seed);
+ writeZeroBytes(fc, off, len);
+ checkZeroBytes(fc, 0, MAX_FILE_SIZE);
+
+ // Check that target was updated correctly
+ tgt.verify();
+ }
+
+ static void testFrom(long seed, Source src, FileChannel fc, int off, int len)
+ throws IOException
+ {
+ show("From", src.name(), off, len);
+
+ // Clear target
+ writeZeroBytes(fc, 0, MAX_FILE_SIZE);
+
+ // Randomize position
+ int pos = (int)seed & 0xfff;
+ fc.position(pos);
+
+ int n = (int)fc.transferFrom(src.channel(), off, len);
+ if (n != len)
+ throw new Failure("Incorrect transfer length: " + n
+ + " (expected " + len + ")");
+
+ // Check that source didn't change, and was read correctly
+ src.verify();
+
+ // Check that target was updated correctly
+ if (fc.position() != pos)
+ throw new Failure("Position changed");
+ if (debug)
+ dump(fc);
+ checkRandomBytes(fc, off, len, seed);
+ writeZeroBytes(fc, off, len);
+ checkZeroBytes(fc, 0, MAX_FILE_SIZE);
+ }
+
+ public static void main(String[] args)
+ throws Exception
+ {
+ if (args.length > 0) {
+ if (args[0].indexOf('v') >= 0)
+ verbose = true;
+ if (args[0].indexOf('d') >= 0)
+ debug = verbose = true;
+ }
+
+ sourceFile = File.createTempFile("xfer.src.", "");
+ sourceFile.deleteOnExit();
+ targetFile = File.createTempFile("xfer.tgt.", "");
+ targetFile.deleteOnExit();
+
+ File fn = File.createTempFile("xfer.fch.", "");
+ fn.deleteOnExit();
+ FileChannel fc = new RandomAccessFile(fn, "rw").getChannel();
+
+ Random rnd = new Random();
+ int failures = 0;
+
+ for (boolean to = false;; to = true) {
+ for (boolean user = false;; user = true) {
+ if (!verbose)
+ out.print((to ? "To " : "From ") +
+ (user ? "user channel" : "file channel")
+ + ":");
+ IntGenerator offGen = new IntGenerator(MAX_XFER_SIZE + 2);
+ while (offGen.hasNext()) {
+ int off = offGen.next();
+ if (!verbose) out.print(" " + off);
+ IntGenerator lenGen = new IntGenerator(MAX_XFER_SIZE + 2);
+ while (lenGen.hasNext()) {
+ int len = lenGen.next();
+ long s = rnd.nextLong();
+ String chName = null;
+ try {
+ if (to) {
+ Target tgt;
+ if (user)
+ tgt = new UserTarget(len, s);
+ else
+ tgt = new FileTarget(len, s);
+ chName = tgt.name();
+ testTo(s, fc, off, len, tgt);
+ }
+ else {
+ Source src;
+ if (user)
+ src = new UserSource(len, s);
+ else
+ src = new FileSource(len, s);
+ chName = src.name();
+ testFrom(s, src, fc, off, len);
+ }
+ } catch (Failure x) {
+ out.println();
+ out.println("FAILURE: " + chName
+ + ", offset " + off
+ + ", length " + len);
+ x.printStackTrace(out);
+ failures++;
+ }
+ }
+ }
+ if (!verbose)
+ out.println();
+ if (user)
+ break;
+ }
+ if (to)
+ break;
+ }
+
+ if (failures > 0) {
+ out.println();
+ throw new RuntimeException("Some tests failed");
+ }
+
+ }
+
+}
diff --git a/test/java/nio/channels/FileChannel/Truncate.java b/test/java/nio/channels/FileChannel/Truncate.java
new file mode 100644
index 0000000..f2bd4f4
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Truncate.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 6191269
+ * @summary Test truncate method of FileChannel
+ */
+
+import java.io.*;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.*;
+import java.nio.channels.FileChannel;
+import java.util.Random;
+
+
+/**
+ * Testing FileChannel's truncate method.
+ */
+
+public class Truncate {
+
+ private static Random generator = new Random();
+
+ private static File blah;
+
+ public static void main(String[] args) throws Exception {
+ blah = File.createTempFile("blah", null);
+ blah.deleteOnExit();
+ for(int i=0; i<100; i++) {
+ long testSize = generator.nextInt(1000) + 10;
+ initTestFile(blah, testSize);
+ RandomAccessFile fis = new RandomAccessFile(blah, "rw");
+ FileChannel c = fis.getChannel();
+ if (c.size() != testSize)
+ throw new RuntimeException("Size failed");
+
+ long position = generator.nextInt((int)testSize);
+ c.position(position);
+
+ long newSize = generator.nextInt((int)testSize);
+ c.truncate(newSize);
+
+ if (c.size() != newSize)
+ throw new RuntimeException("Truncate failed");
+
+ if (position > newSize) {
+ if (c.position() != newSize)
+ throw new RuntimeException("Position greater than size");
+ } else {
+ if (c.position() != position)
+ throw new RuntimeException("Truncate changed position");
+ }
+
+ c.close();
+ fis.close();
+ }
+ blah.delete();
+ }
+
+ /**
+ * Creates file blah of specified size in bytes.
+ *
+ */
+ private static void initTestFile(File blah, long size) throws Exception {
+ if (blah.exists())
+ blah.delete();
+ FileOutputStream fos = new FileOutputStream(blah);
+ BufferedWriter awriter
+ = new BufferedWriter(new OutputStreamWriter(fos, "8859_1"));
+
+ for(int i=0; i<size; i++) {
+ awriter.write("e");
+ }
+ awriter.flush();
+ awriter.close();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/TryLock.java b/test/java/nio/channels/FileChannel/TryLock.java
new file mode 100644
index 0000000..4d5b9a4
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/TryLock.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4486154 4495729
+ * @summary The FileChannel file locking
+ */
+
+import java.io.*;
+import java.nio.channels.*;
+import java.nio.*;
+
+/**
+ * Testing FileChannel's locking methods.
+ */
+
+public class TryLock {
+
+ public static void main(String[] args) throws Exception {
+ test1(true, true);
+ test1(false, true);
+ test1(true, false);
+ test1(false, false);
+
+ test2(true, true);
+ test2(false, true);
+ test2(true, false);
+ test2(false, false);
+
+ test3(true, true);
+ test3(false, true);
+ test3(true, false);
+ test3(false, false);
+ }
+
+ public static void test1(boolean shared, boolean trylock) throws Exception {
+ File testFile = File.createTempFile("test1", null);
+ testFile.deleteOnExit();
+ FileInputStream fis = new FileInputStream(testFile);
+ FileChannel fc = fis.getChannel();
+ FileLock fl = null;
+ try {
+ if (trylock)
+ fl = fc.tryLock(0, fc.size(), shared);
+ else
+ fl = fc.lock(0, fc.size(), shared);
+ if (!shared)
+ throw new RuntimeException("No exception thrown for test1");
+ } catch (NonWritableChannelException e) {
+ if (shared)
+ throw new RuntimeException("Exception thrown for wrong case test1");
+ } finally {
+ if (fl != null)
+ fl.release();
+ }
+ }
+
+ public static void test2(boolean shared, boolean trylock) throws Exception {
+ File testFile = File.createTempFile("test2", null);
+ testFile.deleteOnExit();
+ FileOutputStream fis = new FileOutputStream(testFile);
+ FileChannel fc = fis.getChannel();
+ FileLock fl = null;
+ try {
+ if (trylock)
+ fl = fc.tryLock(0, fc.size(), shared);
+ else
+ fl = fc.lock(0, fc.size(), shared);
+ if (shared)
+ throw new RuntimeException("No exception thrown for test2");
+ } catch (NonReadableChannelException e) {
+ if (!shared)
+ throw new RuntimeException("Exception thrown incorrectly for test2");
+ } finally {
+ if (fl != null)
+ fl.release();
+ }
+ }
+
+ public static void test3(boolean shared, boolean trylock) throws Exception {
+ File testFile = File.createTempFile("test3", null);
+ testFile.deleteOnExit();
+ RandomAccessFile fis = new RandomAccessFile(testFile, "rw");
+ FileChannel fc = fis.getChannel();
+ FileLock fl = null;
+ if (trylock)
+ fl = fc.tryLock(0, fc.size(), shared);
+ else
+ fl = fc.lock(0, fc.size(), shared);
+ fl.release();
+ }
+}
diff --git a/test/java/nio/channels/FileChannel/Write.java b/test/java/nio/channels/FileChannel/Write.java
new file mode 100644
index 0000000..1fec06e
--- /dev/null
+++ b/test/java/nio/channels/FileChannel/Write.java
@@ -0,0 +1,183 @@
+/*
+ * Copyright 2001-2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4475533 4698138 4638365 4796221
+ * @summary Test FileChannel write
+ */
+
+import java.nio.channels.*;
+import java.nio.*;
+import java.io.*;
+
+public class Write {
+
+ public static void main(String[] args) throws Exception {
+ test1(); // for bug 4475533
+ test2();
+ test3(); // for bug 4698138
+
+ // This test is not suitable for automated testing at this time.
+ // I am commenting it out but it will be easy to manually
+ // test for a regression in this area. See also 4796221.
+ //test4(); // for bug 4638365
+ }
+
+ // Test to see that offset > length does not throw exception
+ static void test1() throws Exception {
+ File testFile = File.createTempFile("test1", null);
+ testFile.deleteOnExit();
+
+ ByteBuffer[] dsts = new ByteBuffer[4];
+ for (int i=0; i<4; i++)
+ dsts[i] = ByteBuffer.allocateDirect(10);
+
+ FileOutputStream fos = new FileOutputStream(testFile);
+ FileChannel fc = fos.getChannel();
+ fc.write(dsts, 2, 1);
+ fos.close();
+ }
+
+ // Test to see that the appropriate buffers are updated
+ static void test2() throws Exception {
+ File testFile = File.createTempFile("test2", null);
+ testFile.deleteOnExit();
+ ByteBuffer[] srcs = new ByteBuffer[4];
+ for (int i=0; i<4; i++)
+ srcs[i] = ByteBuffer.allocateDirect(10);
+
+ srcs[0].put((byte)1); srcs[0].flip();
+ srcs[1].put((byte)2); srcs[1].flip();
+ srcs[2].put((byte)3); srcs[2].flip();
+ srcs[3].put((byte)4); srcs[3].flip();
+
+ FileOutputStream fos = new FileOutputStream(testFile);
+ FileChannel fc = fos.getChannel();
+ fc.write(srcs, 1, 2);
+ fos.close();
+
+ FileInputStream fis = new FileInputStream(testFile);
+ fc = fis.getChannel();
+ ByteBuffer bb = ByteBuffer.allocateDirect(10);
+ fc.read(bb);
+ bb.flip();
+ if (bb.get() != 2)
+ throw new RuntimeException("Write failure");
+ if (bb.get() != 3)
+ throw new RuntimeException("Write failure");
+ try {
+ bb.get();
+ throw new RuntimeException("Write failure");
+ } catch (BufferUnderflowException bufe) {
+ // correct result
+ }
+ fis.close();
+ }
+
+ // Test write to a negative position (bug 4698138).
+ static void test3() throws Exception {
+ File testFile = File.createTempFile("test1", null);
+ testFile.deleteOnExit();
+ ByteBuffer dst = ByteBuffer.allocate(10);
+ FileOutputStream fos = new FileOutputStream(testFile);
+ FileChannel fc = fos.getChannel();
+ try {
+ fc.write(dst, -1);
+ throw new RuntimeException("Expected IAE not thrown");
+ } catch (IllegalArgumentException iae) {
+ // Correct result
+ } finally {
+ fos.close();
+ }
+ }
+
+ private static final int TEST4_NUM_BUFFERS = 3;
+
+ private static final int TEST4_BUF_CAP = Integer.MAX_VALUE / 2;
+
+ /**
+ * Test to see that vector write can return > Integer.MAX_VALUE
+ *
+ * Note that under certain circumstances disk space problems occur
+ * with this test. It typically relies upon adequate disk space and/or
+ * a Solaris disk space optimization where empty files take up less
+ * space than their logical size.
+ *
+ * Note that if this test fails it is not necessarily a violation of
+ * spec: the value returned by fc.write can be smaller than the number
+ * of bytes requested to write. It is testing an optimization that allows
+ * for larger return values.
+ */
+ static void test4() throws Exception {
+ // Only works on 64 bit Solaris
+ String osName = System.getProperty("os.name");
+ if (!osName.startsWith("SunOS"))
+ return;
+ String dataModel = System.getProperty("sun.arch.data.model");
+ if (!dataModel.startsWith("64"))
+ return;
+
+ File testFile = File.createTempFile("test4", null);
+ testFile.deleteOnExit();
+
+ FileChannel[] fcs = new FileChannel[TEST4_NUM_BUFFERS];
+
+ ByteBuffer[] dsts = new ByteBuffer[TEST4_NUM_BUFFERS];
+ // Map these buffers from a file so we don't run out of memory
+ for (int i=0; i<TEST4_NUM_BUFFERS; i++) {
+ File f = File.createTempFile("test4." + i, null);
+ f.deleteOnExit();
+ prepTest4File(f);
+ FileInputStream fis = new FileInputStream(f);
+ FileChannel fc = fis.getChannel();
+ MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0,
+ TEST4_BUF_CAP);
+ dsts[i] = mbb;
+ }
+
+ FileOutputStream fos = new FileOutputStream(testFile);
+ FileChannel fc = fos.getChannel();
+ try {
+ long bytesWritten = fc.write(dsts);
+ if (bytesWritten < Integer.MAX_VALUE) {
+ // Note: this is not a violation of the spec
+ throw new RuntimeException("Test 4 failed but wrote " +
+ bytesWritten);
+ }
+ } finally {
+ fc.close();
+ fos.close();
+ }
+ }
+
+ static void prepTest4File(File blah) throws Exception {
+ RandomAccessFile raf = new RandomAccessFile(blah, "rw");
+ FileChannel fc = raf.getChannel();
+ fc.write(ByteBuffer.wrap("Use the source!".getBytes()),
+ TEST4_BUF_CAP);
+ fc.close();
+ raf.close();
+ }
+
+}
diff --git a/test/java/nio/channels/Pipe/EmptyRead.java b/test/java/nio/channels/Pipe/EmptyRead.java
new file mode 100644
index 0000000..f24fa9d
--- /dev/null
+++ b/test/java/nio/channels/Pipe/EmptyRead.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4494818
+ * @summary Test reading 0 bytes over a pipe
+ */
+
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
+
+/**
+ * Testing PipeChannel
+ */
+public class EmptyRead {
+ public static void main(String[] args) throws Exception {
+ SelectorProvider sp = SelectorProvider.provider();
+ Pipe p = sp.openPipe();
+ Pipe.SinkChannel sink = p.sink();
+ Pipe.SourceChannel source = p.source();
+
+ byte[] someBytes = new byte[0];
+ ByteBuffer outgoingdata = ByteBuffer.wrap(someBytes);
+
+ int totalWritten = 0;
+ int written = sink.write(outgoingdata);
+ if (written < 0)
+ throw new Exception("Write failed");
+
+ ByteBuffer incomingdata = ByteBuffer.allocateDirect(0);
+ int read = source.read(incomingdata);
+ if (read < 0)
+ throw new Exception("Read EOF");
+
+ sink.close();
+ source.close();
+ }
+}
diff --git a/test/java/nio/channels/Pipe/NonBlocking.java b/test/java/nio/channels/Pipe/NonBlocking.java
new file mode 100644
index 0000000..c2dc12a
--- /dev/null
+++ b/test/java/nio/channels/Pipe/NonBlocking.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2001-2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4458401
+ * @summary Ensure that the Pipe.{sink,source}() methods don't create
+ * superfluous channel objects
+ * @library ..
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+
+public class NonBlocking {
+
+ public static void main(String[] args) throws Exception {
+ test1();
+ }
+
+ static void test1() throws Exception {
+ Pipe p = Pipe.open();
+ p.sink().configureBlocking(false);
+ if (p.sink().isBlocking())
+ throw new Exception("Sink still blocking");
+ p.source().configureBlocking(false);
+ if (p.source().isBlocking())
+ throw new Exception("Source still blocking");
+ }
+
+}
diff --git a/test/java/nio/channels/Pipe/PipeChannel.java b/test/java/nio/channels/Pipe/PipeChannel.java
new file mode 100644
index 0000000..6f45eb2
--- /dev/null
+++ b/test/java/nio/channels/Pipe/PipeChannel.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test reading and writing from Pipes
+ */
+
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
+import java.util.Random;
+
+
+/**
+ * Testing PipeChannel
+ */
+public class PipeChannel {
+
+ private static Random generator = new Random();
+
+ public static void main(String[] args) throws Exception {
+ for (int x=0; x<100; x++) {
+ SelectorProvider sp = SelectorProvider.provider();
+ Pipe p = sp.openPipe();
+ Pipe.SinkChannel sink = p.sink();
+ Pipe.SourceChannel source = p.source();
+
+ ByteBuffer outgoingdata = ByteBuffer.allocateDirect(10);
+ byte[] someBytes = new byte[10];
+ generator.nextBytes(someBytes);
+ outgoingdata.put(someBytes);
+ outgoingdata.flip();
+
+ int totalWritten = 0;
+ while (totalWritten < 10) {
+ int written = sink.write(outgoingdata);
+ if (written < 0)
+ throw new Exception("Write failed");
+ totalWritten += written;
+ }
+
+ ByteBuffer incomingdata = ByteBuffer.allocateDirect(10);
+ int totalRead = 0;
+ do {
+ int bytesRead = source.read(incomingdata);
+ if (bytesRead > 0)
+ totalRead += bytesRead;
+ } while(totalRead < 10);
+
+ for(int i=0; i<10; i++)
+ if (outgoingdata.get(i) != incomingdata.get(i))
+ throw new Exception("Pipe failed");
+ sink.close();
+ source.close();
+ }
+ }
+}
diff --git a/test/java/nio/channels/Pipe/ScatteringRead.java b/test/java/nio/channels/Pipe/ScatteringRead.java
new file mode 100644
index 0000000..e16d0a9
--- /dev/null
+++ b/test/java/nio/channels/Pipe/ScatteringRead.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ @bug 4526754
+ * @summary Test Pipe scattering reads
+ */
+
+import java.nio.channels.*;
+import java.nio.*;
+import java.util.Random;
+
+public class ScatteringRead {
+
+ private static Random generator = new Random();
+
+ public static void main(String[] args) throws Exception {
+ scScatter();
+ }
+
+ private static void scScatter() throws Exception {
+ Pipe p = Pipe.open();
+ Pipe.SinkChannel sink = p.sink();
+ Pipe.SourceChannel source = p.source();
+ sink.configureBlocking(false);
+
+ ByteBuffer outgoingdata = ByteBuffer.allocateDirect(30);
+ byte[] someBytes = new byte[30];
+ generator.nextBytes(someBytes);
+ outgoingdata.put(someBytes);
+ outgoingdata.flip();
+
+ int totalWritten = 0;
+ while (totalWritten < 30) {
+ int written = sink.write(outgoingdata);
+ if (written < 0)
+ throw new Exception("Write failed");
+ totalWritten += written;
+ }
+
+ ByteBuffer[] bufs = new ByteBuffer[3];
+ for(int i=0; i<3; i++)
+ bufs[i] = ByteBuffer.allocateDirect(10);
+ long numBytesRead = source.read(bufs);
+ if (numBytesRead < 30)
+ throw new Exception("Pipe test failed");
+ sink.close();
+ source.close();
+ }
+
+}
diff --git a/test/java/nio/channels/Pipe/SelectPipe.java b/test/java/nio/channels/Pipe/SelectPipe.java
new file mode 100644
index 0000000..9971fbf
--- /dev/null
+++ b/test/java/nio/channels/Pipe/SelectPipe.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test selection of ready pipe
+ */
+
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
+import java.util.Random;
+
+/**
+ * Testing PipeChannel
+ */
+public class SelectPipe {
+
+ private static Random generator = new Random();
+
+ public static void main(String[] args) throws Exception {
+
+ SelectorProvider sp = SelectorProvider.provider();
+ Selector selector = Selector.open();
+ Pipe p = sp.openPipe();
+ Pipe.SinkChannel sink = p.sink();
+ Pipe.SourceChannel source = p.source();
+
+ source.configureBlocking(false);
+ sink.configureBlocking(false);
+
+ SelectionKey readkey = source.register(selector, SelectionKey.OP_READ);
+ SelectionKey writekey = sink.register(selector, SelectionKey.OP_WRITE);
+
+ ByteBuffer outgoingdata = ByteBuffer.allocateDirect(10);
+ byte[] someBytes = new byte[10];
+ generator.nextBytes(someBytes);
+ outgoingdata.put(someBytes);
+ outgoingdata.flip();
+
+ int totalWritten = 0;
+ while (totalWritten < 10) {
+ int written = sink.write(outgoingdata);
+ if (written < 0)
+ throw new Exception("Write failed");
+ totalWritten += written;
+ }
+
+ if (selector.select(1000) == 0) {
+ throw new Exception("test failed");
+ }
+
+ ByteBuffer incomingdata = ByteBuffer.allocateDirect(10);
+ int totalRead = 0;
+ do {
+ int bytesRead = source.read(incomingdata);
+ if (bytesRead > 0)
+ totalRead += bytesRead;
+ } while(totalRead < 10);
+
+ for(int i=0; i<10; i++)
+ if (outgoingdata.get(i) != incomingdata.get(i))
+ throw new Exception("Pipe failed");
+ sink.close();
+ source.close();
+ }
+}
diff --git a/test/java/nio/channels/SelectionKey/AtomicAttachTest.java b/test/java/nio/channels/SelectionKey/AtomicAttachTest.java
new file mode 100644
index 0000000..fe926d3
--- /dev/null
+++ b/test/java/nio/channels/SelectionKey/AtomicAttachTest.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 6436220
+ * @summary SelectionKey.attach should atomically set and return the attachment
+ */
+import java.nio.channels.*;
+import java.util.concurrent.atomic.*;
+
+public class AtomicAttachTest {
+ public static void main(String[] args) throws Exception {
+ Selector selector = Selector.open();
+ Pipe pipe = Pipe.open();
+ SelectableChannel channel = pipe.sink().configureBlocking(false);
+ final SelectionKey key = channel.register(selector, 0);
+ key.attach(new AtomicBoolean());
+
+ final AtomicInteger errorCount = new AtomicInteger();
+
+ Thread t = new Thread() {
+ public void run() {
+ AtomicBoolean att = new AtomicBoolean();
+ for (int i=0; i<(10*1000*1000); i++) {
+ att = (AtomicBoolean)key.attach(att);
+ // We should have exclusive ownership of att.
+ if (!att.compareAndSet(false, true) ||
+ !att.compareAndSet(true, false))
+ {
+ errorCount.incrementAndGet();
+ }
+ }
+ }
+ {
+ start();
+ run();
+ }
+ };
+
+ t.join();
+ int count = errorCount.get();
+ if (count > 0) {
+ throw new RuntimeException("Error count:" + count);
+ }
+ }
+}
diff --git a/test/java/nio/channels/Selector/Alias.java b/test/java/nio/channels/Selector/Alias.java
new file mode 100644
index 0000000..8be1505
--- /dev/null
+++ b/test/java/nio/channels/Selector/Alias.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2001-2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4513011
+ * @summary Registering and cancelling same fd many times
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.util.*;
+import java.nio.channels.spi.SelectorProvider;
+
+public class Alias {
+
+ static int success = 0;
+ static int LIMIT = 20; // Hangs after just 1 if problem is present
+
+ public static void main(String[] args) throws Exception {
+ test1();
+ }
+
+ public static void test1() throws Exception {
+ Selector selector = SelectorProvider.provider().openSelector();
+ InetAddress myAddress=InetAddress.getByName(TestUtil.HOST);
+ InetSocketAddress isa = new InetSocketAddress(myAddress,13);
+
+ for (int j=0; j<LIMIT; j++) {
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ boolean result = sc.connect(isa);
+ if (!result) {
+ SelectionKey key = sc.register(selector,
+ SelectionKey.OP_CONNECT);
+ while (!result) {
+ int keysAdded = selector.select(100);
+ if (keysAdded > 0) {
+ Set readyKeys = selector.selectedKeys();
+ Iterator i = readyKeys.iterator();
+ while (i.hasNext()) {
+ SelectionKey sk = (SelectionKey)i.next();
+ SocketChannel nextReady =
+ (SocketChannel)sk.channel();
+ result = nextReady.finishConnect();
+ }
+ }
+ }
+ key.cancel();
+ }
+ read(sc);
+ }
+ selector.close();
+ }
+
+ static void read(SocketChannel sc) throws Exception {
+ ByteBuffer bb = ByteBuffer.allocateDirect(100);
+ int n = 0;
+ while (n == 0) // Note this is not a rigorous check for done reading
+ n = sc.read(bb);
+ //bb.position(bb.position() - 2);
+ //bb.flip();
+ //CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
+ //System.out.println("Received: \"" + cb + "\"");
+ sc.close();
+ success++;
+ }
+}
diff --git a/test/java/nio/channels/Selector/BasicAccept.java b/test/java/nio/channels/Selector/BasicAccept.java
new file mode 100644
index 0000000..8f269b0
--- /dev/null
+++ b/test/java/nio/channels/Selector/BasicAccept.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test Selector with ServerSocketChannels
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
+import java.util.*;
+
+
+public class BasicAccept {
+
+ public static int TEST_PORT = 40170;
+
+ static void server() throws Exception {
+ Selector acceptSelector = Selector.open();
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.configureBlocking(false);
+ InetAddress lh = InetAddress.getLocalHost();
+ InetSocketAddress isa
+ = new InetSocketAddress(lh, SelectorTest.TEST_PORT);
+ ssc.socket().bind(isa);
+ SelectionKey acceptKey
+ = ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
+ for (;;) {
+ if (acceptSelector.select() == 0)
+ continue;
+ Set readyKeys = acceptSelector.selectedKeys();
+ Iterator i = readyKeys.iterator();
+ while (i.hasNext()) {
+ SelectionKey sk = (SelectionKey)i.next();
+ i.remove();
+ ServerSocketChannel nextReady
+ = (ServerSocketChannel)sk.channel();
+ SocketChannel sc = nextReady.accept();
+ ByteBuffer bb = ByteBuffer.wrap(new byte[] { 42 });
+ sc.write(bb);
+ }
+ }
+ }
+
+ private static class Server extends TestThread {
+ Server() {
+ super("Server", System.err);
+ }
+ void go() throws Exception {
+ server();
+ }
+ }
+
+ static void client() throws Exception {
+ // Get a connection from the server
+ InetAddress lh = InetAddress.getLocalHost();
+ InetSocketAddress isa
+ = new InetSocketAddress(lh, SelectorTest.TEST_PORT);
+ int connectFailures = 0;
+ boolean result = false;
+ SocketChannel sc = SocketChannel.open();
+ for (;;) {
+ try {
+ result = sc.connect(isa);
+ break;
+ } catch (java.net.ConnectException e) {
+ connectFailures++;
+ if (connectFailures > 30)
+ throw new RuntimeException("Cannot connect");
+ Thread.currentThread().sleep(100);
+ sc = SocketChannel.open();
+ }
+ }
+ if (result) {
+ System.err.println("Connected");
+ } else {
+ // Only happens when server and client are on separate machines
+ System.err.println("Connection pending...");
+ connectFailures = 0;
+ while (!result) {
+ try {
+ result = sc.finishConnect();
+ if (!result)
+ System.err.println("Not finished");
+ Thread.sleep(50);
+ } catch (java.net.ConnectException e) {
+ Thread.sleep(100);
+ connectFailures++;
+ if (connectFailures > 30)
+ throw new RuntimeException("Cannot finish connecting");
+ }
+ }
+ System.err.println("Finished connecting");
+ }
+
+ ByteBuffer bb = ByteBuffer.allocateDirect(1024);
+ if (sc.read(bb) < 0)
+ throw new RuntimeException("Failed to read from server");
+ if (bb.get(0) != 42)
+ throw new RuntimeException("Read wrong byte from server");
+ System.err.println("Read from server");
+ }
+
+ public static void main(String[] args) throws Exception {
+ if (args.length == 0) {
+ Server server = new Server();
+ server.start();
+ client();
+ } else if (args[0].equals("client")) {
+ client();
+ } else if (args[0].equals("server")) {
+ server();
+ }
+ }
+
+}
diff --git a/test/java/nio/channels/Selector/BasicConnect.java b/test/java/nio/channels/Selector/BasicConnect.java
new file mode 100644
index 0000000..f1ead65
--- /dev/null
+++ b/test/java/nio/channels/Selector/BasicConnect.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test nonblocking connect and finishConnect
+ * @bug 4457776
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
+import java.nio.charset.*;
+import java.util.*;
+
+
+/**
+ * Typically there would be more than one channel registered to select
+ * on, this test is just a very simple version with only one channel
+ * registered for the connectSelector.
+ */
+
+public class BasicConnect {
+
+ static final int PORT = 7; // echo
+ static final String HOST = TestUtil.HOST;
+
+ public static void main(String[] args) throws Exception {
+ Selector connectSelector =
+ SelectorProvider.provider().openSelector();
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getByName(HOST), PORT);
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ boolean result = sc.connect(isa);
+ while (!result) {
+ SelectionKey connectKey = sc.register(connectSelector,
+ SelectionKey.OP_CONNECT);
+ int keysAdded = connectSelector.select();
+ if (keysAdded > 0) {
+ Set readyKeys = connectSelector.selectedKeys();
+ Iterator i = readyKeys.iterator();
+ while (i.hasNext()) {
+ SelectionKey sk = (SelectionKey)i.next();
+ i.remove();
+ SocketChannel nextReady = (SocketChannel)sk.channel();
+ result = nextReady.finishConnect();
+ if (result)
+ sk.cancel();
+ }
+ }
+ }
+
+ byte[] bs = new byte[] { (byte)0xca, (byte)0xfe,
+ (byte)0xba, (byte)0xbe };
+ ByteBuffer bb = ByteBuffer.wrap(bs);
+ sc.configureBlocking(true);
+ sc.write(bb);
+ bb.rewind();
+
+ ByteBuffer bb2 = ByteBuffer.allocateDirect(100);
+ int n = sc.read(bb2);
+ bb2.flip();
+ if (!bb.equals(bb2))
+ throw new Exception("Echoed bytes incorrect: Sent "
+ + bb + ", got " + bb2);
+ sc.close();
+ }
+
+}
diff --git a/test/java/nio/channels/Selector/ByteServer.java b/test/java/nio/channels/Selector/ByteServer.java
new file mode 100644
index 0000000..ca4725a
--- /dev/null
+++ b/test/java/nio/channels/Selector/ByteServer.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ *
+ * Utility class for tests. A simple server, which waits for a connection,
+ * writes out n bytes and waits.
+ * @author kladko
+ */
+
+import java.net.Socket;
+import java.net.ServerSocket;
+
+public class ByteServer {
+
+ public static final int PORT = 31415;
+ public static final String LOCALHOST = "localhost";
+ private int bytecount;
+ private Socket socket;
+ private ServerSocket serversocket;
+ private Thread serverthread;
+ volatile Exception savedException;
+
+ public ByteServer(int bytecount) throws Exception{
+ this.bytecount = bytecount;
+ serversocket = new ServerSocket(PORT);
+ }
+
+ public void start() {
+ serverthread = new Thread() {
+ public void run() {
+ try {
+ socket = serversocket.accept();
+ socket.getOutputStream().write(new byte[bytecount]);
+ socket.getOutputStream().flush();
+ } catch (Exception e) {
+ System.err.println("Exception in ByteServer: " + e);
+ System.exit(1);
+ }
+ }
+ };
+ serverthread.start();
+ }
+
+ public void exit() throws Exception {
+ serverthread.join();
+ socket.close();
+ serversocket.close();
+ }
+}
diff --git a/test/java/nio/channels/Selector/CheckLocking.java b/test/java/nio/channels/Selector/CheckLocking.java
new file mode 100644
index 0000000..56ad55f
--- /dev/null
+++ b/test/java/nio/channels/Selector/CheckLocking.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4953599
+ * @run main/timeout=15 CheckLocking
+ * @summary check if setInterest blocks while in select
+ */
+
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.channels.spi.*;
+import java.net.*;
+
+public class CheckLocking implements Runnable {
+
+ private static Selector selector;
+
+ public CheckLocking() {
+ }
+
+ public void run() {
+ try {
+ selector.select();
+ } catch (Throwable th) {
+ th.printStackTrace();
+ }
+ }
+
+ private static void doSelect() throws Exception {
+ Thread thread = new Thread(new CheckLocking());
+ thread.start();
+ Thread.sleep(1000);
+ }
+
+ public static void main (String[] args) throws Exception {
+ selector = SelectorProvider.provider().openSelector();
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ SelectionKey sk = sc.register(selector,0,null);
+ doSelect();
+ sk.interestOps(SelectionKey.OP_READ);
+ selector.wakeup();
+ }
+}
diff --git a/test/java/nio/channels/Selector/Close.java b/test/java/nio/channels/Selector/Close.java
new file mode 100644
index 0000000..b4109b8
--- /dev/null
+++ b/test/java/nio/channels/Selector/Close.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4744052
+ * @summary Test for keys remaining in selector after channel closed
+ */
+
+import java.nio.*;
+import java.nio.channels.*;
+
+public class Close {
+
+ public static void main(String args[]) throws Exception {
+ Selector sa = Selector.open();
+ Selector sb = Selector.open();
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ SelectionKey sk = sc.register(sa, SelectionKey.OP_READ);
+ sc.register(sb, SelectionKey.OP_READ);
+ sc.keyFor(sa).cancel();
+ sa.select(1);
+ sc.close();
+ sa.select(1);
+ sb.select(1);
+ if (sa.keys().size() > 0)
+ throw new RuntimeException("Keys remain in selector a");
+ if (sb.keys().size() > 0)
+ throw new RuntimeException("Keys remain in selector b");
+ sa.close();
+ sb.close();
+ }
+}
diff --git a/test/java/nio/channels/Selector/CloseInvalidatesKeys.java b/test/java/nio/channels/Selector/CloseInvalidatesKeys.java
new file mode 100644
index 0000000..b6d90cc
--- /dev/null
+++ b/test/java/nio/channels/Selector/CloseInvalidatesKeys.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4783178
+ * @summary Ensure that closing a selector invalidates its keys
+ */
+
+import java.nio.channels.*;
+
+
+public class CloseInvalidatesKeys {
+
+ public static void main (String [] args) throws Exception {
+ DatagramChannel ch = DatagramChannel.open();
+ ch.configureBlocking(false);
+ Selector sel = Selector.open();
+ SelectionKey key = ch.register(sel, SelectionKey.OP_WRITE);
+ sel.close();
+ if (key.isValid())
+ throw new Exception("Key valid after selector closed");
+ }
+
+}
diff --git a/test/java/nio/channels/Selector/CloseWhenKeyIdle.java b/test/java/nio/channels/Selector/CloseWhenKeyIdle.java
new file mode 100644
index 0000000..5a09f15
--- /dev/null
+++ b/test/java/nio/channels/Selector/CloseWhenKeyIdle.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 6403933
+ * @summary POLLHUP or POLLERR on "idle" key can cause Selector to spin
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.net.*;
+import java.nio.channels.*;
+
+public class CloseWhenKeyIdle {
+
+ // indicates if the wakeup has happened
+ static volatile boolean wakeupDone = false;
+
+ // Wakes up a Selector after a given delay
+ static class Waker implements Runnable {
+ private Selector sel;
+ private long delay;
+
+ Waker(Selector sel, long delay) {
+ this.sel = sel;
+ this.delay = delay;
+ }
+
+ public void run() {
+ try {
+ Thread.sleep(delay);
+ wakeupDone = true;
+ sel.wakeup();
+ } catch (Exception x) {
+ x.printStackTrace();
+ }
+ }
+ }
+
+
+ public static void main(String[] args) throws Exception {
+
+ // Skip test on pre-2.6 kernels until the poll SelectorProvider
+ // is updated
+ String osname = System.getProperty("os.name");
+ if (osname.equals("Linux")) {
+ String[] ver = System.getProperty("os.version").split("\\.", 0);
+ if (ver.length >=2 ) {
+ int major = Integer.parseInt(ver[0]);
+ int minor = Integer.parseInt(ver[1]);
+ if (major < 2 || (major == 2 && minor < 6)) {
+ System.out.println("Test passing on pre-2.6 kernel");
+ return;
+ }
+ }
+ }
+
+
+ // establish loopback connection
+
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(new InetSocketAddress(0));
+
+ SocketAddress remote = new InetSocketAddress(InetAddress.getLocalHost(),
+ ssc.socket().getLocalPort());
+
+ SocketChannel sc1 = SocketChannel.open(remote);
+ SocketChannel sc2 = ssc.accept();
+
+ // register channel for one end with a Selector, interest set = 0
+
+ Selector sel = Selector.open();
+
+ sc1.configureBlocking(false);
+ SelectionKey k = sc1.register(sel, 0);
+ sel.selectNow();
+
+ // hard close to provoke POLLHUP
+
+ sc2.socket().setSoLinger(true, 0);
+ sc2.close();
+
+ // schedule wakeup after a few seconds
+
+ Thread t = new Thread(new Waker(sel, 5000));
+ t.setDaemon(true);
+ t.start();
+
+ // select should block
+
+ int spinCount = 0;
+ for (;;) {
+ int n = sel.select();
+ if (n > 0)
+ throw new RuntimeException("channel should not be selected");
+
+ // wakeup
+ if (wakeupDone)
+ break;
+
+ // wakeup for no reason - if it happens a few times then we have a
+ // problem
+ spinCount++;
+ if (spinCount >= 3)
+ throw new RuntimeException("Selector appears to be spinning");
+ }
+
+ System.out.println("PASS");
+ }
+
+}
diff --git a/test/java/nio/channels/Selector/Connect.java b/test/java/nio/channels/Selector/Connect.java
new file mode 100644
index 0000000..bb983af
--- /dev/null
+++ b/test/java/nio/channels/Selector/Connect.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2001-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4511624
+ * @summary Test Making lots of Selectors
+ * @library ..
+ * @run main/timeout=240 Connect
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.util.*;
+import java.nio.channels.spi.SelectorProvider;
+
+public class Connect {
+
+ static int success = 0;
+ static int LIMIT = 500;
+
+ public static void main(String[] args) throws Exception {
+ scaleTest();
+ }
+
+ public static void scaleTest() throws Exception {
+ InetAddress myAddress=InetAddress.getByName(TestUtil.HOST);
+ InetSocketAddress isa = new InetSocketAddress(myAddress,13);
+
+ for (int j=0; j<LIMIT; j++) {
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ boolean result = sc.connect(isa);
+ if (!result) {
+ Selector RSelector = SelectorProvider.provider().openSelector();
+ SelectionKey RKey = sc.register (RSelector, SelectionKey.OP_CONNECT);
+ while (!result) {
+ int keysAdded = RSelector.select(100);
+ if (keysAdded > 0) {
+ Set readyKeys = RSelector.selectedKeys();
+ Iterator i = readyKeys.iterator();
+ while (i.hasNext()) {
+ SelectionKey sk = (SelectionKey)i.next();
+ SocketChannel nextReady = (SocketChannel)sk.channel();
+ result = nextReady.finishConnect();
+ }
+ }
+ }
+ RSelector.close();
+ }
+ read(sc);
+ }
+ }
+
+ static void read(SocketChannel sc) throws Exception {
+ ByteBuffer bb = ByteBuffer.allocateDirect(100);
+ int n = 0;
+ while (n == 0) // Note this is not a rigorous check for done reading
+ n = sc.read(bb);
+ //bb.position(bb.position() - 2);
+ //bb.flip();
+ //CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
+ //System.out.println("Received: \"" + cb + "\"");
+ sc.close();
+ success++;
+ }
+}
diff --git a/test/java/nio/channels/Selector/ConnectWrite.java b/test/java/nio/channels/Selector/ConnectWrite.java
new file mode 100644
index 0000000..2dba30b
--- /dev/null
+++ b/test/java/nio/channels/Selector/ConnectWrite.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4505829
+ * @summary Test ready for connect followed by ready for write
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.util.*;
+import java.nio.channels.spi.SelectorProvider;
+
+public class ConnectWrite {
+
+ public static void main(String[] args) throws Exception {
+ test1(13);
+ test1(9);
+ }
+
+ public static void test1(int port) throws Exception {
+ Selector selector = SelectorProvider.provider().openSelector();
+ InetAddress myAddress=InetAddress.getByName(TestUtil.HOST);
+ InetSocketAddress isa = new InetSocketAddress(myAddress, port);
+ try {
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
+ boolean result = sc.connect(isa);
+
+ while (!result) {
+ int keysAdded = selector.select(1000);
+ if (keysAdded > 0) {
+ Set readyKeys = selector.selectedKeys();
+ Iterator i = readyKeys.iterator();
+ while (i.hasNext()) {
+ SelectionKey sk = (SelectionKey)i.next();
+ readyKeys.remove(sk);
+ SocketChannel nextReady = (SocketChannel)sk.channel();
+ result = nextReady.finishConnect();
+ }
+ }
+ }
+ if (key != null) {
+ key.interestOps(SelectionKey.OP_WRITE);
+ int keysAdded = selector.select(1000);
+ if (keysAdded <= 0)
+ throw new Exception("connect->write failed");
+ if (keysAdded > 0) {
+ Set readyKeys = selector.selectedKeys();
+ Iterator i = readyKeys.iterator();
+ while (i.hasNext()) {
+ SelectionKey sk = (SelectionKey)i.next();
+ if (!sk.isWritable())
+ throw new Exception("connect->write failed");
+ }
+ }
+ }
+ } finally {
+ selector.close();
+ }
+ }
+}
diff --git a/test/java/nio/channels/Selector/KeySets.java b/test/java/nio/channels/Selector/KeySets.java
new file mode 100644
index 0000000..3e6992f
--- /dev/null
+++ b/test/java/nio/channels/Selector/KeySets.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4776783 4778091 4778099
+ * @summary Check various properties of key and selected-key sets
+ *
+ * @run main KeySets
+ * @run main/othervm -Dsun.nio.ch.bugLevel=1.4 KeySets
+ */
+
+import java.io.*;
+import java.nio.channels.*;
+import java.util.*;
+
+
+public class KeySets {
+
+ static boolean compat;
+
+ static abstract class Catch {
+ abstract void go() throws Exception;
+ Catch(Class xc) throws Exception {
+ try {
+ go();
+ } catch (Exception x) {
+ if (compat)
+ throw new Exception("Exception thrown", x);
+ if (xc.isInstance(x))
+ return;
+ throw new Exception("Wrong exception", x);
+ }
+ if (compat)
+ return;
+ throw new Exception("Not thrown as expected: "
+ + xc.getName());
+ }
+ }
+
+ // 4776783: Closing a selector should make key sets inaccessible
+ static void testClose() throws Exception {
+
+ final Selector sel = Selector.open();
+ sel.keys();
+ sel.selectedKeys();
+ sel.close();
+
+ new Catch(ClosedSelectorException.class) {
+ void go() throws Exception {
+ sel.keys();
+ }};
+
+ new Catch(ClosedSelectorException.class) {
+ void go() throws Exception {
+ sel.selectedKeys();
+ }};
+
+ }
+
+ static void testNoAddition(final Set s) throws Exception {
+ new Catch(UnsupportedOperationException.class) {
+ void go() throws Exception {
+ s.add(new Object());
+ }};
+ new Catch(UnsupportedOperationException.class) {
+ void go() throws Exception {
+ ArrayList al = new ArrayList();
+ al.add(new Object());
+ s.addAll(al);
+ }};
+ }
+
+ static interface Adder {
+ void add() throws IOException;
+ }
+
+ static void testNoRemoval(final Set s, final Adder adder)
+ throws Exception
+ {
+ new Catch(UnsupportedOperationException.class) {
+ void go() throws Exception {
+ adder.add();
+ s.clear();
+ }};
+ new Catch(UnsupportedOperationException.class) {
+ void go() throws Exception {
+ adder.add();
+ Iterator i = s.iterator();
+ i.next();
+ i.remove();
+ }};
+ new Catch(UnsupportedOperationException.class) {
+ void go() throws Exception {
+ adder.add();
+ s.remove(s.iterator().next());
+ }};
+ new Catch(UnsupportedOperationException.class) {
+ void go() throws Exception {
+ adder.add();
+ HashSet hs = new HashSet();
+ hs.addAll(s);
+ s.removeAll(hs);
+ }};
+ new Catch(UnsupportedOperationException.class) {
+ void go() throws Exception {
+ adder.add();
+ s.retainAll(Collections.EMPTY_SET);
+ }};
+ }
+
+ static SelectionKey reg(Selector sel) throws IOException {
+ DatagramChannel dc = DatagramChannel.open();
+ dc.configureBlocking(false);
+ return dc.register(sel, SelectionKey.OP_WRITE);
+ }
+
+ static void testMutability() throws Exception {
+
+ final Selector sel = Selector.open();
+
+ // 4778091: Selector.keys() should be immutable
+
+ testNoRemoval(sel.keys(), new Adder() {
+ public void add() throws IOException {
+ reg(sel);
+ }
+ });
+ testNoAddition(sel.keys());
+
+ // 4778099: Selector.selectedKeys() should allow removal but not addition
+
+ sel.select();
+ testNoAddition(sel.selectedKeys());
+ SelectionKey sk = reg(sel);
+ sel.select();
+ int n = sel.selectedKeys().size();
+ sel.selectedKeys().remove(sk);
+ if (sel.selectedKeys().size() != n - 1)
+ throw new Exception("remove failed");
+
+ HashSet hs = new HashSet();
+ hs.add(reg(sel));
+ sel.select();
+ sel.selectedKeys().retainAll(hs);
+ if (sel.selectedKeys().isEmpty())
+ throw new Exception("retainAll failed");
+ sel.selectedKeys().removeAll(hs);
+ if (!sel.selectedKeys().isEmpty())
+ throw new Exception("removeAll failed");
+
+ hs.clear();
+ hs.add(reg(sel));
+ sel.select();
+ sel.selectedKeys().clear();
+ if (!sel.selectedKeys().isEmpty())
+ throw new Exception("clear failed");
+
+ }
+
+ public static void main(String[] args) throws Exception {
+ String bl = System.getProperty("sun.nio.ch.bugLevel");
+ compat = (bl != null) && bl.equals("1.4");
+ testClose();
+ testMutability();
+ }
+
+}
diff --git a/test/java/nio/channels/Selector/KeysReady.java b/test/java/nio/channels/Selector/KeysReady.java
new file mode 100644
index 0000000..8274021
--- /dev/null
+++ b/test/java/nio/channels/Selector/KeysReady.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4530007
+ * @summary Test if keys reported ready multiple times
+ * @library ..
+ */
+
+import java.net.*;
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+import java.nio.channels.spi.SelectorProvider;
+
+public class KeysReady {
+
+ static final int DAYTIME_PORT = 13;
+ static final String DAYTIME_HOST = TestUtil.HOST;
+
+ static void test() throws Exception {
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
+ DAYTIME_PORT);
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ sc.connect(isa);
+
+ // Prepare a selector
+ Selector selector = SelectorProvider.provider().openSelector();
+ SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
+ int keysAdded = selector.select();
+ if (keysAdded > 0) {
+ keysAdded = selector.select(1000);
+ if (keysAdded > 0)
+ throw new Exception("Same key reported added twice");
+ }
+ sc.close();
+ }
+
+ public static void main(String[] args) throws Exception {
+ test();
+ }
+
+}
diff --git a/test/java/nio/channels/Selector/LotsOfChannels.java b/test/java/nio/channels/Selector/LotsOfChannels.java
new file mode 100644
index 0000000..1218712
--- /dev/null
+++ b/test/java/nio/channels/Selector/LotsOfChannels.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4503092
+ * @summary Tests that Windows Selector can use more than 63 channels
+ * @run main/timeout=300 LotsOfChannels
+ * @author kladko
+ */
+
+import java.net.*;
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class LotsOfChannels {
+
+ private final static int PIPES_COUNT = 1900;
+ private final static int BUF_SIZE = 8192;
+ private final static int LOOPS = 10;
+
+ public static void main(String[] argv) throws Exception {
+
+
+ String os = System.getProperty("os.name");
+ if (!(os.equals("Windows NT")
+ || os.equals("Windows 2000")
+ || os.equals("Windows XP")))
+ return;
+
+ Pipe[] pipes = new Pipe[PIPES_COUNT];
+ Pipe pipe = Pipe.open();
+ Pipe.SinkChannel sink = pipe.sink();
+ Pipe.SourceChannel source = pipe.source();
+ Selector sel = Selector.open();
+ source.configureBlocking(false);
+ source.register(sel, SelectionKey.OP_READ);
+
+ for (int i = 0; i< PIPES_COUNT; i++ ) {
+ pipes[i]= Pipe.open();
+ Pipe.SourceChannel sc = pipes[i].source();
+ sc.configureBlocking(false);
+ sc.register(sel, SelectionKey.OP_READ);
+ Pipe.SinkChannel sc2 = pipes[i].sink();
+ sc2.configureBlocking(false);
+ sc2.register(sel, SelectionKey.OP_WRITE);
+ }
+
+ for (int i = 0 ; i < LOOPS; i++ ) {
+ sink.write(ByteBuffer.allocate(BUF_SIZE));
+ int x = sel.selectNow();
+ sel.selectedKeys().clear();
+ source.read(ByteBuffer.allocate(BUF_SIZE));
+ }
+ sel.close();
+ }
+}
diff --git a/test/java/nio/channels/Selector/OpRead.java b/test/java/nio/channels/Selector/OpRead.java
new file mode 100644
index 0000000..b9e35fc
--- /dev/null
+++ b/test/java/nio/channels/Selector/OpRead.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2002-2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4755720
+ * @summary Test if OP_READ is detected with OP_WRITE in interestOps
+ * @library ..
+ */
+
+import java.net.*;
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
+import java.util.*;
+
+public class OpRead {
+
+ static final int DAYTIME_PORT = 13;
+ static final String DAYTIME_HOST = TestUtil.HOST;
+
+ static void test() throws Exception {
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
+ DAYTIME_PORT);
+ SocketChannel sc = SocketChannel.open();
+
+ sc.connect(isa);
+
+ sc.configureBlocking(false);
+
+ Selector selector = SelectorProvider.provider().openSelector();
+ SelectionKey key = sc.register(selector, SelectionKey.OP_READ |
+ SelectionKey.OP_WRITE);
+
+ boolean done = false;
+ int failCount = 0;
+ while (!done) {
+ if (selector.select() > 0) {
+ Set keys = selector.selectedKeys();
+ Iterator iterator = keys.iterator();
+ while (iterator.hasNext()) {
+ key = (SelectionKey)iterator.next();
+ iterator.remove();
+ if (key.isWritable()) {
+ failCount++;
+ if (failCount > 10)
+ throw new RuntimeException("Test failed");
+ Thread.sleep(100);
+ }
+ if (key.isReadable()) {
+ done = true;
+ }
+ }
+ }
+ }
+
+
+ sc.close();
+ }
+
+ public static void main(String[] args) throws Exception {
+ test();
+ }
+
+}
diff --git a/test/java/nio/channels/Selector/ReadAfterConnect.java b/test/java/nio/channels/Selector/ReadAfterConnect.java
new file mode 100644
index 0000000..0a48732
--- /dev/null
+++ b/test/java/nio/channels/Selector/ReadAfterConnect.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4629307
+ * @summary Socket with OP_READ would get selected on connect
+ * @author kladko
+ */
+
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class ReadAfterConnect {
+
+ public static void main(String[] argv) throws Exception {
+ ByteServer server = new ByteServer(0); // server: accept connection and do nothing
+ server.start();
+ InetSocketAddress isa = new InetSocketAddress(
+ InetAddress.getByName(ByteServer.LOCALHOST), ByteServer.PORT);
+ Selector sel = Selector.open();
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(isa);
+ sc.configureBlocking(false);
+ sc.register(sel, SelectionKey.OP_READ);
+ // Previously channel would get selected here, although there is nothing to read
+ if (sel.selectNow() != 0)
+ throw new Exception("Select returned nonzero value");
+ sc.close();
+ server.exit();
+ }
+
+}
diff --git a/test/java/nio/channels/Selector/SelectAfterRead.java b/test/java/nio/channels/Selector/SelectAfterRead.java
new file mode 100644
index 0000000..11bc476
--- /dev/null
+++ b/test/java/nio/channels/Selector/SelectAfterRead.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4639943
+ * @summary Checks that Windows behavior matches Solaris for
+ * various read/select combinations.
+ * @author kladko
+ */
+
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class SelectAfterRead {
+
+ final static int TIMEOUT = 1000;
+
+ public static void main(String[] argv) throws Exception {
+ // server: accept connection and write one byte
+ ByteServer server = new ByteServer(1);
+ server.start();
+ InetSocketAddress isa = new InetSocketAddress(
+ InetAddress.getByName(ByteServer.LOCALHOST), ByteServer.PORT);
+ Selector sel = Selector.open();
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(isa);
+ sc.read(ByteBuffer.allocate(1));
+ sc.configureBlocking(false);
+ sc.register(sel, SelectionKey.OP_READ);
+ // previously on Windows select would select channel here, although there was
+ // nothing to read
+ if (sel.selectNow() != 0)
+ throw new Exception("Select returned nonzero value");
+ sc.close();
+ sel.close();
+ server.exit();
+
+ // Now we will test a two reads combination
+ // server: accept connection and write two bytes
+ server = new ByteServer(2);
+ server.start();
+ sc = SocketChannel.open();
+ sc.connect(isa);
+ sc.configureBlocking(false);
+ sel = Selector.open();
+ sc.register(sel, SelectionKey.OP_READ);
+ if (sel.select(TIMEOUT) != 1)
+ throw new Exception("One selected key expected");
+ sel.selectedKeys().clear();
+ // previously on Windows a channel would get selected only once
+ if (sel.selectNow() != 1)
+ throw new Exception("One selected key expected");
+ // Previously on Windows two consequent reads would cause select()
+ // to select a channel, although there was nothing remaining to
+ // read in the channel
+ if (sc.read(ByteBuffer.allocate(1)) != 1)
+ throw new Exception("One byte expected");
+ if (sc.read(ByteBuffer.allocate(1)) != 1)
+ throw new Exception("One byte expected");
+ if (sel.selectNow() != 0)
+ throw new Exception("Select returned nonzero value");
+ sc.close();
+ sel.close();
+ server.exit();
+ }
+}
diff --git a/test/java/nio/channels/Selector/SelectAndCancel.java b/test/java/nio/channels/Selector/SelectAndCancel.java
new file mode 100644
index 0000000..ba43f09
--- /dev/null
+++ b/test/java/nio/channels/Selector/SelectAndCancel.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4729342
+ * @summary Check for CancelledKeyException when key cancelled during select
+ */
+
+import java.nio.channels.*;
+import java.io.IOException;
+import java.net.*;
+
+public class SelectAndCancel {
+ static ServerSocketChannel ssc;
+ static Selector selector;
+ static SelectionKey sk;
+ static InetSocketAddress isa;
+ public static int TEST_PORT = 40170;
+
+ /*
+ * CancelledKeyException is the failure symptom of 4729342
+ * NOTE: The failure is timing dependent and is not always
+ * seen immediately when the bug is present.
+ */
+ public static void main(String[] args) throws Exception {
+ InetAddress lh = InetAddress.getLocalHost();
+ isa = new InetSocketAddress(lh, TEST_PORT);
+ selector = Selector.open();
+ ssc = ServerSocketChannel.open();
+
+ // Create and start a selector in a separate thread.
+ new Thread(new Runnable() {
+ public void run() {
+ try {
+ ssc.configureBlocking(false);
+ ssc.socket().bind(isa);
+ sk = ssc.register(selector, SelectionKey.OP_ACCEPT);
+ selector.select();
+ } catch (IOException e) {
+ System.err.println("error in selecting thread");
+ e.printStackTrace();
+ }
+ }
+ }).start();
+
+ // Wait for above thread to get to select() before we call close.
+ Thread.sleep(3000);
+
+ // Try to close. This should wakeup select.
+ new Thread(new Runnable() {
+ public void run() {
+ try {
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(isa);
+ ssc.close();
+ sk.cancel();
+ sc.close();
+ } catch (IOException e) {
+ System.err.println("error in closing thread");
+ System.err.println(e);
+ }
+ }
+ }).start();
+
+ // Wait for select() to be awakened, which should be done by close.
+ Thread.sleep(3000);
+
+ selector.wakeup();
+ selector.close();
+ }
+}
diff --git a/test/java/nio/channels/Selector/SelectAndClose.java b/test/java/nio/channels/Selector/SelectAndClose.java
new file mode 100644
index 0000000..d8549d8
--- /dev/null
+++ b/test/java/nio/channels/Selector/SelectAndClose.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 5004077
+ * @summary Check blocking of select and close
+ */
+
+import java.nio.channels.*;
+import java.io.IOException;
+
+public class SelectAndClose {
+ static Selector selector;
+ static boolean awakened = false;
+ static boolean closed = false;
+
+ public static void main(String[] args) throws Exception {
+ selector = Selector.open();
+
+ // Create and start a selector in a separate thread.
+ new Thread(new Runnable() {
+ public void run() {
+ try {
+ selector.select();
+ awakened = true;
+ } catch (IOException e) {
+ System.err.println(e);
+ }
+ }
+ }).start();
+
+ // Wait for above thread to get to select() before we call close.
+ Thread.sleep(3000);
+
+ // Try to close. This should wakeup select.
+ new Thread(new Runnable() {
+ public void run() {
+ try {
+ selector.close();
+ closed = true;
+ } catch (IOException e) {
+ System.err.println(e);
+ }
+ }
+ }).start();
+
+ // Wait for select() to be awakened, which should be done by close.
+ Thread.sleep(3000);
+
+ if (!awakened)
+ selector.wakeup();
+
+ // Correct result is true and true
+ if (!awakened)
+ throw new RuntimeException("Select did not wake up");
+ if (!closed)
+ throw new RuntimeException("Selector did not close");
+ }
+}
diff --git a/test/java/nio/channels/Selector/SelectNowWhenEmpty.java b/test/java/nio/channels/Selector/SelectNowWhenEmpty.java
new file mode 100644
index 0000000..7130f7e
--- /dev/null
+++ b/test/java/nio/channels/Selector/SelectNowWhenEmpty.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4473006
+ * @summary Test selectNow method with no registered channels
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
+
+
+public class SelectNowWhenEmpty {
+ public static void main(String[] args) throws Exception {
+ Selector s = SelectorProvider.provider().openSelector();
+ s.selectNow();
+ }
+}
diff --git a/test/java/nio/channels/Selector/SelectWrite.java b/test/java/nio/channels/Selector/SelectWrite.java
new file mode 100644
index 0000000..595133a
--- /dev/null
+++ b/test/java/nio/channels/Selector/SelectWrite.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ @bug 4645302
+ @summary Socket with OP_WRITE would get selected only once
+ @author kladko
+ */
+
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+
+public class SelectWrite {
+
+ public static void main(String[] argv) throws Exception {
+ ByteServer server = new ByteServer(0);
+ // server: accept connection and do nothing
+ server.start();
+ InetSocketAddress isa = new InetSocketAddress(
+ InetAddress.getByName(ByteServer.LOCALHOST), ByteServer.PORT);
+ Selector sel = Selector.open();
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(isa);
+ sc.configureBlocking(false);
+ sc.register(sel, SelectionKey.OP_WRITE);
+ sel.select();
+ sel.selectedKeys().clear();
+ if (sel.select() == 0) {
+ throw new Exception("Select returned zero");
+ }
+ sc.close();
+ sel.close();
+ }
+
+}
diff --git a/test/java/nio/channels/Selector/SelectorLimit.java b/test/java/nio/channels/Selector/SelectorLimit.java
new file mode 100644
index 0000000..68314a2
--- /dev/null
+++ b/test/java/nio/channels/Selector/SelectorLimit.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright 2002-2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4777504
+ * @summary Ensure that a Selector can return at least 100 selected keys
+ * @author Mark Reinhold
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.util.*;
+
+
+public class SelectorLimit {
+
+ static PrintStream log = System.err;
+
+ static class Listener
+ extends TestThread
+ {
+ volatile int count = 0;
+ private ServerSocketChannel ssc;
+
+ Listener(ServerSocketChannel ssc) {
+ super("Listener");
+ this.ssc = ssc;
+ }
+
+ void go() throws IOException {
+ for (;;) {
+ ssc.accept();
+ count++;
+ }
+ }
+
+ }
+
+ static final int N_KEYS = 500;
+ static final int MIN_KEYS = 100;
+
+ public static void main(String[] args) throws Exception {
+ // win9X can't handle many connections at once
+ String osName = System.getProperty("os.name");
+ if (osName.toLowerCase().startsWith("win")) {
+ if (!(osName.equals("Windows NT")
+ || osName.equals("Windows 2000")
+ || osName.equals("Windows XP")))
+ return;
+ }
+
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ TestUtil.bind(ssc);
+ Listener lth = new Listener(ssc);
+ lth.start();
+
+ Selector sel = Selector.open();
+ SocketChannel[] sca = new SocketChannel[N_KEYS];
+ for (int i = 0; i < N_KEYS; i++) {
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ sc.register(sel, SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE);
+ sc.connect(ssc.socket().getLocalSocketAddress());
+ }
+
+ for (int i = 0; i < 10; i++) {
+ if (lth.count >= MIN_KEYS)
+ break;
+ Thread.sleep(1000);
+ }
+ log.println(lth.count + " connections accepted");
+ Thread.sleep(500);
+
+ int n = sel.select();
+ log.println(n + " keys selected");
+ if (n < MIN_KEYS)
+ throw new Exception("Only selected " + n + " keys");
+
+ }
+
+}
diff --git a/test/java/nio/channels/Selector/SelectorTest.java b/test/java/nio/channels/Selector/SelectorTest.java
new file mode 100644
index 0000000..df8518d
--- /dev/null
+++ b/test/java/nio/channels/Selector/SelectorTest.java
@@ -0,0 +1,414 @@
+/*
+ * Copyright 2000-2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test selectors and socketchannels
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
+import java.util.*;
+
+
+public class SelectorTest {
+ private static List clientList = new LinkedList();
+ private static Random rnd = new Random();
+ public static int NUM_CLIENTS = 30;
+ public static int TEST_PORT = 31452;
+ static PrintStream log = System.err;
+ private static int FINISH_TIME = 30000;
+
+ /*
+ * Usage note
+ *
+ * java SelectorTest [server] [client <host>] [<port>]
+ *
+ * No arguments runs both client and server in separate threads
+ * using the default port of 31452.
+ *
+ * client runs the client on this machine and connects to server
+ * at the given IP address.
+ *
+ * server runs the server on localhost.
+ */
+ public static void main(String[] args) throws Exception {
+ if (args.length == 0) {
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getLocalHost(), TEST_PORT);
+ Server server = new Server(isa);
+ server.start();
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) { }
+ Client client = new Client(isa);
+ client.start();
+ if ((server.finish(FINISH_TIME) & client.finish(FINISH_TIME)) == 0)
+ throw new Exception("Failure");
+ log.println();
+
+ } else if (args[0].equals("server")) {
+
+ if (args.length > 1)
+ TEST_PORT = Integer.parseInt(args[1]);
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getLocalHost(), TEST_PORT);
+ Server server = new Server(isa);
+ server.start();
+ if (server.finish(FINISH_TIME) == 0)
+ throw new Exception("Failure");
+ log.println();
+
+ } else if (args[0].equals("client")) {
+
+ if (args.length < 2) {
+ log.println("No host specified: terminating.");
+ return;
+ }
+ String ip = args[1];
+ if (args.length > 2)
+ TEST_PORT = Integer.parseInt(args[2]);
+ InetAddress ia = InetAddress.getByName(ip);
+ InetSocketAddress isa = new InetSocketAddress(ia, TEST_PORT);
+ Client client = new Client(isa);
+ client.start();
+ if (client.finish(FINISH_TIME) == 0)
+ throw new Exception("Failure");
+ log.println();
+
+ } else {
+ System.out.println("Usage note:");
+ System.out.println("java SelectorTest [server] [client <host>] [<port>]");
+ System.out.println("No arguments runs both client and server in separate threads using the default port of 31452.");
+ System.out.println("client runs the client on this machine and connects to the server specified.");
+ System.out.println("server runs the server on localhost.");
+ }
+ }
+
+ static class Client extends TestThread {
+ InetSocketAddress isa;
+ Client(InetSocketAddress isa) {
+ super("Client", SelectorTest.log);
+ this.isa = isa;
+ }
+
+ public void go() throws Exception {
+ log.println("starting client...");
+ for (int i=0; i<NUM_CLIENTS; i++)
+ clientList.add(new RemoteEntity(i, isa, log));
+
+ Collections.shuffle(clientList);
+
+ log.println("created "+NUM_CLIENTS+" clients");
+ do {
+ for (Iterator i = clientList.iterator(); i.hasNext(); ) {
+ RemoteEntity re = (RemoteEntity) i.next();
+ if (re.cycle()) {
+ i.remove();
+ }
+ }
+ Collections.shuffle(clientList);
+ } while (clientList.size() > 0);
+ }
+ }
+
+ static class Server extends TestThread {
+ private List socketList = new ArrayList();
+ private ServerSocket ss;
+ private int connectionsAccepted = 0;
+ private Selector pollSelector;
+ private Selector acceptSelector;
+ private InetSocketAddress isa;
+ private Set pkeys;
+ private Set pskeys;
+
+ Server(InetSocketAddress isa) {
+ super("Server", SelectorTest.log);
+ this.isa = isa;
+ }
+
+ public void go() throws Exception {
+ log.println("starting server...");
+ acceptSelector = SelectorProvider.provider().openSelector();
+ pollSelector = SelectorProvider.provider().openSelector();
+ pkeys = pollSelector.keys();
+ pskeys = pollSelector.selectedKeys();
+ Set readyKeys = acceptSelector.selectedKeys();
+ RequestHandler rh = new RequestHandler(pollSelector, log);
+ Thread requestThread = new Thread(rh);
+
+ requestThread.start();
+
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.configureBlocking(false);
+ ssc.socket().setReuseAddress(true);
+ ssc.socket().bind(isa);
+
+ SelectionKey acceptKey = ssc.register(acceptSelector,
+ SelectionKey.OP_ACCEPT);
+ while(connectionsAccepted < SelectorTest.NUM_CLIENTS) {
+ int keysAdded = acceptSelector.select(100);
+ if (keysAdded > 0) {
+ Iterator i = readyKeys.iterator();
+ while(i.hasNext()) {
+ SelectionKey sk = (SelectionKey)i.next();
+ i.remove();
+ ServerSocketChannel nextReady =
+ (ServerSocketChannel)sk.channel();
+ SocketChannel sc = nextReady.accept();
+ connectionsAccepted++;
+ if (sc != null) {
+ sc.configureBlocking(false);
+ synchronized (pkeys) {
+ sc.register(pollSelector, SelectionKey.OP_READ);
+ }
+ } else {
+ throw new RuntimeException(
+ "Socket does not support Channels");
+ }
+ }
+ }
+ }
+ acceptKey.cancel();
+ requestThread.join();
+ acceptSelector.close();
+ pollSelector.close();
+ }
+ }
+}
+
+class RemoteEntity {
+ private static Random rnd = new Random();
+ int id;
+ ByteBuffer data;
+ int dataWrittenIndex;
+ int totalDataLength;
+ boolean initiated = false;
+ boolean connected = false;
+ boolean written = false;
+ boolean acked = false;
+ boolean closed = false;
+ private SocketChannel sc;
+ ByteBuffer ackBuffer;
+ PrintStream log;
+ InetSocketAddress server;
+
+ RemoteEntity(int id, InetSocketAddress server, PrintStream log)
+ throws Exception
+ {
+ int connectFailures = 0;
+ this.id = id;
+ this.log = log;
+ this.server = server;
+
+ sc = SocketChannel.open();
+ sc.configureBlocking(false);
+
+ // Prepare the data buffer to write out from this entity
+ // Let's use both slow and fast buffers
+ if (rnd.nextBoolean())
+ data = ByteBuffer.allocateDirect(100);
+ else
+ data = ByteBuffer.allocate(100);
+ String number = Integer.toString(id);
+ if (number.length() == 1)
+ number = "0"+number;
+ String source = "Testing from " + number;
+ data.put(source.getBytes("8859_1"));
+ data.flip();
+ totalDataLength = source.length();
+
+ // Allocate an ack buffer
+ ackBuffer = ByteBuffer.allocateDirect(10);
+ }
+
+ private void reset() throws Exception {
+ sc.close();
+ sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ }
+
+ private void connect() throws Exception {
+ try {
+ connected = sc.connect(server);
+ initiated = true;
+ } catch (ConnectException e) {
+ initiated = false;
+ reset();
+ }
+ }
+
+ private void finishConnect() throws Exception {
+ try {
+ connected = sc.finishConnect();
+ } catch (IOException e) {
+ initiated = false;
+ reset();
+ }
+ }
+
+ int id() {
+ return id;
+ }
+
+ boolean cycle() throws Exception {
+ if (!initiated)
+ connect();
+ else if (!connected)
+ finishConnect();
+ else if (!written)
+ writeCycle();
+ else if (!acked)
+ ackCycle();
+ else if (!closed)
+ close();
+ return closed;
+ }
+
+ private void ackCycle() throws Exception {
+ //log.println("acking from "+id);
+ int bytesRead = sc.read(ackBuffer);
+ if (bytesRead > 0) {
+ acked = true;
+ }
+ }
+
+ private void close() throws Exception {
+ sc.close();
+ closed = true;
+ }
+
+ private void writeCycle() throws Exception {
+ log.println("writing from "+id);
+ int numBytesToWrite = rnd.nextInt(10)+1;
+ int newWriteTarget = dataWrittenIndex + numBytesToWrite;
+ if (newWriteTarget > totalDataLength)
+ newWriteTarget = totalDataLength;
+ data.limit(newWriteTarget);
+ int bytesWritten = sc.write(data);
+ if (bytesWritten > 0)
+ dataWrittenIndex += bytesWritten;
+ if (dataWrittenIndex == totalDataLength) {
+ written = true;
+ sc.socket().shutdownOutput();
+ }
+ }
+
+}
+
+
+class RequestHandler implements Runnable {
+ private static Random rnd = new Random();
+ private Selector selector;
+ private int connectionsHandled = 0;
+ private HashMap dataBin = new HashMap();
+ PrintStream log;
+
+ public RequestHandler(Selector selector, PrintStream log) {
+ this.selector = selector;
+ this.log = log;
+ }
+
+ public void run() {
+ log.println("starting request handler...");
+ int connectionsAccepted = 0;
+
+ Set nKeys = selector.keys();
+ Set readyKeys = selector.selectedKeys();
+
+ try {
+ while(connectionsHandled < SelectorTest.NUM_CLIENTS) {
+ int numKeys = selector.select(100);
+
+ // Process channels with data
+ synchronized (nKeys) {
+ if (readyKeys.size() > 0) {
+ Iterator i = readyKeys.iterator();
+ while(i.hasNext()) {
+ SelectionKey sk = (SelectionKey)i.next();
+ i.remove();
+ SocketChannel sc = (SocketChannel)sk.channel();
+ if (sc.isOpen())
+ read(sk, sc);
+ }
+ }
+ }
+
+ // Give other threads a chance to run
+ if (numKeys == 0) {
+ try {
+ Thread.sleep(1);
+ } catch (Exception x) {}
+ }
+ }
+ } catch (Exception e) {
+ log.println("Unexpected error 1: "+e);
+ e.printStackTrace();
+ }
+ }
+
+ private void read(SelectionKey sk, SocketChannel sc) throws Exception {
+ ByteBuffer bin = (ByteBuffer)dataBin.get(sc);
+ if (bin == null) {
+ if (rnd.nextBoolean())
+ bin = ByteBuffer.allocateDirect(100);
+ else
+ bin = ByteBuffer.allocate(100);
+ dataBin.put(sc, bin);
+ }
+
+ int bytesRead = 0;
+ do {
+ bytesRead = sc.read(bin);
+ } while(bytesRead > 0);
+
+ if (bytesRead == -1) {
+ sk.interestOps(0);
+ bin.flip();
+ int size = bin.limit();
+ byte[] data = new byte[size];
+ for(int j=0; j<size; j++)
+ data[j] = bin.get();
+ String message = new String(data, "8859_1");
+ connectionsHandled++;
+ acknowledge(sc);
+ log.println("Received >>>"+message + "<<<");
+ log.println("Handled: "+connectionsHandled);
+ }
+ }
+
+ private void acknowledge(SocketChannel sc) throws Exception {
+ ByteBuffer ackBuffer = ByteBuffer.allocateDirect(10);
+ String s = "ack";
+ ackBuffer.put(s.getBytes("8859_1"));
+ ackBuffer.flip();
+ int bytesWritten = 0;
+ while(bytesWritten == 0) {
+ bytesWritten += sc.write(ackBuffer);
+ }
+ sc.close();
+ }
+}
diff --git a/test/java/nio/channels/Selector/WakeupAfterClose.java b/test/java/nio/channels/Selector/WakeupAfterClose.java
new file mode 100644
index 0000000..d739dc4
--- /dev/null
+++ b/test/java/nio/channels/Selector/WakeupAfterClose.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 6524172
+ * @summary Invoking wakeup on closed Selector can throw NPE if close resets interrupt status
+ */
+
+import java.nio.channels.Selector;
+import java.io.IOException;
+
+public class WakeupAfterClose {
+
+ public static void main(String[] args) throws Exception {
+ final Selector sel = Selector.open();
+
+ Runnable r = new Runnable() {
+ public void run() {
+ try {
+ sel.select();
+ } catch (IOException x) {
+ x.printStackTrace();
+ }
+ }
+ };
+
+ // start thread to block in Selector
+ Thread t = new Thread(r);
+ t.start();
+
+ // give thread time to start
+ Thread.sleep(1000);
+
+ // interrupt, close, and wakeup is the magic sequence to provoke the NPE
+ t.interrupt();
+ sel.close();
+ sel.wakeup();
+ }
+}
diff --git a/test/java/nio/channels/Selector/WakeupEmpty.java b/test/java/nio/channels/Selector/WakeupEmpty.java
new file mode 100644
index 0000000..331e8b8
--- /dev/null
+++ b/test/java/nio/channels/Selector/WakeupEmpty.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4531740
+ * @summary Checks that wakeup works for an empty Selector
+ * @author kladko
+ */
+
+import java.nio.*;
+import java.nio.channels.*;
+
+public class WakeupEmpty {
+
+ private final static int SLEEP_TIME = 100;
+
+ public static void main(String[] argv) throws Exception {
+ final Selector sel = Selector.open();
+ Thread thread = new Thread() {
+ public void run() {
+ try {
+ sleep(SLEEP_TIME);
+ } catch (InterruptedException e) {
+ //ignore
+ }
+ sel.wakeup();
+ }
+ };
+ thread.start();
+ if (sel.select() != 0)
+ throw new Exception("Zero expected");
+ }
+}
diff --git a/test/java/nio/channels/Selector/WakeupNow.java b/test/java/nio/channels/Selector/WakeupNow.java
new file mode 100644
index 0000000..f939e90
--- /dev/null
+++ b/test/java/nio/channels/Selector/WakeupNow.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2001-2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4940372
+ * @summary Ensure that the wakeup state is cleared by selectNow()
+ */
+
+import java.nio.channels.*;
+
+public class WakeupNow {
+
+ public static void main(String[] args) throws Exception {
+ test1();
+ test2();
+ }
+
+ // Test if selectNow clears wakeup with the wakeup fd and
+ // another fd in the selector.
+ // This fails before the fix on Linux
+ private static void test1() throws Exception {
+ Selector sel = Selector.open();
+ Pipe p = Pipe.open();
+ p.source().configureBlocking(false);
+ p.source().register(sel, SelectionKey.OP_READ);
+ sel.wakeup();
+ sel.selectNow();
+ long startTime = System.currentTimeMillis();
+ int n = sel.select(2000);
+ long endTime = System.currentTimeMillis();
+ if (endTime - startTime < 1000)
+ throw new RuntimeException("test failed");
+ }
+
+ // Test if selectNow clears wakeup with only the wakeup fd
+ // in the selector.
+ // This fails before the fix on Solaris
+ private static void test2() throws Exception {
+ Selector sel = Selector.open();
+ Pipe p = Pipe.open();
+ p.source().configureBlocking(false);
+ sel.wakeup();
+ sel.selectNow();
+ long startTime = System.currentTimeMillis();
+ int n = sel.select(2000);
+ long endTime = System.currentTimeMillis();
+ if (endTime - startTime < 1000)
+ throw new RuntimeException("test failed");
+ }
+
+}
diff --git a/test/java/nio/channels/Selector/WakeupOverflow.java b/test/java/nio/channels/Selector/WakeupOverflow.java
new file mode 100644
index 0000000..109e00e
--- /dev/null
+++ b/test/java/nio/channels/Selector/WakeupOverflow.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4619326
+ * @summary Check for overflow of wakeup buffer
+ */
+
+import java.nio.channels.*;
+
+public class WakeupOverflow {
+ public static void main( String[] args ) throws Exception {
+ Selector selector = Selector.open();
+ for(int i=0; i<10000; i++) {
+ selector.wakeup();
+ }
+ }
+}
diff --git a/test/java/nio/channels/Selector/WakeupSpeed.java b/test/java/nio/channels/Selector/WakeupSpeed.java
new file mode 100644
index 0000000..269e467
--- /dev/null
+++ b/test/java/nio/channels/Selector/WakeupSpeed.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4467968
+ * @summary Tests wether wakeup makes the next select() call return immediately
+ */
+
+import java.io.IOException;
+import java.nio.channels.Selector;
+
+
+public class WakeupSpeed {
+
+ public static void main(String argv[]) throws Exception {
+ int waitTime = 4000;
+ Selector selector = Selector.open();
+
+ selector.wakeup();
+
+ long t1 = System.currentTimeMillis();
+ selector.select(waitTime);
+ long t2 = System.currentTimeMillis();
+ long totalTime = t2 - t1;
+
+ if (totalTime > waitTime)
+ throw new RuntimeException("Test failed");
+ }
+
+}
diff --git a/test/java/nio/channels/ServerSocketChannel/AcceptAddress.java b/test/java/nio/channels/ServerSocketChannel/AcceptAddress.java
new file mode 100644
index 0000000..a05e33e
--- /dev/null
+++ b/test/java/nio/channels/ServerSocketChannel/AcceptAddress.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary test the address returned in socket from accept
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+
+public class AcceptAddress {
+
+ public static void main(String[] args) throws Exception {
+ InetAddress local = InetAddress.getLocalHost();
+ InetSocketAddress isa = new InetSocketAddress(local, 5555);
+
+ ServerSocketChannel ssc;
+ ssc = ServerSocketChannel.open();
+ ssc.socket().bind(isa);
+
+ SocketChannel sc;
+ sc = SocketChannel.open();
+ sc.connect(isa);
+
+ SocketChannel sc2 = ssc.accept();
+ System.err.println("Socket connected to " + sc2);
+ }
+}
diff --git a/test/java/nio/channels/ServerSocketChannel/AdaptServerSocket.java b/test/java/nio/channels/ServerSocketChannel/AdaptServerSocket.java
new file mode 100644
index 0000000..9b1c701
--- /dev/null
+++ b/test/java/nio/channels/ServerSocketChannel/AdaptServerSocket.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Unit test for server-socket-channel adaptors
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+
+
+public class AdaptServerSocket {
+
+ static java.io.PrintStream out = System.out;
+
+ static volatile Exception clientException = null;
+ static volatile Thread client = null;
+
+ static void startClient(final int port, final int dally)
+ throws Exception
+ {
+ Thread t = new Thread() {
+ public void run() {
+ try {
+ Socket so = new Socket();
+ out.println("client: " + so);
+ if (dally > 0)
+ Thread.sleep(dally);
+ so.connect(new InetSocketAddress(port));
+ if (Thread.interrupted()) {
+ out.println("client interrupted");
+ so.close();
+ return;
+ }
+ out.println("client: " + so);
+ int a = so.getInputStream().read();
+ out.println("client: read " + a);
+ a += 1;
+ so.getOutputStream().write(a);
+ out.println("client: wrote " + a);
+ so.close();
+ } catch (Exception x) {
+ if (x instanceof InterruptedException)
+ return;
+ clientException = x;
+ x.printStackTrace();
+ }
+ }
+ };
+ t.setDaemon(true);
+ t.start();
+ client = t;
+ }
+
+ static void test(int clientDally, int timeout, boolean shouldTimeout)
+ throws Exception
+ {
+ out.println();
+
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ServerSocket sso = ssc.socket();
+ out.println("created: " + ssc);
+ out.println(" " + sso);
+ if (timeout != 0)
+ sso.setSoTimeout(timeout);
+ out.println("timeout: " + sso.getSoTimeout());
+ sso.bind(null);
+ out.println("bound: " + ssc);
+ out.println(" " + sso);
+ startClient(sso.getLocalPort(), clientDally);
+ Thread.sleep(10);
+
+ Socket so = null;
+ try {
+ so = sso.accept();
+ } catch (SocketTimeoutException x) {
+ if (shouldTimeout)
+ out.println("Accept timed out, as expected");
+ else
+ throw x;
+ }
+ if (shouldTimeout && (so != null))
+ throw new Exception("Accept did not time out");
+
+ if (so != null) {
+ int a = 42;
+ so.getOutputStream().write(a);
+ int b = so.getInputStream().read();
+ if (b != a + 1)
+ throw new Exception("Read incorrect data");
+ out.println("server: read " + b);
+ sso.close();
+ }
+
+ client.interrupt();
+ client.join();
+ if (clientException != null)
+ throw clientException;
+ }
+
+ public static void main(String[] args) throws Exception {
+ test(0, 0, false);
+ test(50, 500, false);
+ test(500, 50, true);
+ }
+
+}
diff --git a/test/java/nio/channels/ServerSocketChannel/Basic.java b/test/java/nio/channels/ServerSocketChannel/Basic.java
new file mode 100644
index 0000000..90aa6cc
--- /dev/null
+++ b/test/java/nio/channels/ServerSocketChannel/Basic.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Unit test for server-socket channels
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+
+public class Basic {
+
+ static PrintStream log = System.err;
+
+ static class Server
+ extends TestThread
+ {
+ ServerSocketChannel ssc;
+ boolean block;
+
+ Server(ServerSocketChannel ssc, boolean block) {
+ super("Server", Basic.log);
+ this.ssc = ssc;
+ this.block = block;
+ }
+
+ void go() throws Exception {
+ log.println("Server: Listening "
+ + (block ? "(blocking)" : "(non-blocking)"));
+ if (!block)
+ ssc.configureBlocking(false);
+ log.println(" " + ssc);
+ //log.println(" " + ssc.options());
+ SocketChannel sc = null;
+ for (;;) {
+ sc = ssc.accept();
+ if (sc != null) {
+ break;
+ }
+ log.println("Server: Sleeping...");
+ Thread.sleep(50);
+ }
+ log.println("Server: Accepted " + sc);
+ ByteBuffer bb = ByteBuffer.allocateDirect(100);
+ if (sc.read(bb) != 1)
+ throw new Exception("Read failed");
+ bb.flip();
+ byte b = bb.get();
+ log.println("Server: Read " + b + ", writing " + (b + 1));
+ bb.clear();
+ bb.put((byte)43);
+ bb.flip();
+ if (sc.write(bb) != 1)
+ throw new Exception("Write failed");
+ sc.close();
+ ssc.close();
+ log.println("Server: Finished");
+ }
+
+ }
+
+ static class Client
+ extends TestThread
+ {
+ int port;
+ boolean dally;
+
+ Client(int port, boolean block) {
+ super("Client", Basic.log);
+ this.port = port;
+ this.dally = !block;
+ }
+
+ public void go() throws Exception {
+ if (dally)
+ Thread.sleep(200);
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getLocalHost(), port);
+ log.println("Client: Connecting to " + isa);
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(isa);
+ log.println("Client: Connected");
+ ByteBuffer bb = ByteBuffer.allocateDirect(512);
+ bb.put((byte)42).flip();
+ log.println("Client: Writing " + bb.get(0));
+ if (sc.write(bb) != 1)
+ throw new Exception("Write failed");
+ bb.clear();
+ if (sc.read(bb) != 1)
+ throw new Exception("Read failed");
+ bb.flip();
+ if (bb.get() != 43)
+ throw new Exception("Read " + bb.get(bb.position() - 1));
+ log.println("Client: Read " + bb.get(0));
+ sc.close();
+ log.println("Client: Finished");
+ }
+
+ }
+
+ static void test(boolean block) throws Exception {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().setReuseAddress(true);
+ int port = TestUtil.bind(ssc);
+ Server server = new Server(ssc, block);
+ Client client = new Client(port, block);
+ server.start();
+ client.start();
+ if ((server.finish(2000) & client.finish(100)) == 0)
+ throw new Exception("Failure");
+ log.println();
+ }
+
+ public static void main(String[] args) throws Exception {
+ log.println();
+ test(true);
+ test(false);
+ }
+
+}
diff --git a/test/java/nio/channels/ServerSocketChannel/NonBlockingAccept.java b/test/java/nio/channels/ServerSocketChannel/NonBlockingAccept.java
new file mode 100644
index 0000000..bf68b22
--- /dev/null
+++ b/test/java/nio/channels/ServerSocketChannel/NonBlockingAccept.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4801882 5046333
+ * @summary test ServerSocketAdaptor.accept on nonblocking channel
+ * @library ..
+ * @build TestUtil
+ * @run main NonBlockingAccept
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+
+public class NonBlockingAccept {
+
+ public static void main(String[] args) throws Exception {
+
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ InetSocketAddress isa = TestUtil.bindToRandomPort(ssc);
+ ssc.configureBlocking(false);
+ ServerSocket ss = ssc.socket();
+
+ // Exception should be thrown when no connection is waiting
+ try {
+ ss.accept();
+ throw new RuntimeException("Expected exception not thrown");
+ } catch (IllegalBlockingModeException ibme) {
+ // Correct result
+ }
+
+ // No exception should be thrown when a connection is waiting (5046333)
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ sc.connect(isa);
+ Thread.sleep(100);
+ ss.accept();
+
+ }
+
+}
diff --git a/test/java/nio/channels/ServerSocketChannel/Open.java b/test/java/nio/channels/ServerSocketChannel/Open.java
new file mode 100644
index 0000000..ac15d1b
--- /dev/null
+++ b/test/java/nio/channels/ServerSocketChannel/Open.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4481869
+ * @summary test the address returned in socket from accept
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+
+public class Open {
+ public static void main(String args[]) throws IOException {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.configureBlocking(false);
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/AdaptSocket.java b/test/java/nio/channels/SocketChannel/AdaptSocket.java
new file mode 100644
index 0000000..9683f34
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/AdaptSocket.java
@@ -0,0 +1,162 @@
+/*
+ * Copyright 2001-2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Unit test for socket-channel adaptors
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+
+
+public class AdaptSocket {
+
+ static java.io.PrintStream out = System.out;
+
+ static final int ECHO_PORT = 7;
+ static final int DAYTIME_PORT = 13;
+ static final String REMOTE_HOST = TestUtil.HOST;
+ static final String VERY_REMOTE_HOST = TestUtil.FAR_HOST;
+
+ static void test(String hn, int timeout, boolean shouldTimeout)
+ throws Exception
+ {
+ out.println();
+
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getByName(hn),
+ DAYTIME_PORT);
+ SocketChannel sc = SocketChannel.open();
+ Socket so = sc.socket();
+ out.println("opened: " + so);
+ out.println(" " + sc);
+
+ //out.println("opts: " + sc.options());
+ so.setTcpNoDelay(true);
+ //so.setTrafficClass(SocketOpts.IP.TOS_THROUGHPUT);
+ so.setKeepAlive(true);
+ so.setSoLinger(true, 42);
+ so.setOOBInline(true);
+ so.setReceiveBufferSize(512);
+ so.setSendBufferSize(512);
+ //out.println(" " + sc.options());
+
+ if (timeout == 0)
+ so.connect(isa);
+ else {
+ try {
+ so.connect(isa, timeout);
+ } catch (SocketTimeoutException x) {
+ if (shouldTimeout) {
+ out.println("Connection timed out, as expected");
+ return;
+ } else {
+ throw x;
+ }
+ }
+ if (shouldTimeout)
+ throw new Exception("Connection did not time out");
+ }
+ out.println("connected: " + so);
+ out.println(" " + sc);
+ byte[] bb = new byte[100];
+ int n = so.getInputStream().read(bb);
+ String s = new String(bb, 0, n - 2, "US-ASCII");
+ out.println(isa + " says: \"" + s + "\"");
+ so.shutdownInput();
+ out.println("ishut: " + sc);
+ so.shutdownOutput();
+ out.println("oshut: " + sc);
+ so.close();
+ out.println("closed: " + so);
+ out.println(" " + sc);
+ }
+
+ static String dataString = "foo\r\n";
+
+ static void testRead(Socket so, boolean shouldTimeout)
+ throws Exception
+ {
+ String data = "foo\r\n";
+ so.getOutputStream().write(dataString.getBytes("US-ASCII"));
+ InputStream is = so.getInputStream();
+ try {
+ byte[] b = new byte[100];
+ int n = is.read(b);
+ if (n != 5)
+ throw new Exception("Incorrect number of bytes read: " + n);
+ if (!dataString.equals(new String(b, 0, n, "US-ASCII")))
+ throw new Exception("Incorrect data read: " + n);
+ } catch (SocketTimeoutException x) {
+ if (shouldTimeout) {
+ out.println("Read timed out, as expected");
+ return;
+ }
+ throw x;
+ }
+ if (shouldTimeout)
+ throw new Exception("Read did not time out");
+ }
+
+ static void testRead(String hn, int timeout, boolean shouldTimeout)
+ throws Exception
+ {
+ out.println();
+
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getByName(hn), ECHO_PORT);
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(isa);
+ Socket so = sc.socket();
+ out.println("connected: " + so);
+ out.println(" " + sc);
+
+ if (timeout > 0)
+ so.setSoTimeout(timeout);
+ out.println("timeout: " + so.getSoTimeout());
+
+ testRead(so, shouldTimeout);
+ if (!TestUtil.onME())
+ for (int i = 0; i < 4; i++)
+ testRead(so, shouldTimeout);
+
+ sc.close();
+ }
+
+ public static void main(String[] args) throws Exception {
+
+ test(REMOTE_HOST, 0, false);
+ test(REMOTE_HOST, 1000, false);
+ test(VERY_REMOTE_HOST, 10, true);
+
+ testRead(REMOTE_HOST, 0, false);
+ testRead(REMOTE_HOST, 8000, false);
+ testRead(VERY_REMOTE_HOST, 10, true);
+
+ }
+
+}
diff --git a/test/java/nio/channels/SocketChannel/AsyncCloseChannel.java b/test/java/nio/channels/SocketChannel/AsyncCloseChannel.java
new file mode 100644
index 0000000..eca9295
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/AsyncCloseChannel.java
@@ -0,0 +1,241 @@
+/*
+ * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 6285901
+ * @summary Check no data is written to wrong socket channel during async closing.
+ * @author Xueming Shen
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.net.*;
+
+public class AsyncCloseChannel {
+ static boolean failed = false;
+ static boolean keepGoing = true;
+ static String host = "127.0.0.1";
+ static int sensorPort = 3010;
+ static int targetPort = 3020;
+ static int maxAcceptCount = 1000;
+ static int acceptCount = 0;
+
+ public static void main(String args[]) throws Exception {
+ if (System.getProperty("os.name").startsWith("Windows")) {
+ System.err.println("WARNING: Still does not work on Windows!");
+ return;
+ }
+ Thread ss = new SensorServer(); ss.start();
+ Thread ts = new TargetServer(); ts.start();
+ Thread sc = new SensorClient(); sc.start();
+ Thread tc = new TargetClient(); tc.start();
+
+ while(acceptCount < maxAcceptCount && !failed) {
+ Thread.yield();
+ }
+ keepGoing = false;
+ try {
+ ss.interrupt();
+ ts.interrupt();
+ sc.interrupt();
+ tc.interrupt();
+ } catch (Exception e) {}
+ if (failed)
+ throw new RuntimeException("AsyncCloseChannel2 failed after <"
+ + acceptCount + "> times of accept!");
+ }
+
+
+ static class SensorServer extends ThreadEx {
+ public void runEx() throws Exception {
+ ServerSocket server;
+ server = new ServerSocket(sensorPort);
+ while(keepGoing) {
+ try {
+ final Socket s = server.accept();
+ new Thread() {
+ public void run() {
+ try {
+ int c = s.getInputStream().read();
+ if(c != -1) {
+ // No data is ever written to the peer's socket!
+ System.out.println("Oops: read a character: "
+ + (char) c);
+ failed = true;
+ }
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ } finally {
+ closeIt(s);
+ }
+ }
+ }.start();
+ } catch (IOException ex) {
+ //ex.printStackTrace();
+ }
+ }
+ }
+ }
+
+ static class TargetServer extends ThreadEx {
+ public void runEx() throws Exception {
+
+ ServerSocket server;
+ server = new ServerSocket(targetPort);
+ while (keepGoing) {
+ try {
+ final Socket s = server.accept();
+ acceptCount++;
+ new Thread() {
+ public void run() {
+ boolean empty = true;
+ try {
+ for(;;) {
+ int c = s.getInputStream().read();
+ if(c == -1) {
+ if(!empty)
+ break;
+ }
+ empty = false;
+ }
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ } finally {
+ closeIt(s);
+ }
+ }
+ }.start();
+ } catch (IOException ex) {
+ //ex.printStackTrace();
+ }
+ }
+ }
+ }
+
+ static class SensorClient extends Thread {
+ private static boolean wake;
+ private static SensorClient theClient;
+ public void run() {
+ while (keepGoing) {
+ Socket s = null;
+ try {
+ s = new Socket();
+ synchronized(this) {
+ while(!wake) {
+ try {
+ wait();
+ } catch (InterruptedException ex) { }
+ }
+ }
+ wake = false;
+ s.connect(new InetSocketAddress(host, sensorPort));
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException ex) { }
+ } catch (IOException ex) {
+ System.out.println("Exception on sensor client " + ex.getMessage());
+ } finally {
+ if(s != null) {
+ try {
+ s.close();
+ } catch(IOException ex) { ex.printStackTrace();}
+ }
+ }
+ }
+ }
+
+ public SensorClient() {
+ theClient = this;
+ }
+
+ public static void wakeMe() {
+ synchronized(theClient) {
+ wake = true;
+ theClient.notify();
+ }
+ }
+ }
+
+ static class TargetClient extends Thread {
+ volatile boolean ready = false;
+ public void run() {
+ while(keepGoing) {
+ try {
+ final SocketChannel s = SocketChannel.open(
+ new InetSocketAddress(host, targetPort));
+ s.finishConnect();
+ s.socket().setSoLinger(false, 0);
+ ready = false;
+ Thread t = new Thread() {
+ public void run() {
+ ByteBuffer b = ByteBuffer.allocate(1);
+ try {
+ for(;;) {
+ b.clear();
+ b.put((byte) 'A');
+ b.flip();
+ s.write(b);
+ ready = true;
+ }
+ } catch (IOException ex) {
+ if(!(ex instanceof ClosedChannelException))
+ System.out.println("Exception in target client child "
+ + ex.toString());
+ }
+ }
+ };
+ t.start();
+ while(!ready)
+ Thread.yield();
+ s.close();
+ SensorClient.wakeMe();
+ t.join();
+ } catch (IOException ex) {
+ System.out.println("Exception in target client parent "
+ + ex.getMessage());
+ } catch (InterruptedException ex) {}
+ }
+ }
+ }
+
+ static abstract class ThreadEx extends Thread {
+ public void run() {
+ try {
+ runEx();
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ abstract void runEx() throws Exception;
+ }
+
+
+ public static void closeIt(Socket s) {
+ try {
+ if(s != null)
+ s.close();
+ } catch (IOException ex) { }
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/Basic.java b/test/java/nio/channels/SocketChannel/Basic.java
new file mode 100644
index 0000000..dd1a34f
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/Basic.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2000-2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Unit test for socket channels
+ * @library ..
+ */
+
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+
+
+public class Basic {
+
+ static java.io.PrintStream out = System.out;
+
+ static final int DAYTIME_PORT = 13;
+ static final String DAYTIME_HOST = TestUtil.HOST;
+
+ static void test() throws Exception {
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
+ DAYTIME_PORT);
+ SocketChannel sc = SocketChannel.open(isa);
+ out.println("opened: " + sc);
+ /*
+ out.println("opts: " + sc.options());
+ ((SocketOpts.IP.TCP)sc.options())
+ .noDelay(true)
+ .typeOfService(SocketOpts.IP.TOS_THROUGHPUT)
+ .broadcast(true)
+ .keepAlive(true)
+ .linger(42)
+ .outOfBandInline(true)
+ .receiveBufferSize(128)
+ .sendBufferSize(128)
+ .reuseAddress(true);
+ out.println(" " + sc.options());
+ */
+ // sc.connect(isa);
+ out.println("connected: " + sc);
+ ByteBuffer bb = ByteBuffer.allocateDirect(100);
+ int n = sc.read(bb);
+ bb.position(bb.position() - 2); // Drop CRLF
+ bb.flip();
+ CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
+ out.println(isa + " says: \"" + cb + "\"");
+ sc.socket().shutdownInput();
+ out.println("ishut: " + sc);
+ sc.socket().shutdownOutput();
+ out.println("oshut: " + sc);
+ sc.close();
+ out.println("closed: " + sc);
+ }
+
+ public static void main(String[] args) throws Exception {
+ test();
+ }
+
+}
diff --git a/test/java/nio/channels/SocketChannel/BigReadWrite.java b/test/java/nio/channels/SocketChannel/BigReadWrite.java
new file mode 100644
index 0000000..dcc22bc
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/BigReadWrite.java
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4863423
+ * @summary Test Util caching policy
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class BigReadWrite {
+
+ static int port = 40170;
+ static int testSize = 15;
+
+ public static void main(String[] args) throws Exception {
+ // One platform suffices to check for this bug
+ String osName = System.getProperty("os.name");
+ if (!osName.startsWith("SunOS"))
+ return;
+
+ FileOutputStream fos = new FileOutputStream("/dev/zero");
+ FileChannel fc = fos.getChannel();
+
+ // Three small writes to fill up the Util cache
+ ByteBuffer buf = ByteBuffer.allocate(900);
+ fc.write(buf);
+ buf = ByteBuffer.allocate(950);
+ fc.write(buf);
+ buf = ByteBuffer.allocate(975);
+ fc.write(buf);
+ buf = ByteBuffer.allocate(4419000);
+
+ // Now initiate large write to create larger direct buffers
+ long iterations = 0;
+ while (iterations < 50) {
+ fc.write(buf);
+ buf.rewind();
+ iterations++;
+ }
+ // Clean up
+ fc.close();
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/Bind.java b/test/java/nio/channels/SocketChannel/Bind.java
new file mode 100644
index 0000000..3c29fe6
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/Bind.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4774315
+ * @summary Test if bind problems cause BindException not SocketException
+ */
+
+import java.net.*;
+import java.nio.channels.*;
+
+public class Bind {
+ public static void main(String[] args) throws Exception {
+ try {
+ SocketChannel channel1 = SocketChannel.open();
+ channel1.socket().bind(new InetSocketAddress(5555));
+ SocketChannel channel2 = SocketChannel.open();
+ channel2.socket().bind(new InetSocketAddress(5555));
+ } catch (BindException be) {
+ // Correct result
+ }
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/BufferSize.java b/test/java/nio/channels/SocketChannel/BufferSize.java
new file mode 100644
index 0000000..cde4d83
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/BufferSize.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4514230
+ * @summary Test setting illegal buffer sizes
+ * @library ..
+ */
+
+import java.nio.channels.*;
+import java.net.*;
+
+public class BufferSize {
+
+ static final int DAYTIME_PORT = 13;
+ static final String DAYTIME_HOST = TestUtil.HOST;
+
+ public static void main(String[] args) throws Exception {
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
+ DAYTIME_PORT);
+ ServerSocketChannel sc = ServerSocketChannel.open();
+ try {
+ sc.socket().setReceiveBufferSize(-1);
+ throw new Exception("Illegal size accepted");
+ } catch (IllegalArgumentException iae) {
+ // correct behavior
+ }
+ try {
+ sc.socket().setReceiveBufferSize(0);
+ throw new Exception("Illegal size accepted");
+ } catch (IllegalArgumentException iae) {
+ // correct behavior
+ }
+ sc.close();
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/Close.java b/test/java/nio/channels/SocketChannel/Close.java
new file mode 100644
index 0000000..89e9cea
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/Close.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4458266
+ */
+
+import java.io.IOException;
+import java.net.*;
+import java.nio.channels.*;
+
+
+public class Close {
+
+ static SelectionKey open() throws IOException {
+ SocketChannel sc = SocketChannel.open();
+ Selector sel = Selector.open();
+ sc.configureBlocking(false);
+ return sc.register(sel, SelectionKey.OP_READ);
+ }
+
+ static void check(SelectionKey sk) throws IOException {
+ if (sk.isValid())
+ throw new RuntimeException("Key still valid");
+ if (sk.channel().isOpen())
+ throw new RuntimeException("Channel still open");
+ // if (!((SocketChannel)sk.channel()).socket().isClosed())
+ // throw new RuntimeException("Socket still open");
+ }
+
+ static void testSocketClose() throws IOException {
+ SelectionKey sk = open();
+ //((SocketChannel)sk.channel()).socket().close();
+ check(sk);
+ }
+
+ static void testChannelClose() throws IOException {
+ SelectionKey sk = open();
+ sk.channel().close();
+ check(sk);
+ }
+
+ public static void main(String[] args) throws Exception {
+ //## testSocketClose();
+ testChannelClose();
+ }
+
+}
diff --git a/test/java/nio/channels/SocketChannel/CloseAfterConnect.java b/test/java/nio/channels/SocketChannel/CloseAfterConnect.java
new file mode 100644
index 0000000..d316332
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/CloseAfterConnect.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 6380091
+ */
+import java.nio.channels.SocketChannel;
+import java.nio.channels.ServerSocketChannel;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.io.IOException;
+
+public class CloseAfterConnect {
+ public static void main(String[] args) throws Exception {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(new InetSocketAddress(0));
+
+ InetAddress lh = InetAddress.getLocalHost();
+ final SocketChannel sc = SocketChannel.open();
+ final InetSocketAddress isa =
+ new InetSocketAddress(lh, ssc.socket().getLocalPort());
+
+ // establish connection in another thread
+ Runnable connector =
+ new Runnable() {
+ public void run() {
+ try {
+ sc.connect(isa);
+ } catch (IOException ioe) {
+ ioe.printStackTrace();
+ }
+ }
+ };
+ Thread thr = new Thread(connector);
+ thr.start();
+
+ // wait for connect to be established and for thread to
+ // terminate
+ do {
+ try {
+ thr.join();
+ } catch (InterruptedException x) { }
+ } while (thr.isAlive());
+
+ // check connection is established
+ if (!sc.isConnected()) {
+ throw new RuntimeException("SocketChannel not connected");
+ }
+
+ // close channel - this triggered the bug as it attempted to signal
+ // a thread that no longer exists
+ sc.close();
+
+ // clean-up
+ ssc.accept().close();
+ ssc.close();
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/CloseRegisteredChannel.java b/test/java/nio/channels/SocketChannel/CloseRegisteredChannel.java
new file mode 100644
index 0000000..20b12cd
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/CloseRegisteredChannel.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ @bug 4960962 6215050
+ @summary Test if the registered SocketChannel can be closed immediately
+ @run main/timeout=10 CloseRegisteredChannel
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.net.*;
+
+public class CloseRegisteredChannel {
+ public static void main(String[] args) throws Exception {
+ ServerSocketChannel server = ServerSocketChannel.open();
+ ServerSocket s = server.socket ();
+ s.bind (new InetSocketAddress (0));
+ int port = s.getLocalPort ();
+ //System.out.println ("listening on port " + port);
+
+ SocketChannel client = SocketChannel.open ();
+ client.connect (new InetSocketAddress ("127.0.0.1", port));
+ SocketChannel slave = server.accept ();
+ slave.configureBlocking (true);
+
+ Selector selector = Selector.open ();
+ client.configureBlocking (false);
+ SelectionKey key = client.register (
+ selector, SelectionKey.OP_READ, null
+ );
+ client.close();
+ //System.out.println ("client.isOpen = " + client.isOpen());
+ System.out.println ("Will hang here...");
+ int nb = slave.read (ByteBuffer.allocate (1024));
+ //System.out.println("read nb=" + nb);
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/CloseTimeoutChannel.java b/test/java/nio/channels/SocketChannel/CloseTimeoutChannel.java
new file mode 100644
index 0000000..311c109
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/CloseTimeoutChannel.java
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ @bug 4726957 4724030 6232954
+ @summary Test if the SocketChannel with timeout set can be closed immediately
+ @run main/timeout=20 CloseTimeoutChannel
+ */
+
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.net.*;
+
+public class CloseTimeoutChannel {
+ final static int PORT=6347;
+ public static void main(String args[]) throws Exception {
+ try {
+ ServerSocketChannel listener=ServerSocketChannel.open();
+ listener.socket().bind(new InetSocketAddress(PORT));
+ AcceptorThread thread=new AcceptorThread(listener);
+ thread.start();
+ } catch (IOException e) {
+ System.out.println("Mysterious IO problem");
+ e.printStackTrace();
+ System.exit(1);
+ }
+
+ //Establish connection. Bug only happens if we open with channel.
+ try {
+ System.out.println("Establishing connection");
+ Socket socket=SocketChannel.open(
+ new InetSocketAddress("127.0.0.1", PORT)).socket();
+ OutputStream out=socket.getOutputStream();
+ InputStream in=socket.getInputStream();
+
+ System.out.println("1. Writing byte 1");
+ out.write((byte)1);
+
+ int n=read(socket, in);
+ System.out.println("Read byte "+n+"\n");
+
+ System.out.println("3. Writing byte 3");
+ out.write((byte)3);
+
+ System.out.println("Closing");
+ socket.close();
+ } catch (IOException e) {
+ System.out.println("Mysterious IO problem");
+ e.printStackTrace();
+ System.exit(1);
+ }
+ }
+
+ /** Reads one byte from in, which must be s.getInputStream. */
+ private static int read(Socket s, InputStream in) throws IOException {
+ try {
+ s.setSoTimeout(8000); //causes a bug!
+ return in.read();
+ } finally {
+ s.setSoTimeout(0);
+ }
+
+ }
+
+ /** Server thread */
+ static class AcceptorThread extends Thread {
+ final String INDENT="\t\t\t\t";
+ ServerSocketChannel _listener;
+ /** @param listener MUST be bound to a port */
+ AcceptorThread(ServerSocketChannel listener) {
+ _listener=listener;
+ }
+
+ public void run() {
+ try {
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) { }
+
+ System.out.println(INDENT+"Listening on port "+ PORT);
+ ByteBuffer buf=ByteBuffer.allocate(5);
+ Socket client=_listener.accept().socket();;
+ System.out.println(INDENT+"Accepted client");
+
+ OutputStream out=client.getOutputStream();
+ InputStream in=client.getInputStream();
+
+ int n=in.read();
+ System.out.println(INDENT+"Read byte "+n+"\n");
+
+ System.out.println(INDENT+"2. Writing byte 2");
+ out.write((byte)2);
+
+ n=in.read();
+ System.out.println(INDENT+"Read byte "+n+"\n");
+
+ n=in.read();
+ System.out.println(INDENT+"Read byte "
+ +(n<0 ? "EOF" : Integer.toString(n)));
+
+ System.out.println(INDENT+"Closing");
+ client.close();
+ } catch (IOException e) {
+ System.out.println(INDENT+"Error accepting!");
+ }
+ }
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/Connect.java b/test/java/nio/channels/SocketChannel/Connect.java
new file mode 100644
index 0000000..8e98d5f
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/Connect.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4650679
+ * @summary Unit test for socket channels
+ * @library ..
+ */
+
+import java.nio.*;
+import java.nio.channels.*;
+import java.net.*;
+import java.util.*;
+
+public class Connect {
+
+ private static final long INCREMENTAL_DELAY = 30L * 1000L;
+
+ public static void main(String args[]) throws Exception {
+ test1(TestUtil.HOST);
+ try {
+ test1(TestUtil.REFUSING_HOST);
+ throw new Exception("Refused connection throws no exception");
+ } catch (ConnectException ce) {
+ // Correct result
+ }
+ }
+
+ static void test1(String hostname) throws Exception {
+ Selector selector;
+ SocketChannel sc;
+ SelectionKey sk;
+ InetSocketAddress isa = new InetSocketAddress(
+ InetAddress.getByName (hostname), 80);
+ sc = SocketChannel.open();
+ sc.configureBlocking(false);
+
+ selector = Selector.open();
+ sk = sc.register(selector, SelectionKey.OP_CONNECT);
+ if (sc.connect(isa)) {
+ System.err.println("Connected immediately!");
+ sc.close();
+ selector.close();
+ return;
+ } else {
+ ByteBuffer buf = ByteBuffer.allocateDirect(100);
+ buf.asCharBuffer().put(new String(
+ "The quick brown fox jumped over the lazy dog."
+ ).toCharArray());
+ buf.flip();
+ long startTime = System.currentTimeMillis();
+ while(true) {
+ selector.select(INCREMENTAL_DELAY);
+ Set selectedKeys = selector.selectedKeys();
+
+ if(selectedKeys.isEmpty()) {
+ System.err.println("Elapsed time without response: " +
+ (System.currentTimeMillis() -
+ startTime) / 1000L + " seconds.");
+ }
+ else if(!selectedKeys.contains(sk))
+ {
+ System.err.println("Got wrong event about selection key.");
+ } else {
+ System.err.println("Got event for our selection key.");
+ if(sk.isConnectable()) {
+ if(sc.finishConnect()) {
+ if(sc.isConnected()) {
+ System.err.println("Successful connect.");
+ sk.interestOps(SelectionKey.OP_WRITE);
+ sc.write(buf);
+ } else {
+ System.err.println(
+ "Finish connect completed incorrectly.");
+ }
+ } else {
+ System.err.println(
+ "key incorrectly indicated socket channel connectable.");
+ }
+ }
+ if(sk.isWritable() && (buf.remaining() > 0)) {
+ sc.write(buf);
+ }
+ if(buf.remaining() == 0) {
+ System.err.println(
+ "SUCCESS! buffer contents were sent.");
+ sc.close();
+ selector.close();
+ return;
+ }
+ }
+ selectedKeys.clear();
+ }
+ }
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/ConnectState.java b/test/java/nio/channels/SocketChannel/ConnectState.java
new file mode 100644
index 0000000..f806585
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/ConnectState.java
@@ -0,0 +1,216 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test socket-channel connection-state transitions
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+
+public class ConnectState {
+
+ static PrintStream log = System.err;
+
+ static String REMOTE_HOST = TestUtil.HOST;
+ static int REMOTE_PORT = 7; // echo
+ static InetSocketAddress remote;
+
+ final static int ST_UNCONNECTED = 0;
+ final static int ST_PENDING = 1;
+ final static int ST_CONNECTED = 2;
+ final static int ST_CLOSED = 3;
+
+ static abstract class Test {
+
+ abstract String go(SocketChannel sc) throws Exception;
+
+ static void check(boolean test, String desc) throws Exception {
+ if (!test)
+ throw new Exception("Incorrect state: " + desc);
+ }
+
+ static void check(SocketChannel sc, int state) throws Exception {
+ switch (state) {
+ case ST_UNCONNECTED:
+ check(!sc.isConnected(), "!isConnected");
+ check(!sc.isConnectionPending(), "!isConnectionPending");
+ check(sc.isOpen(), "isOpen");
+ break;
+ case ST_PENDING:
+ check(!sc.isConnected(), "!isConnected");
+ check(sc.isConnectionPending(), "isConnectionPending");
+ check(sc.isOpen(), "isOpen");
+ break;
+ case ST_CONNECTED:
+ check(sc.isConnected(), "isConnected");
+ check(!sc.isConnectionPending(), "!isConnectionPending");
+ check(sc.isOpen(), "isOpen");
+ break;
+ case ST_CLOSED:
+ check(sc.isConnected(), "isConnected");
+ check(!sc.isConnectionPending(), "!isConnectionPending");
+ check(sc.isOpen(), "isOpen");
+ break;
+ }
+ }
+
+ Test(String name, Class exception, int state) throws Exception {
+ SocketChannel sc = SocketChannel.open();
+ String note = null;
+ try {
+ try {
+ note = go(sc);
+ } catch (Exception x) {
+ if (exception != null) {
+ if (exception.isInstance(x)) {
+ log.println(name + ": As expected: "
+ + x);
+ check(sc, state);
+ return;
+ } else {
+ throw new Exception(name
+ + ": Incorrect exception",
+ x);
+ }
+ } else {
+ throw new Exception(name
+ + ": Unexpected exception",
+ x);
+ }
+ }
+ if (exception != null)
+ throw new Exception(name
+ + ": Expected exception not thrown: "
+ + exception);
+ check(sc, state);
+ log.println(name + ": Returned normally"
+ + ((note != null) ? ": " + note : ""));
+ } finally {
+ if (sc.isOpen())
+ sc.close();
+ }
+ }
+
+ }
+
+ static void tests() throws Exception {
+ log.println(remote);
+
+ new Test("Read unconnected", NotYetConnectedException.class,
+ ST_UNCONNECTED) {
+ String go(SocketChannel sc) throws Exception {
+ ByteBuffer b = ByteBuffer.allocateDirect(1024);
+ sc.read(b);
+ return null;
+ }};
+
+ new Test("Write unconnected", NotYetConnectedException.class,
+ ST_UNCONNECTED) {
+ String go(SocketChannel sc) throws Exception {
+ ByteBuffer b = ByteBuffer.allocateDirect(1024);
+ sc.write(b);
+ return null;
+ }};
+
+ new Test("Simple connect", null, ST_CONNECTED) {
+ String go(SocketChannel sc) throws Exception {
+ sc.connect(remote);
+ return null;
+ }};
+
+ new Test("Simple connect & finish", null, ST_CONNECTED) {
+ String go(SocketChannel sc) throws Exception {
+ sc.connect(remote);
+ if (!sc.finishConnect())
+ throw new Exception("finishConnect returned false");
+ return null;
+ }};
+
+ new Test("Double connect",
+ AlreadyConnectedException.class, ST_CONNECTED) {
+ String go(SocketChannel sc) throws Exception {
+ sc.connect(remote);
+ sc.connect(remote);
+ return null;
+ }};
+
+ new Test("Finish w/o start",
+ NoConnectionPendingException.class, ST_UNCONNECTED) {
+ String go(SocketChannel sc) throws Exception {
+ sc.finishConnect();
+ return null;
+ }};
+
+ new Test("NB simple connect", null, ST_CONNECTED) {
+ String go(SocketChannel sc) throws Exception {
+ sc.configureBlocking(false);
+ sc.connect(remote);
+ int n = 0;
+ while (!sc.finishConnect()) {
+ Thread.sleep(10);
+ n++;
+ }
+ sc.finishConnect(); // Check redundant invocation
+ return ("Tries to finish = " + n);
+ }};
+
+ new Test("NB double connect",
+ ConnectionPendingException.class, ST_PENDING) {
+ String go(SocketChannel sc) throws Exception {
+ sc.configureBlocking(false);
+ sc.connect(remote);
+ sc.connect(remote);
+ return null;
+ }};
+
+ new Test("NB finish w/o start",
+ NoConnectionPendingException.class, ST_UNCONNECTED) {
+ String go(SocketChannel sc) throws Exception {
+ sc.configureBlocking(false);
+ sc.finishConnect();
+ return null;
+ }};
+
+ new Test("NB connect, B finish", null, ST_CONNECTED) {
+ String go(SocketChannel sc) throws Exception {
+ sc.configureBlocking(false);
+ sc.connect(remote);
+ sc.configureBlocking(true);
+ sc.finishConnect();
+ return null;
+ }};
+
+ }
+
+ public static void main(String[] args) throws Exception {
+ remote = new InetSocketAddress(InetAddress.getByName(REMOTE_HOST),
+ REMOTE_PORT);
+ tests();
+ }
+
+}
diff --git a/test/java/nio/channels/SocketChannel/ExceptionTranslation.java b/test/java/nio/channels/SocketChannel/ExceptionTranslation.java
new file mode 100644
index 0000000..6c8c9db
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/ExceptionTranslation.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/**
+ * @test
+ * @bug 4915501 6303753
+
+ * @summary check exception translation of SocketAdaptor
+ */
+
+import java.io.IOException;
+import java.nio.channels.*;
+import java.net.*;
+
+public class ExceptionTranslation {
+ public static void main(String args[]) throws Exception {
+ InetSocketAddress iAddr = new InetSocketAddress("nosuchhostname",5182);
+ try {
+ SocketChannel channel = SocketChannel.open();
+ channel.socket().connect(iAddr, 30000);
+ throw new RuntimeException("Expected exception not thrown");
+ } catch (UnknownHostException x) {
+ // Expected result
+ }
+
+ try {
+ SocketChannel chan1 = SocketChannel.open();
+ chan1.socket().bind(new InetSocketAddress(0));
+ chan1.socket().bind(new InetSocketAddress(0));
+ throw new RuntimeException("Expected exception not thrown");
+ } catch(IOException e) {
+ // Expepected result
+ }
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/FinishConnect.java b/test/java/nio/channels/SocketChannel/FinishConnect.java
new file mode 100644
index 0000000..c792abb
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/FinishConnect.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test SocketChannel.finishConnect
+ * @library ..
+ */
+
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
+import java.nio.charset.*;
+import java.util.*;
+
+
+public class FinishConnect {
+
+ static final int DAYTIME_PORT = 13;
+ static final String DAYTIME_HOST = TestUtil.HOST;
+
+ public static void main(String[] args) throws Exception {
+ test1(true, true);
+ test1(true, false);
+ test1(false, true);
+ test1(false, false);
+ test2();
+ }
+
+ static void test1(boolean select, boolean setBlocking) throws Exception {
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
+ DAYTIME_PORT);
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ boolean connected = sc.connect(isa);
+ int attempts = 0;
+
+ try {
+ sc.connect(isa);
+ throw new RuntimeException("Allowed another connect call");
+ } catch (IllegalStateException ise) {
+ // Correct behavior
+ }
+
+ if (setBlocking)
+ sc.configureBlocking(true);
+
+ if (!connected && select && !setBlocking) {
+ Selector selector = SelectorProvider.provider().openSelector();
+ sc.register(selector, SelectionKey.OP_CONNECT);
+ while (!connected) {
+ int keysAdded = selector.select(100);
+ if (keysAdded > 0) {
+ Set readyKeys = selector.selectedKeys();
+ Iterator i = readyKeys.iterator();
+ while (i.hasNext()) {
+ SelectionKey sk = (SelectionKey)i.next();
+ SocketChannel nextReady =
+ (SocketChannel)sk.channel();
+ connected = sc.finishConnect();
+ }
+ }
+ }
+ selector.close();
+ }
+
+ while (!connected) {
+ if (attempts++ > 30)
+ throw new RuntimeException("Failed to connect");
+ Thread.sleep(100);
+ connected = sc.finishConnect();
+ }
+
+ ByteBuffer bb = ByteBuffer.allocateDirect(100);
+ int bytesRead = 0;
+ int totalRead = 0;
+ while (totalRead < 20) {
+ bytesRead = sc.read(bb);
+ if (bytesRead > 0)
+ totalRead += bytesRead;
+ if (bytesRead < 0)
+ throw new RuntimeException("Message shorter than expected");
+ }
+ bb.position(bb.position() - 2); // Drop CRLF
+ bb.flip();
+ CharBuffer cb = Charset.forName("US-ASCII").newDecoder().decode(bb);
+ System.err.println(isa + " says: \"" + cb + "\"");
+ sc.close();
+ }
+
+ static void test2() throws Exception {
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
+ DAYTIME_PORT);
+ boolean done = false;
+ int globalAttempts = 0;
+ while (!done) {
+ if (globalAttempts++ > 50)
+ throw new RuntimeException("Failed to connect");
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ boolean connected = sc.connect(isa);
+ int localAttempts = 0;
+ while (!connected) {
+ if (localAttempts++ > 500)
+ throw new RuntimeException("Failed to connect");
+ connected = sc.finishConnect();
+ if (connected) {
+ done = true;
+ break;
+ }
+ Thread.sleep(10);
+ }
+ sc.close();
+ }
+ }
+
+}
diff --git a/test/java/nio/channels/SocketChannel/GetChannel.java b/test/java/nio/channels/SocketChannel/GetChannel.java
new file mode 100644
index 0000000..d5cd478
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/GetChannel.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4403255
+ * @summary Tests old streams using channels in socket case
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.util.*;
+
+
+public class GetChannel {
+ public static void main(String args[]) throws Exception {
+ InetAddress sin = null;
+ Socket soc = null,soc1 = null;
+ InputStream is = null;
+ OutputStream os = null;
+ ServerSocket srv = null;
+ int port = 0;
+ int tout = 1000;
+
+ sin = InetAddress.getLocalHost();
+ srv = new ServerSocket(port);
+ port = srv.getLocalPort();
+ soc = new Socket(sin, port);
+ soc1 = srv.accept();
+
+ BufferedReader bin = new BufferedReader(
+ new InputStreamReader(soc.getInputStream()));
+ BufferedWriter bout = new BufferedWriter(
+ new OutputStreamWriter(soc1.getOutputStream()));
+
+ bout.write("hello");
+ bout.newLine();
+ bout.flush();
+
+ String reply = bin.readLine();
+ if (!reply.equals("hello"))
+ throw new RuntimeException("Test failed");
+
+ soc.close();
+ soc1.close();
+ srv.close();
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/Hangup.java b/test/java/nio/channels/SocketChannel/Hangup.java
new file mode 100644
index 0000000..55bebc3
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/Hangup.java
@@ -0,0 +1,192 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4617165
+ * @summary Ensure that socket hangups are handled correctly
+ * @library ..
+ * @build TestUtil
+ * @run main Hangup
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.util.*;
+
+
+public class Hangup {
+
+ static PrintStream log = System.err;
+ static int failures = 0;
+
+ private static class Failure
+ extends RuntimeException
+ {
+
+ Failure(String s) {
+ super(s);
+ }
+
+ }
+
+ static void doSelect(Selector sel, SelectionKey sk, int count)
+ throws IOException
+ {
+ int n = sel.select();
+ if (n != 1)
+ throw new Failure("Select returned zero");
+ Set sks = sel.selectedKeys();
+ if (sks.size() != 1)
+ throw new Failure("Wrong size for selected-key set: "
+ + sks.size());
+ if (!sks.remove(sk))
+ throw new Failure("Key not in selected-key set");
+ log.println("S: Socket selected #" + count);
+ }
+
+ static void dally() {
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException x) { }
+ }
+
+ static void test(boolean writeFromClient, boolean readAfterClose)
+ throws IOException
+ {
+
+ ServerSocketChannel ssc = null;
+ SocketChannel cl = null; // client end
+ SocketChannel sv = null; // server end
+ Selector sel = null;
+
+ log.println();
+ log.println("Test: writeFromClient = " + writeFromClient
+ + ", readAfterClose = " + readAfterClose);
+
+ try {
+
+ int ns = 0; // Number of selection operations done
+
+ // Set up server socket
+ ssc = ServerSocketChannel.open();
+ SocketAddress sa = TestUtil.bindToRandomPort(ssc);
+ log.println("S: Listening on port "
+ + ssc.socket().getLocalPort());
+
+ // Connect client
+ cl = SocketChannel.open(sa);
+ log.println("C: Connected via port "
+ + cl.socket().getLocalPort());
+
+ // Accept client connection
+ sv = ssc.accept();
+ log.println("S: Client connection accepted");
+
+ // Create selector and register server side
+ sel = Selector.open();
+ sv.configureBlocking(false);
+ SelectionKey sk = sv.register(sel, SelectionKey.OP_READ);
+
+ ByteBuffer stuff = ByteBuffer.allocate(10);
+ int n;
+
+ if (writeFromClient) {
+
+ // Write from client, read from server
+
+ stuff.clear();
+ if (cl.write(stuff) != stuff.capacity())
+ throw new Failure("Incorrect number of bytes written");
+ log.println("C: Wrote stuff");
+ dally();
+
+ doSelect(sel, sk, ++ns);
+
+ stuff.clear();
+ if (sv.read(stuff) != stuff.capacity())
+ throw new Failure("Wrong number of bytes read");
+ log.println("S: Read stuff");
+ }
+
+ // Close client side
+ cl.close();
+ log.println("C: Socket closed");
+ dally();
+
+ // Select again
+ doSelect(sel, sk, ++ns);
+
+ if (readAfterClose) {
+ // Read from client after client has disconnected
+ stuff.clear();
+ if (sv.read(stuff) != -1)
+ throw new Failure("Wrong number of bytes read");
+ log.println("S: Read EOF");
+ }
+
+ // Select a couple more times just to make sure we're doing
+ // the right thing
+
+ doSelect(sel, sk, ++ns);
+ doSelect(sel, sk, ++ns);
+
+ } finally {
+ if (ssc != null)
+ ssc.close();
+ if (cl != null)
+ cl.close();
+ if (sv != null)
+ sv.close();
+ if (sel != null)
+ sel.close();
+ }
+
+ }
+
+ public static void main(String[] args) throws IOException {
+
+ for (boolean writeFromClient = false;; writeFromClient = true) {
+ for (boolean readAfterClose = false;; readAfterClose = true) {
+ try {
+ test(writeFromClient, readAfterClose);
+ } catch (Failure x) {
+ x.printStackTrace(log);
+ failures++;
+ }
+ if (readAfterClose)
+ break;
+ }
+ if (writeFromClient)
+ break;
+ }
+
+ if (failures > 0) {
+ log.println();
+ throw new RuntimeException("Some tests failed");
+ }
+
+ }
+
+}
diff --git a/test/java/nio/channels/SocketChannel/IsConnectable.java b/test/java/nio/channels/SocketChannel/IsConnectable.java
new file mode 100644
index 0000000..d404aaf
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/IsConnectable.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4737146 4750573
+ * @summary Test if isConnectable returns true after connected
+ * @library ..
+ */
+
+import java.net.*;
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
+import java.util.*;
+
+public class IsConnectable {
+
+ static final int DAYTIME_PORT = 13;
+ static final String DAYTIME_HOST = TestUtil.HOST;
+
+ static void test() throws Exception {
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
+ DAYTIME_PORT);
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ sc.connect(isa);
+
+ Selector selector = SelectorProvider.provider().openSelector();
+ SelectionKey key = sc.register(selector, SelectionKey.OP_CONNECT);
+ int keysAdded = selector.select();
+ if (keysAdded > 0) {
+ boolean result = sc.finishConnect();
+ if (result) {
+ keysAdded = selector.select(5000);
+ // 4750573: keysAdded should not be incremented when op is dropped
+ // from a key already in the selected key set
+ if (keysAdded > 0)
+ throw new Exception("Test failed: 4750573 detected");
+ Set sel = selector.selectedKeys();
+ Iterator i = sel.iterator();
+ SelectionKey sk = (SelectionKey)i.next();
+ // 4737146: isConnectable should be false while connected
+ if (sk.isConnectable())
+ throw new Exception("Test failed: 4737146 detected");
+ }
+ } else {
+ throw new Exception("Select failed");
+ }
+ sc.close();
+ }
+
+ public static void main(String[] args) throws Exception {
+ test();
+ }
+
+}
diff --git a/test/java/nio/channels/SocketChannel/LocalAddress.java b/test/java/nio/channels/SocketChannel/LocalAddress.java
new file mode 100644
index 0000000..76d99fe
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/LocalAddress.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2002-2005 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4672609 5076965 4739238
+ * @summary Test getLocalAddress getLocalPort
+ * @library ..
+ */
+
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class LocalAddress {
+ public static void main(String[] args) throws Exception {
+ test1();
+ }
+
+ static void test1() throws Exception {
+ InetAddress bogus = InetAddress.getByName("0.0.0.0");
+ SocketChannel sc = SocketChannel.open();
+ InetSocketAddress saddr = new InetSocketAddress(
+ InetAddress.getByName(TestUtil.HOST), 23);
+
+ //Test1: connect only
+ sc.connect(saddr);
+ InetAddress isa = sc.socket().getLocalAddress();
+ if (isa == null || isa.equals(bogus))
+ throw new RuntimeException("test failed");
+
+ //Test2: bind and connect
+ sc = SocketChannel.open();
+ sc.socket().bind(new InetSocketAddress(0));
+ if (sc.socket().getLocalPort() == 0)
+ throw new RuntimeException("test failed");
+ sc.socket().connect(saddr);
+ isa = sc.socket().getLocalAddress();
+ if (isa == null || isa.isAnyLocalAddress())
+ throw new RuntimeException("test failed");
+
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/Open.java b/test/java/nio/channels/SocketChannel/Open.java
new file mode 100644
index 0000000..bc6e912
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/Open.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4614065
+ * @summary Test SocketChannel gc after running out of fds
+ * @build Open
+ * @run shell Open.sh
+ */
+
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.channels.spi.SelectorProvider;
+
+public class Open {
+
+ static void test1() {
+ for (int i=0; i<11000; i++) {
+ try {
+ SocketChannel sc = SocketChannel.open();
+ } catch (Exception e) {
+ // Presumably "Too many open files"
+ }
+ }
+ }
+ static void test2() {
+ for (int i=0; i<11000; i++) {
+ try {
+ DatagramChannel sc = DatagramChannel.open();
+ } catch (Exception e) {
+ // Presumably "Too many open files"
+ }
+ }
+ }
+ static void test3() {
+ SelectorProvider sp = SelectorProvider.provider();
+ for (int i=0; i<11000; i++) {
+ try {
+ Pipe p = sp.openPipe();
+ } catch (Exception e) {
+ // Presumably "Too many open files"
+ }
+ }
+ }
+ static void test4() {
+ for (int i=0; i<11000; i++) {
+ try {
+ ServerSocketChannel sc = ServerSocketChannel.open();
+ } catch (Exception e) {
+ // Presumably "Too many open files"
+ }
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+
+ // Load necessary classes ahead of time
+ DatagramChannel dc = DatagramChannel.open();
+ Exception se = new SocketException();
+ SelectorProvider sp = SelectorProvider.provider();
+ Pipe p = sp.openPipe();
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+
+ test1();
+ test2();
+ test3();
+ test4();
+ }
+
+}
diff --git a/test/java/nio/channels/SocketChannel/Open.sh b/test/java/nio/channels/SocketChannel/Open.sh
new file mode 100644
index 0000000..1372e80
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/Open.sh
@@ -0,0 +1,38 @@
+#! /bin/sh
+
+#
+# Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+#
+
+ OS=`uname -s`
+ case "$OS" in
+ SunOS )
+ ulimit -n 100
+ $TESTJAVA/bin/java -classpath $TESTCLASSES Open ;;
+ * )
+ echo "unrecognized system: $OS" ;;
+ esac
+
+
+
diff --git a/test/java/nio/channels/SocketChannel/OpenLeak.java b/test/java/nio/channels/SocketChannel/OpenLeak.java
new file mode 100644
index 0000000..ab0f7df
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/OpenLeak.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 6548464
+ * @summary SocketChannel.open(SocketAddress) leaks file descriptor if
+ * connection cannot be established
+ */
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.channels.SocketChannel;
+
+public class OpenLeak {
+
+ public static void main(String[] args) throws Exception {
+ InetAddress lh = InetAddress.getLocalHost();
+ InetSocketAddress isa = new InetSocketAddress(lh, 12345);
+
+ System.setSecurityManager( new SecurityManager() );
+ for (int i=0; i<100000; i++) {
+ try {
+ SocketChannel.open(isa);
+ throw new RuntimeException("This should not happen");
+ } catch (SecurityException x) { }
+ }
+
+ }
+
+}
diff --git a/test/java/nio/channels/SocketChannel/Shutdown.java b/test/java/nio/channels/SocketChannel/Shutdown.java
new file mode 100644
index 0000000..16bd7a0
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/Shutdown.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4618960
+ * @summary Test isInputShutdown
+ * @library ..
+ */
+
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+public class Shutdown {
+
+ public static void main(String args[]) throws Exception {
+ InetSocketAddress sa = new InetSocketAddress(
+ InetAddress.getByName(TestUtil.HOST), 23);
+ SocketChannel sc = SocketChannel.open(sa);
+ boolean before = sc.socket().isInputShutdown();
+ sc.socket().shutdownInput();
+ boolean after = sc.socket().isInputShutdown();
+ sc.close();
+ if (before || !after)
+ throw new Exception("Test failed");
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/SocketInheritance.java b/test/java/nio/channels/SocketChannel/SocketInheritance.java
new file mode 100644
index 0000000..41df813
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/SocketInheritance.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright 2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @summary Sockets shouldn't be inherited when creating a child process
+ */
+import java.nio.ByteBuffer;
+import java.nio.channels.*;
+import java.net.*;
+import java.io.*;
+
+public class SocketInheritance {
+
+ /*
+ * Simple helper class to direct process output to the parent
+ * System.out
+ */
+ static class IOHandler implements Runnable {
+ InputStream in;
+
+ IOHandler(InputStream in) {
+ this.in = in;
+ }
+
+ static void handle(InputStream in) {
+ IOHandler handler = new IOHandler(in);
+ Thread thr = new Thread(handler);
+ thr.setDaemon(true);
+ thr.start();
+ }
+
+ public void run() {
+ try {
+ byte b[] = new byte[100];
+ for (;;) {
+ int n = in.read(b);
+ if (n < 0) return;
+ System.out.write(b, 0, n);
+ }
+ } catch (IOException ioe) { }
+ }
+
+ }
+
+ // connect to the given port
+ static SocketChannel connect(int port) throws IOException {
+ InetAddress lh = InetAddress.getByName("127.0.0.1");
+ InetSocketAddress isa = new InetSocketAddress(lh, port);
+ return SocketChannel.open(isa);
+ }
+
+ // simple child process that handshakes with the parent and then
+ // waits indefinitely until it is destroyed
+ static void child(int port) {
+ try {
+ connect(port).close();
+ } catch (IOException x) {
+ x.printStackTrace();
+ return;
+ }
+
+ for (;;) {
+ try {
+ Thread.sleep(10*1000);
+ } catch (InterruptedException x) { }
+ }
+ }
+
+
+ // Creates a loopback connection.
+ // Forks process which should not inherit the sockets.
+ // Close the sockets, and attempt to re-bind the listener.
+
+ static void start() throws Exception {
+
+ // setup loopback connection
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind( new InetSocketAddress(0) );
+
+ int port = ssc.socket().getLocalPort();
+
+ SocketChannel sc1 = connect(port);
+ SocketChannel sc2 = ssc.accept();
+
+ // launch the child
+ String cmd = System.getProperty("java.home") + File.separator + "bin" +
+ File.separator + "java SocketInheritance -child " + port;
+
+ Process p = Runtime.getRuntime().exec(cmd);
+
+ IOHandler.handle(p.getInputStream());
+ IOHandler.handle(p.getErrorStream());
+
+ // wait for child to connect
+ SocketChannel sc3 = ssc.accept();
+
+ // close sockets
+ sc1.close();
+ sc2.close();
+ sc3.close();
+ ssc.close();
+
+ // re-bind the listener - if the sockets were inherited then
+ // this will fail
+ try {
+ ssc = ServerSocketChannel.open();
+ ssc.socket().bind(new InetSocketAddress(port));
+ ssc.close();
+ } finally {
+ p.destroy();
+ }
+
+ }
+
+ public static void main(String[] args) throws Exception {
+ if (!System.getProperty("os.name").startsWith("Windows"))
+ return;
+
+ if (args.length == 0) {
+ start();
+ } else {
+ if (args[0].equals("-child")) {
+ child(Integer.parseInt(args[1]));
+ }
+ }
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/Stream.java b/test/java/nio/channels/SocketChannel/Stream.java
new file mode 100644
index 0000000..21b0640
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/Stream.java
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4430139
+ * @summary Test result of read on stream from nonblocking channel
+ * @library ..
+ */
+
+import java.net.*;
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+
+
+public class Stream {
+
+ static final int DAYTIME_PORT = 13;
+ static final String DAYTIME_HOST = TestUtil.HOST;
+
+ static void test() throws Exception {
+ InetSocketAddress isa
+ = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
+ DAYTIME_PORT);
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(isa);
+ sc.configureBlocking(false);
+ InputStream is = sc.socket().getInputStream();
+ byte b[] = new byte[10];
+ try {
+ int n = is.read(b);
+ throw new RuntimeException("Exception expected; none thrown");
+ } catch (IllegalBlockingModeException e) {
+ // expected result
+ }
+ sc.close();
+ }
+
+ public static void main(String[] args) throws Exception {
+ test();
+ }
+
+}
diff --git a/test/java/nio/channels/SocketChannel/Trivial.java b/test/java/nio/channels/SocketChannel/Trivial.java
new file mode 100644
index 0000000..170933e
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/Trivial.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test trivial stuff
+ */
+
+import java.nio.channels.*;
+
+
+public class Trivial {
+
+ public static void main(String[] args) throws Exception {
+ SocketChannel sc = SocketChannel.open();
+ Selector sel = Selector.open();
+ if (sc.keyFor(sel) != null)
+ throw new Exception("keyFor != null");
+ sc.configureBlocking(false);
+ SelectionKey sk = sc.register(sel, SelectionKey.OP_READ, args);
+ if (sc.keyFor(sel) != sk)
+ throw new Exception("keyFor returned " + sc.keyFor(sel));
+ if (sk.attachment() != args)
+ throw new Exception("attachment() returned " + sk.attachment());
+ Trivial t = new Trivial();
+ sk.attach(t);
+ if (sk.attachment() != t)
+ throw new Exception("Wrong attachment");
+ sk.isReadable();
+ sk.isWritable();
+ sk.isConnectable();
+ sk.isAcceptable();
+ }
+
+}
diff --git a/test/java/nio/channels/SocketChannel/UnboundSocketTests.java b/test/java/nio/channels/SocketChannel/UnboundSocketTests.java
new file mode 100644
index 0000000..325c47c
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/UnboundSocketTests.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 6442073
+ * @summary Check getXXX methods for local/remote port/address/socketaddress
+ * match socket spec for unbound case
+ */
+import java.net.*;
+import java.nio.channels.*;
+
+public class UnboundSocketTests {
+
+ static int failures = 0;
+
+ static void check(String msg, Object actual, Object expected) {
+ System.out.format("%s expected: %s, actual: %s", msg, expected, actual);
+ if (actual == expected) {
+ System.out.println(" [PASS]");
+ } else {
+ System.out.println(" [FAIL]");
+ failures++;
+ }
+ }
+
+ static void checkIsAnyLocalAddress(String msg, InetAddress actual) {
+ System.out.format("%s actual: %s", msg, actual);
+ if (actual.isAnyLocalAddress()) {
+ System.out.println(" [PASS]");
+ } else {
+ System.out.println(" [FAIL]");
+ failures++;
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+ System.out.println("\n-- SocketChannel --");
+
+ SocketChannel sc = SocketChannel.open();
+
+ check("getLocalPort()", sc.socket().getLocalPort(), -1);
+ checkIsAnyLocalAddress("getLocalAddress()",
+ sc.socket().getLocalAddress());
+ check("getLocalSocketAddress()", sc.socket().getLocalSocketAddress(), null);
+
+ check("getPort()", sc.socket().getPort(), 0);
+ check("getInetAddress()", sc.socket().getInetAddress(), null);
+ check("getRemoteSocketAddress()", sc.socket().getRemoteSocketAddress(), null);
+
+
+ System.out.println("\n-- ServerSocketChannel --");
+
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+
+ check("getLocalPort()", ssc.socket().getLocalPort(), -1);
+ check("getInetAddress()", ssc.socket().getInetAddress(), null);
+ check("getLocalSocketAddress()", ssc.socket().getLocalSocketAddress(), null);
+
+ System.out.println("\n-- DatagramChannel --");
+
+ DatagramChannel dc = DatagramChannel.open();
+
+ // not specified
+ check("getLocalPort()", dc.socket().getLocalPort(), 0);
+
+ checkIsAnyLocalAddress("getLocalAddress()",
+ dc.socket().getLocalAddress());
+ check("getLocalSocketAddress()", dc.socket().getLocalSocketAddress(), null);
+
+ check("getPort()", dc.socket().getPort(), -1);
+ check("getInetAddress()", dc.socket().getInetAddress(), null);
+ check("getRemoteSocketAddress()", dc.socket().getRemoteSocketAddress(), null);
+
+ if (failures > 0) {
+ throw new RuntimeException(failures + " sub-tests(s) failed.");
+ }
+
+ }
+}
diff --git a/test/java/nio/channels/SocketChannel/VectorIO.java b/test/java/nio/channels/SocketChannel/VectorIO.java
new file mode 100644
index 0000000..0dbd32e
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/VectorIO.java
@@ -0,0 +1,186 @@
+/*
+ * Copyright 2000-2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @summary Test socketchannel vector IO
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.util.*;
+import sun.misc.*;
+
+
+public class VectorIO {
+
+ static int port = 40170;
+
+ static Random generator = new Random();
+
+ static int testSize;
+
+ public static void main(String[] args) throws Exception {
+ testSize = 1;
+ runTest();
+ for(int i=15; i<18; i++) {
+ testSize = i;
+ runTest();
+ }
+ }
+
+ static void runTest() throws Exception {
+ System.err.println("Length " + testSize);
+ Server sv = new Server(testSize);
+ sv.start();
+ do {
+ try {
+ Thread.currentThread().sleep(200);
+ } catch (InterruptedException x) {
+ if (sv.finish(8000) == 0)
+ throw new Exception("Failed: Error in server thread");
+ }
+ } while (!sv.ready);
+ bufferTest();
+ if (sv.finish(8000) == 0)
+ throw new Exception("Failed: Length = " + testSize);
+ }
+
+ static void bufferTest() throws Exception {
+ ByteBuffer[] bufs = new ByteBuffer[testSize];
+ for(int i=0; i<testSize; i++) {
+ String source = "buffer" + i;
+ if (generator.nextBoolean())
+ bufs[i] = ByteBuffer.allocateDirect(source.length());
+ else
+ bufs[i] = ByteBuffer.allocate(source.length());
+
+ bufs[i].put(source.getBytes("8859_1"));
+ bufs[i].flip();
+ }
+
+ // Get a connection to the server
+ InetAddress lh = InetAddress.getLocalHost();
+ InetSocketAddress isa = new InetSocketAddress(lh, port);
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(isa);
+ sc.configureBlocking(false);
+
+ // Write the data out
+ long bytesWritten = 0;
+ do {
+ bytesWritten = sc.write(bufs);
+ } while (bytesWritten > 0);
+
+ try {
+ Thread.currentThread().sleep(500);
+ } catch (InterruptedException ie) { }
+
+ // Clean up
+ sc.close();
+ }
+
+ static class Server
+ extends TestThread
+ {
+ static int port = 40170;
+
+ static Random generator = new Random();
+
+ int testSize;
+
+ volatile boolean ready = false;
+
+ Server(int testSize) {
+ super("Server " + testSize);
+ this.testSize = testSize;
+ }
+
+ void go() throws Exception {
+ bufferTest();
+ }
+
+ void bufferTest() throws Exception {
+ ByteBuffer[] bufs = new ByteBuffer[testSize];
+ for(int i=0; i<testSize; i++) {
+ String source = "buffer" + i;
+ if (generator.nextBoolean())
+ bufs[i] = ByteBuffer.allocateDirect(source.length());
+ else
+ bufs[i] = ByteBuffer.allocate(source.length());
+ }
+
+ // Get a connection from client
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ SocketChannel sc = null;
+
+ try {
+
+ ssc.configureBlocking(false);
+ InetAddress lh = InetAddress.getLocalHost();
+ InetSocketAddress isa = new InetSocketAddress(lh, port);
+ ssc.socket().bind(isa);
+ ready = true;
+
+ for (;;) {
+ sc = ssc.accept();
+ if (sc != null)
+ break;
+ Thread.sleep(50);
+ }
+
+ // Read data into multiple buffers
+ long bytesRead = 0;
+ do {
+ bytesRead = sc.read(bufs);
+ } while (bytesRead > 0);
+
+ // Check results
+ for(int i=0; i<testSize; i++) {
+ String expected = "buffer" + i;
+ bufs[i].flip();
+ int size = bufs[i].capacity();
+ byte[] data = new byte[size];
+ for(int j=0; j<size; j++)
+ data[j] = bufs[i].get();
+ String message = new String(data, "8859_1");
+ if (!message.equals(expected))
+ throw new Exception("Wrong data: Got "
+ + message + ", expected "
+ + expected);
+ }
+
+ } finally {
+ // Clean up
+ ssc.close();
+ if (sc != null)
+ sc.close();
+ }
+
+ }
+
+ }
+
+}
diff --git a/test/java/nio/channels/SocketChannel/VectorParams.java b/test/java/nio/channels/SocketChannel/VectorParams.java
new file mode 100644
index 0000000..f08f226
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/VectorParams.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4865031
+ * @summary Test ScatteringByteChannel/GatheringByteChannel read/write
+ * @library ..
+ */
+
+import java.net.*;
+import java.io.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.nio.charset.*;
+
+public class VectorParams {
+
+ static java.io.PrintStream out = System.out;
+
+ static final int DAYTIME_PORT = 13;
+ static final String DAYTIME_HOST = TestUtil.HOST;
+ static final int testSize = 10;
+ static ByteBuffer[] bufs = null;
+ static InetSocketAddress isa = null;
+
+ public static void main(String[] args) throws Exception {
+ initBufs();
+ testSocketChannelVectorParams();
+ testDatagramChannelVectorParams();
+ testPipeVectorParams();
+ testFileVectorParams();
+ }
+
+ static void initBufs() throws Exception {
+ bufs = new ByteBuffer[testSize];
+ for(int i=0; i<testSize; i++) {
+ String source = "buffer" + i;
+ bufs[i] = ByteBuffer.allocate(source.length());
+ bufs[i].put(source.getBytes("8859_1"));
+ bufs[i].flip();
+ }
+ isa = new InetSocketAddress(InetAddress.getByName(DAYTIME_HOST),
+ DAYTIME_PORT);
+ }
+
+ static void testSocketChannelVectorParams() throws Exception {
+ SocketChannel sc = SocketChannel.open(isa);
+ tryBadWrite(sc, bufs, 0, -1);
+ tryBadWrite(sc, bufs, -1, 0);
+ tryBadWrite(sc, bufs, 0, 1000);
+ tryBadWrite(sc, bufs, 1000, 1);
+ tryBadRead(sc, bufs, 0, -1);
+ tryBadRead(sc, bufs, -1, 0);
+ tryBadRead(sc, bufs, 0, 1000);
+ tryBadRead(sc, bufs, 1000, 1);
+ sc.close();
+ }
+
+ static void testDatagramChannelVectorParams() throws Exception {
+ DatagramChannel dc = DatagramChannel.open();
+ dc.connect(isa);
+ tryBadRead(dc, bufs, 0, -1);
+ tryBadRead(dc, bufs, -1, 0);
+ tryBadRead(dc, bufs, 0, 1000);
+ tryBadRead(dc, bufs, 1000, 1);
+ tryBadWrite(dc, bufs, 0, -1);
+ tryBadWrite(dc, bufs, -1, 0);
+ tryBadWrite(dc, bufs, 0, 1000);
+ tryBadWrite(dc, bufs, 1000, 1);
+ dc.close();
+ }
+
+ static void testPipeVectorParams() throws Exception {
+ Pipe p = Pipe.open();
+ Pipe.SinkChannel sink = p.sink();
+ Pipe.SourceChannel source = p.source();
+ tryBadWrite(sink, bufs, 0, -1);
+ tryBadWrite(sink, bufs, -1, 0);
+ tryBadWrite(sink, bufs, 0, 1000);
+ tryBadWrite(sink, bufs, 1000, 1);
+ tryBadRead(source, bufs, 0, -1);
+ tryBadRead(source, bufs, -1, 0);
+ tryBadRead(source, bufs, 0, 1000);
+ tryBadRead(source, bufs, 1000, 1);
+ sink.close();
+ source.close();
+ }
+
+ static void testFileVectorParams() throws Exception {
+ File testFile = File.createTempFile("filevec", null);
+ testFile.deleteOnExit();
+ RandomAccessFile raf = new RandomAccessFile(testFile, "rw");
+ FileChannel fc = raf.getChannel();
+ tryBadWrite(fc, bufs, 0, -1);
+ tryBadWrite(fc, bufs, -1, 0);
+ tryBadWrite(fc, bufs, 0, 1000);
+ tryBadWrite(fc, bufs, 1000, 1);
+ tryBadRead(fc, bufs, 0, -1);
+ tryBadRead(fc, bufs, -1, 0);
+ tryBadRead(fc, bufs, 0, 1000);
+ tryBadRead(fc, bufs, 1000, 1);
+ fc.close();
+ }
+
+ private static void tryBadWrite(GatheringByteChannel gbc,
+ ByteBuffer[] bufs, int offset, int len)
+ throws Exception
+ {
+ try {
+ gbc.write(bufs, offset, len);
+ throw new RuntimeException("Expected exception not thrown");
+ } catch (IndexOutOfBoundsException ioobe) {
+ // Correct result
+ }
+ }
+
+ private static void tryBadRead(ScatteringByteChannel sbc,
+ ByteBuffer[] bufs, int offset, int len)
+ throws Exception
+ {
+ try {
+ sbc.read(bufs, offset, len);
+ throw new RuntimeException("Expected exception not thrown");
+ } catch (IndexOutOfBoundsException ioobe) {
+ // Correct result
+ }
+ }
+
+}
diff --git a/test/java/nio/channels/SocketChannel/Write.java b/test/java/nio/channels/SocketChannel/Write.java
new file mode 100644
index 0000000..8cec8c2
--- /dev/null
+++ b/test/java/nio/channels/SocketChannel/Write.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4854354
+ * @summary Test vector write faster than can be read
+ * @library ..
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.util.*;
+import sun.misc.*;
+
+
+public class Write {
+
+ static int port = 40170;
+
+ static Random generator = new Random();
+
+ static int testSize = 15;
+
+ public static void main(String[] args) throws Exception {
+ WriteServer sv = new WriteServer();
+ sv.start();
+ do {
+ try {
+ Thread.currentThread().sleep(200);
+ } catch (InterruptedException x) {
+ if (sv.finish(8000) == 0)
+ throw new Exception("Failed: Error in server thread");
+ }
+ } while (!sv.ready);
+ bufferTest();
+ if (sv.finish(8000) == 0)
+ throw new Exception("Failed" );
+ }
+
+ static void bufferTest() throws Exception {
+ ByteBuffer[] bufs = new ByteBuffer[testSize];
+ for(int i=0; i<testSize; i++) {
+ String source =
+ "a muchmuchmuchmuchmuchmuchmuchmuch larger buffer numbered " +
+ i;
+ bufs[i] = ByteBuffer.allocateDirect(source.length());
+ }
+
+ // Get a connection to the server
+ InetAddress lh = InetAddress.getLocalHost();
+ InetSocketAddress isa = new InetSocketAddress(lh, port);
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(isa);
+ sc.configureBlocking(false);
+
+ // Try to overflow the socket buffer
+ long total = 0;
+ for (int i=0; i<100; i++) {
+ long bytesWritten = sc.write(bufs);
+ if (bytesWritten > 0)
+ total += bytesWritten;
+ for(int j=0; j<testSize; j++)
+ bufs[j].rewind();
+ }
+
+ // Clean up
+ sc.close();
+ }
+
+}
+
+
+class WriteServer extends TestThread {
+
+ static int port = 40170;
+
+ static Random generator = new Random();
+
+ volatile boolean ready = false;
+
+ WriteServer() {
+ super("WriteServer");
+ }
+
+ void go() throws Exception {
+ bufferTest();
+ }
+
+ void bufferTest() throws Exception {
+ ByteBuffer buf = ByteBuffer.allocateDirect(5);
+
+ // Get a connection from client
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ SocketChannel sc = null;
+
+ try {
+ ssc.configureBlocking(false);
+ InetAddress lh = InetAddress.getLocalHost();
+ InetSocketAddress isa = new InetSocketAddress(lh, port);
+ ssc.socket().bind(isa);
+ ready = true;
+
+ for (;;) {
+ sc = ssc.accept();
+ if (sc != null)
+ break;
+ Thread.sleep(50);
+ }
+
+ // I'm a slow reader...
+ Thread.sleep(3000);
+
+ } finally {
+ // Clean up
+ ssc.close();
+ if (sc != null)
+ sc.close();
+ }
+
+ }
+
+}
diff --git a/test/java/nio/channels/TestThread.java b/test/java/nio/channels/TestThread.java
new file mode 100644
index 0000000..b2a7029
--- /dev/null
+++ b/test/java/nio/channels/TestThread.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2000-2002 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* Utility class for test threads
+ *
+ */
+
+import java.io.*;
+
+
+public abstract class TestThread
+ extends Thread
+{
+ Exception failure = null;
+ String name;
+ protected final PrintStream log;
+ Thread main;
+
+ TestThread(String name, PrintStream log) {
+ super("TestThread-" + name);
+ this.name = name;
+ this.log = log;
+ this.main = Thread.currentThread();
+ setDaemon(true);
+ }
+
+ TestThread(String name) {
+ this(name, System.err);
+ }
+
+ abstract void go() throws Exception;
+
+ public void run() {
+ try {
+ go();
+ } catch (Exception x) {
+ failure = x;
+ main.interrupt();
+ }
+ }
+
+ int finish(long timeout) {
+ try {
+ join(timeout);
+ } catch (InterruptedException x) { }
+ if (isAlive() && (failure == null))
+ failure = new Exception(name + ": Timed out");
+ if (failure != null) {
+ failure.printStackTrace(log);
+ return 0;
+ }
+ return 1;
+ }
+
+ void finishAndThrow(long timeout) throws Exception {
+ try {
+ join(timeout);
+ } catch (InterruptedException x) { }
+ if (failure != null)
+ failure = new Exception(name + " threw an exception",
+ failure);
+ if (isAlive() && (failure == null))
+ failure = new Exception(name + " timed out");
+ if (failure != null)
+ throw failure;
+ }
+
+ public String toString() {
+ return name;
+ }
+
+}
diff --git a/test/java/nio/channels/TestUtil.java b/test/java/nio/channels/TestUtil.java
new file mode 100644
index 0000000..10cc488
--- /dev/null
+++ b/test/java/nio/channels/TestUtil.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* Test utilities
+ *
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+import java.util.Random;
+
+
+public class TestUtil {
+
+ // Test hosts used by the channels tests - change these when
+ // executing in a different network.
+ public static final String HOST = "javaweb.sfbay.sun.com";
+ public static final String REFUSING_HOST = "jano.sfbay.sun.com";
+ public static final String FAR_HOST = "theclub.ireland.sun.com";
+ public static final String UNRESOLVABLE_HOST = "blah-blah.blah-blah.blah";
+
+ private TestUtil() { }
+
+ // Repeatedly try random ports until we bind to one. You might be tempted
+ // to do this:
+ //
+ // ServerSocketChannel ssc = ServerSocketChannel.open();
+ // ssc.socket().bind(new InetSocketAddress(0));
+ // SocketAddress sa = ssc.socket().getLocalSocketAddress();
+ //
+ // but unfortunately it doesn't work on NT 4.0.
+ //
+ // Returns the bound port.
+ //
+ static int bind(ServerSocketChannel ssc) throws IOException {
+ InetAddress lh = InetAddress.getLocalHost();
+ Random r = new Random();
+ for (;;) {
+ int p = r.nextInt((1 << 16) - 1024) + 1024;
+ InetSocketAddress isa = new InetSocketAddress(lh, p);
+ try {
+ ssc.socket().bind(isa);
+ } catch (IOException x) {
+ continue;
+ }
+ return p;
+ }
+ }
+
+ // A more convenient form of bind(ServerSocketChannel) that returns a full
+ // socket address.
+ //
+ static InetSocketAddress bindToRandomPort(ServerSocketChannel ssc)
+ throws IOException
+ {
+ int p = bind(ssc);
+ return new InetSocketAddress(InetAddress.getLocalHost(), p);
+ }
+
+ private static String osName = System.getProperty("os.name");
+
+ // Examines os.name property to determine if running on 95/98/ME.
+ //
+ // Returns true if running on windows95/98/ME.
+ //
+ static boolean onME() {
+ if (osName.startsWith("Windows")) {
+ if (osName.indexOf("9") > 0)
+ return true;
+ if (osName.indexOf("M") > 0)
+ return true;
+ }
+ return false;
+ }
+
+ static boolean onSolaris() {
+ return osName.startsWith("SunOS");
+ }
+
+ static boolean onWindows() {
+ return osName.startsWith("Windows");
+ }
+
+}
diff --git a/test/java/nio/channels/etc/Shadow.java b/test/java/nio/channels/etc/Shadow.java
new file mode 100644
index 0000000..331e2bf
--- /dev/null
+++ b/test/java/nio/channels/etc/Shadow.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test
+ * @bug 4455376
+ * @summary Ensure that socket objects obtained from channels
+ * carry the correct address information
+ */
+
+import java.io.*;
+import java.net.*;
+import java.nio.*;
+import java.nio.channels.*;
+
+
+public class Shadow {
+
+ private static final int PORT = 2019;
+ static PrintStream log = System.err;
+
+ private static void dump(ServerSocket s) {
+ log.println("getInetAddress(): " + s.getInetAddress());
+ log.println("getLocalPort(): " + s.getLocalPort());
+ }
+
+ private static void dump(Socket s) {
+ log.println("getInetAddress(): " + s.getInetAddress());
+ log.println("getPort(): " + s.getPort());
+ log.println("getLocalAddress(): " + s.getLocalAddress());
+ log.println("getLocalPort(): " + s.getLocalPort());
+ }
+
+ private static int problems = 0;
+
+ private static void problem(String s) {
+ log.println("FAILURE: " + s);
+ problems++;
+ }
+
+ private static void check(Socket s) {
+ if (s.getPort() == 0)
+ problem("Socket has no port");
+ if (s.getLocalPort() == 0)
+ problem("Socket has no local port");
+ if (!s.getLocalAddress().equals(s.getInetAddress()))
+ problem("Socket has wrong local address");
+ }
+
+ public static void main(String[] args) throws Exception {
+ boolean useChannels
+ = ((args.length == 0) || Boolean.valueOf(args[0]).booleanValue());
+ int port = (args.length > 1 ? Integer.parseInt(args[1]) : PORT);
+
+ // open server socket
+ ServerSocket serverSocket;
+ if (useChannels) {
+ ServerSocketChannel serverSocketChannel =
+ ServerSocketChannel.open();
+ log.println("opened ServerSocketChannel: " +
+ serverSocketChannel);
+ serverSocket = serverSocketChannel.socket();
+ log.println("associated ServerSocket: " + serverSocket);
+ } else {
+ serverSocket = new ServerSocket();
+ log.println("opened ServerSocket: " + serverSocket);
+ }
+
+ // bind server socket to port
+ SocketAddress bindAddr = new InetSocketAddress(port);
+ serverSocket.bind(bindAddr);
+ log.println("bound ServerSocket: " + serverSocket);
+
+ log.println();
+
+ // open client socket
+ Socket socket;
+ if (useChannels) {
+ SocketChannel socketChannel = SocketChannel.open();
+ log.println("opened SocketChannel: " + socketChannel);
+
+ socket = socketChannel.socket();
+ log.println("associated Socket: " + socket);
+ } else {
+ socket = new Socket();
+ log.println("opened Socket: " + socket);
+ }
+
+ // connect client socket to port
+ SocketAddress connectAddr =
+ new InetSocketAddress("127.0.0.1",
+ serverSocket.getLocalPort());
+ socket.connect(connectAddr);
+ log.println("connected Socket: " + socket);
+
+ log.println();
+
+ // accept connection
+ Socket acceptedSocket = serverSocket.accept();
+ log.println("accepted Socket: " + acceptedSocket);
+
+ log.println();
+ log.println("========================================");
+
+ log.println("*** ServerSocket info: ");
+ dump(serverSocket);
+ log.println();
+
+ log.println("*** client Socket info: ");
+ dump(socket);
+ check(socket);
+ log.println();
+
+ log.println("*** accepted Socket info: ");
+ dump(acceptedSocket);
+ check(acceptedSocket);
+ log.println();
+
+ if (problems > 0)
+ throw new Exception(problems + " tests failed");
+ }
+
+}
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/CloseTest.java b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/CloseTest.java
new file mode 100644
index 0000000..35b4af5
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/CloseTest.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * This unit test checks that closing the channel returned by
+ * System.inheritedChannel closes the underlying network socket.
+ *
+ * The test launches the "echo service" with arguments to instruct the
+ * service to close the channel after it receives a small message. The
+ * service then delays/lingers for 15 seconds before shuting down. To
+ * prove that the close works we check that we see EOF (meaning the
+ * peer has closed the connection) in less than 15 seconds.
+ */
+import java.nio.ByteBuffer;
+import java.nio.channels.*;
+
+public class CloseTest {
+
+ public static void main(String args[]) throws Exception {
+ String msg = "HELLO";
+
+ // Launch the service with arguments to tell it to close
+ // the connection after reading 5 bytes ("HELLO"). After
+ // closing the connection the service should hang around
+ // for 15 seconds.
+
+ String service_args[] = new String[2];
+ service_args[0] = String.valueOf(msg.length());
+ service_args[1] = String.valueOf( 15*1000 );
+
+
+ SocketChannel sc = Launcher.launchWithSocketChannel("EchoService", service_args);
+
+ // send message - service will echo the message and close the connection.
+
+ sc.write(ByteBuffer.wrap(msg.getBytes("UTF-8")));
+
+ // read the reply (with timeout)
+ ByteBuffer bb = ByteBuffer.allocateDirect(50);
+ sc.configureBlocking(false);
+ Selector sel = sc.provider().openSelector();
+ SelectionKey sk = sc.register(sel, SelectionKey.OP_READ);
+
+ long to = 12 * 1000;
+ for (;;) {
+ long st = System.currentTimeMillis();
+ sel.select(to);
+ if (sk.isReadable()) {
+ int n = sc.read(bb);
+
+ // EOF
+ if (n < 0) {
+ break;
+ }
+ }
+ sel.selectedKeys().remove(sk);
+ to -= System.currentTimeMillis() - st;
+ if (to <= 0) {
+ throw new RuntimeException("Timed out waiting for connection to close");
+ }
+ }
+ sel.close();
+ sc.close();
+
+ // finally check that the reply length is okay
+ bb.flip();
+ if (bb.remaining() < msg.length()) {
+ throw new RuntimeException("Premature EOF from echo service");
+ }
+
+ System.out.println("Test passed - service closed connection.");
+ }
+}
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/ClosedStreams.java b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/ClosedStreams.java
new file mode 100644
index 0000000..a1416b9
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/ClosedStreams.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ * @test
+ * @bug 4997227
+ * @summary Calling inheritedChannel() after FileDescriptor.in was closed
+ * caused an InternalError to be thrown.
+ */
+
+import java.io.FileDescriptor;
+import java.io.FileInputStream;
+import java.io.IOException;
+
+public class ClosedStreams {
+ public static void main(String args[]) throws IOException {
+
+ // close FileDescriptor.in
+ (new FileInputStream(FileDescriptor.in)).close();
+
+ // get the inherited channel
+ if (System.inheritedChannel() != null) {
+ throw new RuntimeException("inherited channel not null - unexpected!");
+ }
+ }
+}
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/EchoService.java b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/EchoService.java
new file mode 100644
index 0000000..9e8146c
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/EchoService.java
@@ -0,0 +1,200 @@
+/*
+ * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * An "echo" service designed to be used with inetd. It can be configured in
+ * inetd.conf to be used by any of the following types of services :-
+ *
+ * stream tcp nowait
+ * stream tcp6 nowait
+ * stream tcp wait
+ * stream tcp6 wait
+ * dgram udp wait
+ * dgram udp6 wait
+ *
+ * If configured as a "tcp nowait" service then inetd will launch a
+ * VM to run the EchoService each time that a client connects to
+ * the TCP port. The EchoService simply echos any messages it
+ * receives from the client and shuts if the client closes the
+ * connection.
+ *
+ * If configured as a "tcp wait" service then inetd will launch a VM
+ * to run the EchoService when a client connects to the port. When
+ * launched the EchoService takes over the listener socket. It
+ * terminates when all clients have disconnected and the service
+ * is idle for a few seconds.
+ *
+ * If configured as a "udp wait" service then a VM will be launched for
+ * each UDP packet to the configured port. System.inheritedChannel()
+ * will return a DatagramChannel. The echo service here will terminate after
+ * echoing the UDP packet back to the client.
+ *
+ * The service closes the inherited network channel when complete. To
+ * facilate testing that the channel is closed the "tcp nowait" service
+ * can close the connection after a given number of bytes.
+ */
+import java.nio.*;
+import java.nio.channels.*;
+import java.io.IOException;
+import java.net.*;
+
+public class EchoService {
+
+ private static void doIt(SocketChannel sc, int closeAfter, int delay) throws IOException {
+ ByteBuffer bb = ByteBuffer.allocate(1024);
+ int total = 0;
+ for (;;) {
+ bb.clear();
+ int n = sc.read(bb);
+ if (n < 0) {
+ break;
+ }
+ total += n;
+
+ // echo
+ bb.flip();
+ sc.write(bb);
+
+ // close after X bytes?
+ if (closeAfter > 0 && total >= closeAfter) {
+ break;
+ }
+ }
+
+ sc.close();
+ if (delay > 0) {
+ try {
+ Thread.currentThread().sleep(delay);
+ } catch (InterruptedException x) { }
+ }
+ }
+
+ private static void doIt(DatagramChannel dc) throws IOException {
+ ByteBuffer bb = ByteBuffer.allocate(1024);
+ SocketAddress sa = dc.receive(bb);
+ bb.flip();
+ dc.send(bb, sa);
+ dc.close();
+ }
+
+
+ // A worker thread to service a single connection
+ // The class maintains a count of the number of worker threads so
+ // can the service can terminate then all clients disconnect.
+
+ static class Worker implements Runnable {
+ private static int count = 0;
+ private static Object lock = new Object();
+
+ public static int count() {
+ synchronized (lock) {
+ return count;
+ }
+ }
+
+ private SocketChannel sc;
+
+ Worker(SocketChannel sc) {
+ this.sc = sc;
+ synchronized (lock) {
+ count++;
+ }
+ }
+
+ public void run() {
+ try {
+ doIt(sc, -1, -1);
+ } catch (IOException x) {
+ } finally {
+ synchronized (lock) {
+ count--;
+ }
+ }
+
+ }
+ }
+
+ public static void main(String args[]) throws IOException {
+ Channel c = System.inheritedChannel();
+ if (c == null) {
+ return;
+ }
+
+ // tcp nowait
+ if (c instanceof SocketChannel) {
+ int closeAfter = 0;
+ int delay = 0;
+ if (args.length > 0) {
+ closeAfter = Integer.parseInt(args[0]);
+ }
+ if (args.length > 1) {
+ delay = Integer.parseInt(args[1]);
+ }
+ doIt((SocketChannel)c, closeAfter, delay);
+ }
+
+ // tcp wait - in this case we take over the listener socket
+ // In this test case we create a thread to service each connection
+ // and terminate after all clients are gone.
+ //
+ if (c instanceof ServerSocketChannel) {
+ ServerSocketChannel ssc = (ServerSocketChannel)c;
+
+ ssc.configureBlocking(false);
+ Selector sel = ssc.provider().openSelector();
+ SelectionKey sk = ssc.register(sel, SelectionKey.OP_ACCEPT);
+ SocketChannel sc;
+ int count = 0;
+ for (;;) {
+ sel.select(5000);
+ if (sk.isAcceptable() && ((sc = ssc.accept()) != null)) {
+ Worker w = new Worker(sc);
+ (new Thread(w)).start();
+ } else {
+ // if all clients have disconnected then we die as well.
+ if (Worker.count() == 0) {
+ break;
+ }
+ }
+ }
+ ssc.close();
+ }
+
+ // udp wait
+ if (c instanceof DatagramChannel) {
+ doIt((DatagramChannel)c);
+ }
+
+ // linger?
+ if (args.length > 0) {
+ int delay = Integer.parseInt(args[0]);
+ try {
+ Thread.currentThread().sleep(delay);
+ } catch (InterruptedException x) { }
+ }
+
+ }
+
+}
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/EchoTest.java b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/EchoTest.java
new file mode 100644
index 0000000..6a60343
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/EchoTest.java
@@ -0,0 +1,180 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Used in conjunction to EchoService to test System.inheritedChannel().
+ *
+ * The first test is the TCP echo test. A service is launched with a TCP
+ * socket and a TCP message is sent to the service. The test checks that
+ * the message is correctly echoed.
+ *
+ * The second test is a UDP echo test. A service is launched with a UDP
+ * socket and a UDP packet is sent to the service. The test checks that
+ * the packet is correctly echoed.
+ *
+ */
+import java.net.*;
+import java.io.*;
+import java.nio.ByteBuffer;
+import java.nio.channels.*;
+import java.util.Random;
+
+public class EchoTest {
+
+ private static int failures = 0;
+
+ private static String ECHO_SERVICE = "EchoService";
+
+ /*
+ * Sends a message with random bytes to the service, and then waits for
+ * a reply (with timeout). Once the reply is received it is checked to ensure
+ * that it matches the original message.
+ */
+ private static void TCPEchoTest() throws IOException {
+ SocketChannel sc = Launcher.launchWithSocketChannel(ECHO_SERVICE, null);
+
+ String msg = "Where's that damn torpedo?";
+ int repeat = 100;
+ int size = msg.length() * repeat;
+
+ // generate bytes into a buffer and send it to the service
+
+ ByteBuffer bb1 = ByteBuffer.allocate(size);
+ Random gen = new Random();
+ for (int i=0; i<repeat; i++) {
+ bb1.put(msg.getBytes("UTF-8"));
+ }
+ bb1.flip();
+ sc.write(bb1);
+
+ // now we put the channel into non-blocking mode and we read the
+ // reply from the service into a second buffer.
+
+ ByteBuffer bb2 = ByteBuffer.allocate(size+100);
+ sc.configureBlocking(false);
+ Selector sel = sc.provider().openSelector();
+ SelectionKey sk = sc.register(sel, SelectionKey.OP_READ);
+ int nread = 0;
+ long to = 5000;
+ while (nread < size) {
+ long st = System.currentTimeMillis();
+ sel.select(to);
+ if (sk.isReadable()) {
+ int n = sc.read(bb2);
+ if (n > 0) {
+ nread += n;
+ }
+ if (n < 0) {
+ break; // EOF
+ }
+ }
+ sel.selectedKeys().remove(sk);
+ to -= System.currentTimeMillis() - st;
+ if (to <= 0) {
+ break;
+ }
+ }
+ sc.close();
+
+ // and compare the response
+
+ boolean err = false;
+
+ if (nread != size) {
+ err = true;
+ } else {
+ bb1.flip();
+ bb2.flip();
+ while (bb1.hasRemaining()) {
+ if (bb1.get() != bb2.get()) {
+ err = true;
+ }
+ }
+ }
+
+ // if error print out the response from the service (could be a stack trace)
+ if (err) {
+ System.err.println("Bad response or premature EOF, bytes read: ");
+ bb2.flip();
+ while (bb2.hasRemaining()) {
+ char c = (char)bb2.get();
+ System.out.print(c);
+ }
+ throw new RuntimeException("Bad response or premature EOF from service");
+ }
+ }
+
+ /*
+ * Send a UDP packet to the service, wait for a reply (with timeout). Finally
+ * check that the packet is the same length as the original.
+ */
+ private static void UDPEchoTest() throws IOException {
+ DatagramChannel dc = Launcher.launchWithDatagramChannel(ECHO_SERVICE, null);
+
+ String msg = "I was out saving the galaxy when your grandfather was in diapers";
+
+ ByteBuffer bb = ByteBuffer.wrap(msg.getBytes("UTF-8"));
+ dc.write(bb);
+
+ // and receive the echo
+ byte b[] = new byte[msg.length() + 100];
+ DatagramPacket pkt2 = new DatagramPacket(b, b.length);
+ dc.socket().setSoTimeout(2000);
+ dc.socket().receive(pkt2);
+
+ if (pkt2.getLength() != msg.length()) {
+ throw new RuntimeException("Received packet of incorrect length");
+ }
+
+ dc.close();
+ }
+
+ public static void main(String args[]) throws IOException {
+
+ // TCP echo
+ try {
+ TCPEchoTest();
+ System.out.println("TCP echo test passed.");
+ } catch (Exception x) {
+ System.err.println(x);
+ failures++;
+ }
+
+ // UDP echo
+ try {
+ UDPEchoTest();
+ System.out.println("UDP echo test passed.");
+ } catch (Exception x) {
+ x.printStackTrace();
+ System.err.println(x);
+ failures++;
+ }
+
+ if (failures > 0) {
+ throw new RuntimeException("Test failed - see log for details");
+ }
+ }
+
+}
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/Launcher.c b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/Launcher.c
new file mode 100644
index 0000000..25159ad
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/Launcher.c
@@ -0,0 +1,165 @@
+/*
+ *
+ *
+ * A simple launcher to launch a program as if it was launched by inetd.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <unistd.h>
+#include <dirent.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <ctype.h>
+
+#include "jni.h"
+
+#include "Launcher.h"
+
+/*
+ * Throws the exception of the given class name and detail message
+ */
+static void ThrowException(JNIEnv *env, const char *name, const char *msg) {
+ jclass cls = (*env)->FindClass(env, name);
+ if (cls != NULL) {
+ (*env)->ThrowNew(env, cls, msg);
+ }
+}
+
+/*
+ * Convert a jstring to an ISO 8859_1 encoded C string
+ */
+static char* getString8859_1Chars(JNIEnv *env, jstring jstr) {
+ int i;
+ char *result;
+ jint len = (*env)->GetStringLength(env, jstr);
+ const jchar *str = (*env)->GetStringCritical(env, jstr, 0);
+ if (str == 0) {
+ return NULL;
+ }
+
+ result = (char*)malloc(len+1);
+ if (result == 0) {
+ (*env)->ReleaseStringCritical(env, jstr, str);
+ ThrowException(env, "java/lang/OutOfMemoryError", NULL);
+ return NULL;
+ }
+
+ for (i=0; i<len; i++) {
+ jchar unicode = str[i];
+ if (unicode <= 0x00ff)
+ result[i] = unicode;
+ else
+ result[i] = '?';
+ }
+
+ result[len] = 0;
+ (*env)->ReleaseStringCritical(env, jstr, str);
+ return result;
+}
+
+
+/*
+ * Class: Launcher
+ * Method: launch0
+ * Signature: ([Ljava/lang/String;I)V
+ */
+JNIEXPORT void JNICALL Java_Launcher_launch0
+ (JNIEnv *env, jclass cls, jobjectArray cmdarray, jint serviceFd)
+{
+ pid_t pid;
+ DIR* dp;
+ struct dirent* dirp;
+ int thisFd;
+ char** cmdv;
+ int i, cmdlen;
+
+ /*
+ * Argument 0 of the command array is the program name.
+ * Here we just extract the program name and any arguments into
+ * a command array suitable for use with execvp.
+ */
+ cmdlen = (*env)->GetArrayLength(env, cmdarray);
+ if (cmdlen == 0) {
+ ThrowException(env, "java/lang/IllegalArgumentException",
+ "command array must at least include the program name");
+ return;
+ }
+ cmdv = (char **)malloc((cmdlen + 1) * sizeof(char *));
+ if (cmdv == NULL) {
+ ThrowException(env, "java/lang/OutOfMemoryError", NULL);
+ return;
+ }
+
+ for (i=0; i<cmdlen; i++) {
+ jstring str = (*env)->GetObjectArrayElement(env, cmdarray, i);
+ cmdv[i] = (char *) getString8859_1Chars(env, str);
+ if (cmdv[i] == NULL) {
+ return;
+ }
+ }
+
+ /*
+ * Command array must have NULL as the last entry
+ */
+ cmdv[cmdlen] = NULL;
+
+ /*
+ * Launch the program. As this isn't a complete inetd or Runtime.exec
+ * implementation we don't have a reaper to pick up child exit status.
+ */
+#ifdef __solaris__
+ pid = fork1();
+#else
+ pid = fork();
+#endif
+ if (pid != 0) {
+ if (pid < 0) {
+ ThrowException(env, "java/io/IOException", "fork failed");
+ }
+ return;
+ }
+
+ /*
+ * We need to close all file descriptors except for serviceFd. To
+ * get the list of open file descriptos we read through /proc/self/fd
+ * but to open this requires a file descriptor. We could use a specific
+ * file descriptor and fdopendir but Linux doesn't seem to support
+ * fdopendir. Instead we use opendir and make an assumption on the
+ * file descriptor that is used (by opening & closing a file).
+ */
+ thisFd = open("/dev/null", O_RDONLY);
+ if (thisFd < 0) {
+ _exit(-1);
+ }
+ close(thisFd);
+
+ if ((dp = opendir("/proc/self/fd")) == NULL) {
+ _exit(-1);
+ }
+
+ while ((dirp = readdir(dp)) != NULL) {
+ if (isdigit(dirp->d_name[0])) {
+ int fd = strtol(dirp->d_name, NULL, 10);
+ if (fd != serviceFd && fd != thisFd) {
+ close(fd);
+ }
+ }
+ }
+ closedir(dp);
+
+ /*
+ * At this point all file descriptors are closed except for
+ * serviceFd. We not dup 0,1,2 to this file descriptor and
+ * close serviceFd. This should leave us with only 0,1,2
+ * open and all connected to the same socket.
+ */
+ dup2(serviceFd, STDIN_FILENO);
+ dup2(serviceFd, STDOUT_FILENO);
+ dup2(serviceFd, STDERR_FILENO);
+ close(serviceFd);
+
+ execvp(cmdv[0], cmdv);
+ _exit(-1);
+}
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/Launcher.java b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/Launcher.java
new file mode 100644
index 0000000..89ff467
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/Launcher.java
@@ -0,0 +1,150 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * A Launcher to launch a java process with its standard input, output,
+ * and error streams connected to a socket.
+ */
+import java.net.*;
+import java.nio.channels.*;
+import java.io.IOException;
+
+public class Launcher {
+
+ static {
+ System.loadLibrary("Launcher");
+ }
+
+ private static native void launch0(String cmdarray[], int fd) throws IOException;
+
+ private static void launch(String className, String options[], String args[], int fd) throws IOException {
+ String[] javacmd = Util.javaCommand();
+ int options_len = (options == null) ? 0 : options.length;
+ int args_len = (args == null) ? 0 : args.length;
+
+ // java [-options] class [args...]
+ int len = javacmd.length + options_len + 1 + args_len;
+
+ String cmdarray[] = new String[len];
+ int pos = 0;
+ for (int i=0; i<javacmd.length; i++) {
+ cmdarray[pos++] = javacmd[i];
+ }
+ for (int i=0; i<options_len; i++) {
+ cmdarray[pos++] = options[i];
+ }
+ cmdarray[pos++] = className;
+ for (int i=0; i<args_len; i++) {
+ cmdarray[pos++] = args[i];
+ }
+ launch0(cmdarray, fd);
+ }
+
+ /*
+ * Launch 'java' with specified class with the specified arguments (may be null).
+ * The launched process will inherit a connected TCP socket. The remote endpoint
+ * will be the SocketChannel returned by this method.
+ */
+ public static SocketChannel launchWithSocketChannel(String className, String options[], String args[]) throws IOException {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(new InetSocketAddress(0));
+ InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(),
+ ssc.socket().getLocalPort());
+ SocketChannel sc1 = SocketChannel.open(isa);
+ SocketChannel sc2 = ssc.accept();
+ launch(className, options, args, Util.getFD(sc2));
+ sc2.close();
+ ssc.close();
+ return sc1;
+ }
+
+ public static SocketChannel launchWithSocketChannel(String className, String args[]) throws IOException {
+ return launchWithSocketChannel(className, null, args);
+ }
+
+ public static SocketChannel launchWithSocketChannel(String className) throws IOException {
+ return launchWithSocketChannel(className, null);
+ }
+
+ /*
+ * Launch 'java' with specified class with the specified arguments (may be null).
+ * The launched process will inherited a TCP listener socket.
+ * Once launched this method tries to connect to service. If a connection
+ * can be established a SocketChannel, connected to the service, is returned.
+ */
+ public static SocketChannel launchWithServerSocketChannel(String className, String options[], String args[])
+ throws IOException
+ {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(new InetSocketAddress(0));
+ int port = ssc.socket().getLocalPort();
+ launch(className, options, args, Util.getFD(ssc));
+ ssc.close();
+ InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), port);
+ return SocketChannel.open(isa);
+ }
+
+ public static SocketChannel launchWithServerSocketChannel(String className, String args[]) throws IOException {
+ return launchWithServerSocketChannel(className, null, args);
+ }
+
+ public static SocketChannel launchWithServerSocketChannel(String className) throws IOException {
+ return launchWithServerSocketChannel(className, null);
+ }
+
+ /*
+ * Launch 'java' with specified class with the specified arguments (may be null).
+ * The launch process will inherited a bound UDP socket.
+ * Once launched this method creates a DatagramChannel and "connects
+ * it to the service. The created DatagramChannel is then returned.
+ * As it is connected any packets sent from the socket will be
+ * sent to the service.
+ */
+ public static DatagramChannel launchWithDatagramChannel(String className, String options[], String args[])
+ throws IOException
+ {
+ DatagramChannel dc = DatagramChannel.open();
+ dc.socket().bind(new InetSocketAddress(0));
+
+ int port = dc.socket().getLocalPort();
+ launch(className, options, args, Util.getFD(dc));
+ dc.close();
+
+ dc = DatagramChannel.open();
+
+ InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), port);
+
+ dc.connect(isa);
+ return dc;
+ }
+
+ public static DatagramChannel launchWithDatagramChannel(String className, String args[]) throws IOException {
+ return launchWithDatagramChannel(className, null, args);
+ }
+
+ public static DatagramChannel launchWithDatagramChannel(String className) throws IOException {
+ return launchWithDatagramChannel(className, null);
+ }
+}
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/Makefile b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/Makefile
new file mode 100644
index 0000000..c868afe
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/Makefile
@@ -0,0 +1,101 @@
+#
+#
+# Makefile for building libLauncher.so
+#
+# To build libLauncher.so requires :-
+# JAVA_HOME environment variable
+# cc (Solaris) or gcc (Linux) on PATH
+#
+# The library is created in a architecture specific directory :-
+#
+# lib/solaris-sparc/libLauncher.so (Solaris/SPARC)
+# lib/solaris-i586/libLauncher.so (Solaris/x86)
+# lib/linux-i586/libLauncher.so (Linux/x86)
+
+ECHO = echo
+MKDIR = mkdir
+UNAME = uname
+
+uname := $(shell uname)
+
+ifeq ($(uname), SunOS)
+ PLATFORM = solaris
+ ISAINFO = isainfo
+ ifndef ARCH_DATA_MODEL
+ ARCH_DATA_MODEL=32
+ endif
+ ifeq ($(ARCH_DATA_MODEL), 32)
+ archExpr = case "`$(UNAME) -p`" in \
+ i386) \
+ $(ECHO) i586 \
+ ;; \
+ sparc*) \
+ $(ECHO) sparc \
+ ;; \
+ *) \
+ $(UNAME) -p \
+ ;; \
+ esac
+ ARCH := $(shell $(archExpr) )
+ else
+ ARCH := $(shell $(ISAINFO) -n)
+ endif
+ CC = cc
+ LD = ld
+ CFLAGS = -D_REENTRANT -D__solaris__
+ LDFLAGS_COMMON = -G
+ EXTRA_LIBS = -lc
+ ifeq ($(ARCH_DATA_MODEL), 64)
+ CC += -xarch=v9
+ endif
+endif
+
+ifeq ($(uname), Linux)
+ PLATFORM = linux
+ archExpr = case "`$(UNAME) -m`" in \
+ i[3-6]86) \
+ $(ECHO) i586 \
+ ;; \
+ sparc*) \
+ $(ECHO) sparc \
+ ;; \
+ *) \
+ $(UNAME) -m \
+ ;; \
+ esac
+ ARCH := $(shell $(archExpr) )
+ CC = gcc
+ CFLAGS = -fno-strict-aliasing -fPIC -W -Wall
+ LD = ld
+ LDFLAGS_COMMON = -shared
+ EXTRA_LIBS = -lc
+endif
+
+LIBDIR=lib/$(PLATFORM)-$(ARCH)
+LAUNCHERLIB=$(LIBDIR)/libLauncher.so
+
+all: java_home $(LAUNCHERLIB)
+
+$(LAUNCHERLIB) : $(LIBDIR) $(LIBDIR)/Launcher.o
+ $(LD) $(LDFLAGS_COMMON) -o $(LAUNCHERLIB) $(LIBDIR)/Launcher.o $(EXTRA_LIBS)
+
+$(LIBDIR):
+ @$(MKDIR) -p $(LIBDIR)
+
+$(LIBDIR)/Launcher.o : Launcher.c \
+ Launcher.h
+ $(CC) -c $(CFLAGS) -o $(LIBDIR)/Launcher.o \
+ -I$(JAVA_HOME)/include -I$(JAVA_HOME)/include/$(PLATFORM) Launcher.c
+
+Launcher.h : Launcher.class
+ $(JAVA_HOME)/bin/javah -force Launcher
+
+Launcher.class : Launcher.java
+ $(JAVA_HOME)/bin/javac Launcher.java
+
+java_home:
+ifndef JAVA_HOME
+ @$(ECHO) "ERROR: Your JAVA_HOME environment variable is not set."
+ exit 1
+endif
+
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/NullTest.java b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/NullTest.java
new file mode 100644
index 0000000..53566d2
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/NullTest.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/* @test 1.1 03/07/25
+ * @summary Unit test for inetd feature
+ * @bug 4673940
+ */
+
+import java.nio.channels.Channel;
+import java.nio.channels.spi.SelectorProvider;
+import java.io.IOException;
+
+public class NullTest {
+
+ public static void main(String args[]) {
+
+ // test the assertion that SelectorProvider.inheritedChannel()
+ // and System.inheritedChannel return null when standard input
+ // is not connected to a socket
+
+ Channel c1, c2;
+ try {
+ c1 = SelectorProvider.provider().inheritedChannel();
+ c2 = System.inheritedChannel();
+ } catch (IOException ioe) {
+ throw new RuntimeException("Unexpected IOException: " + ioe);
+ }
+ if (c1 != null || c2 != null) {
+ throw new RuntimeException("Channel returned - unexpected");
+ }
+ }
+
+}
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/README b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/README
new file mode 100644
index 0000000..f305638
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/README
@@ -0,0 +1,35 @@
+
+The unit tests in this directory depend on a native launcher library
+(libLauncher.so). This native library is built off-line and the
+resulting libLauncher.so for each processor/OS combination is checked
+into the workspace. The reason for this is because the test environment
+may not have the required compilers/build environment.
+
+In order to rebuild libLauncher.so the following is required :-
+
+1. Check-out each of the shared libraries (sccs edit)
+
+2. Edit Launcher.c with the appropriate changes
+
+3. Execute the make script (gnumake all) on each processor/OS so
+that the appropriate lib/<platform>/libLauncher.so is built.
+
+4. Test the changes
+
+5. Check-in each of the shared library (sccs delget)
+
+
+For step 4 (re-building libLauncher.so) the following environment is required:
+
+(a) JAVA_HOME needs to be set to J2SE directory, eg:-
+ export JAVA_HOME=/usr/local/java/jdk1.5/solaris-sparc
+
+(b) For Solaris the SOS8 'cc' needs to be on the PATH, check using:
+ # cc -V
+ cc: Sun C 5.5 2003/03/12
+
+(c) Execute the make script :-
+ Solaris: gnumake all
+ Linux: gmake all
+
+
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/StateTest.java b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/StateTest.java
new file mode 100644
index 0000000..168f1a3
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/StateTest.java
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * Tests that the channel returned by System.inheritedChannel()
+ * is in blocking mode, bound, and in the case of a SocketChannel
+ * connected to a peer.
+ *
+ * The test works by launching a test service (called StateTestService) so
+ * that it inherits each type of channel. The test service checks the
+ * socket state and replies back to this class via an out-of-band
+ * channel.
+ */
+import java.io.*;
+import java.net.*;
+import java.nio.ByteBuffer;
+import java.nio.channels.*;
+
+public class StateTest {
+
+ private static int failures = 0;
+
+ private static String TEST_SERVICE = "StateTestService";
+
+ /*
+ * Reads the test result from the "out-of-band" connection to the test service.
+ *
+ * The out-of-band connection is just a TCP connection from the service to
+ * this class. waitForTestResult just waits (with timeout) for the service
+ * to connect. Once connected it waits (with timeout) for the test result.
+ * The test result is examined.
+ */
+ private static void waitForTestResult(ServerSocketChannel ssc, boolean expectFail) throws IOException {
+ Selector sel = ssc.provider().openSelector();
+ SelectionKey sk;
+ SocketChannel sc;
+
+ /*
+ * Wait for service to connect
+ */
+ ssc.configureBlocking(false);
+ sk = ssc.register(sel, SelectionKey.OP_ACCEPT);
+ long to = 15*1000;
+ sc = null;
+ for (;;) {
+ long st = System.currentTimeMillis();
+ sel.select(to);
+ if (sk.isAcceptable() && ((sc = ssc.accept()) != null)) {
+ // connection established
+ break;
+ }
+ sel.selectedKeys().remove(sk);
+ to -= System.currentTimeMillis() - st;
+ if (to <= 0) {
+ throw new IOException("Timed out waiting for service to report test result");
+ }
+ }
+ sk.cancel();
+ ssc.configureBlocking(false);
+
+ /*
+ * Wait for service to report test result
+ */
+ sc.configureBlocking(false);
+ sk = sc.register(sel, SelectionKey.OP_READ);
+ to = 5000;
+ ByteBuffer bb = ByteBuffer.allocateDirect(20);
+ for (;;) {
+ long st = System.currentTimeMillis();
+ sel.select(to);
+ if (sk.isReadable()) {
+ int n = sc.read(bb);
+ if (n > 0) {
+ break;
+ }
+ if (n < 0) {
+ throw new IOException("Premature EOF - no test result from service");
+ }
+ }
+ sel.selectedKeys().remove(sk);
+ to -= System.currentTimeMillis() - st;
+ if (to <= 0) {
+ throw new IOException("Timed out waiting for service to report test result");
+ }
+ }
+ sk.cancel();
+ sc.close();
+ sel.close();
+
+ /*
+ * Examine the test result
+ */
+ bb.flip();
+ byte b = bb.get();
+
+ if (expectFail && b == 'P') {
+ System.err.println("Test passed - test is expected to fail!!!");
+ failures++;
+ }
+ if (!expectFail && b != 'P') {
+ System.err.println("Test failed!");
+ failures++;
+ }
+ }
+
+ public static void main(String args[]) throws IOException {
+ boolean expectFail = false;
+
+ /*
+ * [-expectFail] [options...]
+ */
+ String options[] = args;
+ if (args.length > 0 && args[0].equals("-expectFail")) {
+ // shift out first arg to create options
+ expectFail = true;
+ options = new String[args.length-1];
+ if (args.length > 1) {
+ System.arraycopy(args, 1, options, 0, args.length-1);
+ }
+ }
+
+ /*
+ * Create the listener which will be used to read the test result
+ * from the service.
+ */
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(new InetSocketAddress(0));
+
+ /*
+ * The port is passed to the service as an argument.
+ */
+ int port = ssc.socket().getLocalPort();
+ String arg[] = new String[1];
+ arg[0] = String.valueOf(port);
+
+ /*
+ * Launch service with a SocketChannel (tcp nowait)
+ */
+ SocketChannel sc = Launcher.launchWithSocketChannel(TEST_SERVICE, options, arg);
+ waitForTestResult(ssc, expectFail);
+ sc.close();
+
+ /*
+ * Launch service with a ServerSocketChannel (tcp wait)
+ * launchWithServerSocketChannel establishes a connection to the service
+ * and the returned SocketChannel is connected to the service.
+ */
+ sc = Launcher.launchWithServerSocketChannel(TEST_SERVICE, options, arg);
+ waitForTestResult(ssc, expectFail);
+ sc.close();
+
+ /*
+ * Launch service with a DatagramChannel (udp wait)
+ */
+ DatagramChannel dc = Launcher.launchWithDatagramChannel(TEST_SERVICE, options, arg);
+ waitForTestResult(ssc, expectFail);
+ dc.close();
+
+ if (failures > 0) {
+ throw new RuntimeException("Test failed - see log for details");
+ } else {
+ System.out.println("All tests passed.");
+ }
+ }
+}
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/StateTestService.java b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/StateTestService.java
new file mode 100644
index 0000000..003f544
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/StateTestService.java
@@ -0,0 +1,111 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * A test service for use in the inetd/System.inheritedChannel unit
+ * tests.
+ *
+ * The test checks that the channel returned by System.inheritiedChannel
+ * is in blocking mode and is bound. In addition, in the case of a
+ * SocketChannel checks that the socket is connected.
+ *
+ * The test service is launched with an argument that is the reply port.
+ * This reply port is used as an out-of-band connection to the unit test
+ * so that the test status can be reported. When the test completes it
+ * establishes a TCP connection to the port and sends a PASSED/FAILED
+ * message to indicate the test result.
+ */
+import java.nio.*;
+import java.nio.channels.*;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+
+public class StateTestService {
+
+ static boolean failed = false;
+ static int reply_port;
+
+ static void check(boolean okay) {
+ if (!okay) {
+ failed = true;
+ }
+ }
+
+ private static void reply(String msg) throws IOException {
+ InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), reply_port);
+ SocketChannel sc = SocketChannel.open(isa);
+ byte b[] = msg.getBytes("UTF-8");
+ ByteBuffer bb = ByteBuffer.wrap(b);
+ sc.write(bb);
+ sc.close();
+ }
+
+ public static void main(String args[]) throws IOException {
+ if (args.length == 0) {
+ System.err.println("Usage: StateTestService [reply-port]");
+ return;
+ }
+ reply_port = Integer.parseInt(args[0]);
+
+ Channel c = null;
+ try {
+ c = System.inheritedChannel();
+ } catch (SecurityException se) {
+ // ignore
+ }
+ if (c == null) {
+ reply("FAILED");
+ return;
+ }
+
+ if (c instanceof SocketChannel) {
+ SocketChannel sc = (SocketChannel)c;
+ check( sc.isBlocking() );
+ check( sc.socket().isBound() );
+ check( sc.socket().isConnected() );
+ }
+
+ if (c instanceof ServerSocketChannel) {
+ ServerSocketChannel ssc = (ServerSocketChannel)c;
+ check( ssc.isBlocking() );
+ check( ssc.socket().isBound() );
+ }
+
+ if (c instanceof DatagramChannel) {
+ DatagramChannel dc = (DatagramChannel)c;
+ check( dc.isBlocking() );
+ check( dc.socket().isBound() );
+ }
+
+ if (failed) {
+ reply("FAILED");
+ } else {
+ reply("PASSED");
+ }
+
+ }
+
+}
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/Util.java b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/Util.java
new file mode 100644
index 0000000..acf52c2
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/Util.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+/*
+ *
+ *
+ * A collection of utility methods used by the SelectorProvider.inheritedChannel
+ * unit tests.
+ */
+import java.net.*;
+import java.io.*;
+import java.nio.channels.*;
+import java.lang.reflect.*;
+
+// dependency on Sun implementation
+import sun.nio.ch.*;
+
+public class Util {
+
+ private static Object get(String className, String fieldName, Object o) throws Exception {
+ Class cl = Class.forName(className);
+ Field fld = cl.getDeclaredField(fieldName);
+ fld.setAccessible(true);
+ return fld.get(o);
+ }
+
+ private static int fdVal(FileDescriptor fdObj) throws Exception {
+ Object fdVal = get("java.io.FileDescriptor", "fd", fdObj);
+ return ((Integer)fdVal).intValue();
+ }
+
+ /*
+ * Return the file descriptor underlying a given SocketChannel
+ */
+ public static int getFD(SocketChannel sc) {
+ try {
+ Object fdObj = get("sun.nio.ch.SocketChannelImpl", "fd", sc);
+ return fdVal((FileDescriptor)fdObj);
+ } catch (Exception x) {
+ x.printStackTrace();
+ throw new InternalError(x.getMessage());
+ }
+ }
+
+ /*
+ * Return the file descriptor underlying a given ServerSocketChannel
+ */
+ public static int getFD(ServerSocketChannel ssc) {
+ try {
+ Object fdObj = get("sun.nio.ch.ServerSocketChannelImpl", "fd", ssc);
+ return fdVal((FileDescriptor)fdObj);
+ } catch (Exception x) {
+ x.printStackTrace();
+ throw new InternalError(x.getMessage());
+ }
+ }
+
+ /*
+ * Return the file descriptor underlying a given DatagramChannel
+ */
+ public static int getFD(DatagramChannel dc) {
+ try {
+ Object fdObj = get("sun.nio.ch.DatagramChannelImpl", "fd", dc);
+ return fdVal((FileDescriptor)fdObj);
+ } catch (Exception x) {
+ x.printStackTrace();
+ throw new InternalError(x.getMessage());
+ }
+ }
+
+ /*
+ * Return the "java" command and any initial arguments to start the runtime
+ * in the current configuration.
+ *
+ * Typically it will return something like :-
+ * cmd[0] = "/usr/local/java/solaris-sparc/bin/java"
+ * or
+ * cmd[0] = "/usr/local/java/solaris-sparc/bin/sparcv9/java"
+ * cmd[1] = "-d64"
+ */
+ public static String[] javaCommand() {
+ String exe = System.getProperty("java.home") + File.separator + "bin" +
+ File.separator;
+ String arch = System.getProperty("os.arch");
+ if (arch.equals("sparcv9")) {
+ String cmd[] = new String[2];
+ cmd[0] = exe + "sparcv9/java";
+ cmd[1] = "-d64";
+ return cmd;
+ } else {
+ String cmd[] = new String[1];
+ cmd[0] = exe += "java";
+ return cmd;
+ }
+ }
+}
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/java.policy.fail b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/java.policy.fail
new file mode 100644
index 0000000..8e04de2
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/java.policy.fail
@@ -0,0 +1,11 @@
+//
+//
+//
+// Used by unit tests for System.inheritedChannel() method. This policy
+// file allows doesn't grant the service the runtime permission needed
+// to obtain the inherited channel but does grant the socket permission
+// needed to report a test result over a socket connection.
+//
+grant {
+ permission java.net.SocketPermission "*:1024-", "resolve,connect";
+};
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/java.policy.pass b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/java.policy.pass
new file mode 100644
index 0000000..fc7cf75
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/java.policy.pass
@@ -0,0 +1,11 @@
+//
+//
+//
+// Used by unit tests for System.inheritedChannel() method. This policy
+// file allows a service to obtain the inherited channel and additionally
+// allows the service to report a test result over a socket connection.
+//
+grant {
+ permission java.lang.RuntimePermission "inheritedChannel";
+ permission java.net.SocketPermission "*:1024-", "resolve,connect";
+};
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/lib/linux-i586/libLauncher.so b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/lib/linux-i586/libLauncher.so
new file mode 100644
index 0000000..bbfdd89
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/lib/linux-i586/libLauncher.so
Binary files differ
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/lib/solaris-i586/libLauncher.so b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/lib/solaris-i586/libLauncher.so
new file mode 100644
index 0000000..440f6d7
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/lib/solaris-i586/libLauncher.so
Binary files differ
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/lib/solaris-sparc/libLauncher.so b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/lib/solaris-sparc/libLauncher.so
new file mode 100644
index 0000000..9e3ae2b
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/lib/solaris-sparc/libLauncher.so
Binary files differ
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/lib/solaris-sparcv9/libLauncher.so b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/lib/solaris-sparcv9/libLauncher.so
new file mode 100644
index 0000000..1a427a7
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/lib/solaris-sparcv9/libLauncher.so
Binary files differ
diff --git a/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/run_tests.sh b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/run_tests.sh
new file mode 100644
index 0000000..17debd1
--- /dev/null
+++ b/test/java/nio/channels/spi/SelectorProvider/inheritedChannel/run_tests.sh
@@ -0,0 +1,147 @@
+#!/bin/sh
+
+#
+# Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+# CA 95054 USA or visit www.sun.com if you need additional information or
+# have any questions.
+#
+
+
+# @test
+# @bug 4673940
+# @bug 4930794
+# @summary Unit tests for inetd feature
+#
+# @build StateTest StateTestService EchoTest EchoService CloseTest Launcher Util
+# @run shell run_tests.sh
+
+os=`uname -s`
+
+if [ "$os" != "Linux" -a "$os" != "SunOS" ]; then
+ echo "Test not designed to run on this operating system, skipping..."
+ exit 0
+fi
+
+
+# if TESTJAVA isn't set then we assume an interactive run. So that it's
+# clear which version of 'java' is running we do a 'which java' and
+# a 'java -version'.
+
+if [ -z "$TESTJAVA" ]; then
+ TESTSRC=`pwd`
+ TESTCLASSES=`pwd`
+ JAVA=java
+ which $JAVA
+ ${JAVA} -d64 -version > /dev/null 2<&1
+ if [ $? = 1 ]; then
+ ${JAVA} -version
+ else
+ ${JAVA} -d64 -version
+ fi
+else
+ JAVA="${TESTJAVA}/bin/java"
+fi
+
+CLASSPATH=${TESTCLASSES}
+export CLASSPATH
+
+
+# Check that we have libLauncher.so for the right platform.
+# On Solaris we assume 64-bit if java -d64 works.
+
+DFLAG=
+if [ "$os" = "SunOS" ]; then
+ PLATFORM=solaris
+ case "`uname -p`" in
+ i[3-9]86)
+ ARCH=i586
+ ;;
+ sparc)
+ ARCH=sparc
+ ${JAVA} -d64 -version > /dev/null 2<&1
+ if [ $? = 1 ]; then
+ ARCH=sparc
+ else
+ ARCH=sparcv9
+ DFLAG=-d64
+ fi
+ ;;
+ esac
+fi
+
+if [ "$os" = "Linux" ]; then
+ PLATFORM=linux
+ ARCH=unknown
+ case "`uname -m`" in
+ i[3-6]86)
+ ARCH=i586
+ ;;
+ ia64)
+ ARCH=ia64
+ ;;
+ x86_64)
+ ARCH=amd64
+ ;;
+ esac
+fi
+
+LIBDIR=lib/${PLATFORM}-${ARCH}
+LAUNCHERLIB=${LIBDIR}/libLauncher.so
+echo $LIBDIR
+
+if [ ! -f "${TESTSRC}/${LAUNCHERLIB}" ]; then
+ echo "Cannot find ${LAUNCHERLIB} - library not available for this system"
+ exit 0
+fi
+
+LD_LIBRARY_PATH=${TESTSRC}/${LIBDIR}
+export LD_LIBRARY_PATH
+
+failures=0
+
+go() {
+ echo ''
+ sh -xc "$JAVA $DFLAG $1 $2 $3 $4 $5 $6 $7 $8" 2>&1
+ if [ $? != 0 ]; then failures=`expr $failures + 1`; fi
+}
+
+# Run the tests
+
+go StateTest
+go EchoTest
+go CloseTest
+
+# Re-run StateTest with a SecurityManager set
+# Note that the system properties are arguments to StateTest and not options.
+# These system properties are passed to the launched service as options:
+# java [-options] class [args...]
+
+go StateTest -Djava.security.manager -Djava.security.policy=${TESTSRC}/java.policy.pass
+go StateTest -expectFail -Djava.security.manager -Djava.security.policy=${TESTSRC}/java.policy.fail
+
+
+#
+# Results
+#
+echo ''
+if [ $failures -gt 0 ];
+ then echo "$failures test(s) failed";
+ else echo "All test(s) passed"; fi
+exit $failures