diff options
author | duke <none@none> | 2007-12-01 00:00:00 +0000 |
---|---|---|
committer | duke <none@none> | 2007-12-01 00:00:00 +0000 |
commit | 6e45e10b03bafdc125c46a4864ba802c24d6bc78 (patch) | |
tree | 182810ab2fece13f57a928d026f93e9ede0827f9 /test/java/io | |
download | jdk8u_jdk-6e45e10b03bafdc125c46a4864ba802c24d6bc78.tar.gz |
Initial load
Diffstat (limited to 'test/java/io')
412 files changed, 33889 insertions, 0 deletions
diff --git a/test/java/io/BufferedInputStream/CloseStream.java b/test/java/io/BufferedInputStream/CloseStream.java new file mode 100644 index 0000000000..0f7b3417ac --- /dev/null +++ b/test/java/io/BufferedInputStream/CloseStream.java @@ -0,0 +1,73 @@ +/* + * Copyright 1998 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 4072173 + @summary Test BufferdInputStream close method */ + +import java.io.*; + +/** + * This class tests to see if BufferedInputStream closes + * properly + */ + +public class CloseStream { + + public static void main( String argv[] ) throws Exception { + BufferedInputStream in = new BufferedInputStream(new MyInputStream()); + + in.read(); + in.close(); + + try { + in.read(); // IOException should be thrown here + throw new RuntimeException("No exception during read on closed stream"); + } + catch (IOException e) { + System.err.println("Test passed: IOException is thrown"); + } + } +} + +class MyInputStream extends InputStream { + + public MyInputStream() { + } + + public void close() throws IOException { + if (status == OPEN) { + status = CLOSED; + } else throw new IOException(); + } + + public int read() throws IOException { + if (status == CLOSED) + throw new IOException(); + return (byte)'a'; + } + + private final int OPEN = 1; + private final int CLOSED = 2; + private int status = OPEN; +} diff --git a/test/java/io/BufferedInputStream/CountUpdate.java b/test/java/io/BufferedInputStream/CountUpdate.java new file mode 100644 index 0000000000..babfb2051f --- /dev/null +++ b/test/java/io/BufferedInputStream/CountUpdate.java @@ -0,0 +1,104 @@ +/* + * Copyright 1998 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 4054043 + * @summary Test bufferedinputstream when stream is interrupted + * + */ + +import java.io.*; + +/** + * This class tests to see if bufferinputstream updates count + * when the stream is interrupted and restarted + * It was adapted from a test class provided in the bug report + * + */ + +public class CountUpdate { + + public static void main(String[] args) throws Exception { + BufferBreaker breaker = new BufferBreaker(); + BufferedInputStream in = new BufferedInputStream(breaker, 1000); + + byte b[] = new byte[100]; + int total = 0; + + for (int i=0; i<5; i++) { + + if (i>0) breaker.breakIt = true; + try { + int n = in.read(b); + total += n; + //System.out.print("read "+n+" bytes: ["); + //System.out.write(b, 0, n); + //System.out.println("]"); + } + catch (IOException e) { + //System.out.println(e); + } + } + + if (total>7) + throw new RuntimeException( + "BufferedInputStream did not reset count."); + } +} + +class BufferBreaker extends InputStream { + public boolean breakIt = false; + + public int read() { + return 'x'; + } + + public static final byte[] buffer = {(byte)'a', + (byte)'b', + (byte)'c', + (byte)'d', + (byte)'e', + (byte)'f', + (byte)'g'}; + + public int read(byte b[]) throws IOException { + return read(b, 0, b.length); + } + + public int read(byte b[], int off, int len) throws IOException { + if (breakIt) throw new IOException("BREAK"); + if (len > buffer.length) len = buffer.length; + System.arraycopy(buffer, 0, b, off, len); + return len; + } + + public long skip(long n) { + return 0; + } + + public int available() { + return 0; + } + +} diff --git a/test/java/io/BufferedInputStream/Fill.java b/test/java/io/BufferedInputStream/Fill.java new file mode 100644 index 0000000000..034269e21d --- /dev/null +++ b/test/java/io/BufferedInputStream/Fill.java @@ -0,0 +1,95 @@ +/* + * Copyright 1998-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 4090383 + @summary Ensure that BufferedInputStream's read method will fill the target + array whenever possible + */ + + +import java.io.IOException; +import java.io.InputStream; +import java.io.BufferedInputStream; + + +public class Fill { + + /** + * A simple InputStream that is always ready but may read fewer than the + * requested number of bytes + */ + static class Source extends InputStream { + + int shortFall; + byte next = 0; + + Source(int shortFall) { + this.shortFall = shortFall; + } + + public int read() throws IOException { + return next++; + } + + public int read(byte[] buf, int off, int len) throws IOException { + int n = len - shortFall; + for (int i = off; i < n; i++) + buf[i] = next++; + return n; + } + + public int available() { + return Integer.MAX_VALUE; + } + + public void close() throws IOException { + } + + } + + /** + * Test BufferedInputStream with an underlying source that always reads + * shortFall fewer bytes than requested + */ + static void go(int shortFall) throws Exception { + + InputStream r = new BufferedInputStream(new Source(shortFall), 10); + byte[] buf = new byte[8]; + + int n1 = r.read(buf); + int n2 = r.read(buf); + System.err.println("Shortfall " + shortFall + + ": Read " + n1 + ", then " + n2 + " bytes"); + if (n1 != buf.length) + throw new Exception("First read returned " + n1); + if (n2 != buf.length) + throw new Exception("Second read returned " + n2); + + } + + public static void main(String[] args) throws Exception { + for (int i = 0; i < 8; i++) go(i); + } + +} diff --git a/test/java/io/BufferedInputStream/ReadAfterClose.java b/test/java/io/BufferedInputStream/ReadAfterClose.java new file mode 100644 index 0000000000..09f7e59d31 --- /dev/null +++ b/test/java/io/BufferedInputStream/ReadAfterClose.java @@ -0,0 +1,57 @@ +/* + * Copyright 1998 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 4143651 + @summary Test if I/O methods will check if the stream + has been closed. +*/ + + + +import java.io.*; + +public class ReadAfterClose { + static void testRead(InputStream in) throws Exception { + in.close(); + byte[] buf = new byte[2]; + + try { + in.read(buf, 0, 1); + throw new Exception("Should not allow read on a closed stream"); + } catch (IOException e) { + } + + try { + in.read(buf, 0, 0); + throw new Exception("Should not allow read on a closed stream"); + } catch (IOException e) { + } + } + + public static void main(String argv[]) throws Exception { + BufferedInputStream bis = new BufferedInputStream + (new ByteArrayInputStream(new byte[32])); + testRead(bis); + } +} diff --git a/test/java/io/BufferedInputStream/ReadZeroBytes.java b/test/java/io/BufferedInputStream/ReadZeroBytes.java new file mode 100644 index 0000000000..55b634f698 --- /dev/null +++ b/test/java/io/BufferedInputStream/ReadZeroBytes.java @@ -0,0 +1,55 @@ +/* + * 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 5041041 + * @summary Test BufferedInputStream read of zero byte array + */ + +import java.io.*; + +/** + * This class tests to see if BufferedInputStream of zero length array + * invokes the read method or not. Invoking read could block which is + * incompatible behavior for zero length array. + */ +public class ReadZeroBytes { + + public static void main( String argv[] ) throws Exception { + BufferedInputStream in = new BufferedInputStream( + new ThrowingInputStream()); + in.read(new byte[0], 0, 0); + } +} + +class ThrowingInputStream extends InputStream { + + public ThrowingInputStream() { + } + public int read() throws IOException { + return 0; + } + public int read(byte[] b, int off, int len) throws IOException { + throw new RuntimeException("Read invoked for len == 0"); + } +} diff --git a/test/java/io/BufferedInputStream/SkipTest.java b/test/java/io/BufferedInputStream/SkipTest.java new file mode 100644 index 0000000000..2b202169e4 --- /dev/null +++ b/test/java/io/BufferedInputStream/SkipTest.java @@ -0,0 +1,97 @@ +/* + * Copyright 1998 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 98/01/12 + * @bug 4022294 + * @summary Test bufferedinputstream for data loss during skip + * + */ + +import java.io.*; +import java.util.*; + +/** + * This class tests to see if bufferinputstream can be reset + * to recover data that was skipped over when the buffer did + * not contain all the bytes to be skipped + */ +public class SkipTest { + + public static void main(String[] args) throws Exception { + long skipped = 0; + + // Create a tiny buffered stream so it can be easily + // set up to contain only some of the bytes to skip + DataSupplier source = new DataSupplier(); + BufferedInputStream in = new BufferedInputStream(source, 4); + + // Set up data to be skipped and recovered + // the skip must be longer than the buffer size + in.mark(30); + while (skipped < 15) { + skipped += in.skip(15-skipped); + } + int nextint = in.read(); + in.reset(); + + // Resume reading and see if data was lost + nextint = in.read(); + + if (nextint != 'a') + throw new RuntimeException("BufferedInputStream skip lost data"); + } +} + + +class DataSupplier extends InputStream { + + private int aposition=0; + + public int read() { + return 'x'; + } + + public long skip(long n) { + aposition += (int) n; + return n; + } + + public static final byte[] buffer = {(byte)'a',(byte)'b',(byte)'c', +(byte)'d',(byte)'e',(byte)'f',(byte)'g',(byte)'h',(byte)'i', +(byte)'j',(byte)'k',(byte)'l',(byte)'m',(byte)'n',(byte)'o', +(byte)'p',(byte)'q',(byte)'r',(byte)'s',(byte)'t',(byte)'u', +(byte)'v',(byte)'w',(byte)'x',(byte)'y',(byte)'z' + }; + + public int read(byte b[]) throws IOException { + return read(b, 0, b.length); + } + + public int read(byte b[], int off, int len) throws IOException { + if (len > buffer.length) len = buffer.length; + System.arraycopy(buffer, aposition, b, off, len); + return len; + } + +} diff --git a/test/java/io/BufferedReader/BigMark.java b/test/java/io/BufferedReader/BigMark.java new file mode 100644 index 0000000000..c4207d9ce8 --- /dev/null +++ b/test/java/io/BufferedReader/BigMark.java @@ -0,0 +1,58 @@ +/* + * Copyright 1997-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 + @summary BufferedReader should throw an OutOfMemoryError when the + read-ahead limit is very large + @bug 6350733 +*/ + +import java.io.*; + + +public class BigMark { + + public static void main(String[] args) throws IOException { + String line; + int i = 0; + String dir = System.getProperty("test.src", "."); + BufferedReader br + = new BufferedReader(new FileReader(new File(dir, "BigMark.java")), 100); + + br.mark(200); + line = br.readLine(); + System.err.println(i + ": " + line); + i++; + + try { + // BR.fill() call to new char[Integer.MAX_VALUE] should succeed + br.mark(Integer.MAX_VALUE); + line = br.readLine(); + } catch (OutOfMemoryError x) { + x.printStackTrace(); + throw x; + } + System.out.println("OutOfMemoryError not thrown as expected"); + } + +} diff --git a/test/java/io/BufferedReader/EOL.java b/test/java/io/BufferedReader/EOL.java new file mode 100644 index 0000000000..d6bda3a696 --- /dev/null +++ b/test/java/io/BufferedReader/EOL.java @@ -0,0 +1,47 @@ +/* + * Copyright 1997 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 4072575 + @summary Test all the EOL delimiters accepted by BufferedReader +*/ + +import java.io.*; + +public class EOL { + + public static void main(String[] args) throws IOException { + Reader sr = new StringReader("one\rtwo\r\nthree\nfour\r"); + BufferedReader br = new BufferedReader(sr); + for (int i = 0;; i++) { + String l = br.readLine(); + if (l == null) { + if (i != 4) + throw new RuntimeException("Expected 4 lines, got " + i); + break; + } + System.err.println(i + ": " + l); + } + } + +} diff --git a/test/java/io/BufferedReader/Fill.java b/test/java/io/BufferedReader/Fill.java new file mode 100644 index 0000000000..224349e702 --- /dev/null +++ b/test/java/io/BufferedReader/Fill.java @@ -0,0 +1,91 @@ +/* + * Copyright 1998 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 4090383 + @summary Ensure that BufferedReader's read method will fill the target array + whenever possible + */ + + +import java.io.IOException; +import java.io.Reader; +import java.io.BufferedReader; + + +public class Fill { + + /** + * A simple Reader that is always ready but may read fewer than the + * requested number of characters + */ + static class Source extends Reader { + + int shortFall; + char next = 0; + + Source(int shortFall) { + this.shortFall = shortFall; + } + + public int read(char[] cbuf, int off, int len) throws IOException { + int n = len - shortFall; + for (int i = off; i < n; i++) + cbuf[i] = next++; + return n; + } + + public boolean ready() { + return true; + } + + public void close() throws IOException { + } + + } + + /** + * Test BufferedReader with an underlying source that always reads + * shortFall fewer characters than requested + */ + static void go(int shortFall) throws Exception { + + Reader r = new BufferedReader(new Source(shortFall), 10); + char[] cbuf = new char[8]; + + int n1 = r.read(cbuf); + int n2 = r.read(cbuf); + System.err.println("Shortfall " + shortFall + + ": Read " + n1 + ", then " + n2 + " chars"); + if (n1 != cbuf.length) + throw new Exception("First read returned " + n1); + if (n2 != cbuf.length) + throw new Exception("Second read returned " + n2); + + } + + public static void main(String[] args) throws Exception { + for (int i = 0; i < 8; i++) go(i); + } + +} diff --git a/test/java/io/BufferedReader/MarkedFillAtEOF.java b/test/java/io/BufferedReader/MarkedFillAtEOF.java new file mode 100644 index 0000000000..1cee476640 --- /dev/null +++ b/test/java/io/BufferedReader/MarkedFillAtEOF.java @@ -0,0 +1,52 @@ +/* + * Copyright 1998 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 4069687 + @summary Test if fill() will behave correctly at EOF + when mark is set. +*/ + +import java.io.*; + +public class MarkedFillAtEOF { + + public static void main(String[] args) throws Exception { + BufferedReader r = new BufferedReader(new StringReader("12")); + int count = 0; + + r.read(); + r.mark(2); + // trigger the call to fill() + while (r.read() != -1); + r.reset(); + + // now should only read 1 character + while (r.read() != -1) { + count++; + } + if (count != 1) { + throw new Exception("Expect 1 character, but got " + count); + } + } +} diff --git a/test/java/io/BufferedReader/ReadLine.java b/test/java/io/BufferedReader/ReadLine.java new file mode 100644 index 0000000000..0b66668e7e --- /dev/null +++ b/test/java/io/BufferedReader/ReadLine.java @@ -0,0 +1,147 @@ +/* + * Copyright 1999 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 4151072 + * @summary Ensure that BufferedReader's methods handle the new line character + * following the carriage return correctly after a readLine + * operation that resulted in reading a line terminated by a + * carriage return (\r). + */ +import java.io.*; + +public class ReadLine { + + public static void main(String[] args) throws IOException { + // Make sure that the reader does not wait for additional characters to + // be read after reading a new line. + BufferedReader reader; + String[][] strings = { + {"CR/LF\r\n", "CR/LF"}, + {"LF-Only\n", "LF-Only"}, + {"CR-Only\r", "CR-Only"}, + {"CR/LF line\r\nMore data", "More data"} + }; + + // test 0 "CR/LF\r\n" + // test 1 "LF-Only\n" + // test 2 "CR-Only\r" + for (int i = 0; i < 3; i++) { + reader = new BufferedReader(new + BoundedReader(strings[i][0]), strings[i][0].length()); + if (!reader.readLine().equals(strings[i][1])) + throw new RuntimeException("Read incorrect text"); + } + + + // Now test the mark and reset operations. Consider two cases. + // 1. For lines ending with CR only. + markResetTest("Lot of textual data\rMore textual data\n", + "More textual data"); + + // 2. Now for lines ending with CR/LF + markResetTest("Lot of textual data\r\nMore textual data\n", + "More textual data"); + + // 3. Now for lines ending with LF only + markResetTest("Lot of textual data\nMore textual data\n", + "More textual data"); + + // Need to ensure behavior of read() after a readLine() read of a CR/LF + // terminated line. + // 1. For lines ending with CR/LF only. + + // uses "CR/LF line\r\nMore data" + reader = new BufferedReader(new + BoundedReader(strings[3][0]), strings[3][0].length()); + reader.readLine(); + if (reader.read() != 'M') + throw new RuntimeException("Read() failed"); + + + // Need to ensure that a read(char[], int, int) following a readLine() + // read of a CR/LF terminated line behaves correctly. + + // uses "CR/LF line\r\nMore data" + reader = new BufferedReader(new + BoundedReader(strings[3][0]), strings[3][0].length()); + reader.readLine(); + + char[] buf = new char[9]; + reader.read(buf, 0, 9); + String newStr = new String(buf); + if (!newStr.equals(strings[3][1])) + throw new RuntimeException("Read(char[],int,int) failed"); + } + + static void markResetTest(String inputStr, String resetStr) + throws IOException { + BufferedReader reader = new BufferedReader(new + BoundedReader(inputStr), inputStr.length()); + System.out.println("> " + reader.readLine()); + reader.mark(30); + System.out.println("......Marking stream ....."); + String str = reader.readLine(); + System.out.println("> " + str); + reader.reset(); + String newStr = reader.readLine(); + System.out.println("reset> " + newStr); + + // Make sure that the reset point was set correctly. + if (!newStr.equals(resetStr)) + throw new RuntimeException("Mark/Reset failed"); + } + + + private static class BoundedReader extends Reader{ + + private char[] content; + private int limit; + private int pos = 0; + + public BoundedReader(String content) { + this.limit = content.length(); + this.content = new char[limit]; + content.getChars(0, limit, this.content, 0); + } + + public int read() throws IOException { + if (pos >= limit) + throw new RuntimeException("Read past limit"); + return content[pos++]; + } + + public int read(char[] buf, int offset, int length) + throws IOException + { + int oldPos = pos; + for (int i = offset; i < length; i++) { + buf[i] = (char)read(); + } + return (pos - oldPos); + } + + public void close() {} + } + +} diff --git a/test/java/io/BufferedReader/ReadLineSync.java b/test/java/io/BufferedReader/ReadLineSync.java new file mode 100644 index 0000000000..0b85fabfbf --- /dev/null +++ b/test/java/io/BufferedReader/ReadLineSync.java @@ -0,0 +1,130 @@ +/* + * 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 5073414 + * @summary Ensure that there is no race condition in BufferedReader.readLine() + * when a line is terminated by '\r\n' is read by multiple threads. + */ + +import java.io.*; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class ReadLineSync { + + public static int lineCount = 0; + + public static void main( String[] args ) throws Exception { + + String dir = System.getProperty(".", "."); + File f = new File(dir, "test.txt"); + createFile(f); + f.deleteOnExit(); + + BufferedReader reader = new BufferedReader( + new FileReader(f)); + int threadCount = 2; + + ExecutorService es = Executors.newFixedThreadPool(threadCount); + + for (int i=0; i < threadCount; i++) + es.execute(new BufferedReaderConsumer(reader)); + + // Wait for the tasks to complete + es.shutdown(); + while (!es.awaitTermination(60, TimeUnit.SECONDS)); + } + + static class BufferedReaderConsumer extends Thread { + BufferedReader reader; + + public BufferedReaderConsumer( BufferedReader reader ) { + this.reader = reader; + } + + public void run() { + try { + String record = reader.readLine(); + + if ( record == null ) { + // if the first thread is too fast the second will hit + // this which is ok + System.out.println( "File already finished" ); + return; + } + + if ( record.length() == 0 ) { + // usually it comes out here indicating the first read + // done by the second thread to run failed + System.out.println("Empty string on first read." + + Thread.currentThread().getName() ); + } + + while ( record != null ) { + lineCount++; + + // Verify the token count + if ( record.length() == 0 ) { + // very occasionally it will fall over here + throw new Exception( "Invalid tokens with string '" + + record + "' on line " + lineCount ); + } + record = reader.readLine(); + } + } + catch ( Exception e ) { + e.printStackTrace(); + } + } + } + + + // Create a relatively big file + + private static void createFile(File f) throws IOException { + BufferedWriter w = new BufferedWriter( + new FileWriter(f)); + int count = 10000; + while (count > 0) { + + w.write("abcd \r\n"); + w.write("efg \r\n"); + w.write("hijk \r\n"); + w.write("lmnop \r\n"); + w.write("qrstuv \r\n"); + w.write("wxy and z \r\n"); + w.write("now you \r\n"); + w.write("know your \r\n"); + w.write("abc \r\n"); + w.write("next time \r\n"); + w.write("want you \r\n"); + w.write("sing with me \r\n"); + + count--; + } + w.close(); + } +} diff --git a/test/java/io/BufferedReader/Ready.java b/test/java/io/BufferedReader/Ready.java new file mode 100644 index 0000000000..391351d4f2 --- /dev/null +++ b/test/java/io/BufferedReader/Ready.java @@ -0,0 +1,105 @@ +/* + * Copyright 2000 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 4329985 + * @summary Ensure that BufferedReader's ready() method handles the new line + * character following the carriage return correctly and returns the right + * value so that a read operation after a ready() does not block unnecessarily. + */ +import java.io.*; + +public class Ready { + + public static void main(String[] args) throws IOException { + BufferedReader reader; + String[] strings = { + "LF-Only\n", + "LF-Only\n", + "CR/LF\r\n", + "CR/LF\r\n", + "CR-Only\r", + "CR-Only\r", + "CR/LF line\r\nMore data.\r\n", + "CR/LF line\r\nMore data.\r\n" + }; + + // The buffer sizes are chosen such that the boundary conditions are + // tested. + int[] bufsizes = { 7, 8, 6, 5, 7, 8, 11, 10}; + + for (int i = 0; i < strings.length; i++) { + reader = new BufferedReader(new BoundedReader(strings[i]), + bufsizes[i]); + while (reader.ready()) { + String str = reader.readLine(); + System.out.println("read>>" + str); + } + } + } + + + + private static class BoundedReader extends Reader{ + + private char[] content; + private int limit; + private int pos = 0; + + public BoundedReader(String content) { + this.limit = content.length(); + this.content = new char[limit]; + content.getChars(0, limit, this.content, 0); + } + + public int read() throws IOException { + if (pos >= limit) + throw new RuntimeException("Hit infinite wait condition"); + return content[pos++]; + } + + public int read(char[] buf, int offset, int length) + throws IOException + { + if (pos >= limit) + throw new RuntimeException("Hit infinite wait condition"); + int oldPos = pos; + int readlen = (length > (limit - pos)) ? (limit - pos) : length; + for (int i = offset; i < readlen; i++) { + buf[i] = (char)read(); + } + + return (pos - oldPos); + } + + public void close() {} + + public boolean ready() { + if (pos < limit) + return true; + else + return false; + } + } + +} diff --git a/test/java/io/BufferedReader/SkipNegative.java b/test/java/io/BufferedReader/SkipNegative.java new file mode 100644 index 0000000000..1b4072341c --- /dev/null +++ b/test/java/io/BufferedReader/SkipNegative.java @@ -0,0 +1,47 @@ +/* + * Copyright 1998 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 4152453 + @summary Skip must throw an exception for negative args +*/ + + + +import java.io.*; + +public class SkipNegative { + public static void main(String argv[]) throws Exception { + char[] cbuf = "testString".toCharArray(); + CharArrayReader CAR = new CharArrayReader(cbuf); + BufferedReader BR = new BufferedReader(CAR); + long nchars = -1L; + try { + long actual = BR.skip(nchars); + } catch(IllegalArgumentException e){ + // Negative argument caught + return; + } + throw new Exception("Skip should not accept negative values"); + } +} diff --git a/test/java/io/BufferedWriter/Cleanup.java b/test/java/io/BufferedWriter/Cleanup.java new file mode 100644 index 0000000000..30a42e8046 --- /dev/null +++ b/test/java/io/BufferedWriter/Cleanup.java @@ -0,0 +1,98 @@ +/* + * 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 6266377 + * @summary Test to ensure that BufferedWriter releases + * resources if flushing the buffer results in an + * exception during a call to close(). + */ + +import java.io.*; + +public class Cleanup extends Thread { + + static PipedWriter w; + static PipedReader r; + static boolean isWriterClosed = false; + + public void run() { + try { + System.out.println("Reader reading..."); + r.read(new char[2048], 0, 2048); + + // Close abruptly before reading all the bytes + System.out.println("Reader closing stream..."); + r.close(); + + Thread.sleep(3000); + } catch (Throwable e) { + System.out.println("Reader exception:"); + e.printStackTrace(); + } + } + + public static void main(String args[]) throws Exception { + r = new PipedReader(); + w = new PipedWriter(r); + + Cleanup reader = new Cleanup(); + reader.start(); + + BufferedWriter bw = new BufferedWriter(w); + + boolean isWriterClosed = false; + + try { + System.out.println("Writer started."); + + for (int i = 0; i < 3; i++) { + bw.write(new char[1024], 0, (1024)); + } + + // This call to close() will raise an exception during + // flush() since the reader is already closed + bw.close(); + + } catch (Throwable e) { + try { + e.printStackTrace(); + + // Make sure that the BufferedWriter releases the resources + // A write to a properly closed Writer should raise an exception + bw.write('a'); + + } catch (IOException ex) { + ex.printStackTrace(); + isWriterClosed = true; + } + } finally { + System.out.println("Writer done."); + reader.join(); + if (!isWriterClosed) { + throw new Exception("BufferedWriter is not closed properly"); + } + } + } +} diff --git a/test/java/io/ByteArrayOutputStream/ToString.java b/test/java/io/ByteArrayOutputStream/ToString.java new file mode 100644 index 0000000000..639a1f426c --- /dev/null +++ b/test/java/io/ByteArrayOutputStream/ToString.java @@ -0,0 +1,48 @@ +/* + * Copyright 1997 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 1226190 + @summary Heartbeat test of ByteArrayOutputStream's toString methods + */ + +import java.io.*; + +public class ToString { + + public static void main(String[] args) throws IOException { + String test = "This is a test."; + ByteArrayOutputStream b = new ByteArrayOutputStream(); + PrintStream p = new PrintStream(b); + p.print(test); + p.close(); + + if (! b.toString().equals(test)) + throw new RuntimeException("Default encoding failed"); + if (! b.toString("UTF8").equals(test)) + throw new RuntimeException("UTF8 encoding failed"); + if (! b.toString(0).equals(test)) + throw new RuntimeException("Hibyte0 encoding failed"); + } + +} diff --git a/test/java/io/ByteArrayOutputStream/WriteBounds.java b/test/java/io/ByteArrayOutputStream/WriteBounds.java new file mode 100644 index 0000000000..0ec1e599a9 --- /dev/null +++ b/test/java/io/ByteArrayOutputStream/WriteBounds.java @@ -0,0 +1,76 @@ +/* + * Copyright 1997 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 4017158 + @summary Check for correct implementation of ByteArrayInputStream.write + */ + +import java.io.*; + + +public class WriteBounds{ + + private static void dotest(byte[] b, int off, int len, + ByteArrayOutputStream baos) + throws Exception + { + + if (b != null) { + System.err.println("ByteArrayOutStream.write -- b.length = " + + b.length + " off = " + off + " len = " + len); + } + else{ + System.err.println("ByteArrayOutStream.write - b is null off = " + + off + " len = " + len); + } + + try { + baos.write(b, off, len); + } catch (IndexOutOfBoundsException e) { + System.err.println("IndexOutOfBoundsException is thrown -- OKAY"); + } catch (NullPointerException e) { + System.err.println("NullPointerException is thrown -- OKAY"); + } catch (Throwable e){ + throw new RuntimeException("Unexpected Exception is thrown"); + } + + } + + public static void main( String argv[] ) throws Exception { + + ByteArrayOutputStream y1; + byte array1[]={1 , 2 , 3 , 4 , 5}; // Simple array + + //Create new ByteArrayOutputStream object + y1 = new ByteArrayOutputStream(5); + + dotest(array1, 0, Integer.MAX_VALUE , y1); + dotest(array1, 0, array1.length+100, y1); + dotest(array1, -1, 2, y1); + dotest(array1, 0, -1, y1); + dotest(null, 0, 2, y1); + + } + +} diff --git a/test/java/io/CharArrayReader/Constructor.java b/test/java/io/CharArrayReader/Constructor.java new file mode 100644 index 0000000000..b298a3072d --- /dev/null +++ b/test/java/io/CharArrayReader/Constructor.java @@ -0,0 +1,79 @@ +/* + * Copyright 1998 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 4140445 4140451 + @summary Test if constructor will check for illegal + arguments. +*/ + + + +import java.io.*; + +public class Constructor { + public static void main(String argv[]) throws Exception { + int values[] = {Integer.MIN_VALUE, -1, 0, 1, 4, 16, 31, + 32, 33, Integer.MAX_VALUE}; + char b[][] = {null, new char[32]}; + + int i = 0, j = 0, k = 0; + boolean nullPtr = false, indexOutBnd = false; + + for (i = 0; i < b.length; i++) { + for ( j = 0; j < values.length; j++) { + for ( k = 0; k < values.length; k++) { + + nullPtr = (b[i] == null); + + int bufLen = nullPtr ? 0 : b[i].length; + indexOutBnd = (values[j] < 0) + || (values[j] > bufLen) + || (values[k] < 0) + || ((values[j] + values[k]) < 0); + + try { + CharArrayReader rdr = new CharArrayReader + (b[i], values[j], values[k]); + } catch (NullPointerException e) { + if (!nullPtr) { + throw new Exception + ("should not throw NullPointerException"); + } + continue; + } catch (IllegalArgumentException e) { + if (!indexOutBnd) { + throw new Exception + ("should not throw IllegalArgumentException"); + } + continue; + } + + if (nullPtr || indexOutBnd) { + throw new Exception("Failed to detect illegal argument"); + } + } + } + } + } +} diff --git a/test/java/io/DataInputStream/OpsAfterClose.java b/test/java/io/DataInputStream/OpsAfterClose.java new file mode 100644 index 0000000000..189fa76196 --- /dev/null +++ b/test/java/io/DataInputStream/OpsAfterClose.java @@ -0,0 +1,276 @@ +/* + * 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 4181483 + * @summary Test if DataInputStream methods will check if the stream + * has been closed. + */ + +import java.io.*; + +public enum OpsAfterClose { + + READ { boolean check(DataInputStream is) { + try { + int read = is.read(); + System.out.println("read returns: " + read); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + + READ_BUF { boolean check(DataInputStream is) { + try { + byte buf[] = new byte[2]; + int read = is.read(buf); + System.out.println("read(buf) returns: " + read); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + READ_BUF_OFF { boolean check(DataInputStream is) { + try { + byte buf[] = new byte[2]; + int len = 1; + int read = is.read(buf, 0, len); + System.out.println("read(buf, 0, len) returns: " + read); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + AVAILABLE { boolean check(DataInputStream is) { + try { + int avail = is.available(); + System.out.println("available() returns: " + avail); + return false; + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + } }, + SKIP { boolean check(DataInputStream is) { + try { + long skipped = is.skip(1); + System.out.println("skip() returns: " + skipped); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + MARK { boolean check(DataInputStream is) { + is.mark(20); + return true; + } }, + RESET { boolean check(DataInputStream is) { + try { + is.reset(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + MARK_SUPPORTED { boolean check(DataInputStream is) { + is.markSupported(); + return true; + } }, + CLOSE { boolean check(DataInputStream is) { + try { + is.close(); + return true; // No Exception thrown on windows + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; // Exception thrown on solaris and linux + } + }}, + READ_BYTE { boolean check(DataInputStream is) { + try { + is.readByte(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + READ_CHAR { boolean check(DataInputStream is) { + try { + is.readChar(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + READ_DOUBLE { boolean check(DataInputStream is) { + try { + is.readDouble(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + + READ_FLOAT { boolean check(DataInputStream is) { + try { + is.readFloat(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + READ_INT { boolean check(DataInputStream is) { + try { + is.readInt(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + READ_LONG { boolean check(DataInputStream is) { + try { + is.readLong(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + READ_SHORT { boolean check(DataInputStream is) { + try { + is.readShort(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + READ_UnsignedByte { boolean check(DataInputStream is) { + try { + is.readUnsignedByte(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + READ_UnsignedShort { boolean check(DataInputStream is) { + try { + is.readUnsignedShort(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + READ_UTF { boolean check(DataInputStream is) { + try { + is.readUTF(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + SKIP_BYTES { boolean check(DataInputStream is) { + try { + is.skipBytes(1); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + READ_FULLY { boolean check(DataInputStream is) { + try { + is.readFully(new byte[1]); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + READ_FULLY_BUF { boolean check(DataInputStream is) { + try { + is.readFully(new byte[1], 0, 1); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }; + + + abstract boolean check(DataInputStream is); + + public static void main(String args[]) throws Exception { + + boolean failed = false; + + File f = new File(System.getProperty("test.dir", "."), + "f.txt"); + f.createNewFile(); + f.deleteOnExit(); + + FileInputStream fis = new FileInputStream(f); + + DataInputStream dis = new DataInputStream( + new FileInputStream(f)); + if (testDataInputStream(dis)) { + failed = true; + } + + } + + private static boolean testDataInputStream(DataInputStream is) + throws Exception { + is.close(); + boolean failed = false; + boolean result; + System.out.println("Testing :" + is); + for (OpsAfterClose op : OpsAfterClose.values()) { + + result = op.check(is); + if (!result) { + failed = true; + } + System.out.println(op + ":" + result); + } + if (failed) { + System.out.println("Test failed for the failed operation{s}" + + " above for :" + is); + } + return failed; + } +} diff --git a/test/java/io/DataInputStream/ReadFully.java b/test/java/io/DataInputStream/ReadFully.java new file mode 100644 index 0000000000..be05f2be4b --- /dev/null +++ b/test/java/io/DataInputStream/ReadFully.java @@ -0,0 +1,50 @@ +/* + * Copyright 1999 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 4214513 + * @summary Passing a negative length argument for readFully must throw + * IndexOutOfBoundsException. + */ + + +import java.io.*; +public class ReadFully { + public static final void main(String[] args) throws Exception { + byte[] buffer = new byte[100]; + File file = new File(System.getProperty("test.src"), + "ReadFully.java"); + FileInputStream in = new FileInputStream(file); + DataInputStream dis = new DataInputStream(in); + + boolean caughtException = false; + try { + dis.readFully(buffer, 0, -20); + } catch (IndexOutOfBoundsException ie) { + caughtException = true; + } finally { + if (!caughtException) + throw new RuntimeException("Test failed"); + } + } +} diff --git a/test/java/io/DataInputStream/ReadLinePushback.java b/test/java/io/DataInputStream/ReadLinePushback.java new file mode 100644 index 0000000000..2ac54a8242 --- /dev/null +++ b/test/java/io/DataInputStream/ReadLinePushback.java @@ -0,0 +1,50 @@ +/* + * Copyright 1998 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 4093646 + @summary Make sure readLine would not push back -1. + */ + +import java.io.*; + +public class ReadLinePushback { + + public static void main(String args[]) throws Exception { + PushbackInputStream pis = new PushbackInputStream + ((new StringBufferInputStream("\r"))); + DataInputStream dis = new DataInputStream(pis); + + String line = dis.readLine(); + if (line == null) { + throw new Exception ("Got null, should return empty line"); + } + + int count = pis.available(); + + if (count != 0) { + throw new Exception ("Test failed: available() returns " + + count + "when the file is empty"); + } + } +} diff --git a/test/java/io/DataInputStream/ReadUTF.java b/test/java/io/DataInputStream/ReadUTF.java new file mode 100644 index 0000000000..b3e22c446b --- /dev/null +++ b/test/java/io/DataInputStream/ReadUTF.java @@ -0,0 +1,86 @@ +/* + * 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 4806007 + * @summary Checks for vague exceptions from writeUTF/readUTF + */ + +import java.io.*; +import java.util.*; + +public class ReadUTF { + + private static Random generator = new Random(); + + private static final int TEST_ITERATIONS = 1000; + + private static final int A_NUMBER_NEAR_65535 = 60000; + + private static final int MAX_CORRUPTIONS_PER_CYCLE = 3; + + public static final void main(String[] args) throws Exception { + for (int i=0; i<TEST_ITERATIONS; i++) { + try { + writeAndReadAString(); + } catch (UTFDataFormatException utfdfe) { + if (utfdfe.getMessage() == null) + throw new RuntimeException("vague exception thrown"); + } catch (EOFException eofe) { + // These are rare and beyond the scope of the test + } + } + } + + private static void writeAndReadAString() throws Exception { + // Write out a string whose UTF-8 encoding is quite possibly + // longer than 65535 bytes + int length = generator.nextInt(A_NUMBER_NEAR_65535) + 1; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + StringBuffer testBuffer = new StringBuffer(); + for (int i=0; i<length; i++) + testBuffer.append((char)generator.nextInt()); + String testString = testBuffer.toString(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeUTF(testString); + + // Corrupt the data to produce malformed characters + byte[] testBytes = baos.toByteArray(); + int dataLength = testBytes.length; + int corruptions = generator.nextInt(MAX_CORRUPTIONS_PER_CYCLE); + for (int i=0; i<corruptions; i++) { + int index = generator.nextInt(dataLength); + testBytes[index] = (byte)generator.nextInt(); + } + + // Pay special attention to mangling the end to produce + // partial characters at end + testBytes[dataLength-1] = (byte)generator.nextInt(); + testBytes[dataLength-2] = (byte)generator.nextInt(); + + // Attempt to decode the bytes back into a String + ByteArrayInputStream bais = new ByteArrayInputStream(testBytes); + DataInputStream dis = new DataInputStream(bais); + dis.readUTF(); + } +} diff --git a/test/java/io/DataInputStream/SkipBytes.java b/test/java/io/DataInputStream/SkipBytes.java new file mode 100644 index 0000000000..a0c91a54d4 --- /dev/null +++ b/test/java/io/DataInputStream/SkipBytes.java @@ -0,0 +1,87 @@ +/* + * Copyright 1997 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 4085938 + @summary Check for the correct behaviour of DataInputStream.skipBytes + */ + +import java.io.*; + +public class SkipBytes{ + + private static void dotest(DataInputStream dis, int pos, int total, + int toskip, int expected) { + + try { + System.err.println("\n\nTotal bytes in the stream = " + total); + System.err.println("Currently at position = " + pos); + System.err.println("Bytes to skip = " + toskip); + System.err.println("Expected result = " + expected); + int skipped = dis.skipBytes(toskip); + System.err.println("Actual skipped = " + skipped); + if (skipped != expected) { + throw new RuntimeException + ("DataInputStream.skipBytes does not return expected value"); + } + } catch(EOFException e){ + throw new RuntimeException + ("DataInputStream.skipBytes throws unexpected EOFException"); + } catch (IOException e) { + System.err.println("IOException is thrown - possible result"); + } + + + } + + + + public static void main(String args[]) throws Exception { + + DataInputStream dis = new DataInputStream(new MyInputStream()); + dotest(dis, 0, 11, -1, 0); + dotest(dis, 0, 11, 5, 5); + System.err.println("\n***CAUTION**** - may go into an infinite loop"); + dotest(dis, 5, 11, 20, 6); + } +} + + +class MyInputStream extends InputStream { + + private int readctr = 0; + + public int read() { + + if (readctr > 10){ + return -1; + } + else{ + readctr++; + return 0; + } + + } + + public int available() { return 0; } +} diff --git a/test/java/io/DataOutputStream/CounterOverflow.java b/test/java/io/DataOutputStream/CounterOverflow.java new file mode 100644 index 0000000000..fe371ff2cc --- /dev/null +++ b/test/java/io/DataOutputStream/CounterOverflow.java @@ -0,0 +1,47 @@ +/* + * Copyright 1998 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 4017419 + @summary Test if DataOutputStream will control the + overflow of its internal counter. +*/ + +import java.io.*; + +public class CounterOverflow extends DataOutputStream { + + public CounterOverflow(OutputStream out) { + super(out); + written = Integer.MAX_VALUE; + } + + public static void main(String[] args) throws Exception { + CounterOverflow dataOut = new CounterOverflow(System.out); + + dataOut.writeByte(1); + if (dataOut.size() < 0) { + throw new Exception("Internal counter less than 0."); + } + } +} diff --git a/test/java/io/DataOutputStream/WriteUTF.java b/test/java/io/DataOutputStream/WriteUTF.java new file mode 100644 index 0000000000..11b706a035 --- /dev/null +++ b/test/java/io/DataOutputStream/WriteUTF.java @@ -0,0 +1,40 @@ +/* + * Copyright 1999 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 4260284 + @summary Test if DataOutputStream will overcount written field. +*/ + +import java.io.*; + +public class WriteUTF { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeUTF("Hello, World!"); // 15 + dos.flush(); + if (baos.size() != dos.size()) + throw new RuntimeException("Miscounted bytes in DataOutputStream."); + } +} diff --git a/test/java/io/Externalizable/compatibility/ExternalizableBlockData.java b/test/java/io/Externalizable/compatibility/ExternalizableBlockData.java new file mode 100644 index 0000000000..49e5ccbf7f --- /dev/null +++ b/test/java/io/Externalizable/compatibility/ExternalizableBlockData.java @@ -0,0 +1,113 @@ +/* + * Copyright 2000 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 4089540 + * @summary Verify compatibility with 1.1 externalizable format + */ + +import java.io.*; +import java.util.*; + +class Foo implements Externalizable { + private static final long serialVersionUID = 0xbabel; + + int x; + int y; + Object obj; + + public Foo() { + } + + public Foo(int x, int y, Object obj) { + this.x = x; + this.y = y; + this.obj = obj; + } + + public void writeExternal(ObjectOutput out) throws IOException { + out.writeInt(x); + out.writeInt(y); + out.writeObject(obj); + } + + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException + { + x = in.readInt(); + y = in.readInt(); + obj = in.readObject(); + } + + public boolean equals(Object other) { + if (other instanceof Foo) { + Foo f = (Foo) other; + return ((x == f.x) && (y == f.y) && + ((obj != null) ? obj.equals(f.obj) : (f.obj == null))); + } + return false; + } +} + +public class ExternalizableBlockData { + public static void main(String[] args) throws Exception { + byte[] oldExternalizableBytes = getFileBytes( + new File(System.getProperty("test.src", "."), "old.ser")); + Foo foo = new Foo(0xbad, 0xbeef, "burrito"); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.useProtocolVersion(ObjectStreamConstants.PROTOCOL_VERSION_1); + oout.writeObject(foo); + oout.close(); + if (! Arrays.equals(bout.toByteArray(), oldExternalizableBytes)) { + throw new Error(); + } + + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(oldExternalizableBytes)); + if (! foo.equals(oin.readObject())) { + throw new Error(); + } + + bout = new ByteArrayOutputStream(); + oout = new ObjectOutputStream(bout); + oout.writeObject(foo); + oout.close(); + if (Arrays.equals(bout.toByteArray(), oldExternalizableBytes)) { + throw new Error(); + } + } + + static byte[] getFileBytes(File file) throws IOException { + FileInputStream fin = new FileInputStream(file); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + byte[] buf = new byte[256]; + int n; + + while ((n = fin.read(buf)) != -1) { + bout.write(buf, 0, n); + } + fin.close(); + return bout.toByteArray(); + } +} diff --git a/test/java/io/Externalizable/compatibility/old.ser b/test/java/io/Externalizable/compatibility/old.ser Binary files differnew file mode 100644 index 0000000000..d75a6eb171 --- /dev/null +++ b/test/java/io/Externalizable/compatibility/old.ser diff --git a/test/java/io/Externalizable/definesWriteObject/DefinesWriteObject.java b/test/java/io/Externalizable/definesWriteObject/DefinesWriteObject.java new file mode 100644 index 0000000000..f7e6bcce6e --- /dev/null +++ b/test/java/io/Externalizable/definesWriteObject/DefinesWriteObject.java @@ -0,0 +1,104 @@ +/* + * Copyright 1998 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 4151469 + * @summary Write and read an Externalizable class that defines writeObject. + * There was some confusion over writeObject method needing + * to be defined by an Externalizable class. It does not + * need to exist, but Externalizable class should work correctly + * if the member exists. + */ + +import java.io.*; + +public class DefinesWriteObject implements Externalizable { + + private int intData = 4; + private Object objData = new String("hello"); + + public DefinesWriteObject() { + } + + public DefinesWriteObject(int i, Object o) { + intData = i; + objData = o; + } + + /** + * There was some confusion over writeObject method needing + * to be defined by an Externalizable class. It does not + * need to exist, but Externalizable class should work correctly + * if the member exists. + */ + private void writeObject(ObjectOutputStream out) throws IOException { + } + + /** + * @serialData Writes an integer, Object. + */ + public void writeExternal(ObjectOutput out) + throws IOException + { + out.writeInt(intData); + out.writeObject(objData); + } + + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException + { + intData = in.readInt(); + objData = in.readObject(); + } + + public static void main(String args[]) + throws IOException, ClassNotFoundException + { + DefinesWriteObject obj1 = new DefinesWriteObject(5, "GoodBye"); + DefinesWriteObject obj2 = new DefinesWriteObject(6, "AuRevoir"); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(obj1); + oos.writeObject(obj2); + oos.close(); + + ByteArrayInputStream bais = + new ByteArrayInputStream(baos.toByteArray()); + ObjectInputStream ois = new ObjectInputStream(bais); + DefinesWriteObject readObject1 = (DefinesWriteObject)ois.readObject(); + DefinesWriteObject readObject2 = (DefinesWriteObject)ois.readObject(); + ois.close(); + + // verify that deserialize data matches objects serialized. + if (obj1.intData != readObject1.intData || + obj2.intData != readObject2.intData) { + throw new Error("Unexpected mismatch between integer data written and read."); + } + if ( ! ((String)obj1.objData).equals((String)readObject1.objData) || + ! ((String)obj2.objData).equals((String)readObject2.objData)) { + throw new Error("Unexpected mismatch between String data written and read."); + } + } +}; diff --git a/test/java/io/File/AccessDenied.java b/test/java/io/File/AccessDenied.java new file mode 100644 index 0000000000..66acd40c07 --- /dev/null +++ b/test/java/io/File/AccessDenied.java @@ -0,0 +1,54 @@ +/* + * 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 6198547 + * @summary Test to ensure that File.createNewFile() consistently + * returns the same (false) value when the specified path + * is already present as a directory. + */ + +import java.io.*; + +public class AccessDenied { + public static void main(String[] args) + throws Exception { + File dir = new File(System.getProperty("test.dir", "."), + "hugo"); + dir.deleteOnExit(); + if (!dir.mkdir()) { + throw new Exception("Could not create directory:" + dir); + } + System.out.println("Created directory:" + dir); + + File file = new File(System.getProperty("test.dir", "."), "hugo"); + boolean result = file.createNewFile(); + System.out.println("CreateNewFile() for:" + file + " returned:" + + result); + if (result) { + throw new Exception( + "Expected createNewFile() to return false but it returned true"); + } + } +} diff --git a/test/java/io/File/Basic.java b/test/java/io/File/Basic.java new file mode 100644 index 0000000000..a57c6ccdde --- /dev/null +++ b/test/java/io/File/Basic.java @@ -0,0 +1,150 @@ +/* + * Copyright 1998-1999 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 4165666 4203706 4288670 4290024 + @summary Basic heartbeat test for File methods that access the filesystem + + @build Basic + @run shell basic.sh + */ + +import java.io.IOException; +import java.io.File; +import java.io.PrintStream; +import java.io.RandomAccessFile; + + +public class Basic { + + static PrintStream out = System.err; + + static File nonExistantFile = new File("x.Basic.non"); + static File rwFile = new File("x.Basic.rw"); + static File bigFile = new File("x.Basic.big"); + static File roFile = new File("x.Basic.ro"); + static File thisDir = new File("."); + static File dir = new File("x.Basic.dir"); + static File nonDir = new File("x.Basic.nonDir"); + + static void showBoolean(String what, boolean value) { + out.println(" " + what + ": " + value); + } + + static void showLong(String what, long value) { + out.println(" " + what + ": " + value); + } + + static void show(File f) throws Exception { + out.println(f + ": "); + showBoolean("exists", f.exists()); + showBoolean("isFile", f.isFile()); + showBoolean("isDirectory", f.isDirectory()); + showBoolean("canRead", f.canRead()); + showBoolean("canWrite", f.canWrite()); + showLong("lastModified", f.lastModified()); + showLong("length", f.length()); + } + + static void testFile(File f, boolean writeable, long length) + throws Exception + { + if (!f.exists()) fail(f, "does not exist"); + if (!f.isFile()) fail(f, "is not a file"); + if (f.isDirectory()) fail(f, "is a directory"); + if (!f.canRead()) fail(f, "is not readable"); + if (f.canWrite() != writeable) + fail(f, writeable ? "is not writeable" : "is writeable"); + int rwLen = (File.separatorChar == '/' ? 6 : 7); + if (f.length() != length) fail(f, "has wrong length"); + } + + static void fail(File f, String why) throws Exception { + throw new Exception(f + " " + why); + } + + public static void main(String[] args) throws Exception { + + show(nonExistantFile); + if (nonExistantFile.exists()) fail(nonExistantFile, "exists"); + + show(rwFile); + testFile(rwFile, true, File.separatorChar == '/' ? 6 : 7); + rwFile.delete(); + if (rwFile.exists()) + fail(rwFile, "could not delete"); + + show(roFile); + testFile(roFile, false, 0); + + show(thisDir); + if (!thisDir.exists()) fail(thisDir, "does not exist"); + if (thisDir.isFile()) fail(thisDir, "is a file"); + if (!thisDir.isDirectory()) fail(thisDir, "is not a directory"); + if (!thisDir.canRead()) fail(thisDir, "is readable"); + if (!thisDir.canWrite()) fail(thisDir, "is writeable"); + String[] fs = thisDir.list(); + if (fs == null) fail(thisDir, "list() returned null"); + out.print(" [" + fs.length + "]"); + for (int i = 0; i < fs.length; i++) + out.print(" " + fs[i]); + out.println(); + if (fs.length == 0) fail(thisDir, "is empty"); + + if (!nonExistantFile.createNewFile()) + fail(nonExistantFile, "could not create"); + nonExistantFile.deleteOnExit(); + + if (!nonDir.mkdir()) + fail(nonDir, "could not create"); + + if (!dir.renameTo(new File("x.Basic.dir2"))) + fail(dir, "failed to rename"); + + if (System.getProperty("os.name").equals("SunOS") + && System.getProperty("os.version").compareTo("5.6") >= 0) { + if (bigFile.exists()) { + bigFile.delete(); + if (bigFile.exists()) + fail(bigFile, "could not delete"); + } + RandomAccessFile raf = new RandomAccessFile(bigFile, "rw"); + long big = ((long)Integer.MAX_VALUE) * 2; + try { + raf.seek(big); + raf.write('x'); + show(bigFile); + testFile(bigFile, true, big + 1); + } finally { + raf.close(); + } + bigFile.delete(); + if (bigFile.exists()) + fail(bigFile, "could not delete"); + } else { + System.err.println("NOTE: Large files not supported on this system"); + } + + } + +} diff --git a/test/java/io/File/BlockIsDirectory.java b/test/java/io/File/BlockIsDirectory.java new file mode 100644 index 0000000000..42c3b2a09c --- /dev/null +++ b/test/java/io/File/BlockIsDirectory.java @@ -0,0 +1,63 @@ +/* + * Copyright 1998-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 4113217 + @summary Test File.isDirectory on block device + */ + +import java.io.*; +import java.util.*; + +public class BlockIsDirectory { + public static void main( String args[] ) throws Exception { + String osname = System.getProperty("os.name"); + if (osname.equals("SunOS")) { + File dir = new File("/dev/dsk"); + String dirList[] = dir.list(); + + File aFile = new File( "/dev/dsk/" + dirList[0] ); + + boolean result = aFile.isDirectory(); + if (result == true) + throw new RuntimeException( + "IsDirectory returns true for block device."); + } + if (osname.equals("Linux")) { + File dir = new File("/dev/ide0"); + if (dir.exists()) { + boolean result = dir.isDirectory(); + if (result == true) + throw new RuntimeException( + "IsDirectory returns true for block device."); + } + dir = new File("/dev/scd0"); + if (dir.exists()) { + boolean result = dir.isDirectory(); + if (result == true) + throw new RuntimeException( + "IsDirectory returns true for block device."); + } + } + } +} diff --git a/test/java/io/File/CheckTempDir.java b/test/java/io/File/CheckTempDir.java new file mode 100644 index 0000000000..7c45c419c9 --- /dev/null +++ b/test/java/io/File/CheckTempDir.java @@ -0,0 +1,47 @@ +/* + * Copyright 1997 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 4099970 + * + * @summary this tests that the temp dir variable, java.io.tmpdir is + * properly initialized. + * + * @author Benjamin Renaud + */ + +import java.io.File; +import java.io.IOException; + +public class CheckTempDir { + + public static void main (String[] args) { + String tmpdir = null; + if ((tmpdir = System.getProperty("java.io.tmpdir")) == null) { + throw new RuntimeException("java.io.tmpdir is not initialized"); + } else { + System.out.println("checked tmpdir is not null: " + tmpdir); + } + } +} diff --git a/test/java/io/File/CompareTo.java b/test/java/io/File/CompareTo.java new file mode 100644 index 0000000000..299d266ac0 --- /dev/null +++ b/test/java/io/File/CompareTo.java @@ -0,0 +1,53 @@ +/* + * Copyright 1998 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 4131169 + @summary Test respecified compareTo method + */ + +import java.io.*; + + +public class CompareTo { + + private static void testWin32() throws Exception { + File f1 = new File("a"); + File f2 = new File("B"); + if (!(f1.compareTo(f2) < 0)) + throw new Exception("compareTo incorrect"); + } + + private static void testUnix() throws Exception { + File f1 = new File("a"); + File f2 = new File("B"); + if (!(f1.compareTo(f2) > 0)) + throw new Exception("compareTo incorrect"); + } + + public static void main(String[] args) throws Exception { + if (File.separatorChar == '\\') testWin32(); + if (File.separatorChar == '/') testUnix(); + } + +} diff --git a/test/java/io/File/Cons.java b/test/java/io/File/Cons.java new file mode 100644 index 0000000000..7dc9bf8bc8 --- /dev/null +++ b/test/java/io/File/Cons.java @@ -0,0 +1,315 @@ +/* + * Copyright 1998 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 4131169 4168988 + @summary Basic File constructor tests + */ + + +import java.io.*; +import java.util.ArrayList; + + +public class Cons { + + private static boolean debug = false; + private static boolean old = false; + private static boolean win32 = (File.separatorChar == '\\'); + + + private static String cvt(String s) { + if (s == null) return s; + if (win32) return s.replace('/', '\\'); + return s; + } + + private static String[] slashPerms(String s) { + if (!win32) return new String[] { s }; + if (s == null) return new String[] { s }; + int i = s.indexOf('/'); + if (i < 0) return new String[] { s }; + ArrayList a = new ArrayList(); + String p1 = s.substring(0, i); + String[] p2 = slashPerms(s.substring(i + 1)); + for (int j = 0; j < p2.length; j++) + a.add(p1 + '/' + p2[j]); + for (int j = 0; j < p2.length; j++) + a.add(p1 + '\\' + p2[j]); + return (String[])(a.toArray(new String[a.size()])); + } + + + static class F extends File { + String exp; + + public F(String path) { + super(path); + this.exp = cons(path); + } + + public F(String parent, String child) { + super(parent, child); + this.exp = cons(parent, child); + } + + public F(F parent, String child) { + super(parent, child); + if (parent == null) this.exp = cons((String)null, child); + else this.exp = cons(parent, child); + } + + } + + + private static String nos(String s) { + if (s == null) return "null"; + else return "\"" + s + "\""; + } + + private static void ok(String ans, String exp) { + System.err.println(nos(ans) + " <== " + exp); + } + + private static void err(String ans, String exp, String got) throws Exception { + System.err.println(nos(ans) + " <-- " + exp + " ==> " + nos(got)); + if (!debug) { + throw new Exception("Mismatch: " + exp + " ==> " + nos(got) + + ", should be " + nos(ans)); + } + } + + private static void ck(String ans, String exp, String got) + throws Exception + { + if ((got == ans) || ((got != null) && got.equals(ans))) ok(ans, exp); + else err(ans, exp, got); + } + + private static String cons(String arg) { + return "new File(" + nos(arg) + ")"; + } + + private static String cons(String arg1, String arg2) { + return "new File(" + nos(arg1) + ", " + nos(arg2) + ")"; + } + + private static String cons(F arg1, String arg2) { + return "new File(" + arg1.exp + ", " + nos(arg2) + ")"; + } + + private static String op(String exp, String opname) { + return exp + "." + opname + "()"; + } + + private static void ckpnp(F f, + String parent, String name, String path) + throws Exception + { + ck(cvt(path), op(f.exp, "getPath"), f.getPath()); + ck(cvt(parent), op(f.exp, "getParent"), f.getParent()); + ck(cvt(name), op(f.exp, "getName"), f.getName()); + } + + private static void ck1(String arg, + String parent, String name, String path) + throws Exception + { + String[] parg = slashPerms(arg); + for (int i = 0; i < parg.length; i++) + ckpnp(new F(parg[i]), parent, name, path); + } + + private static void ck2(String arg1, String arg2, + String parent, String name, String path) + throws Exception + { + String[] parg1 = slashPerms(arg1); + String[] parg2 = slashPerms(arg2); + for (int i = 0; i < parg1.length; i++) + for (int j = 0; j < parg2.length; j++) + ckpnp(new F(parg1[i], parg2[j]), parent, name, path); + } + + private static void ck2f(String arg1, String arg2, + String parent, String name, String path) + throws Exception + { + String[] parg1 = slashPerms(arg1); + String[] parg2 = slashPerms(arg2); + for (int i = 0; i < parg1.length; i++) + for (int j = 0; j < parg2.length; j++) { + F p = (parg1[i] == null) ? null : new F(parg1[i]); + ckpnp(new F(p, parg2[j]), parent, name, path); + } + } + + + static void testBoth() throws Exception { + + /* Null/empty constructor cases */ + ck1("", null, "", ""); + ck2(null, "", null, "", ""); + ck2("", "", null, "", "/"); /* ugh */ + ck2f("", "", null, "", "/"); + if (!old) { + /* throws NullPointerException */ + ck2f(null, "", null, "", ""); + } + + /* Separators-in-pathnames cases */ + ck1("/", null, "", "/"); + ck2f("/", "", null, "", "/"); + + /* One-arg constructor cases */ + ck1("foo", null, "foo", "foo"); + ck1("/foo", "/", "foo", "/foo"); + ck1("/foo/bar", "/foo", "bar", "/foo/bar"); + ck1("foo/bar", "foo", "bar", "foo/bar"); + if (!old) { + ck1("foo/", null, "foo", "foo"); + ck1("/foo/", "/", "foo", "/foo"); + ck1("/foo//", "/", "foo", "/foo"); + ck1("/foo///", "/", "foo", "/foo"); + ck1("/foo//bar", "/foo", "bar", "/foo/bar"); + ck1("/foo/bar//", "/foo", "bar", "/foo/bar"); + ck1("foo//bar", "foo", "bar", "foo/bar"); + ck1("foo/bar/", "foo", "bar", "foo/bar"); + ck1("foo/bar//", "foo", "bar", "foo/bar"); + } + + /* Two-arg constructor cases, string parent */ + ck2("foo", "bar", "foo", "bar", "foo/bar"); + ck2("foo/", "bar", "foo", "bar", "foo/bar"); + ck2("/foo", "bar", "/foo", "bar", "/foo/bar"); + ck2("/foo/", "bar", "/foo", "bar", "/foo/bar"); + if (!old) { + ck2("foo//", "bar", "foo", "bar", "foo/bar"); + ck2("foo", "bar/", "foo", "bar", "foo/bar"); + ck2("foo", "bar//", "foo", "bar", "foo/bar"); + ck2("/foo//", "bar", "/foo", "bar", "/foo/bar"); + ck2("/foo", "bar/", "/foo", "bar", "/foo/bar"); + ck2("/foo", "bar//", "/foo", "bar", "/foo/bar"); + ck2("foo", "/bar", "foo", "bar", "foo/bar"); + ck2("foo", "//bar", "foo", "bar", "foo/bar"); + ck2("/", "bar", "/", "bar", "/bar"); + ck2("/", "/bar", "/", "bar", "/bar"); + } + + /* Two-arg constructor cases, File parent */ + ck2f("foo", "bar", "foo", "bar", "foo/bar"); + ck2f("foo/", "bar", "foo", "bar", "foo/bar"); + ck2f("/foo", "bar", "/foo", "bar", "/foo/bar"); + ck2f("/foo/", "bar", "/foo", "bar", "/foo/bar"); + if (!old) { + ck2f("foo//", "bar", "foo", "bar", "foo/bar"); + ck2f("foo", "bar/", "foo", "bar", "foo/bar"); + ck2f("foo", "bar//", "foo", "bar", "foo/bar"); + ck2f("/foo//", "bar", "/foo", "bar", "/foo/bar"); + ck2f("/foo", "bar/", "/foo", "bar", "/foo/bar"); + ck2f("/foo", "bar//", "/foo", "bar", "/foo/bar"); + ck2f("foo", "/bar", "foo", "bar", "foo/bar"); + ck2f("foo", "//bar", "foo", "bar", "foo/bar"); + } + } + + + static void testUnix() throws Exception { + + /* Separators-in-pathnames cases */ + if (!old) { + ck1("//", null, "", "/"); + } + + /* One-arg constructor cases */ + if (!old) { + ck1("//foo", "/", "foo", "/foo"); + ck1("///foo", "/", "foo", "/foo"); + ck1("//foo/bar", "/foo", "bar", "/foo/bar"); + } + + /* Two-arg constructors cases, string parent */ + if (!old) { + ck2("//foo", "bar", "/foo", "bar", "/foo/bar"); + } + + /* Two-arg constructor cases, File parent */ + if (!old) { + ck2f("//foo", "bar", "/foo", "bar", "/foo/bar"); + } + + File f = new File("/foo"); + if (! f.isAbsolute()) throw new Exception(f + " should be absolute"); + + f = new File("foo"); + if (f.isAbsolute()) throw new Exception(f + " should not be absolute"); + } + + + static void testWin32() throws Exception { + + if (!old) { + /* Separators-in-pathnames cases */ + ck1("//", null, "", "//"); + + /* One-arg constructor cases */ + ck1("//foo", "//", "foo", "//foo"); + ck1("///foo", "//", "foo", "//foo"); + ck1("//foo/bar", "//foo", "bar", "//foo/bar"); + + ck1("z:", null, "", "z:"); + ck1("z:/", null, "", "z:/"); + ck1("z://", null, "", "z:/"); + ck1("z:/foo", "z:/", "foo", "z:/foo"); + ck1("z:/foo/", "z:/", "foo", "z:/foo"); + ck1("/z:/foo", "z:/", "foo", "z:/foo"); + ck1("//z:/foo", "z:/", "foo", "z:/foo"); + ck1("z:/foo/bar", "z:/foo", "bar", "z:/foo/bar"); + ck1("z:foo", "z:", "foo", "z:foo"); + + /* Two-arg constructors cases, string parent */ + ck2("z:", "/", null, "", "z:/"); /* ## ? */ + ck2("z:", "/foo", "z:/", "foo", "z:/foo"); + ck2("z:/", "foo", "z:/", "foo", "z:/foo"); + ck2("z://", "foo", "z:/", "foo", "z:/foo"); + ck2("z:/", "/foo", "z:/", "foo", "z:/foo"); + ck2("z:/", "//foo", "z:/", "foo", "z:/foo"); + ck2("z:/", "foo/", "z:/", "foo", "z:/foo"); + ck2("//foo", "bar", "//foo", "bar", "//foo/bar"); + + /* Two-arg constructor cases, File parent */ + ck2f("//foo", "bar", "//foo", "bar", "//foo/bar"); + + } + } + + + public static void main(String[] args) throws Exception { + old = new File("foo/").getPath().equals("foo/"); + if (old) System.err.println("** Testing old java.io.File class"); + testBoth(); + if (win32) testWin32(); + else testUnix(); + } + +} diff --git a/test/java/io/File/Create.java b/test/java/io/File/Create.java new file mode 100644 index 0000000000..56f38c2b17 --- /dev/null +++ b/test/java/io/File/Create.java @@ -0,0 +1,58 @@ +/* + * 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 4812991 4804456 + * @summary Test creation of new files with long names + */ + +import java.io.*; + +public class Create { + + static final int length = 512; + + public static void main(String[] args) throws Exception { + String fileName = createFileName(length); + File file = new File(fileName); + try { + boolean result = file.createNewFile(); + if (result) { + if (!file.exists()) + throw new RuntimeException("Result is incorrect"); + } else { + if (file.exists()) + throw new RuntimeException("Result is incorrect"); + } + } catch (IOException ioe) { + // Correct result on some platforms + } + } + + public static String createFileName(int length){ + char[] array = new char[length]; + for(int i = 0 ; i < length ; i++) + array[i] = (char)('0' + (i % 10)); + return new String(array); + } +} diff --git a/test/java/io/File/CreateNewFile.java b/test/java/io/File/CreateNewFile.java new file mode 100644 index 0000000000..3f37deb9c7 --- /dev/null +++ b/test/java/io/File/CreateNewFile.java @@ -0,0 +1,55 @@ +/* + * Copyright 1998-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 4130498 4391178 + @summary Basic test for createNewFile method + */ + +import java.io.*; + + +public class CreateNewFile { + + public static void main(String[] args) throws Exception { + + File f = new File(System.getProperty("test.dir", "."), + "x.CreateNewFile"); + if (f.exists() && !f.delete()) + throw new Exception("Cannot delete test file " + f); + if (!f.createNewFile()) + throw new Exception("Cannot create new file " + f); + if (!f.exists()) + throw new Exception("Did not create new file " + f); + if (f.createNewFile()) + throw new Exception("Created existing file " + f); + + try { + f = new File("/"); + if (f.createNewFile()) + throw new Exception("Created root directory!"); + } catch (IOException e) { + // Exception expected + } + } +} diff --git a/test/java/io/File/DeleteOnExit.java b/test/java/io/File/DeleteOnExit.java new file mode 100644 index 0000000000..205ddbf735 --- /dev/null +++ b/test/java/io/File/DeleteOnExit.java @@ -0,0 +1,104 @@ +/* + * 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 4614121 4809375 6437591 + @summary Basic test for deleteOnExit method + @author kladko + */ + + +import java.io.File; + +public class DeleteOnExit { + + static String tmpdir = System.getProperty("java.io.tmpdir"); + static String java = System.getProperty("java.home") + File.separator + + "bin" + File.separator + "java"; + static File file1 = new File(tmpdir + "deletedOnExit1"); + static File file2 = new File(tmpdir + "deletedOnExit2"); + static File file3 = new File(tmpdir + "deletedOnExit3"); + + // used to verify deletion order + static File dir = new File(tmpdir + "deletedOnExitDir"); + static File file4 = new File(dir + File.separator + "deletedOnExit4"); + static File file5 = new File(dir + File.separator + "dxnsdnguidfgejngognrogn"); + static File file6 = new File(dir + File.separator + "mmmmmmsdmfgmdsmfgmdsfgm"); + static File file7 = new File(dir + File.separator + "12345566777"); + + public static void main (String args[]) throws Exception{ + if (args.length == 0) { + Runtime.getRuntime().exec(java + " DeleteOnExit -test").waitFor(); + if (file1.exists() || file2.exists() || file3.exists() || + dir.exists() || file4.exists() || file5.exists() || + file6.exists() || file7.exists()) { + + System.out.println(file1 + ", exists = " + file1.exists()); + System.out.println(file2 + ", exists = " + file2.exists()); + System.out.println(file3 + ", exists = " + file3.exists()); + System.out.println(dir + ", exists = " + dir.exists()); + System.out.println(file4 + ", exists = " + file4.exists()); + System.out.println(file5 + ", exists = " + file5.exists()); + System.out.println(file6 + ", exists = " + file6.exists()); + System.out.println(file7 + ", exists = " + file7.exists()); + + // cleanup undeleted dir if test fails + dir.delete(); + + throw new Exception("File exists"); + } + } else { + file1.createNewFile(); + file2.createNewFile(); + file3.createNewFile(); + file1.deleteOnExit(); + file2.deleteOnExit(); + file3.deleteOnExit(); + + // verify that deleting a File marked deleteOnExit will not cause a problem + // during shutdown. + file3.delete(); + + // verify that calling deleteOnExit multiple times on a File does not cause + // a problem during shutdown. + file2.deleteOnExit(); + file2.deleteOnExit(); + file2.deleteOnExit(); + + // Verify DeleteOnExit Internal implementation deletion order. + if (dir.mkdir()) { + dir.deleteOnExit(); + + file4.createNewFile(); + file5.createNewFile(); + file6.createNewFile(); + file7.createNewFile(); + + file4.deleteOnExit(); + file5.deleteOnExit(); + file6.deleteOnExit(); + file7.deleteOnExit(); + } + } + } +} diff --git a/test/java/io/File/DeleteOnExitLong.java b/test/java/io/File/DeleteOnExitLong.java new file mode 100644 index 0000000000..096d5f0f0a --- /dev/null +++ b/test/java/io/File/DeleteOnExitLong.java @@ -0,0 +1,37 @@ +/* + * 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 6197510 + @summary Test for deleteOnExit method on long filename + */ + +import java.io.File; + +public class DeleteOnExitLong { + public static void main (String args[]) throws Exception{ + File file = new File("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_DeletedOnExitLong").getCanonicalFile(); + file.createNewFile(); + file.deleteOnExit(); + } +} diff --git a/test/java/io/File/DeleteOnExitNPE.java b/test/java/io/File/DeleteOnExitNPE.java new file mode 100644 index 0000000000..c45c78ec5b --- /dev/null +++ b/test/java/io/File/DeleteOnExitNPE.java @@ -0,0 +1,103 @@ +/* + * 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 6526376 + @summary DeleteOnExitHook.add() produces NullPointerException + */ + +import java.io.*; + +/* NullPointerException in exec'ed process if fails. + * This testcase is timing sensitive. It may sometimes pass even with this bug + * present, but will never fail without it. + */ + +public class DeleteOnExitNPE implements Runnable +{ + public static void main(String[] args) throws Exception { + if (args.length == 0) { + runTest(); + } else { + doTest(); + } + } + + public static void runTest() throws Exception { + String cmd = System.getProperty("java.home") + File.separator + + "bin" + File.separator + "java"; + Process process = Runtime.getRuntime().exec(cmd + " DeleteOnExitNPE -test"); + BufferedReader isReader = new BufferedReader(new InputStreamReader(process.getInputStream())); + BufferedReader esReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); + + process.waitFor(); + + boolean failed = false; + String str; + while ((str = isReader.readLine()) != null) { + failed = true; + System.out.println(str); + } + while ((str = esReader.readLine()) != null) { + failed = true; + System.err.println(str); + } + + if (failed) + throw new RuntimeException("Failed: No output should have been received from the process"); + } + + public static void doTest() { + try { + File file = File.createTempFile("DeleteOnExitNPE", null); + file.deleteOnExit(); + + Thread thread = new Thread(new DeleteOnExitNPE()); + thread.start(); + + try { + Thread.sleep(2000); + } catch (InterruptedException ie) { + ie.printStackTrace(); + } + + System.exit(0); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + + public void run() { + File file = new File("xxyyzz"); + + try { + for (;;) { + file.deleteOnExit(); + } + } catch (IllegalStateException ise) { + // ignore. This is ok. + // Trying to add a file to the list of files marked as deleteOnExit when + // shutdown is in progress and the DeleteOnExitHook is running. + } + } +} diff --git a/test/java/io/File/EmptyPath.java b/test/java/io/File/EmptyPath.java new file mode 100644 index 0000000000..49e2c535bb --- /dev/null +++ b/test/java/io/File/EmptyPath.java @@ -0,0 +1,49 @@ +/* + * 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 4842706 + @summary Test some file operations with empty path + */ + +import java.io.*; + +public class EmptyPath { + public static void main(String [] args) throws Exception { + File f = new File(""); + f.mkdir(); + try { + f.createNewFile(); + throw new RuntimeException("Expected exception not thrown"); + } catch (IOException ioe) { + // Correct result + } + try { + FileInputStream fis = new FileInputStream(f); + fis.close(); + throw new RuntimeException("Expected exception not thrown"); + } catch (FileNotFoundException fnfe) { + // Correct result + } + } +} diff --git a/test/java/io/File/FileMethods.java b/test/java/io/File/FileMethods.java new file mode 100644 index 0000000000..bf508468fe --- /dev/null +++ b/test/java/io/File/FileMethods.java @@ -0,0 +1,86 @@ +/* + * Copyright 1998 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 4107063 4131237 + @summary Basic test for new File-returning methods + */ + +import java.io.*; + + +public class FileMethods { + + private static void ck(String op, File got, File ans) throws Exception { + if (!got.equals(ans)) + throw new Exception(op + " incorrect"); + } + + private static void ck(String op, File f, String[] ls, File[] lf) + throws Exception + { + System.err.println("--- " + op); + int n = lf.length; + if (ls.length != n) + throw new Exception("listFiles returned incorrect count"); + for (int i = 0; i < n; i++) { + if (ls[i].equals(lf[i].getName()) + && lf[i].getParentFile().equals(f)) { + System.err.println(ls[i] + " ==> " + lf[i]); + } else { + throw new Exception("list mismatch: " + ls[i] + ", " + lf[i]); + } + } + } + + public static void main(String[] args) throws Exception { + + File f; + f = new File("foo/bar"); + ck("getParentFile", f.getParentFile(), new File(f.getParent())); + + f = new File("."); + ck("getAbsoluteFile", + f.getAbsoluteFile(), new File(f.getAbsolutePath())); + + ck("getCanonicalFile", + f.getCanonicalFile(), new File(f.getCanonicalPath())); + + f = f.getCanonicalFile(); + ck("listFiles", f, f.list(), f.listFiles()); + + FilenameFilter ff = new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.endsWith(".class"); + }}; + ck("listFiles/filtered", f, f.list(ff), f.listFiles(ff)); + + FileFilter ff2 = new FileFilter() { + public boolean accept(File f) { + return f.getPath().endsWith(".class"); + }}; + ck("listFiles/filtered2", f, f.list(ff), f.listFiles(ff2)); + + } + +} diff --git a/test/java/io/File/GetAbsolutePath.java b/test/java/io/File/GetAbsolutePath.java new file mode 100644 index 0000000000..ce0d47b419 --- /dev/null +++ b/test/java/io/File/GetAbsolutePath.java @@ -0,0 +1,95 @@ +/* + * Copyright 1998-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 4131169 4109131 + @summary Basic test for getAbsolutePath method + */ + +import java.io.*; + + +public class GetAbsolutePath { + + private static boolean ignoreCase = false; + + private static void ck(String path, String ans) throws Exception { + File f = new File(path); + String p = f.getAbsolutePath(); + if ((ignoreCase && p.equalsIgnoreCase(ans)) || p.equals(ans)) + System.err.println(path + " ==> " + p); + else + throw new Exception(path + ": expected " + ans + ", got " + p); + } + + private static void testWin32() throws Exception { + String wd = System.getProperty("user.dir"); + char d; + if ((wd.length() > 2) && (wd.charAt(1) == ':') + && (wd.charAt(2) == '\\')) + d = wd.charAt(0); + else + throw new Exception("Current directory has no drive"); + ck("/foo/bar", d + ":\\foo\\bar"); + ck("\\foo\\bar", d + ":\\foo\\bar"); + ck("c:\\foo\\bar", "c:\\foo\\bar"); + ck("c:/foo/bar", "c:\\foo\\bar"); + ck("\\\\foo\\bar", "\\\\foo\\bar"); + + /* Tricky directory-relative case */ + d = Character.toLowerCase(d); + char z = 0; + if (d != 'c') z = 'c'; + else if (d != 'd') z = 'd'; + if (z != 0) { + File f = new File(z + ":."); + if (f.exists()) { + String zwd = f.getCanonicalPath(); + ck(z + ":foo", zwd + "\\foo"); + } + } + + /* Empty path */ + ck("", wd); + } + + private static void testUnix() throws Exception { + String wd = System.getProperty("user.dir"); + ck("foo", wd + "/foo"); + ck("foo/bar", wd + "/foo/bar"); + ck("/foo", "/foo"); + ck("/foo/bar", "/foo/bar"); + + /* Empty path */ + ck("", wd); + } + + public static void main(String[] args) throws Exception { + if (File.separatorChar == '\\') { + ignoreCase = true; + testWin32(); + } + if (File.separatorChar == '/') testUnix(); + } + +} diff --git a/test/java/io/File/GetCanonicalPath.java b/test/java/io/File/GetCanonicalPath.java new file mode 100644 index 0000000000..26cf4a78ae --- /dev/null +++ b/test/java/io/File/GetCanonicalPath.java @@ -0,0 +1,42 @@ +/* + * 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 4899022 + @summary Look for erroneous representation of drive letter + */ + +import java.io.*; + +public class GetCanonicalPath { + public static void main(String[] args) throws Exception { + if (File.separatorChar == '\\') { + testDriveLetter(); + } + } + private static void testDriveLetter() throws Exception { + String path = new File("c:/").getCanonicalPath(); + if (path.length() > 3) + throw new RuntimeException("Drive letter incorrectly represented"); + } +} diff --git a/test/java/io/File/GetParent.java b/test/java/io/File/GetParent.java new file mode 100644 index 0000000000..cd3180d110 --- /dev/null +++ b/test/java/io/File/GetParent.java @@ -0,0 +1,79 @@ +/* + * Copyright 1997-1998 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 4027914 + @summary Check getParent's handling of root directories + */ + +import java.io.File; + + +public class GetParent { + + static void check(String path, String[] parents) throws Exception { + File f = new File(path); + String p; + System.err.print(path + ":"); + for (int i = 0; i < parents.length; i++) { + p = f.getParent(); + System.err.print(" (" + p + ")"); + if (p == null) + throw new Exception("No parent for " + f); + if (! p.equals(parents[i])) + throw new Exception("Wrong parent for " + f + + ": Expected " + parents[i] + + ", got " + p); + f = new File(p); + } + if (f.getParent() != null) + throw new Exception("Too many parents for " + path); + System.err.println(); + } + + static void testUnix() throws Exception { + check("foo", new String[] { }); + check("./foo", new String[] { "." }); + check("foo/bar/baz", new String[] { "foo/bar", "foo" }); + check("../../foo", new String[] { "../..", ".." }); + check("foo//bar", new String[] { "foo" }); + check("/foo/bar/baz.gorp", + new String[] { "/foo/bar", "/foo", "/" }); + } + + static void testWin32() throws Exception { + System.err.println("Win32"); + check("foo", new String[] { }); + check(".\\foo", new String[] { "." }); + check("foo\\bar\\baz", new String[] { "foo\\bar", "foo" }); + check("..\\..\\foo", new String[] { "..\\..", ".." }); + check("c:\\foo\\bar\\baz.xxx", + new String[] { "c:\\foo\\bar", "c:\\foo", "c:\\" }); + } + + public static void main(String[] args) throws Exception { + if (File.separatorChar == '/') testUnix(); + if (File.separatorChar == '\\') testWin32(); + } + +} diff --git a/test/java/io/File/GetXSpace.java b/test/java/io/File/GetXSpace.java new file mode 100644 index 0000000000..a2855e7b37 --- /dev/null +++ b/test/java/io/File/GetXSpace.java @@ -0,0 +1,387 @@ +/* + * Copyright 2005-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 4057701 6286712 6364377 + * @run build GetXSpace + * @run shell GetXSpace.sh + * @summary Basic functionality of File.get-X-Space methods. + */ + +import java.io.BufferedReader; +import java.io.File; +import java.io.FilePermission; +import java.io.InputStreamReader; +import java.io.IOException; +import java.security.Permission; +import java.util.ArrayList; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static java.lang.System.out; + +public class GetXSpace { + + private static SecurityManager [] sma = { null, new Allow(), new DenyFSA(), + new DenyRead() }; + + private static final String name = System.getProperty("os.name"); + private static final String dfFormat; + static { + if (name.equals("SunOS") || name.equals("Linux")) { + // FileSystem Total Used Available Use% MountedOn + dfFormat = "([^\\s]+)\\s+(\\d+)\\s+\\d+\\s+(\\d+)\\s+\\d+%\\s+([^\\s]+)"; + } else if (name.startsWith("Windows")) { + // Drive (MountedOn) Available/Total + dfFormat = "([^\\s]+)\\s+\\(([^\\s]+)\\)\\s+(\\d+)\\/(\\d+)\\s+"; + } else { + throw new RuntimeException("unrecognized system:" + + " os.name == " + name); + } + } + private static Pattern dfPattern = Pattern.compile(dfFormat); + + private static int fail = 0; + private static int pass = 0; + private static Throwable first; + + static void pass() { + pass++; + } + + static void fail(String p) { + if (first == null) + setFirst(p); + System.err.format("FAILED: %s%n", p); + fail++; + } + + static void fail(String p, long exp, String cmp, long got) { + String s = String.format("'%s': %d %s %d", p, exp, cmp, got); + if (first == null) + setFirst(s); + System.err.format("FAILED: %s%n", s); + fail++; + } + + private static void fail(String p, Class ex) { + String s = String.format("'%s': expected %s - FAILED%n", p, ex.getName()); + if (first == null) + setFirst(s); + System.err.format("FAILED: %s%n", s); + fail++; + } + + private static void setFirst(String s) { + try { + throw new RuntimeException(s); + } catch (RuntimeException x) { + first = x; + } + } + + private static class Space { + private static final long KSIZE = 1024; + private String name; + private long total; + private long free; + + Space(String total, String free, String name) { + try { + this.total = Long.valueOf(total) * KSIZE; + this.free = Long.valueOf(free) * KSIZE; + } catch (NumberFormatException x) { + // the regex should have caught this + assert false; + } + this.name = name; + } + + String name() { return name; } + long total() { return total; } + long free() { return free; } + boolean woomFree(long freeSpace) { + return ((freeSpace >= (free / 10)) && (freeSpace <= (free * 10))); + } + public String toString() { + return String.format("%s (%d/%d)", name, free, total); + } + } + + private static ArrayList space(String f) throws IOException { + ArrayList al = new ArrayList(); + + Process p = null; + String cmd = "df -k" + (f == null ? "" : " " + f); + p = Runtime.getRuntime().exec(cmd); + BufferedReader in = new BufferedReader + (new InputStreamReader(p.getInputStream())); + String s; + int i = 0; + StringBuilder sb = new StringBuilder(); + while ((s = in.readLine()) != null) { + // skip header + if (i++ == 0 && !name.startsWith("Windows")) continue; + sb.append(s).append("\n"); + } + + Matcher m = dfPattern.matcher(sb); + int j = 0; + while (j < sb.length()) { + if (m.find(j)) { + if (!name.startsWith("Windows")) { + // swap can change while this test is running + if (!m.group(1).equals("swap")) { + String name = (f == null ? m.group(4): f); + al.add(new Space(m.group(2), m.group(3), name));; + } + } else { + String name = (f == null ? m.group(2) : f); + al.add(new Space(m.group(4), m.group(3), name ));; + } + j = m.end() + 1; + } else { + throw new RuntimeException("unrecognized df output format: " + + "charAt(" + j + ") = '" + + sb.charAt(j) + "'"); + } + } + + if (al.size() == 0) { + // df did not produce output + String name = (f == null ? "" : f); + al.add(new Space("0", "0", name)); + } + in.close(); + return al; + } + + private static void tryCatch(Space s) { + out.format("%s:%n", s.name()); + File f = new File(s.name()); + SecurityManager sm = System.getSecurityManager(); + if (sm instanceof Deny) { + String fmt = " %14s: \"%s\" thrown as expected%n"; + try { + f.getTotalSpace(); + fail(s.name(), SecurityException.class); + } catch (SecurityException x) { + out.format(fmt, "getTotalSpace", x); + pass(); + } + try { + f.getFreeSpace(); + fail(s.name(), SecurityException.class); + } catch (SecurityException x) { + out.format(fmt, "getFreeSpace", x); + pass(); + } + try { + f.getUsableSpace(); + fail(s.name(), SecurityException.class); + } catch (SecurityException x) { + out.format(fmt, "getUsableSpace", x); + pass(); + } + } + } + + private static void compare(Space s) { + File f = new File(s.name()); + long ts = f.getTotalSpace(); + long fs = f.getFreeSpace(); + long us = f.getUsableSpace(); + + out.format("%s:%n", s.name()); + String fmt = " %-4s total= %12d free = %12d usable = %12d%n"; + out.format(fmt, "df", s.total(), 0, s.free()); + out.format(fmt, "getX", ts, fs, us); + + // if the file system can dynamically change size, this check will fail + if (ts != s.total()) + fail(s.name(), s.total(), "!=", ts); + else + pass(); + + // unix df returns statvfs.f_bavail + long tsp = (!name.startsWith("Windows") ? us : fs); + if (!s.woomFree(tsp)) + fail(s.name(), s.free(), "??", tsp); + else + pass(); + + if (fs > s.total()) + fail(s.name(), s.total(), ">", fs); + else + pass(); + + if (us > s.total()) + fail(s.name(), s.total(), ">", us); + else + pass(); + } + + private static String FILE_PREFIX = "/getSpace."; + private static void compareZeroNonExist() { + File f; + while (true) { + f = new File(FILE_PREFIX + Math.random()); + if (f.exists()) + continue; + break; + } + + long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() }; + + for (int i = 0; i < s.length; i++) { + if (s[i] != 0L) + fail(f.getName(), s[i], "!=", 0L); + else + pass(); + } + } + + private static void compareZeroExist() { + try { + File f = File.createTempFile("tmp", null, new File(".")); + + long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() }; + + for (int i = 0; i < s.length; i++) { + if (s[i] == 0L) + fail(f.getName(), s[i], "==", 0L); + else + pass(); + } + } catch (IOException x) { + fail("Couldn't create temp file for test"); + } + } + + private static class Allow extends SecurityManager { + public void checkRead(String file) {} + public void checkPermission(Permission p) {} + public void checkPermission(Permission p, Object context) {} + } + + private static class Deny extends SecurityManager { + public void checkPermission(Permission p) { + if (p.implies(new RuntimePermission("setSecurityManager")) + || p.implies(new RuntimePermission("getProtectionDomain"))) + return; + super.checkPermission(p); + } + + public void checkPermission(Permission p, Object context) { + if (p.implies(new RuntimePermission("setSecurityManager")) + || p.implies(new RuntimePermission("getProtectionDomain"))) + return; + super.checkPermission(p, context); + } + } + + private static class DenyFSA extends Deny { + private String err = "sorry - getFileSystemAttributes"; + + public void checkPermission(Permission p) { + if (p.implies(new RuntimePermission("getFileSystemAttributes"))) + throw new SecurityException(err); + super.checkPermission(p); + } + + public void checkPermission(Permission p, Object context) { + if (p.implies(new RuntimePermission("getFileSystemAttributes"))) + throw new SecurityException(err); + super.checkPermission(p, context); + } + } + + private static class DenyRead extends Deny { + private String err = "sorry - checkRead()"; + + public void checkRead(String file) { + throw new SecurityException(err); + } + } + + private static void testFile(String dirName) { + out.format("--- Testing %s%n", dirName); + ArrayList l; + try { + l = space(dirName); + } catch (IOException x) { + throw new RuntimeException(dirName + " can't get file system information", x); + } + compare((GetXSpace.Space) l.get(0)); + } + + private static void testDF() { + out.format("--- Testing df"); + // Find all of the partitions on the machine and verify that the size + // returned by "df" is equivalent to File.getXSpace() values. + ArrayList l; + try { + l = space(null); + } catch (IOException x) { + throw new RuntimeException("can't get file system information", x); + } + if (l.size() == 0) + throw new RuntimeException("no partitions?"); + + for (int i = 0; i < sma.length; i++) { + System.setSecurityManager(sma[i]); + SecurityManager sm = System.getSecurityManager(); + if (sma[i] != null && sm == null) + throw new RuntimeException("Test configuration error " + + " - can't set security manager"); + + out.format("%nSecurityManager = %s%n" , + (sm == null ? "null" : sm.getClass().getName())); + for (int j = 0; j < l.size(); j++) { + Space s = (GetXSpace.Space) l.get(j); + if (sm instanceof Deny) { + tryCatch(s); + } else { + compare(s); + compareZeroNonExist(); + compareZeroExist(); + } + } + } + } + + public static void main(String [] args) { + if (args.length > 0) { + testFile(args[0]); + } else { + testDF(); + } + + if (fail != 0) + throw new RuntimeException((fail + pass) + " tests: " + + fail + " failure(s), first", first); + else + out.format("all %d tests passed%n", fail + pass); + } +} diff --git a/test/java/io/File/GetXSpace.sh b/test/java/io/File/GetXSpace.sh new file mode 100644 index 0000000000..7ca2436f06 --- /dev/null +++ b/test/java/io/File/GetXSpace.sh @@ -0,0 +1,81 @@ +# +# 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. +# + +# + +# set platform-dependent variable +OS=`uname -s` +case "$OS" in + SunOS | Linux ) TMP=/tmp ;; + Windows_98 ) return ;; + Windows* ) SID=`sid`; TMP="c:/temp" ;; + * ) + echo "Unrecognized system!" + exit 1 + ;; +esac + +TMP1=${TMP}/tmp1_$$ +FAIL=0; + +deny() { + case "$OS" in + Windows* ) chacl -d ${SID}:f $* ;; + * ) chmod 000 $* ;; + esac +} + +allow() { + case "$OS" in + Windows* ) chacl -g ${SID}:f $* ;; + * ) chmod 777 $* ;; + esac +} + +runTest() { + ${TESTJAVA}/bin/java -cp ${TESTCLASSES} GetXSpace $* + if [ $? -eq 0 ] + then echo "Passed" + else + echo "FAILED" + FAIL=`expr ${FAIL} + 1` + fi +} + +# df output +runTest + +# readable file in an unreadable directory +mkdir ${TMP1} +touch ${TMP1}/foo +deny ${TMP1} +runTest ${TMP1}/foo +allow ${TMP1} +rm -rf ${TMP1} + +if [ ${FAIL} -ne 0 ] +then + echo "" + echo "${FAIL} test(s) failed" + exit 1 +fi diff --git a/test/java/io/File/HashCodeEquals.java b/test/java/io/File/HashCodeEquals.java new file mode 100644 index 0000000000..b4009eb57f --- /dev/null +++ b/test/java/io/File/HashCodeEquals.java @@ -0,0 +1,59 @@ +/* + * Copyright 1998 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 4141318 + @summary Check that equal File instances have identical hash codes + */ + +import java.io.File; + + +public class HashCodeEquals { + + static void test(String fn1, String fn2) throws Exception { + File f1 = new File(fn1); + File f2 = new File(fn2); + if (!f1.equals(f2)) + throw new Exception("Instances with equal paths are not equal"); + int h1 = f1.hashCode(); + int h2 = f2.hashCode(); + if (h1 != h2) + throw new Exception("Hashcodes of equal instances are not equal"); + } + + static void testWin32() throws Exception { + test("a:/foo/bar/baz", "a:/foo/bar/baz"); + test("A:/Foo/Bar/BAZ", "a:/foo/bar/baz"); + } + + static void testUnix() throws Exception { + test("foo/bar/baz", "foo/bar/baz"); + } + + public static void main(String[] args) throws Exception { + if (File.separatorChar == '\\') testWin32(); + if (File.separatorChar == '/') testUnix(); + } + +} diff --git a/test/java/io/File/IsAbsolute.java b/test/java/io/File/IsAbsolute.java new file mode 100644 index 0000000000..b5f7334052 --- /dev/null +++ b/test/java/io/File/IsAbsolute.java @@ -0,0 +1,63 @@ +/* + * Copyright 1997-1998 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 4022397 + @summary General test for isAbsolute + */ + +import java.io.*; + + +public class IsAbsolute { + + private static void ck(String path, boolean ans) throws Exception { + File f = new File(path); + boolean x = f.isAbsolute(); + if (x != ans) + throw new Exception(path + ": expected " + ans + ", got " + x); + System.err.println(path + " ==> " + x); + } + + private static void testWin32() throws Exception { + ck("/foo/bar", false); + ck("\\foo\\bar", false); + ck("c:\\foo\\bar", true); + ck("c:/foo/bar", true); + ck("c:foo\\bar", false); + ck("\\\\foo\\bar", true); + } + + private static void testUnix() throws Exception { + ck("foo", false); + ck("foo/bar", false); + ck("/foo", true); + ck("/foo/bar", true); + } + + public static void main(String[] args) throws Exception { + if (File.separatorChar == '\\') testWin32(); + if (File.separatorChar == '/') testUnix(); + } + +} diff --git a/test/java/io/File/IsHidden.java b/test/java/io/File/IsHidden.java new file mode 100644 index 0000000000..8323a76041 --- /dev/null +++ b/test/java/io/File/IsHidden.java @@ -0,0 +1,72 @@ +/* + * Copyright 1998-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 4131223 6470354 + @summary Basic test for isHidden method + */ + +import java.io.*; + + +public class IsHidden { + + private static String dir = System.getProperty("test.dir", "."); + + private static void ck(String path, boolean ans) throws Exception { + File f = new File(path); + boolean x = f.isHidden(); + if (x != ans) + throw new Exception(path + ": expected " + ans + ", got " + x); + System.err.println(path + " ==> " + x); + } + + private static void testWin32() throws Exception { + File f = new File(dir, "test"); + f.deleteOnExit(); + f.createNewFile(); + String name = f.getCanonicalPath(); + Process p = Runtime.getRuntime().exec("cmd.exe /c attrib +H " + name); + p.waitFor(); + ck(name, true); + + ck(".foo", false); + ck("foo", false); + } + + private static void testUnix() throws Exception { + ck(dir + "/IsHidden.java", false); + ck(dir + "/.", true); + ck(".", true); + ck("..", true); + ck(".foo", true); + ck("foo", false); + ck("", false); + } + + public static void main(String[] args) throws Exception { + if (File.separatorChar == '\\') testWin32(); + if (File.separatorChar == '/') testUnix(); + } + +} diff --git a/test/java/io/File/ListNull.java b/test/java/io/File/ListNull.java new file mode 100644 index 0000000000..5cce2b6dc8 --- /dev/null +++ b/test/java/io/File/ListNull.java @@ -0,0 +1,53 @@ +/* + * Copyright 1998 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 4140693 + @summary Make sure that java.io.File.list*(null) returns an array, not null + */ + +import java.io.File; +import java.io.FileFilter; +import java.io.FilenameFilter; + + +public class ListNull { + + static void go(String what, Object[] fs) throws Exception { + if (fs == null) + throw new Exception(what + " returned null"); + System.err.println("-- " + what); + for (int i = 0; i < fs.length; i++) + System.err.println(fs[i]); + } + + public static void main(String[] args) throws Exception { + File d = new File("."); + go("list()", d.list()); + go("listFiles()", d.listFiles()); + go("list(null)", d.list(null)); + go("listFiles((FilenameFilter)null)", d.listFiles((FilenameFilter)null)); + go("listFiles((FileFilter)null)", d.listFiles((FileFilter)null)); + } + +} diff --git a/test/java/io/File/ListRoots.java b/test/java/io/File/ListRoots.java new file mode 100644 index 0000000000..a77fb2532c --- /dev/null +++ b/test/java/io/File/ListRoots.java @@ -0,0 +1,51 @@ +/* + * Copyright 1998 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 4071322 + @summary Basic test for listRoots method + */ + +import java.io.*; + + +public class ListRoots { + + public static void main(String[] args) throws Exception { + File[] rs = File.listRoots(); + for (int i = 0; i < rs.length; i++) { + System.out.println(i + ": " + rs[i]); + } + + File f = new File(System.getProperty("test.src", "."), + "ListRoots.java"); + String cp = f.getCanonicalPath(); + for (int i = 0; i < rs.length; i++) { + if (cp.startsWith(rs[i].getPath())) break; + if (i == rs.length - 1) + throw new Exception(cp + " does not have a recognized root"); + } + + } + +} diff --git a/test/java/io/File/ListSpace.java b/test/java/io/File/ListSpace.java new file mode 100644 index 0000000000..31eafbbb9d --- /dev/null +++ b/test/java/io/File/ListSpace.java @@ -0,0 +1,40 @@ +/* + * 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 4923243 + * @summary check list with spaces at end of path + */ + +import java.io.*; + +public class ListSpace { + public static void main(String[] args) throws Exception { + File d = new File("."); + d = new File(d.getCanonicalPath()+" "); + if (!d.isDirectory()) + return; + if (d.list() == null) + throw new RuntimeException("list is null"); + } +} diff --git a/test/java/io/File/MaxPathLength.java b/test/java/io/File/MaxPathLength.java new file mode 100644 index 0000000000..effcc19351 --- /dev/null +++ b/test/java/io/File/MaxPathLength.java @@ -0,0 +1,220 @@ +/* + * 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 4759207 4403166 4165006 4403166 6182812 6274272 + @summary Test to see if win32 path length can be greater than 260 + */ + +import java.io.*; + +public class MaxPathLength { + private static String sep = File.separator; + private static String pathComponent = sep + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + private static String fileName = + "areallylongfilenamethatsforsur"; + private static boolean isWindows = false; + private static long totalSpace; + private static long freeSpace; + private static long usableSpace; + private static long ONEMEGA = 1024*1024; + + public static void main(String[] args) throws Exception { + String osName = System.getProperty("os.name"); + if (osName.startsWith("Windows")) { + isWindows = true; + if (osName.startsWith("Windows 9") || + osName.startsWith("Windows Me")) + return; // win9x/Me cannot handle long paths + } + + if (osName.startsWith("SunOS")) { + return; // We don't run this test on Solaris either. + // Some Solaris machines have very "slow" disk + // access performance which causes this one + // to timeout. + } + + if (isWindows) { + File f = new File("."); + totalSpace = f.getTotalSpace()/ONEMEGA; + freeSpace = f.getFreeSpace()/ONEMEGA; + usableSpace = f.getUsableSpace()/ONEMEGA; + } + + for (int i = 4; i < 7; i++) { + String name = fileName; + while (name.length() < 256) { + testLongPath (i, name, false); + testLongPath (i, name, true); + name += "A"; + } + } + + // Testing below will not be run if "-extra" is not + if (args.length == 0 || + !"-extra".equals(args[0]) || + !isWindows) + return; + + /* Testings below should not be run on a remote + dir that exists on a Solaris machine */ + for (int i = 20; i < 21; i++) { + String name = fileName; + while (name.length() < 256) { + testLongPath (i, name, false); + testLongPath (i, name, true); + name += "A"; + } + } + } + + private static int lastMax = 0; + static void testLongPath(int max, String fn, + boolean tryAbsolute) throws Exception { + String[] created = new String[max]; + String pathString = "."; + for (int i = 0; i < max -1; i++) { + pathString = pathString + pathComponent; + created[max - 1 -i] = pathString; + + } + File dirFile = new File(pathString); + File f = new File(pathString + sep + fn); + + String tPath = f.getPath(); + if (tryAbsolute) { + tPath = f.getCanonicalPath(); + } + created[0] = tPath; + + //for getCanonicalPath testing on win32 + File fu = new File(pathString + sep + fn.toUpperCase()); + + if (dirFile.exists()) { + System.err.println("Warning: Test directory structure exists already!"); + return; + } + boolean couldMakeTestDirectory = dirFile.mkdirs(); + if (!couldMakeTestDirectory) { + throw new RuntimeException ("Could not create test directory structure"); + } + try { + if (tryAbsolute) + dirFile = new File(dirFile.getCanonicalPath()); + if (!dirFile.isDirectory()) + throw new RuntimeException ("File.isDirectory() failed"); + if (isWindows && lastMax != max) { + long diff = totalSpace - dirFile.getTotalSpace()/ONEMEGA; + if (diff < -5 || diff > 5) + throw new RuntimeException ("File.getTotalSpace() failed"); + diff = freeSpace - dirFile.getFreeSpace()/ONEMEGA; + if (diff < -5 || diff > 5) + throw new RuntimeException ("File.getFreeSpace() failed"); + diff = usableSpace - dirFile.getUsableSpace()/ONEMEGA; + if (diff < -5 || diff > 5) + throw new RuntimeException ("File.getUsableSpace() failed"); + lastMax = max; + } + f = new File(tPath); + if (!f.createNewFile()) { + throw new RuntimeException ("File.createNewFile() failed"); + } + if (!f.exists()) + throw new RuntimeException ("File.exists() failed"); + if (!f.isFile()) + throw new RuntimeException ("File.isFile() failed"); + if (!f.canRead()) + throw new RuntimeException ("File.canRead() failed"); + if (!f.canWrite()) + throw new RuntimeException ("File.canWrite() failed"); + if (!f.delete()) + throw new RuntimeException ("File.delete() failed"); + FileOutputStream fos = new FileOutputStream(f); + fos.write(1); + fos.close(); + if (f.length() != 1) + throw new RuntimeException ("File.length() failed"); + long time = System.currentTimeMillis(); + if (!f.setLastModified(time)) + throw new RuntimeException ("File.setLastModified() failed"); + if (f.lastModified() == 0) { + throw new RuntimeException ("File.lastModified() failed"); + } + String[] list = dirFile.list(); + if (list == null || !fn.equals(list[0])) { + throw new RuntimeException ("File.list() failed"); + } + + File[] flist = dirFile.listFiles(); + if (flist == null || !fn.equals(flist[0].getName())) + throw new RuntimeException ("File.listFiles() failed"); + + if (isWindows && + !fu.getCanonicalPath().equals(f.getCanonicalPath())) + throw new RuntimeException ("getCanonicalPath() failed"); + + char[] cc = tPath.toCharArray(); + cc[cc.length-1] = 'B'; + File nf = new File(new String(cc)); + if (!f.renameTo(nf)) { + /*there is a known issue that renameTo fails if + (1)the path is a UNC path and + (2)the path length is bigger than 1092 + so don't stop if above are true + */ + String abPath = f.getAbsolutePath(); + if (!abPath.startsWith("\\\\") || + abPath.length() < 1093) { + throw new RuntimeException ("File.renameTo() failed for lenth=" + + abPath.length()); + } + return; + } + if (!nf.canRead()) + throw new RuntimeException ("Renamed file is not readable"); + if (!nf.canWrite()) + throw new RuntimeException ("Renamed file is not writable"); + if (nf.length() != 1) + throw new RuntimeException ("Renamed file's size is not correct"); + nf.renameTo(f); + /* add a script to test these two if we got a regression later + if (!f.setReadOnly()) + throw new RuntimeException ("File.setReadOnly() failed"); + f.deleteOnExit(); + */ + } finally { + // Clean up + for (int i = 0; i < max; i++) { + pathString = created[i]; + // Only works with completex canonical paths + File df = new File(pathString); + pathString = df.getCanonicalPath(); + df = new File(pathString); + if (!df.delete()) + System.out.printf("Delete failed->%s\n", pathString); + } + } + } +} diff --git a/test/java/io/File/Mkdir.java b/test/java/io/File/Mkdir.java new file mode 100644 index 0000000000..e47c77b9e3 --- /dev/null +++ b/test/java/io/File/Mkdir.java @@ -0,0 +1,39 @@ +/* + * 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 4344760 + @summary Test mkdirs with . in path + */ +import java.io.*; + +public class Mkdir { + static File a = new File("a"); + static File a_dot = new File(a, "."); + static File a_dot_b = new File(a_dot, "b"); + + public static void main(String[] args) throws Exception { + if (!a_dot_b.mkdirs()) + throw new Exception("Test failed"); + } +} diff --git a/test/java/io/File/NullArgs.java b/test/java/io/File/NullArgs.java new file mode 100644 index 0000000000..b4e677ff3f --- /dev/null +++ b/test/java/io/File/NullArgs.java @@ -0,0 +1,61 @@ +/* + * Copyright 1999-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 4203650 + @summary Ensure that File constructors and methods catch null arguments + @run main/othervm NullArgs + */ + + +import java.io.File; + +public class NullArgs { + + public static void main(String[] args) throws Exception { + + for (int i = 0;; i++) { + try { + switch (i) { + case 0: new File((String)null); break; + case 1: new File((String)null, null); break; + case 2: new File((File)null, null); break; + case 3: File.createTempFile(null, null, null); break; + case 4: File.createTempFile(null, null); break; + case 5: new File("foo").compareTo(null); break; + case 6: new File("foo").renameTo(null); break; + default: + System.err.println(); + return; + } + } catch (NullPointerException x) { + System.err.print(i + " "); + continue; + } + throw new Exception("NullPointerException not thrown (case " + + i + ")"); + } + + } + +} diff --git a/test/java/io/File/SetAccess.java b/test/java/io/File/SetAccess.java new file mode 100644 index 0000000000..0be12bb448 --- /dev/null +++ b/test/java/io/File/SetAccess.java @@ -0,0 +1,185 @@ +/* + * 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 4167472 5097703 6216563 6284003 + @summary Basic test for setWritable/Readable/Executable methods + */ + +import java.io.*; + +public class SetAccess { + public static void main(String[] args) throws Exception { + File d = new File(System.getProperty("test.dir", ".")); + + File f = new File(d, "x.SetAccessPermission"); + if (f.exists() && !f.delete()) + throw new Exception("Can't delete test file: " + f); + OutputStream o = new FileOutputStream(f); + o.write('x'); + o.close(); + doTest(f); + + f = new File(d, "x.SetAccessPermission.dir"); + if (f.exists() && !f.delete()) + throw new Exception("Can't delete test dir: " + f); + if (!f.mkdir()) + throw new Exception(f + ": Cannot create directory"); + doTest(f); + } + + public static void doTest(File f) throws Exception { + f.setReadOnly(); + if (!System.getProperty("os.name").startsWith("Windows")) { + if (!f.setWritable(true, true) || + !f.canWrite() || + permission(f).charAt(2) != 'w') + throw new Exception(f + ": setWritable(true, ture) Failed"); + if (!f.setWritable(false, true) || + f.canWrite() || + permission(f).charAt(2) != '-') + throw new Exception(f + ": setWritable(false, true) Failed"); + if (!f.setWritable(true, false) || + !f.canWrite() || + !permission(f).matches(".(.w.){3}")) + throw new Exception(f + ": setWritable(true, false) Failed"); + if (!f.setWritable(false, false) || + f.canWrite() || + !permission(f).matches(".(.-.){3}")) + throw new Exception(f + ": setWritable(false, true) Failed"); + if (!f.setWritable(true) || !f.canWrite() || + permission(f).charAt(2) != 'w') + throw new Exception(f + ": setWritable(true, ture) Failed"); + if (!f.setWritable(false) || f.canWrite() || + permission(f).charAt(2) != '-') + throw new Exception(f + ": setWritable(false, true) Failed"); + if (!f.setExecutable(true, true) || + !f.canExecute() || + permission(f).charAt(3) != 'x') + throw new Exception(f + ": setExecutable(true, true) Failed"); + if (!f.setExecutable(false, true) || + f.canExecute() || + permission(f).charAt(3) != '-') + throw new Exception(f + ": setExecutable(false, true) Failed"); + if (!f.setExecutable(true, false) || + !f.canExecute() || + !permission(f).matches(".(..x){3}")) + throw new Exception(f + ": setExecutable(true, false) Failed"); + if (!f.setExecutable(false, false) || + f.canExecute() || + !permission(f).matches(".(..-){3}")) + throw new Exception(f + ": setExecutable(false, false) Failed"); + if (!f.setExecutable(true) || !f.canExecute() || + permission(f).charAt(3) != 'x') + throw new Exception(f + ": setExecutable(true, true) Failed"); + if (!f.setExecutable(false) || f.canExecute() || + permission(f).charAt(3) != '-') + throw new Exception(f + ": setExecutable(false, true) Failed"); + if (!f.setReadable(true, true) || + !f.canRead() || + permission(f).charAt(1) != 'r') + throw new Exception(f + ": setReadable(true, true) Failed"); + if (!f.setReadable(false, true) || + f.canRead() || + permission(f).charAt(1) != '-') + throw new Exception(f + ": setReadable(false, true) Failed"); + if (!f.setReadable(true, false) || + !f.canRead() || + !permission(f).matches(".(r..){3}")) + throw new Exception(f + ": setReadable(true, false) Failed"); + if (!f.setReadable(false, false) || + f.canRead() || + !permission(f).matches(".(-..){3}")) + throw new Exception(f + ": setReadable(false, false) Failed"); + if (!f.setReadable(true) || !f.canRead() || + permission(f).charAt(1) != 'r') + throw new Exception(f + ": setReadable(true, true) Failed"); + if (!f.setReadable(false) || f.canRead() || + permission(f).charAt(1) != '-') + throw new Exception(f + ": setReadable(false, true) Failed"); + } else { + //Windows platform + if (!f.setWritable(true, true) || !f.canWrite()) + throw new Exception(f + ": setWritable(true, ture) Failed"); + if (!f.setWritable(true, false) || !f.canWrite()) + throw new Exception(f + ": setWritable(true, false) Failed"); + if (!f.setWritable(true) || !f.canWrite()) + throw new Exception(f + ": setWritable(true, ture) Failed"); + if (!f.setExecutable(true, true) || !f.canExecute()) + throw new Exception(f + ": setExecutable(true, true) Failed"); + if (!f.setExecutable(true, false) || !f.canExecute()) + throw new Exception(f + ": setExecutable(true, false) Failed"); + if (!f.setExecutable(true) || !f.canExecute()) + throw new Exception(f + ": setExecutable(true, true) Failed"); + if (!f.setReadable(true, true) || !f.canRead()) + throw new Exception(f + ": setReadable(true, true) Failed"); + if (!f.setReadable(true, false) || !f.canRead()) + throw new Exception(f + ": setReadable(true, false) Failed"); + if (!f.setReadable(true) || !f.canRead()) + throw new Exception(f + ": setReadable(true, true) Failed"); + if (f.isDirectory()) { + //All directories on Windows always have read&write access perm, + //setting a directory to "unwritable" actually means "not deletable" + if (!f.setWritable(false, true) || !f.canWrite()) + throw new Exception(f + ": setWritable(false, true) Failed"); + if (!f.setWritable(false, false) || !f.canWrite()) + throw new Exception(f + ": setWritable(false, true) Failed"); + if (!f.setWritable(false) || !f.canWrite()) + throw new Exception(f + ": setWritable(false, true) Failed"); + } else { + if (!f.setWritable(false, true) || f.canWrite()) + throw new Exception(f + ": setWritable(false, true) Failed"); + if (!f.setWritable(false, false) || f.canWrite()) + throw new Exception(f + ": setWritable(false, true) Failed"); + if (!f.setWritable(false) || f.canWrite()) + throw new Exception(f + ": setWritable(false, true) Failed"); + } + if (f.setExecutable(false, true)) + throw new Exception(f + ": setExecutable(false, true) Failed"); + if (f.setExecutable(false, false)) + throw new Exception(f + ": setExecutable(false, false) Failed"); + if (f.setExecutable(false)) + throw new Exception(f + ": setExecutable(false, true) Failed"); + if (f.setReadable(false, true)) + throw new Exception(f + ": setReadable(false, true) Failed"); + if (f.setReadable(false, false)) + throw new Exception(f + ": setReadable(false, false) Failed"); + if (f.setReadable(false)) + throw new Exception(f + ": setReadable(false, true) Failed"); + } + if (f.exists() && !f.delete()) + throw new Exception("Can't delete test dir: " + f); + } + + private static String permission(File f) throws Exception { + byte[] bb = new byte[1024]; + String command = f.isDirectory()?"ls -dl ":"ls -l "; + int len = Runtime.getRuntime() + .exec(command + f.getPath()) + .getInputStream() + .read(bb, 0, 1024); + if (len > 0) + return new String(bb, 0, len).substring(0, 10); + return ""; + } +} diff --git a/test/java/io/File/SetLastModified.java b/test/java/io/File/SetLastModified.java new file mode 100644 index 0000000000..22cb532655 --- /dev/null +++ b/test/java/io/File/SetLastModified.java @@ -0,0 +1,110 @@ +/* + * Copyright 1998-1999 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 4091757 + @summary Basic test for setLastModified method + */ + +import java.io.*; + + +public class SetLastModified { + + private static void ck(File f, long nt, long rt) throws Exception { + if (rt == nt) return; + if ((rt / 10 == nt / 10) + || (rt / 100 == nt / 100) + || (rt / 1000 == nt / 1000) + || (rt / 10000 == (nt / 10000))) { + System.err.println(f + ": Time set to " + nt + + ", rounded down by filesystem to " + rt); + return; + } + if ((rt / 10 == (nt + 5) / 10) + || (rt / 100 == (nt + 50) / 100) + || (rt / 1000 == (nt + 500) / 1000) + || (rt / 10000 == ((nt + 5000) / 10000))) { + System.err.println(f + ": Time set to " + nt + + ", rounded up by filesystem to " + rt); + return; + } + throw new Exception(f + ": Time set to " + nt + + ", then read as " + rt); + } + + public static void main(String[] args) throws Exception { + File d = new File(System.getProperty("test.dir", ".")); + File d2 = new File(d, "x.SetLastModified.dir"); + File f = new File(d2, "x.SetLastModified"); + long ot, t; + + /* New time: One week ago */ + long nt = System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 7; + + if (f.exists()) f.delete(); + if (d2.exists()) d2.delete(); + if (!d2.mkdir()) { + throw new Exception("Can't create test directory " + d2); + } + + boolean threw = false; + try { + d2.setLastModified(-nt); + } catch (IllegalArgumentException x) { + threw = true; + } + if (!threw) + throw new Exception("setLastModified succeeded with a negative time"); + + ot = d2.lastModified(); + if (ot != 0) { + if (d2.setLastModified(nt)) { + ck(d2, nt, d2.lastModified()); + d2.setLastModified(ot); + } else { + System.err.println("Warning: setLastModified on directories " + + "not supported"); + } + } + + if (f.exists()) { + if (!f.delete()) + throw new Exception("Can't delete test file " + f); + } + if (f.setLastModified(nt)) + throw new Exception("Succeeded on non-existent file: " + f); + + OutputStream o = new FileOutputStream(f); + o.write('x'); + o.close(); + ot = f.lastModified(); + if (!f.setLastModified(nt)) + throw new Exception("setLastModified failed on file: " + f); + ck(f, nt, f.lastModified()); + + if (!f.delete()) throw new Exception("Can't delete test file " + f); + if (!d2.delete()) throw new Exception("Can't delete test directory " + d2); + } + +} diff --git a/test/java/io/File/SetReadOnly.java b/test/java/io/File/SetReadOnly.java new file mode 100644 index 0000000000..ed89513f8b --- /dev/null +++ b/test/java/io/File/SetReadOnly.java @@ -0,0 +1,69 @@ +/* + * Copyright 1998 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 4091757 + @summary Basic test for setReadOnly method + */ + +import java.io.*; + + +public class SetReadOnly { + + public static void main(String[] args) throws Exception { + File d = new File(System.getProperty("test.dir", ".")); + File f = new File(d, "x.SetReadOnly"); + + if (f.exists()) { + if (!f.delete()) + throw new Exception("Can't delete test file " + f); + } + if (f.setReadOnly()) + throw new Exception("Succeeded on non-existent file: " + f); + + OutputStream o = new FileOutputStream(f); + o.write('x'); + o.close(); + if (!f.setReadOnly()) + throw new Exception(f + ": Failed on file"); + if (f.canWrite()) + throw new Exception(f + ": File is writeable"); + + f = new File(d, "x.SetReadOnly.dir"); + if (f.exists()) { + if (!f.delete()) + throw new Exception("Can't delete test directory " + f); + } + if (!f.mkdir()) + throw new Exception(f + ": Cannot create directory"); + if (!f.setReadOnly()) + throw new Exception(f + ": Failed on directory"); + if (f.canWrite()) + throw new Exception(f + ": Directory is writeable"); + if (!f.delete()) + throw new Exception(f + ": Cannot delete directory"); + + } + +} diff --git a/test/java/io/File/ToURI.java b/test/java/io/File/ToURI.java new file mode 100644 index 0000000000..716bdeb46d --- /dev/null +++ b/test/java/io/File/ToURI.java @@ -0,0 +1,76 @@ +/* + * 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 4468322 + @summary Unit test for File.toURI()/File(URI) + */ + +import java.io.*; +import java.net.URI; + + +public class ToURI { + + static PrintStream log = System.err; + static int failures = 0; + + static void go(String fn) throws Exception { + File f = new File(fn); + log.println(); + log.println(f); + URI u = f.toURI(); + log.println(" --> " + u); + File g = new File(u); + log.println(" --> " + g); + if (!f.getAbsoluteFile().equals(g)) { + log.println("ERROR: Expected " + f + ", got " + g); + failures++; + } + } + + public static void main(String[] args) throws Exception { + go("foo"); + go("foo/bar/baz"); + go("/cdrom/#2"); + go("My Computer"); + go("/tmp"); + go("/"); + go(""); + go("!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`" + + "abcdefghijklmnopqrstuvwxyz{|}~\u00D0"); + + if (File.separatorChar == '\\') { + go("c:"); + go("c:\\"); + go("c:\\a\\b"); + go("\\\\foo"); + go("\\\\foo\\bar"); + } + + if (failures > 0) + throw new Exception("Tests failed: " + failures); + + } + +} diff --git a/test/java/io/File/ToURL.java b/test/java/io/File/ToURL.java new file mode 100644 index 0000000000..ba4b41070e --- /dev/null +++ b/test/java/io/File/ToURL.java @@ -0,0 +1,54 @@ +/* + * Copyright 1998 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 4166902 + @summary Ensure that File.toURL does not append a slash to root directories + */ + +import java.io.File; +import java.net.URL; + + +public class ToURL { + + static void go(String fn) throws Exception { + File f = new File(fn); + URL u = f.toURL(); + String ufn = u.getFile(); + if (!ufn.endsWith("/")) + throw new Exception(u + " does not end with slash"); + if (ufn.endsWith("//")) + throw new Exception(u + " ends with two slashes"); + } + + public static void main(String[] args) throws Exception { + if (File.separatorChar == '/') { + go("/"); + } else if (File.separatorChar == '\\') { + go("\\"); + go("c:\\"); + } + } + +} diff --git a/test/java/io/File/Unicode.java b/test/java/io/File/Unicode.java new file mode 100644 index 0000000000..46289f2cb5 --- /dev/null +++ b/test/java/io/File/Unicode.java @@ -0,0 +1,97 @@ +/* + * 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 5016938 + * @summary Test file operations with Unicode filenames + * @author Martin Buchholz + */ + +import java.io.*; + +public class Unicode +{ + static int fail = 0; + static void fail(String msg) { + fail++; + System.err.println(msg); + } + + static boolean creat(File f) throws Exception { + try { + FileOutputStream out = new FileOutputStream(f); + out.write(new byte[]{'a', 'b', 'c'}); + out.close(); + // Check that the file we tried to create has the expected name + return find(f); + } catch (Exception e) { + return false; + } + } + + static boolean find(File f) throws Exception { + String fn = f.getPath(); + String[] fns = new File(".").list(); + for (int i = 0; i < fns.length; i++) + if (fns[i].equals(fn)) + return true; + return false; + } + + static void sanityCheck(File f) throws Exception { + if (! f.exists()) fail("! f.exists()"); + if ( f.length() != 3) fail(" f.length() != 3"); + if ( f.isAbsolute()) fail(" f.isAbsolute()"); + if (! f.canRead()) fail("! f.canRead()"); + if (! f.canWrite()) fail("! f.canWrite()"); + if ( f.isHidden()) fail(" f.isHidden()"); + if (! f.isFile()) fail("! f.isFile()"); + if ( f.isDirectory()) fail(" f.isDirectory()"); + } + + public static void main(String [] args) throws Exception { + final File f1 = new File("\u0411.tst"); + final File f2 = new File("\u0412.tst"); + + try { + if (! creat(f1)) + // Couldn't create file with Unicode filename? + return; + + System.out.println("This system supports Unicode filenames!"); + sanityCheck(f1); + + f1.renameTo(f2); + sanityCheck(f2); + if (! f2.delete()) fail("! f2.delete()"); + if ( f2.exists()) fail(" f2.exists()"); + if ( f1.exists()) fail(" f1.exists()"); + if ( f1.delete()) fail(" f1.delete()"); + + if (fail != 0) throw new Exception(fail + " failures"); + } finally { + f1.delete(); + f2.delete(); + } + } +} diff --git a/test/java/io/File/WinDeviceName.java b/test/java/io/File/WinDeviceName.java new file mode 100644 index 0000000000..45f34c4762 --- /dev/null +++ b/test/java/io/File/WinDeviceName.java @@ -0,0 +1,57 @@ +/* + * 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 6176051 + @summary Check isFile's handling of Windows device names + */ + +import java.io.File; + +public class WinDeviceName { + private static String devnames[] = { + "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", + "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", + "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", + "CLOCK$" + }; + public static void main(String[] args) throws Exception { + String osName = System.getProperty("os.name"); + if (!osName.startsWith("Windows")) { + return; + } + for (int i = 0; i < devnames.length; i++) { + if (new File(devnames[i]).isFile() || + new File(devnames[i] + ".txt").isFile()) { + if ("CLOCK$".equals(devnames[i]) && + (osName.startsWith("Windows 9") || + osName.startsWith("Windows Me"))) { + //"CLOCK$" is a reserved device name for NT + continue; + } + throw new Exception("isFile() returns true for Device name " + + devnames[i]); + } + } + } +} diff --git a/test/java/io/File/WinMaxPath.java b/test/java/io/File/WinMaxPath.java new file mode 100644 index 0000000000..671fd7fa86 --- /dev/null +++ b/test/java/io/File/WinMaxPath.java @@ -0,0 +1,46 @@ +/* + * 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 6384833 + @summary Check if appropriate exception FileNotFoundException gets + thrown when the pathlengh exceeds the limit. + */ + +import java.io.*; +public class WinMaxPath { + public static void main(String[] args) throws Exception { + String osName = System.getProperty("os.name"); + if (!osName.startsWith("Windows")) { + return; + } + try { + char[] as = new char[65000]; + java.util.Arrays.fill(as, 'a'); + FileOutputStream out = new FileOutputStream(new String(as)); + out.close(); + } catch (FileNotFoundException x) { + //expected + } + } +} diff --git a/test/java/io/File/WinSpecialFiles.java b/test/java/io/File/WinSpecialFiles.java new file mode 100644 index 0000000000..647f45806a --- /dev/null +++ b/test/java/io/File/WinSpecialFiles.java @@ -0,0 +1,55 @@ +/* + * 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 6192331 6348207 + @summary Check if File.exists()/length() works correctly on Windows + special files hiberfil.sys and pagefile.sys + */ + +import java.io.File; +public class WinSpecialFiles { + public static void main(String[] args) throws Exception { + String osName = System.getProperty("os.name"); + if (!osName.startsWith("Windows")) { + return; + } + File root = new File("C:\\"); + File[] dir = root.listFiles(); + for (int i = 0; i < dir.length; i++) { + if (!dir[i].exists()) { + throw new Exception("exists() returns false for <" + + dir[i].getPath() + ">"); + } + String name = dir[i].getPath().toLowerCase(); + if (name.indexOf("pagefile.sys") != -1 || + name.indexOf("hiberfil.sys") != -1) { + if (dir[i].length() == 0) { + throw new Exception("Size of existing <" + + dir[i].getPath() + + " is ZERO"); + } + } + } + } +} diff --git a/test/java/io/File/basic.sh b/test/java/io/File/basic.sh new file mode 100644 index 0000000000..fa11c66536 --- /dev/null +++ b/test/java/io/File/basic.sh @@ -0,0 +1,47 @@ +#! /bin/sh + +# +# Copyright 1998-1999 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. +# + +# + +if [ "x$TESTJAVA" = x ]; then + TESTJAVA=$1; shift + TESTCLASSES=. +fi + +rm -rf x.Basic.* +rm -f x.Basic.non +echo xyzzy > x.Basic.rw +touch x.Basic.ro; chmod ugo-w x.Basic.ro +mkdir x.Basic.dir +if $TESTJAVA/bin/java $* -classpath $TESTCLASSES Basic; then + [ -f x.Basic.rw ] && (echo "x.Basic.rw not deleted"; exit 1) + ([ -d x.Basic.dir ] || [ \! -d x.Basic.dir2 ]) \ + && (echo "x.Basic.dir not renamed"; exit 1) + [ \! -d x.Basic.nonDir ] && (echo "x.Basic.nonDir not created"; exit 1) + [ -f x.Basic.non ] && (echo "x.Basic.non not deleted"; exit 1) + exit 0 +else + exit 1 +fi diff --git a/test/java/io/File/createTempFile/Patterns.java b/test/java/io/File/createTempFile/Patterns.java new file mode 100644 index 0000000000..02059e08dc --- /dev/null +++ b/test/java/io/File/createTempFile/Patterns.java @@ -0,0 +1,71 @@ +/* + * Copyright 1998 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 4152178 + @summary Check various temp-file prefix/suffix cases */ + +import java.io.File; +import java.io.IOException; + +public class Patterns { + + static File dir = new File("."); + + static void ckn(String prefix, String suffix) throws Exception { + try { + File f = File.createTempFile(prefix, suffix, dir); + f.deleteOnExit(); + } catch (Exception x) { + if ((x instanceof IOException) + || (x instanceof NullPointerException) + || (x instanceof IllegalArgumentException)) { + System.err.println("\"" + prefix + "\", \"" + suffix + + "\" failed as expected: " + x.getMessage()); + return; + } + throw x; + } + throw new Exception("\"" + prefix + "\", \"" + suffix + + "\" should have failed"); + } + + static void cky(String prefix, String suffix) throws Exception { + File f = File.createTempFile(prefix, suffix, dir); + f.deleteOnExit(); + System.err.println("\"" + prefix + "\", \"" + suffix + + "\" --> " + f.getPath()); + } + + public static void main(String[] args) throws Exception { + ckn(null, null); + ckn("", null); + ckn("x", null); + ckn("xx", null); + cky("xxx", null); + cky("xxx", ""); + cky("xxx", "y"); + cky("xxx", ".y"); + } + +} diff --git a/test/java/io/File/isDirectory/Applet.html b/test/java/io/File/isDirectory/Applet.html new file mode 100644 index 0000000000..69d57f4725 --- /dev/null +++ b/test/java/io/File/isDirectory/Applet.html @@ -0,0 +1,2 @@ +<!----> +<applet code=Applet.class width=100 height=100></applet> diff --git a/test/java/io/File/isDirectory/Applet.java b/test/java/io/File/isDirectory/Applet.java new file mode 100644 index 0000000000..65ccf36932 --- /dev/null +++ b/test/java/io/File/isDirectory/Applet.java @@ -0,0 +1,48 @@ +/* + * Copyright 1998 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 4054511 + @summary Check that applets don't get a security exception when invoking + the File.isDirectory method on a non-existent directory + @author Mark Reinhold + @run applet Applet.html + */ + +import java.io.*; + + +public class Applet extends java.applet.Applet { + + void go(String fn) { + File f = new File(fn); + System.err.println(fn + ": " + f.isDirectory()); + } + + public void init() { + String nxdir = "non_EX_is_TENT_dir_EC_tory"; + go(nxdir); + go(nxdir + File.separator + "bar" + File.separator + "baz"); + } + +} diff --git a/test/java/io/FileDescriptor/FileChannelFDTest.java b/test/java/io/FileDescriptor/FileChannelFDTest.java new file mode 100644 index 0000000000..eb3c69adb6 --- /dev/null +++ b/test/java/io/FileDescriptor/FileChannelFDTest.java @@ -0,0 +1,92 @@ +/* + * 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 6322678 + * @summary Test for making sure that fd is closed during + * finalization of a stream, when an associated + * file channel is not available + */ + +import java.io.*; +import java.nio.*; +import java.nio.channels.*; + +public class FileChannelFDTest { + + static byte data[] = new byte[] {48, 49, 50, 51, 52, 53, 54, 55, 56, 57,}; + static String inFileName = "fd-in-test.txt"; + static String outFileName = "fd-out-test.txt"; + static File inFile; + static File outFile; + + private static void writeToInFile() throws IOException { + FileOutputStream out = new FileOutputStream(inFile); + out.write(data); + out.close(); + } + + public static void main(String[] args) + throws Exception { + + inFile= new File(System.getProperty("test.dir", "."), + inFileName); + inFile.createNewFile(); + inFile.deleteOnExit(); + writeToInFile(); + + outFile = new File(System.getProperty("test.dir", "."), + outFileName); + outFile.createNewFile(); + outFile.deleteOnExit(); + + doFileChannel(); + } + + private static void doFileChannel() throws Exception { + + FileInputStream fis = new FileInputStream(inFile); + FileDescriptor fd = fis.getFD(); + FileChannel fc = fis.getChannel(); + System.out.println("Created fis:" + fis); + + /** + * Encourage the GC + */ + fis = null; + fc = null; + System.gc(); + Thread.sleep(500); + + if (fd.valid()) { + throw new Exception("Finalizer either didn't run --" + + "try increasing the Thread's sleep time after System.gc();" + + "or the finalizer didn't close the file"); + } + + System.out.println("File Closed successfully"); + System.out.println(); + } +} diff --git a/test/java/io/FileDescriptor/Finalize.java b/test/java/io/FileDescriptor/Finalize.java new file mode 100644 index 0000000000..00976c9212 --- /dev/null +++ b/test/java/io/FileDescriptor/Finalize.java @@ -0,0 +1,257 @@ +/* + * 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 6322678 + * @summary Test for making sure that FIS/FOS.finalize() will + * not disturb the FD that is still in use. + */ + +import java.io.*; +import java.nio.*; +import java.nio.channels.*; + +public class Finalize { + + static byte data[] = new byte[] {48, 49, 50, 51, 52, 53, 54, 55, 56, 57,}; + static String inFileName = "fd-in-test.txt"; + static String outFileName = "fd-out-test.txt"; + static File inFile; + static File outFile; + + public static void main(String[] args) + throws Exception { + Thread.sleep(5000); + + inFile= new File(System.getProperty("test.dir", "."), + inFileName); + inFile.createNewFile(); + inFile.deleteOnExit(); + writeToInFile(); + + doFileInputStream(); + + outFile = new File(System.getProperty("test.dir", "."), + outFileName); + outFile.createNewFile(); + outFile.deleteOnExit(); + + doFileOutputStream(); + doRandomAccessFile(); + doFileChannel(); + } + + private static void doFileInputStream() throws Exception { + + /* Create initial FIS for file */ + FileInputStream fis1 = new FileInputStream(inFile); + + /* Get the FileDescriptor from the fis */ + FileDescriptor fd = fis1.getFD(); + + /* + * Create a new FIS based on the existing FD + * (so the two FIS's share the same native fd) + */ + FileInputStream fis2 = new FileInputStream(fd); + + /* allow fis1 to be gc'ed */ + fis1 = null; + int ret = 0; + + /* encourage gc */ + System.gc(); + Thread.sleep(200); + + while((ret = fis2.read()) != -1 ) { + /* + * read from fis2 - when fis1 is gc'ed and finalizer is run, + * read should not fail + */ + System.out.println("read from fis2:" + ret); + } + fis2.close(); + } + + private static void writeToInFile() throws IOException { + FileOutputStream out = new FileOutputStream(inFile); + out.write(data); + out.close(); + } + + private static void doFileOutputStream() + throws Exception { + + System.out.println("--------FileOutputStream Test Started----------"); + + /*Create initial FIS for file */ + FileOutputStream fos1 = new FileOutputStream(outFile); + + /* Get the FileDescriptor from the fos */ + FileDescriptor fd = fos1.getFD(); + FileOutputStream fos2 = new FileOutputStream(fd); + + /* allow fos1 to be gc'ed */ + fos1 = null; + + /* encourage gc */ + System.gc(); + Thread.sleep(200); + + /* + * write to fos2 - when fos1 is gc'ed and finalizer is run, + * write to fos2 should not fail + */ + fos2.write(data); + System.out.println("wrote:" + data.length + " bytes to fos2"); + fos2.close(); + + System.out.println("--------FileOutputStream Test Over----------"); + System.out.println(); + } + + + private static void doRandomAccessFile() + throws Exception { + + System.out.println("--------RandomAccessFile Read Test Started----------"); + + // Create initial FIS for file + RandomAccessFile raf = new RandomAccessFile(inFile, "r"); + + /* Get the FileDescriptor from the fis */ + FileDescriptor fd = raf.getFD(); + + /* Create a new FIS based on the existing FD + * (so the two FIS's share the same native fd) + */ + FileInputStream fis = new FileInputStream(fd); + + /* allow fis to be gc'ed */ + fis = null; + int ret = 0; + + /* encourage gc */ + System.gc(); + Thread.sleep(50); + + /* + * read from raf - when fis is gc'ed and finalizer is run, + * read from raf should not fail + */ + while((ret = raf.read()) != -1 ) { + System.out.println("read from raf:" + ret); + } + raf.close(); + Thread.sleep(200); + + System.out.println("--------RandomAccessFile Write Test Started----------"); + System.out.println(); + + raf = new RandomAccessFile(outFile, "rw"); + fd = raf.getFD(); + FileOutputStream fos = new FileOutputStream(fd); + + /* allow fos to be gc'ed */ + fos = null; + + /* encourage gc */ + System.gc(); + Thread.sleep(200); + + /* + * write to raf - when fos is gc'ed and finalizer is run, + * write to raf should not fail + */ + raf.write(data); + System.out.println("wrote:" + data.length + " bytes to raf"); + raf.close(); + + System.out.println("--------RandomAccessFile Write Test Over----------"); + System.out.println(); + } + + private static void doFileChannel() throws Exception { + + System.out.println("--------FileChannel Read Test Started----------"); + System.out.println(); + + FileInputStream fis1 = new FileInputStream(inFile); + + /* Get the FileDescriptor from the fis */ + FileDescriptor fd = fis1.getFD(); + + /* Create a new FIS based on the existing FD + * (so the two FIS's share the same native fd) + */ + FileInputStream fis2 = new FileInputStream(fd); + FileChannel fc2 = fis2.getChannel(); + + /** + * Encourage the GC + */ + fis1 = null; + System.gc(); + Thread.sleep(200); + + int ret = 1; + ByteBuffer bb = ByteBuffer.allocateDirect(1); + ret = fc2.read(bb); + System.out.println("read " + ret + " bytes from fc2:"); + fc2.close(); + + System.out.println("--------FileChannel Read Test Over----------"); + System.out.println(); + + System.out.println("--------FileChannel Write Test Started----------"); + + FileOutputStream fos1 = new FileOutputStream(outFile); + + /* Get the FileDescriptor from the fos */ + fd = fos1.getFD(); + FileOutputStream fos2 = new FileOutputStream(fd); + fc2 = fos2.getChannel(); + + /** + * Encourage the GC + */ + fos1 = null; + System.gc(); + Thread.sleep(200); + + /* + * write to fc2 - when fos1 is gc'ed and finalizer is run, + * write to fc2 should not fail + */ + bb = ByteBuffer.allocateDirect(data.length); + bb = bb.put(data); + bb = (ByteBuffer) bb.flip(); + ret = fc2.write(bb); + System.out.println("Wrote:" + ret + " bytes to fc2"); + fc2.close(); + + System.out.println("--------Channel Write Test Over----------"); + } +} diff --git a/test/java/io/FileInputStream/Available.java b/test/java/io/FileInputStream/Available.java new file mode 100644 index 0000000000..ae1b3a66cf --- /dev/null +++ b/test/java/io/FileInputStream/Available.java @@ -0,0 +1,47 @@ +/* + * Copyright 1998 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 4129479 + * @summary Test if available would throw an IOException + * when the stream is closed. + */ + +import java.io.*; + +public class Available { + public static void main(String args[]) throws Exception { + File file = new File(System.getProperty("test.src", "."), + "Available.java"); + FileInputStream fis = new FileInputStream(file); + fis.close(); + try { + fis.available(); + throw new Exception + ("available should throw an exception after stream is closed"); + } + catch (IOException e) { + } + } +} diff --git a/test/java/io/FileInputStream/FinalizeShdCallClose.java b/test/java/io/FileInputStream/FinalizeShdCallClose.java new file mode 100644 index 0000000000..2f74bcc39f --- /dev/null +++ b/test/java/io/FileInputStream/FinalizeShdCallClose.java @@ -0,0 +1,90 @@ +/* + * 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 6524062 + * @summary Test to ensure that FIS.finalize() invokes the close() method as per + * the specification. + */ +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; + +public class FinalizeShdCallClose { + + static final String FILE_NAME = "empty.txt"; + + public static class MyStream extends FileInputStream { + private boolean closed = false; + + public MyStream(String name) throws FileNotFoundException { + super(name); + } + + public void finalize() { + try { + super.finalize(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + + public void close() { + try { + super.close(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + closed = true; + } + + public boolean isClosed() { + return closed; + } + } + + /* standalone interface */ + public static void main(String argv[]) throws Exception { + + File inFile= new File(System.getProperty("test.dir", "."), FILE_NAME); + inFile.createNewFile(); + inFile.deleteOnExit(); + + String name = inFile.getPath(); + MyStream ms = null; + try { + ms = new MyStream(name); + } catch (FileNotFoundException e) { + System.out.println("Unexpected exception " + e); + throw(e); + } + ms.finalize(); + if (!ms.isClosed()) { + throw new Exception("MyStream.close() method is not called"); + } + System.out.println("OK"); + } +} diff --git a/test/java/io/FileInputStream/LeadingSlash.java b/test/java/io/FileInputStream/LeadingSlash.java new file mode 100644 index 0000000000..07843cc3d3 --- /dev/null +++ b/test/java/io/FileInputStream/LeadingSlash.java @@ -0,0 +1,47 @@ +/* + * 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 4487368 + * @summary Test, if FileInputStream can handle + * a leading slash in file name. + */ + +import java.io.*; + +public class LeadingSlash { + public static void main (String args[]) throws Exception { + if (File.separatorChar == '\\') { // Windows + File file = null; + try { + file = File.createTempFile("bug", "4487368"); + new FileInputStream("\\" + file.getPath()); + new FileOutputStream("\\" + file.getPath()); + } finally { + if (file != null) + file.delete(); + } + } + } +} diff --git a/test/java/io/FileInputStream/OpenDir.java b/test/java/io/FileInputStream/OpenDir.java new file mode 100644 index 0000000000..987a88640f --- /dev/null +++ b/test/java/io/FileInputStream/OpenDir.java @@ -0,0 +1,67 @@ +/* + * Copyright 1998 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 4092350 + * @summary Attempting to open a stream on a directory should fail on + * all platforms. + * + */ + +import java.io.*; + +public class OpenDir { + + public static void main(String args[]) throws Exception { + // Perform the same test for FileInputStream, FileOutputStream + // and RandomAccessFile. + FileInputStream fs = null; + // This test attempts to FileInputStream.open(".") + // This should fail since . is a directory. + try { + fs = new FileInputStream("."); + throw new + Exception("FileInputStream.open should not work on dirs"); + } catch (IOException e) { + } + + FileOutputStream fos = null; + try { + fos = new FileOutputStream("."); + throw new + Exception("FileOutputStream.open should'nt work on dirs"); + } catch (IOException e) { + } + + RandomAccessFile ras = null; + try { + ras = new RandomAccessFile(".","r"); + throw new + Exception("RandomAccessFile.open should'nt work on dirs"); + } catch (IOException e) { + } + } + + +} diff --git a/test/java/io/FileInputStream/OpsAfterClose.java b/test/java/io/FileInputStream/OpsAfterClose.java new file mode 100644 index 0000000000..2a4f7004c4 --- /dev/null +++ b/test/java/io/FileInputStream/OpsAfterClose.java @@ -0,0 +1,112 @@ +/** + * @test + * @bug 6359397 + * @summary Test if FileInputStream methods will check if the stream + * has been closed. + */ + +import java.io.*; + +public enum OpsAfterClose { + + READ { boolean check(FileInputStream r) { + try { + r.read(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + + READ_BUF { boolean check(FileInputStream r) { + try { + byte buf[] = new byte[2]; + r.read(buf); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + READ_BUF_OFF { boolean check(FileInputStream r) { + try { + byte buf[] = new byte[2]; + int len = 1; + r.read(buf, 0, len); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + GET_CHANNEL { boolean check(FileInputStream r) { + r.getChannel(); + return true; + } }, + GET_FD { boolean check(FileInputStream r) { + try { + r.getFD(); + return true; + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return false; + } + } }, + SKIP { boolean check(FileInputStream r) { + try { + r.skip(1); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + CLOSE { boolean check(FileInputStream r) { + try { + r.close(); + return true; // No Exception thrown on windows + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; // Exception thrown on solaris and linux + } + } }; + + abstract boolean check(FileInputStream r); + + public static void main(String args[]) throws Exception { + + boolean failed = false; + + File f = new File(System.getProperty("test.dir", "."), + "f.txt"); + f.createNewFile(); + f.deleteOnExit(); + + FileInputStream fis = new FileInputStream(f); + if (testFileInputStream(fis)) { + throw new Exception("Test failed for some of the operation{s}" + + " on FileInputStream, check the messages"); + } + } + + private static boolean testFileInputStream(FileInputStream r) + throws Exception { + r.close(); + boolean failed = false; + boolean result; + System.out.println("Testing File:" + r); + for (OpsAfterClose op : OpsAfterClose.values()) { + result = op.check(r); + if (!result) { + failed = true; + } + System.out.println(op + ":" + result); + } + if (failed) { + System.out.println("Test failed for the failed operation{s}" + + " above for the FileInputStream:" + r); + } + return failed; + } +} diff --git a/test/java/io/FileOutputStream/FileOpen.sh b/test/java/io/FileOutputStream/FileOpen.sh new file mode 100644 index 0000000000..d3989c1a2e --- /dev/null +++ b/test/java/io/FileOutputStream/FileOpen.sh @@ -0,0 +1,76 @@ +#!/bin/sh + +# +# 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 6364894 +# @run shell FileOpen.sh +# @summary Test to ensure that opening of hidden Vs non-hidden, +# read/write Vs read-only files for writing works as expected. + + +# We use a TMP directory on a local disk because this test +# requires that the file to be tested be present on the local disk, +# not on a samba mounted drive or on a drive that is mapped. +# The cmd 'attrib' works only on the local files. +TMP="C:\TEMP" +hfile=${TMP}"\random_file1.txt" +ATTRIB=${SystemRoot}"\system32\attrib.exe" + +OS=`uname -s` +case "$OS" in + Windows_* ) + if [ ! -d ${TMP} ] ; then + echo "Could not find the directory-" ${TMP} "- passing test" + exit 0; + fi + ${TESTJAVA}/bin/javac -d . ${TESTSRC}\\FileOpenPos.java + ${TESTJAVA}/bin/javac -d . ${TESTSRC}\\FileOpenNeg.java + + echo "Opening Writable Normal File.." + ${TESTJAVA}/bin/java FileOpenPos ${hfile} + + echo "Opening Writable Hidden File.." + ${ATTRIB} +h ${hfile} + ${TESTJAVA}/bin/java FileOpenNeg ${hfile} + + echo "Opening Read-Only Normal File.." + ${ATTRIB} -h ${hfile} + ${ATTRIB} +r ${hfile} + ${TESTJAVA}/bin/java FileOpenNeg ${hfile} + + echo "Opening Read-Only Hidden File.." + ${ATTRIB} +h ${hfile} + ${TESTJAVA}/bin/java FileOpenNeg ${hfile} + + rm -f ${hfile} + exit + ;; + + * ) + echo "This test is not intended for this OS - passing test" + exit 0 + ;; +esac diff --git a/test/java/io/FileOutputStream/FileOpenNeg.java b/test/java/io/FileOutputStream/FileOpenNeg.java new file mode 100644 index 0000000000..ca1221abe6 --- /dev/null +++ b/test/java/io/FileOutputStream/FileOpenNeg.java @@ -0,0 +1,45 @@ +/* + * 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. + */ + +import java.io.*; + +public class FileOpenNeg { + + public static void main( String[] args) throws Exception { + boolean openForWrite = true; + + File f = new File(args[0]); + try { + FileOutputStream fs = new FileOutputStream(f); + fs.write(1); + fs.close(); + } catch( IOException e ) { + System.out.println("Caught the Exception as expected"); + e.printStackTrace(System.out); + openForWrite = false; + } + if (openForWrite && !f.canWrite()) { + throw new Exception("Able to open READ-ONLY file for WRITING!"); + } + } +} diff --git a/test/java/io/FileOutputStream/FileOpenPos.java b/test/java/io/FileOutputStream/FileOpenPos.java new file mode 100644 index 0000000000..39cf26c926 --- /dev/null +++ b/test/java/io/FileOutputStream/FileOpenPos.java @@ -0,0 +1,37 @@ +/* + * 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. + */ + +import java.io.*; + +public class FileOpenPos { + + public static void main( String[] args) + throws IOException { + File f = new File(args[0]); + FileOutputStream fs = new FileOutputStream(f); + fs.write(1); + fs.close(); + System.out.println("Can Write ?" + f.canWrite()); + System.out.println("The File was successfully opened"); + } +} diff --git a/test/java/io/FileOutputStream/FinalizeShdCallClose.java b/test/java/io/FileOutputStream/FinalizeShdCallClose.java new file mode 100644 index 0000000000..d3442ba6b9 --- /dev/null +++ b/test/java/io/FileOutputStream/FinalizeShdCallClose.java @@ -0,0 +1,90 @@ +/* + * 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 6524062 + * @summary Test to ensure that FOS.finalize() invokes the close() method as per + * the specification. + */ +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileNotFoundException; +import java.io.IOException; + +public class FinalizeShdCallClose { + + static final String FILE_NAME = "empty.txt"; + + public static class MyStream extends FileOutputStream { + private boolean closed = false; + + public MyStream(String name) throws FileNotFoundException { + super(name); + } + + public void finalize() { + try { + super.finalize(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + + public void close() { + try { + super.close(); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + closed = true; + } + + public boolean isClosed() { + return closed; + } + } + + /* standalone interface */ + public static void main(String argv[]) throws Exception { + + File inFile= new File(System.getProperty("test.dir", "."), FILE_NAME); + inFile.createNewFile(); + inFile.deleteOnExit(); + + String name = inFile.getPath(); + MyStream ms = null; + try { + ms = new MyStream(name); + } catch (FileNotFoundException e) { + System.out.println("Unexpected exception " + e); + throw(e); + } + ms.finalize(); + if (!ms.isClosed()) { + throw new Exception("MyStream.close() method is not called"); + } + System.out.println("OK"); + } +} diff --git a/test/java/io/FileOutputStream/ManyFiles.java b/test/java/io/FileOutputStream/ManyFiles.java new file mode 100644 index 0000000000..bd2fce83de --- /dev/null +++ b/test/java/io/FileOutputStream/ManyFiles.java @@ -0,0 +1,67 @@ +/* + * 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 4189011 5019303 + * @summary Test opening over 2048 files + * @run main/timeout=300 ManyFiles + */ + +import java.io.*; +import java.util.*; + +public class ManyFiles { + static int count; + static List files = new ArrayList(); + static List streams = new ArrayList(); + static int NUM_FILES = 2050; + + public static void main(String args[]) throws Exception { + // Linux does not yet allow opening this many files; Solaris + // 8 requires an explicit allocation of more file descriptors + // to succeed. Since this test is written to check for a + // Windows capability it is much simpler to only run it + // on that platform. + String osName = System.getProperty("os.name"); + if (osName.startsWith("Linux")||osName.startsWith("SunOS")) + return; + + for (int n = 0; n < NUM_FILES; n++) { + File f = new File("file" + count++); + files.add(f); + streams.add(new FileOutputStream(f)); + } + + Iterator i = streams.iterator(); + while(i.hasNext()) { + FileOutputStream fos = (FileOutputStream)i.next(); + fos.close(); + } + + i = files.iterator(); + while(i.hasNext()) { + File f = (File)i.next(); + f.delete(); + } + } +} diff --git a/test/java/io/FileOutputStream/OpsAfterClose.java b/test/java/io/FileOutputStream/OpsAfterClose.java new file mode 100644 index 0000000000..8ea086626d --- /dev/null +++ b/test/java/io/FileOutputStream/OpsAfterClose.java @@ -0,0 +1,103 @@ +/** + * @test + * @bug 6359397 + * @summary Test if FileOutputStream methods will check if the stream + * has been closed. + */ + +import java.io.*; + +public enum OpsAfterClose { + + WRITE { boolean check(FileOutputStream r) { + try { + r.write(1); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + + WRITE_BUF { boolean check(FileOutputStream r) { + try { + byte buf[] = new byte[2]; + r.write(buf); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + WRITE_BUF_OFF { boolean check(FileOutputStream r) { + try { + byte buf[] = new byte[2]; + int len = 1; + r.write(buf, 0, len); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + GET_CHANNEL { boolean check(FileOutputStream r) { + r.getChannel(); + return true; + } }, + GET_FD { boolean check(FileOutputStream r) { + try { + r.getFD(); + return true; + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return false; + } + } }, + CLOSE { boolean check(FileOutputStream r) { + try { + r.close(); + return true; // No Exceptin thrown on Windows + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; // Exception thrown on solaris and linux + } + } }; + + abstract boolean check(FileOutputStream r); + + public static void main(String args[]) throws Exception { + + boolean failed = false; + + File f = new File(System.getProperty("test.dir", "."), + "f.txt"); + f.createNewFile(); + f.deleteOnExit(); + + FileOutputStream fis = new FileOutputStream(f); + if (testFileOutputStream(fis)) { + throw new Exception("Test failed for some of the operation{s}" + + " on FileOutputStream, check the messages"); + } + } + + private static boolean testFileOutputStream(FileOutputStream r) + throws Exception { + r.close(); + boolean failed = false; + boolean result; + System.out.println("Testing File:" + r); + for (OpsAfterClose op : OpsAfterClose.values()) { + result = op.check(r); + if (!result) { + failed = true; + } + System.out.println(op + ":" + result); + } + if (failed) { + System.out.println("Test failed for the failed operation{s}" + + " above for the FileOutputStream:" + r); + } + return failed; + } +} diff --git a/test/java/io/FilePermission/SpecTests.java b/test/java/io/FilePermission/SpecTests.java new file mode 100644 index 0000000000..1bacbd7e75 --- /dev/null +++ b/test/java/io/FilePermission/SpecTests.java @@ -0,0 +1,68 @@ +/* + * 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 4955804 + * @summary Tests for FilePermission constructor spec for null + * and empty String parameters + */ + +import java.io.*; + +public class SpecTests { + + public static void main(String args[]) throws Exception { + String ILE = "java.lang.IllegalArgumentException"; + String NPE = "java.lang.NullPointerException"; + + String names[] = {"", null, "foo", "foo", "foo", "foo"}; + String actions[] = {"read", "read", "", null, "junk", + "read,write,execute,delete,rename"}; + String exps[] = { null, NPE, ILE, ILE, ILE, ILE }; + + FilePermission permit; + for (int i = 0; i < names.length; i++) { + try { + permit = new FilePermission(names[i], actions[i]); + } catch (Exception e) { + if (exps[i] == null) { + throw e; + } else if (!((e.getClass().getName()).equals(exps[i]))) { + throw new Exception("Expecting: " + exps[i] + + " for name:" + names[i] + + " actions:" + actions[i]); + } else { + System.out.println(names[i] + ", [" + actions[i] + "] " + + "resulted in " + exps[i] + " as Expected"); + } + } + if (exps[i] == null) { + System.out.println(names[i] + ", [" + actions[i] + "] " + + "resulted in No Exception as Expected"); + } + } + + } +} diff --git a/test/java/io/FilterOutputStream/BoundsCheck.java b/test/java/io/FilterOutputStream/BoundsCheck.java new file mode 100644 index 0000000000..1d3690454b --- /dev/null +++ b/test/java/io/FilterOutputStream/BoundsCheck.java @@ -0,0 +1,93 @@ +/* + * Copyright 1999 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 4176379 + @summary Ensure that FilterOutputStream.write(byte[], int, int) with + negative len, throws appropriate exception. + */ + +import java.io.*; + +public class BoundsCheck { + static class DummyFilterStream extends FilterOutputStream { + + public DummyFilterStream(OutputStream o) { + super(o); + } + + public void write(int val) throws IOException { + super.write(val + 1); + } + } + + public static void main(String[] args) throws Exception { + byte data[] = {90, 91, 92, 93, 94, 95, 96, 97, 98, 99}; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + DummyFilterStream dfs = new DummyFilterStream(bos); + boolean caughtException = false; + + // -ve length + try { + dfs.write(data, 0, -5); + } catch (IndexOutOfBoundsException ie) { + caughtException = true; + } finally { + if (!caughtException) + throw new RuntimeException("Test failed"); + } + + // -ve offset + caughtException = false; + try { + dfs.write(data, -2, 5); + } catch (IndexOutOfBoundsException ie) { + caughtException = true; + } finally { + if (!caughtException) + throw new RuntimeException("Test failed"); + } + + // off + len > data.length + caughtException = false; + try { + dfs.write(data, 6, 5); + } catch (IndexOutOfBoundsException ie) { + caughtException = true; + } finally { + if (!caughtException) + throw new RuntimeException("Test failed"); + } + + // null data + caughtException = false; + try { + dfs.write(null, 0, 5); + } catch (NullPointerException re) { + caughtException = true; + } finally { + if (!caughtException) + throw new RuntimeException("Test failed"); + } + } +} diff --git a/test/java/io/FilterOutputStream/Write.java b/test/java/io/FilterOutputStream/Write.java new file mode 100644 index 0000000000..c5faf3348c --- /dev/null +++ b/test/java/io/FilterOutputStream/Write.java @@ -0,0 +1,64 @@ +/* + * Copyright 1998 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 4015830 + @summary Ensure that FilterOutputStream.write(byte[], int, int) calls the + one-argument write method in the same class + */ + +import java.io.OutputStream; +import java.io.FilterOutputStream; +import java.io.IOException; + + +public class Write { + + static class F extends FilterOutputStream { + + public F(OutputStream o) { + super(o); + } + + public void write(int b) { + System.err.println("Ignoring write of " + b); + } + + } + + static class Sink extends OutputStream { + + public void write(int b) { + throw new RuntimeException("Filter stream directly invoked" + + " write(int) method of underlying" + + " stream"); + } + + } + + public static void main(String[] args) throws Exception { + OutputStream f = new F(new Sink()); + f.write(new byte[] { 1, 2, 3 }, 0, 3); + } + +} diff --git a/test/java/io/IOException/LastErrorString.java b/test/java/io/IOException/LastErrorString.java new file mode 100644 index 0000000000..d2d9eb88f8 --- /dev/null +++ b/test/java/io/IOException/LastErrorString.java @@ -0,0 +1,265 @@ +/* + * Copyright 1998 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 4167937 + @summary Test code paths that use the JVM_LastErrorString procedure + */ + +import java.io.IOException; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.RandomAccessFile; + + +public class LastErrorString { + + static String UNWRITEABLE_DIR; + static String UNREADABLE_FILE; + static String READABLE_FILE; + static String WRITEABLE_FILE; + static String INVALID_PATH; + + static { + if (File.separatorChar == '/') { + UNWRITEABLE_DIR = "/etc/dfs"; + UNREADABLE_FILE = "/etc/shadow"; + } else if (File.separatorChar == '\\') { + UNREADABLE_FILE = "c:/pagefile.sys"; + UNWRITEABLE_DIR = "z:/fooBAR/baz/GORP"; + } else { + throw new RuntimeException("What kind of system is this?"); + } + File d = new File(System.getProperty("test.src", ".")); + READABLE_FILE = new File(d, "LastErrorString.java").getPath(); + WRITEABLE_FILE = "x.LastErrorString"; + String s = "foo/"; + for (;;) { + s = s + s; + if (s.length() > 8192) break; + } + s += "bar"; + INVALID_PATH = s; + } + + + static abstract class Test { + + String name; + + public Test(String name) { + this.name = name; + } + + abstract public void run() throws IOException; + + public void go() throws IOException { + try { + this.run(); + } catch (IOException x) { + System.err.println(name); + System.err.println(" " + x); + return; + } + System.err.println("WARNING: No exception for " + name); + } + + } + + static abstract class ClosedFISTest extends Test { + + FileInputStream in; + + public ClosedFISTest(String name) { + super("FileInputStream." + name); + } + + public void go() throws IOException { + this.in = new FileInputStream(READABLE_FILE); + this.in.close(); + super.go(); + } + + } + + static abstract class ClosedFOSTest extends Test { + + FileOutputStream out; + + public ClosedFOSTest(String name) { + super("FileOutputStream." + name); + } + + public void go() throws IOException { + this.out = new FileOutputStream(WRITEABLE_FILE); + this.out.close(); + super.go(); + } + + } + + static abstract class ClosedRAFTest extends Test { + + RandomAccessFile raf; + + public ClosedRAFTest(String name) { + super("RandomAccessFile." + name); + } + + public void go() throws IOException { + this.raf = new RandomAccessFile(WRITEABLE_FILE, "rw"); + this.raf.close(); + super.go(); + } + + } + + static abstract class ReadOnlyRAFTest extends Test { + + RandomAccessFile raf; + + public ReadOnlyRAFTest(String name) { + super("RandomAccessFile." + name); + } + + public void go() throws IOException { + this.raf = new RandomAccessFile(READABLE_FILE, "r"); + super.go(); + this.raf.close(); + } + + } + + + static void go() throws Exception { + + new Test("File.createNewFile") { + public void run() throws IOException { + new File(UNWRITEABLE_DIR, "foo").createNewFile(); + }}.go(); + + new Test("File.getCanonicalpath") { + public void run() throws IOException { + new File(INVALID_PATH).getCanonicalPath(); + }}.go(); + + new Test("FileInputStream(file)") { + public void run() throws IOException { + new FileInputStream(UNREADABLE_FILE); + }}.go(); + + new Test("FileInputStream(dir)") { + public void run() throws IOException { + new FileInputStream("."); + }}.go(); + + new ClosedFISTest("read()") { + public void run() throws IOException { + in.read(); + }}.go(); + + new ClosedFISTest("read(byte[])") { + public void run() throws IOException { + byte[] b = new byte[10]; + in.read(b); + }}.go(); + + new ClosedFISTest("skip") { + public void run() throws IOException { + in.skip(10); + }}.go(); + + new ClosedFISTest("available") { + public void run() throws IOException { + in.available(); + }}.go(); + + new Test("FileOutputStream") { + public void run() throws IOException { + new FileOutputStream(UNREADABLE_FILE); + }}.go(); + + new ClosedFOSTest("write()") { + public void run() throws IOException { + out.write(10); + }}.go(); + + new ClosedFOSTest("write(byte[])") { + public void run() throws IOException { + out.write(new byte[] { 1, 2, 3 }); + }}.go(); + + new Test("RandomAccessFile") { + public void run() throws IOException { + new RandomAccessFile(UNREADABLE_FILE, "r"); + }}.go(); + + new ClosedRAFTest("getFilePointer") { + public void run() throws IOException { + raf.getFilePointer(); + }}.go(); + + new ClosedRAFTest("length") { + public void run() throws IOException { + raf.length(); + }}.go(); + + new ClosedRAFTest("seek") { + public void run() throws IOException { + raf.seek(20); + }}.go(); + + new ClosedRAFTest("setLength") { + public void run() throws IOException { + raf.setLength(0); + }}.go(); + + new ClosedRAFTest("readShort") { + public void run() throws IOException { + raf.readShort(); + }}.go(); + + new ClosedRAFTest("readInt") { + public void run() throws IOException { + raf.readInt(); + }}.go(); + + new ReadOnlyRAFTest("writeShort") { + public void run() throws IOException { + raf.writeShort(10); + }}.go(); + + new ReadOnlyRAFTest("getFilePointer") { + public void run() throws IOException { + raf.writeInt(10); + }}.go(); + + } + + + public static void main(String[] args) throws Exception { + go(); + } + +} diff --git a/test/java/io/InputStream/OpsAfterClose.java b/test/java/io/InputStream/OpsAfterClose.java new file mode 100644 index 0000000000..aed993d78b --- /dev/null +++ b/test/java/io/InputStream/OpsAfterClose.java @@ -0,0 +1,263 @@ +/* + * 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 4181483 + * @summary Test if InputStream methods will check if the stream + * has been closed. + */ + +import java.io.*; + +public enum OpsAfterClose { + + READ { boolean check(InputStream is) { + try { + int read = is.read(); + System.out.println("read returns: " + read); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + + READ_BUF { boolean check(InputStream is) { + try { + byte buf[] = new byte[2]; + int read = is.read(buf); + System.out.println("read(buf) returns: " + read); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + READ_BUF_OFF { boolean check(InputStream is) { + try { + byte buf[] = new byte[2]; + int len = 1; + int read = is.read(buf, 0, len); + System.out.println("read(buf, 0, len) returns: " + read); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + AVAILABLE { boolean check(InputStream is) { + try { + int avail = is.available(); + System.out.println("available() returns: " + avail); + return false; + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + } }, + SKIP { boolean check(InputStream is) { + try { + long skipped = is.skip(1); + System.out.println("skip() returns: " + skipped); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + MARK { boolean check(InputStream is) { + is.mark(20); + return true; + } }, + RESET { boolean check(InputStream is) { + try { + is.reset(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + MARK_SUPPORTED { boolean check(InputStream is) { + is.markSupported(); + return true; + } }, + CLOSE { boolean check(InputStream is) { + try { + is.close(); + return true; // No Exception thrown on windows for FileInputStream + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; // Exception thrown on solaris and linux for FileInputStream + } + } }; + + abstract boolean check(InputStream is); + + public static void main(String args[]) throws Exception { + + boolean failed = false; + + File f = new File(System.getProperty("test.dir", "."), + "f.txt"); + f.createNewFile(); + f.deleteOnExit(); + + FileInputStream fis = new FileInputStream(f); + if (testInputStream(fis)) { + failed = true; + } + if (testFileInputStream(fis)) { + failed = true; + } + + BufferedInputStream bs = new BufferedInputStream( + new FileInputStream(f)); + if (testInputStream(bs)) { + failed = true; + } + + DataInputStream dis = new DataInputStream( + new FileInputStream(f)); + if (testInputStream(dis)) { + failed = true; + } + + PushbackInputStream pbis = new PushbackInputStream( + new ByteArrayInputStream(new byte[20])); + if (testInputStream(pbis)) { + failed = true; + } + + if (testPushbackInputStream(pbis)) { + failed = true; + } + + PipedInputStream pis = new PipedInputStream(new PipedOutputStream()); + if (testInputStream(pis)) { + failed = true; + } + + /** + * The SequenceInputStream and ObjectInputStream does not throw IOException + + SequenceInputStream sqis = new SequenceInputStream( + new FileInputStream(f), + new PipedInputStream(new PipedOutputStream()) + ); + if (testInputStream(sqis)) { + failed = true; + } + + String serStr = "abc"; + ObjectOutputStream oos = new ObjectOutputStream( + new FileOutputStream(f)); + oos.writeObject(serStr); + oos.close(); + + ObjectInputStream ois = new ObjectInputStream( + new FileInputStream(f)); + if (testInputStream(ois)) { + failed = true; + } + + */ + + if (failed) { + throw new Exception( + "Some Op for some Stream failed, check the failed status above"); + } + } + + private static boolean testInputStream(InputStream is) + throws Exception { + is.close(); + boolean failed = false; + boolean result; + System.out.println("Testing :" + is); + for (OpsAfterClose op : OpsAfterClose.values()) { + + if (op.equals(AVAILABLE) && (is instanceof PipedInputStream)) { + // skip the test as available() returns 0 + continue; + } + + result = op.check(is); + if (!result) { + failed = true; + } + System.out.println(op + ":" + result); + } + if (failed) { + System.out.println("Test failed for the failed operation{s}" + + " above for :" + is); + } + return failed; + } + + private static boolean testPushbackInputStream(PushbackInputStream pis) + throws Exception { + boolean failed = false; + try { + pis.unread(1); + System.out.println("Test failed for unread(int):" + pis); + failed = true; + } catch (IOException io) { + System.out.println("UNREAD(int):true"); + } + + byte buf[] = new byte[2]; + try { + pis.unread(buf, 0, 2); + System.out.println("Test failed for unread(buf, offset, len):" + + pis); + failed = true; + } catch (IOException io) { + System.out.println("UNREAD(buf, offset, len):true"); + } + try { + pis.unread(buf); + System.out.println("Test failed for unread(char[] buf):" + pis); + failed = true; + } catch (IOException io) { + System.out.println("UNREAD(buf):true"); + } + return failed; + } + + private static boolean testFileInputStream(FileInputStream fis) + throws Exception { + boolean failed = false; + try { + fis.getFD(); + System.out.println("GetFD: true"); + } catch (IOException io) { + System.out.println("GetFD: false"); + failed = true; + } + fis.getChannel(); + System.out.println("GetChannel: true"); + return failed; + } +} diff --git a/test/java/io/InputStream/ReadParams.java b/test/java/io/InputStream/ReadParams.java new file mode 100644 index 0000000000..30ee9cb50b --- /dev/null +++ b/test/java/io/InputStream/ReadParams.java @@ -0,0 +1,225 @@ +/* + * Copyright 1998-1999 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 4008296 4008293 4190090 4193729 + * @summary Check for correct handling of parameters to + * XXXXInputStream.read(b, off, len). + * + */ + +import java.io.*; +import java.util.zip.ZipInputStream; +import java.util.zip.InflaterInputStream; +import java.util.zip.DeflaterOutputStream; + +public class ReadParams { + + /* check for correct handling of different values of off and len */ + public static void doTest(InputStream in) throws Exception { + + int off[] = {-1, -1, 0, 0, 33, 33, 0, 32, 32, 4, 1, 0, -1, + Integer.MAX_VALUE, 1, Integer.MIN_VALUE, + Integer.MIN_VALUE, 1}; + int len[] = {-1, 0, -1, 33, 0, 4, 32, 0, 4, 16, 31, 0, + Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, + 1, -1, Integer.MIN_VALUE}; + boolean results[] = { false, false, false, false, false, false, + true, true, false, true, true, true, false, + false, false, false, false, false}; + int numCases = off.length; + byte b[] = new byte[32]; + int numBad = 0; + + for(int i = 0; i < numCases; i++) { + try { + in.read(b , off[i] , len[i]); + } catch (IndexOutOfBoundsException aiobe) { + if (results[i]) { + System.err.println("Error:IndexOutOfBoundsException thrown"+ + " for read(b, " + off[i] + " " + len[i] + + " ) on " + in + "\nb.length = 32"); + numBad++; + } else { + /* System.err.println("PassE: " + off[i] + " " + len[i]); */ + } + continue; + } catch (OutOfMemoryError ome) { + System.err.println("Error: OutOfMemoryError in read(b, " + + off[i] + " " + len[i] + " ) on " + in + + "\nb.length = 32"); + numBad++; + continue; + } + if (!results[i]) { + System.err.println("Error:No IndexOutOfBoundsException thrown"+ + " for read(b, " + off[i] + " " + len[i] + + " ) on " + in + "\nb.length = 32"); + numBad++; + } else { + /* System.err.println("Pass: " + off[i] + " " + len[i]); */ + } + } + + if (numBad > 0) { + throw new RuntimeException(in + " Failed " + numBad + " cases"); + } else { + System.err.println("Successfully completed bounds tests on " + in); + } + } + + /* check for correct handling of null b */ + public static void doTest1(InputStream in) throws Exception { + byte b[] = null; + try { + in.read(b, 0, 32); + } catch (NullPointerException npe) { + System.err.println("SuccessFully completed null b test on " + in); + return; + } + throw new RuntimeException(in + " Failed null b test"); + } + + public static void main(String args[]) throws Exception{ + /* initialise stuff */ + File fn = new File("x.ReadBounds"); + FileOutputStream fout = new FileOutputStream(fn); + for (int i = 0; i < 32; i++) { + fout.write(i); + } + fout.close(); + + byte b[] = new byte[64]; + for(int i = 0; i < 64; i++) { + b[i] = 1; + } + + /* test all input streams */ + FileInputStream fis = new FileInputStream(fn); + doTest(fis); + doTest1(fis); + fis.close(); + + BufferedInputStream bis = + new BufferedInputStream(new MyInputStream(1024)); + doTest(bis); + doTest1(bis); + bis.close(); + + ByteArrayInputStream bais = new ByteArrayInputStream(b); + doTest(bais); + doTest1(bais); + bais.close(); + + FileOutputStream fos = new FileOutputStream(fn); + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeInt(12345); + oos.writeObject("Today"); + oos.writeObject(new Integer(32)); + ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fn)); + doTest(ois); + doTest1(ois); + ois.close(); + + DataInputStream dis = new DataInputStream(new MyInputStream(1024)); + doTest(dis); + doTest1(dis); + dis.close(); + + LineNumberInputStream lis = + new LineNumberInputStream(new MyInputStream(1024)); + doTest(lis); + doTest1(lis); + lis.close(); + + PipedOutputStream pos = new PipedOutputStream(); + PipedInputStream pis = new PipedInputStream(); + pos.connect(pis); + pos.write(b, 0, 64); + doTest(pis); + doTest1(pis); + pis.close(); + + PushbackInputStream pbis = + new PushbackInputStream(new MyInputStream(1024)); + doTest(pbis); + doTest1(pbis); + pbis.close(); + + StringBufferInputStream sbis = + new StringBufferInputStream(new String(b)); + doTest(sbis); + doTest1(sbis); + sbis.close(); + + SequenceInputStream sis = + new SequenceInputStream(new MyInputStream(1024), + new MyInputStream(1024)); + doTest(sis); + doTest1(sis); + sis.close(); + + ZipInputStream zis = new ZipInputStream(new FileInputStream(fn)); + doTest(zis); + doTest1(zis); + zis.close(); + + byte[] data = new byte[256]; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + DeflaterOutputStream dos = new DeflaterOutputStream(bos); + dos.write(data, 0, data.length); + dos.close(); + InflaterInputStream ifs = new InflaterInputStream + (new ByteArrayInputStream(bos.toByteArray())); + doTest(ifs); + doTest1(ifs); + ifs.close(); + + /* cleanup */ + fn.delete(); + } +} + +/* An InputStream class used in the above tests */ +class MyInputStream extends InputStream { + + private int readctr = 0; + private long endoffile; + + public MyInputStream(long endoffile) { + this.endoffile = endoffile; + } + + public int read() { + if (readctr == endoffile) { + return -1; + } + else { + readctr++; + return 0; + } + } + + public int available() { return 0; } +} diff --git a/test/java/io/InputStream/Skip.java b/test/java/io/InputStream/Skip.java new file mode 100644 index 0000000000..07be724690 --- /dev/null +++ b/test/java/io/InputStream/Skip.java @@ -0,0 +1,126 @@ +/* + * Copyright 1997 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 4016710 + @summary check for correct implementation of InputStream.skip + */ + +import java.io.*; + + +public class Skip{ + + private static void dotest(InputStream in , int curpos , + long total , long toskip , long expected) + throws Exception + { + + try { + + System.err.println("\n\nCurrently at pos = " + curpos + + "\nTotal bytes in the Stream = " + total + + "\nNumber of bytes to skip = " + toskip + + "\nNumber of bytes that should be skipped = " + + expected); + + long skipped = in.skip(toskip); + + System.err.println("actual number skipped: "+ skipped); + + if ((skipped < 0) || (skipped > expected)) { + throw new RuntimeException("Unexpected number of bytes skipped"); + } + + } catch (IOException e) { + System.err.println("IOException is thrown - possible result"); + } catch (Throwable e) { + throw new RuntimeException("Unexpected "+e+" is thrown!"); + } + + } + + public static void main( String argv[] ) throws Exception { + + MyInputStream in = new MyInputStream(11); + + /* test for negative skip */ + dotest(in, 0, 11, -23, 0); + + /* check for skip beyond EOF starting from before EOF */ + dotest(in, 0, 11, 20, 11); + + /* check for skip after EOF */ + dotest(in, -1, 11, 20, 0); + + in = new MyInputStream(9000); + /* check for skip equal to the read chunk size in InputStream.java */ + dotest(in, 0, 9000, 2048, 2048); + + /* check for skip greater than the read chunk size in InputStream.java */ + dotest(in, 2048, 9000, 5000, 5000); + + /* check for skip beyond EOF starting from before EOF */ + dotest(in, 7048, 9000, 5000, 1952); + + in = new MyInputStream(5000); + + /* check for multiple chunk reads */ + dotest(in, 0, 5000, 6000, 5000); + + /* + * check for skip larger than Integer.MAX_VALUE + * (Takes about 2 hrs on a sparc ultra-1) + * long total = (long)Integer.MAX_VALUE + (long)10; + * long toskip = total - (long)6; + * in = new MyInputStream(total); + * dotest(in, 0, total, toskip, toskip); + */ + + } + +} + +class MyInputStream extends InputStream { + + private int readctr = 0; + private long endoffile; + + public MyInputStream(long endoffile) { + this.endoffile = endoffile; + } + + public int read() { + + if (readctr == endoffile) { + return -1; + } + else { + readctr++; + return 0; + } + } + + public int available() { return 0; } +} diff --git a/test/java/io/InputStreamReader/GrowAfterEOF.java b/test/java/io/InputStreamReader/GrowAfterEOF.java new file mode 100644 index 0000000000..27d3c50bcb --- /dev/null +++ b/test/java/io/InputStreamReader/GrowAfterEOF.java @@ -0,0 +1,61 @@ +/* + * Copyright 1998 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 4101707 + @summary Test if fill() will behave correctly at EOF to + allow file to grow. +*/ + +import java.io.*; + +public class GrowAfterEOF { + public static void main(String[] args) throws Exception { + File input = new File(".", "TestEOFInput.txt"); + RandomAccessFile rf = new RandomAccessFile(input, "rw"); + BufferedReader r = new BufferedReader + (new InputStreamReader(new FileInputStream(input))); + + // write something + rf.writeBytes("a line"); + + // read till the end of file + while (r.readLine() != null); + + // append to the end of the file + rf.seek(rf.length()); + rf.writeBytes("new line"); + + // now try to read again + boolean readMore = false; + while (r.readLine() != null) { + readMore = true; + } + if (!readMore) { + input.delete(); + throw new Exception("Failed test: unable to read!"); + } else { + input.delete(); + } + } +} diff --git a/test/java/io/InputStreamReader/NullCreate.java b/test/java/io/InputStreamReader/NullCreate.java new file mode 100644 index 0000000000..6b2d3a071c --- /dev/null +++ b/test/java/io/InputStreamReader/NullCreate.java @@ -0,0 +1,45 @@ +/* + * Copyright 1998 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 4149935 + * @summary Create with a null stream should throw an exception + */ + +import java.io.*; + +public class NullCreate { + + public static void main(String args[]) + { + try{ + InputStreamReader osw = new InputStreamReader(null); + } catch (NullPointerException e){ + // No problem - null create argument caught + return; + } + throw new RuntimeException("Create with null did not throw an error"); + } + +} diff --git a/test/java/io/InputStreamReader/One.java b/test/java/io/InputStreamReader/One.java new file mode 100644 index 0000000000..d7e8322a25 --- /dev/null +++ b/test/java/io/InputStreamReader/One.java @@ -0,0 +1,106 @@ +/* + * 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 4401798 + @summary Check that single-character reads work properly + */ + + +import java.io.*; + + +public class One { + + private static abstract class Test { + + InputStreamReader isr; + StringBuffer sb; + String expect; + + Test(byte[] in, String expect) throws Exception { + isr = new InputStreamReader(new ByteArrayInputStream(in), "UTF-8"); + sb = new StringBuffer(expect.length()); + this.expect = expect; + go(); + } + + void go() throws Exception { + read(); + if (!expect.equals(sb.toString())) + throw new Exception("Expected " + expect + + ", got " + sb.toString()); + } + + abstract void read() throws IOException; + + } + + + private static void test(String expect) throws Exception { + byte[] in = expect.getBytes("UTF-8"); + + new Test(in, expect) { + public void read() throws IOException { + for (;;) { + int c; + if ((c = isr.read()) == -1) + break; + sb.append((char)c); + } + }}; + + new Test(in, expect) { + public void read() throws IOException { + for (;;) { + char[] cb = new char[1]; + if (isr.read(cb) == -1) + break; + sb.append(cb[0]); + } + }}; + + new Test(in, expect) { + public void read() throws IOException { + for (;;) { + char[] cb = new char[2]; + int n; + if ((n = isr.read(cb)) == -1) + break; + sb.append(cb[0]); + if (n == 2) + sb.append(cb[1]); + } + }}; + + } + + public static void main(String[] args) throws Exception { + test("x"); + test("xy"); + test("xyz"); + test("\ud800\udc00"); + test("x\ud800\udc00"); + } + +} diff --git a/test/java/io/InputStreamReader/ReadOffset.java b/test/java/io/InputStreamReader/ReadOffset.java new file mode 100644 index 0000000000..3fcc759c0a --- /dev/null +++ b/test/java/io/InputStreamReader/ReadOffset.java @@ -0,0 +1,43 @@ +/* + * Copyright 2000 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 4399447 + * @summary Ensure that read offsets work properly + */ + +import java.io.*; + +public class ReadOffset { + + public static void main(String[] args) throws Exception { + InputStream is + = new ByteArrayInputStream("foo bar".getBytes("US-ASCII")); + InputStreamReader isr = new InputStreamReader(is, "US-ASCII"); + char[] cbuf = new char[100]; + int n; + System.out.println(n = isr.read(cbuf, 0, 3)); + System.out.println(isr.read(cbuf, n, cbuf.length - n)); + } + +} diff --git a/test/java/io/LineNumberInputStream/Available.java b/test/java/io/LineNumberInputStream/Available.java new file mode 100644 index 0000000000..f44057a01f --- /dev/null +++ b/test/java/io/LineNumberInputStream/Available.java @@ -0,0 +1,69 @@ +/* + * Copyright 1997 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 1238944 + @summary Check for correct implementation of LineNumberInputStream.available + */ + +import java.io.*; + + +public class Available { + + static void check(int a, int bound) throws Exception { + if (a > bound) { + throw new Exception("Available returned " + a + " > " + bound); + } + } + + public static void main(String args[]) throws Exception { + LineNumberInputStream in = new LineNumberInputStream(new MyInStream()); + check(in.available(), 5); + in.read(); + in.read(); + check(in.available(), 4); + in.read(); + in.read(); + in.read(); + check(in.available(), 2); + } + +} + + +class MyInStream extends InputStream { + + char[] buf = {'a', 'b', 'c', 'd', '\n', + 'e', 'f', '\r', '\n', 'g'}; + int ctr = 0; + + public int read() { + return ((ctr == 12) ? -1 : (int)buf[ctr++]); + } + + public int available() { + return (10 - ctr); + } + +} diff --git a/test/java/io/LineNumberInputStream/MarkReset.java b/test/java/io/LineNumberInputStream/MarkReset.java new file mode 100644 index 0000000000..61779be410 --- /dev/null +++ b/test/java/io/LineNumberInputStream/MarkReset.java @@ -0,0 +1,47 @@ +/* + * Copyright 1998 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 4017159 + @summary Check if mark and reset of LineNumberInputStream works + correctly. + */ + +import java.io.*; + +public class MarkReset { + + public static void main(String[] args) throws Exception { + LineNumberInputStream in = new + LineNumberInputStream(new StringBufferInputStream("\rabcd")); + + in.read(); + in.mark(100); + int b1 = in.read(); + in.reset(); + int b2 = in.read(); + + if(b1 != b2) + throw new Exception("Read Wrong bytes: Expected " + b1 + " got " + b2); + } +} diff --git a/test/java/io/LineNumberInputStream/Skip.java b/test/java/io/LineNumberInputStream/Skip.java new file mode 100644 index 0000000000..046717979b --- /dev/null +++ b/test/java/io/LineNumberInputStream/Skip.java @@ -0,0 +1,102 @@ +/* + * Copyright 1997 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 4085939 + @summary Check for the correct behaviour of LineNumberInputStream.skip + */ + +import java.io.*; + + +public class Skip{ + + private static void dotest(LineNumberInputStream in , int curpos , + long total , long toskip , long expected) + throws Exception + { + + try { + + System.err.println("\n\nCurrently at pos = " + curpos + + "\nTotal bytes in the Stream = " + total + + "\nNumber of bytes to skip = " + toskip + + "\nNumber of bytes that should be skipped = " + + expected); + + long skipped = in.skip(toskip); + + System.err.println("actual number skipped: "+ skipped); + + if ((skipped < 0) || (skipped > expected)) { + throw new RuntimeException("Unexpected number of bytes skipped"); + } + + } catch (IOException e) { + System.err.println("IOException is thrown - possible result"); + } catch (Throwable e) { + throw new RuntimeException("Unexpected "+e+" is thrown!"); + } + + } + + public static void main( String argv[] ) throws Exception { + + LineNumberInputStream in = new LineNumberInputStream(new MyInputStream(11)); + + /* test for negative skip */ + dotest(in, 0, 11, -23, 0); + + /* check for skip beyond EOF starting from before EOF */ + dotest(in, 0, 11, 20, 11); + + /* check for skip after EOF */ + dotest(in, -1, 11, 20, 0); + + } + +} + +class MyInputStream extends InputStream { + + private int readctr = 0; + private long endoffile; + + public MyInputStream(long endoffile) { + this.endoffile = endoffile; + } + + public int read() { + + if (readctr == endoffile) { + return -1; + } + else { + readctr++; + return 0; + } + } + + public int available() { return 0; } +} diff --git a/test/java/io/LineNumberInputStream/SkipEOL.java b/test/java/io/LineNumberInputStream/SkipEOL.java new file mode 100644 index 0000000000..af63981664 --- /dev/null +++ b/test/java/io/LineNumberInputStream/SkipEOL.java @@ -0,0 +1,61 @@ +/* + * Copyright 1997 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 4091810 + @summary Test for correct CR/LF handling in LineNumberInputStream.skip + */ + +import java.io.LineNumberInputStream; +import java.io.ByteArrayInputStream; + +public class SkipEOL { + + public static void main( String argv[] ) throws Exception { + byte[] data = {12, 13, 10, 23, 11, 13, 12, 10, 13}; + byte[] expected = {12, 10, 23, 11, 10, 12, 10, 10}; + + LineNumberInputStream in = + new LineNumberInputStream(new ByteArrayInputStream(data)); + long skipped = in.skip(3); // skip 3 bytes + if ((skipped == 3) && ((in.read()) != 11)) { + throw new + RuntimeException("LineNumberInputStream.skip - " + + "unexpected results!"); + } + + in = new LineNumberInputStream(new ByteArrayInputStream(data)); + for (int i = 0; i < 8; i++) { + if (in.read() != expected[i]) { + throw new + RuntimeException("LineNumberInputStream.read - " + + "unexpected results!"); + } + } + + System.err.println("Test completed successfully"); + + } + +} diff --git a/test/java/io/LineNumberReader/MarkReset.java b/test/java/io/LineNumberReader/MarkReset.java new file mode 100644 index 0000000000..1302eb6409 --- /dev/null +++ b/test/java/io/LineNumberReader/MarkReset.java @@ -0,0 +1,77 @@ +/* + * Copyright 1998 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 4081733 + @summary Make sure LineNumberReader returns right line number + when mark and reset are used + */ + + +import java.io.*; + +public class MarkReset { + + /** + * This program creates a LineNumberReader and tries to find all + * the non-whitespace characters in the file. + */ + public static void main(String[] args) throws Exception { + int n, line; + + LineNumberReader reader = new LineNumberReader + (new StringReader("0\r\n1\r2\n3\r\n\r5\r\r7\n\n9")); + for (n = 0; n < 7; n++) { + skipWhiteSpace(reader); /* Skip all whitespace */ + int c = reader.read(); /* Read the non-whitespace character */ + if (c < 0) { /* Might be eof */ + break; /* It is. Get out of the loop */ + } + line = reader.getLineNumber(); + if(line != (c - 48)) { + throw new Exception("Failed test : Line number expected " + + (c - 48) + " got " + line ); + } + } + } + + /** + * Skip whitespace in the file. Mark and reset + */ + private static void skipWhiteSpace(LineNumberReader reader) throws IOException { + while (true) { + /* Mark in case the character is not whitespace */ + reader.mark(10); + /* Read the character */ + int c = reader.read(); + if (Character.isWhitespace((char) c)) { + /* Loop while in whitespace */ + continue; + } + + /* Return to the non-whitespace character */ + reader.reset(); + break; + } + } +} diff --git a/test/java/io/LineNumberReader/Read.java b/test/java/io/LineNumberReader/Read.java new file mode 100644 index 0000000000..3e05677cd2 --- /dev/null +++ b/test/java/io/LineNumberReader/Read.java @@ -0,0 +1,52 @@ +/* + * Copyright 1998 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 4074875 4063511 + @summary Make sure LineNumberReader.read(char, int , int) will increase + the linenumber correctly. + */ + +import java.io.*; + +public class Read { + + public static void main(String[] args) throws Exception { + String s = "aaaa\nbbb\n"; + char[] buf = new char[5]; + int n = 0; + int line = 0; + + LineNumberReader r = new LineNumberReader(new StringReader(s)); + + do { + n = r.read(buf, 0, buf.length); + } while (n > 0); + + line = r.getLineNumber(); + + if (line != 2) + throw new Exception("Failed test: Expected line number: 2, got " + + line); + } +} diff --git a/test/java/io/LineNumberReader/ReadReadLine.java b/test/java/io/LineNumberReader/ReadReadLine.java new file mode 100644 index 0000000000..97cc4ee242 --- /dev/null +++ b/test/java/io/LineNumberReader/ReadReadLine.java @@ -0,0 +1,56 @@ +/* + * Copyright 1998 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 4103987 + @summary Tests LineNumberReader to see if the lineNumber is set correctly + when mixed reads and readLines are used. + */ + +import java.io.*; + +public class ReadReadLine { + + public static void main(String[] args) throws Exception { + test("\r\n", 1); + test("\r\r\n", 2); + test("\r\n\n\n", 3); + } + + static void test(String s, int good) throws Exception { + int c, line; + + LineNumberReader r = new LineNumberReader(new StringReader(s), 2); + if ((c = r.read()) >= 0) { + while (r.readLine() != null) + ; + } + + line = r.getLineNumber(); + + if(line != good) { + throw new Exception("Failed test: Expected line number " + + good + " Got: " + line); + } + } +} diff --git a/test/java/io/LineNumberReader/Skip.java b/test/java/io/LineNumberReader/Skip.java new file mode 100644 index 0000000000..9f56a60858 --- /dev/null +++ b/test/java/io/LineNumberReader/Skip.java @@ -0,0 +1,63 @@ +/* + * Copyright 1998-1999 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 4091789 4173233 + * @summary Check if LineNumberReader will skip right number of characters and + * also check for negative values + */ + +import java.io.*; + +public class Skip { + + public static void main(String[] args) throws Exception { + + int linenum = 0; + long nchars = 164 * 50; + + File f = new File(System.getProperty("test.src", "."), + "SkipInput.txt"); + LineNumberReader reader = new LineNumberReader(new FileReader(f)); + + boolean testFailed = false; + try { + reader.skip(-10); + testFailed = true; + } catch (IllegalArgumentException e) { + } + catch (Exception e) { + testFailed = true; + } + if (testFailed) + throw new Exception("Failed test: Negative value for skip()"); + + long realnum = reader.skip(nchars); + linenum = reader.getLineNumber(); + + if (linenum != 164) { + throw new Exception("Failed test: Should skip 164, really skipped " + + linenum + "lines"); + } + } +} diff --git a/test/java/io/LineNumberReader/SkipInput.txt b/test/java/io/LineNumberReader/SkipInput.txt new file mode 100644 index 0000000000..c690b80da9 --- /dev/null +++ b/test/java/io/LineNumberReader/SkipInput.txt @@ -0,0 +1,400 @@ +This line of text is 50 characters in length 0 +This line of text is 50 characters in length 1 +This line of text is 50 characters in length 2 +This line of text is 50 characters in length 3 +This line of text is 50 characters in length 4 +This line of text is 50 characters in length 5 +This line of text is 50 characters in length 6 +This line of text is 50 characters in length 7 +This line of text is 50 characters in length 8 +This line of text is 50 characters in length 9 +This line of text is 50 characters in length 10 +This line of text is 50 characters in length 11 +This line of text is 50 characters in length 12 +This line of text is 50 characters in length 13 +This line of text is 50 characters in length 14 +This line of text is 50 characters in length 15 +This line of text is 50 characters in length 16 +This line of text is 50 characters in length 17 +This line of text is 50 characters in length 18 +This line of text is 50 characters in length 19 +This line of text is 50 characters in length 20 +This line of text is 50 characters in length 21 +This line of text is 50 characters in length 22 +This line of text is 50 characters in length 23 +This line of text is 50 characters in length 24 +This line of text is 50 characters in length 25 +This line of text is 50 characters in length 26 +This line of text is 50 characters in length 27 +This line of text is 50 characters in length 28 +This line of text is 50 characters in length 29 +This line of text is 50 characters in length 30 +This line of text is 50 characters in length 31 +This line of text is 50 characters in length 32 +This line of text is 50 characters in length 33 +This line of text is 50 characters in length 34 +This line of text is 50 characters in length 35 +This line of text is 50 characters in length 36 +This line of text is 50 characters in length 37 +This line of text is 50 characters in length 38 +This line of text is 50 characters in length 39 +This line of text is 50 characters in length 40 +This line of text is 50 characters in length 41 +This line of text is 50 characters in length 42 +This line of text is 50 characters in length 43 +This line of text is 50 characters in length 44 +This line of text is 50 characters in length 45 +This line of text is 50 characters in length 46 +This line of text is 50 characters in length 47 +This line of text is 50 characters in length 48 +This line of text is 50 characters in length 49 +This line of text is 50 characters in length 50 +This line of text is 50 characters in length 51 +This line of text is 50 characters in length 52 +This line of text is 50 characters in length 53 +This line of text is 50 characters in length 54 +This line of text is 50 characters in length 55 +This line of text is 50 characters in length 56 +This line of text is 50 characters in length 57 +This line of text is 50 characters in length 58 +This line of text is 50 characters in length 59 +This line of text is 50 characters in length 60 +This line of text is 50 characters in length 61 +This line of text is 50 characters in length 62 +This line of text is 50 characters in length 63 +This line of text is 50 characters in length 64 +This line of text is 50 characters in length 65 +This line of text is 50 characters in length 66 +This line of text is 50 characters in length 67 +This line of text is 50 characters in length 68 +This line of text is 50 characters in length 69 +This line of text is 50 characters in length 70 +This line of text is 50 characters in length 71 +This line of text is 50 characters in length 72 +This line of text is 50 characters in length 73 +This line of text is 50 characters in length 74 +This line of text is 50 characters in length 75 +This line of text is 50 characters in length 76 +This line of text is 50 characters in length 77 +This line of text is 50 characters in length 78 +This line of text is 50 characters in length 79 +This line of text is 50 characters in length 80 +This line of text is 50 characters in length 81 +This line of text is 50 characters in length 82 +This line of text is 50 characters in length 83 +This line of text is 50 characters in length 84 +This line of text is 50 characters in length 85 +This line of text is 50 characters in length 86 +This line of text is 50 characters in length 87 +This line of text is 50 characters in length 88 +This line of text is 50 characters in length 89 +This line of text is 50 characters in length 90 +This line of text is 50 characters in length 91 +This line of text is 50 characters in length 92 +This line of text is 50 characters in length 93 +This line of text is 50 characters in length 94 +This line of text is 50 characters in length 95 +This line of text is 50 characters in length 96 +This line of text is 50 characters in length 97 +This line of text is 50 characters in length 98 +This line of text is 50 characters in length 99 +This line of text is 50 characters in length 100 +This line of text is 50 characters in length 101 +This line of text is 50 characters in length 102 +This line of text is 50 characters in length 103 +This line of text is 50 characters in length 104 +This line of text is 50 characters in length 105 +This line of text is 50 characters in length 106 +This line of text is 50 characters in length 107 +This line of text is 50 characters in length 108 +This line of text is 50 characters in length 109 +This line of text is 50 characters in length 110 +This line of text is 50 characters in length 111 +This line of text is 50 characters in length 112 +This line of text is 50 characters in length 113 +This line of text is 50 characters in length 114 +This line of text is 50 characters in length 115 +This line of text is 50 characters in length 116 +This line of text is 50 characters in length 117 +This line of text is 50 characters in length 118 +This line of text is 50 characters in length 119 +This line of text is 50 characters in length 120 +This line of text is 50 characters in length 121 +This line of text is 50 characters in length 122 +This line of text is 50 characters in length 123 +This line of text is 50 characters in length 124 +This line of text is 50 characters in length 125 +This line of text is 50 characters in length 126 +This line of text is 50 characters in length 127 +This line of text is 50 characters in length 128 +This line of text is 50 characters in length 129 +This line of text is 50 characters in length 130 +This line of text is 50 characters in length 131 +This line of text is 50 characters in length 132 +This line of text is 50 characters in length 133 +This line of text is 50 characters in length 134 +This line of text is 50 characters in length 135 +This line of text is 50 characters in length 136 +This line of text is 50 characters in length 137 +This line of text is 50 characters in length 138 +This line of text is 50 characters in length 139 +This line of text is 50 characters in length 140 +This line of text is 50 characters in length 141 +This line of text is 50 characters in length 142 +This line of text is 50 characters in length 143 +This line of text is 50 characters in length 144 +This line of text is 50 characters in length 145 +This line of text is 50 characters in length 146 +This line of text is 50 characters in length 147 +This line of text is 50 characters in length 148 +This line of text is 50 characters in length 149 +This line of text is 50 characters in length 150 +This line of text is 50 characters in length 151 +This line of text is 50 characters in length 152 +This line of text is 50 characters in length 153 +This line of text is 50 characters in length 154 +This line of text is 50 characters in length 155 +This line of text is 50 characters in length 156 +This line of text is 50 characters in length 157 +This line of text is 50 characters in length 158 +This line of text is 50 characters in length 159 +This line of text is 50 characters in length 160 +This line of text is 50 characters in length 161 +This line of text is 50 characters in length 162 +This line of text is 50 characters in length 163 +This line of text is 50 characters in length 164 +This line of text is 50 characters in length 165 +This line of text is 50 characters in length 166 +This line of text is 50 characters in length 167 +This line of text is 50 characters in length 168 +This line of text is 50 characters in length 169 +This line of text is 50 characters in length 170 +This line of text is 50 characters in length 171 +This line of text is 50 characters in length 172 +This line of text is 50 characters in length 173 +This line of text is 50 characters in length 174 +This line of text is 50 characters in length 175 +This line of text is 50 characters in length 176 +This line of text is 50 characters in length 177 +This line of text is 50 characters in length 178 +This line of text is 50 characters in length 179 +This line of text is 50 characters in length 180 +This line of text is 50 characters in length 181 +This line of text is 50 characters in length 182 +This line of text is 50 characters in length 183 +This line of text is 50 characters in length 184 +This line of text is 50 characters in length 185 +This line of text is 50 characters in length 186 +This line of text is 50 characters in length 187 +This line of text is 50 characters in length 188 +This line of text is 50 characters in length 189 +This line of text is 50 characters in length 190 +This line of text is 50 characters in length 191 +This line of text is 50 characters in length 192 +This line of text is 50 characters in length 193 +This line of text is 50 characters in length 194 +This line of text is 50 characters in length 195 +This line of text is 50 characters in length 196 +This line of text is 50 characters in length 197 +This line of text is 50 characters in length 198 +This line of text is 50 characters in length 199 +This line of text is 50 characters in length 200 +This line of text is 50 characters in length 201 +This line of text is 50 characters in length 202 +This line of text is 50 characters in length 203 +This line of text is 50 characters in length 204 +This line of text is 50 characters in length 205 +This line of text is 50 characters in length 206 +This line of text is 50 characters in length 207 +This line of text is 50 characters in length 208 +This line of text is 50 characters in length 209 +This line of text is 50 characters in length 210 +This line of text is 50 characters in length 211 +This line of text is 50 characters in length 212 +This line of text is 50 characters in length 213 +This line of text is 50 characters in length 214 +This line of text is 50 characters in length 215 +This line of text is 50 characters in length 216 +This line of text is 50 characters in length 217 +This line of text is 50 characters in length 218 +This line of text is 50 characters in length 219 +This line of text is 50 characters in length 220 +This line of text is 50 characters in length 221 +This line of text is 50 characters in length 222 +This line of text is 50 characters in length 223 +This line of text is 50 characters in length 224 +This line of text is 50 characters in length 225 +This line of text is 50 characters in length 226 +This line of text is 50 characters in length 227 +This line of text is 50 characters in length 228 +This line of text is 50 characters in length 229 +This line of text is 50 characters in length 230 +This line of text is 50 characters in length 231 +This line of text is 50 characters in length 232 +This line of text is 50 characters in length 233 +This line of text is 50 characters in length 234 +This line of text is 50 characters in length 235 +This line of text is 50 characters in length 236 +This line of text is 50 characters in length 237 +This line of text is 50 characters in length 238 +This line of text is 50 characters in length 239 +This line of text is 50 characters in length 240 +This line of text is 50 characters in length 241 +This line of text is 50 characters in length 242 +This line of text is 50 characters in length 243 +This line of text is 50 characters in length 244 +This line of text is 50 characters in length 245 +This line of text is 50 characters in length 246 +This line of text is 50 characters in length 247 +This line of text is 50 characters in length 248 +This line of text is 50 characters in length 249 +This line of text is 50 characters in length 250 +This line of text is 50 characters in length 251 +This line of text is 50 characters in length 252 +This line of text is 50 characters in length 253 +This line of text is 50 characters in length 254 +This line of text is 50 characters in length 255 +This line of text is 50 characters in length 256 +This line of text is 50 characters in length 257 +This line of text is 50 characters in length 258 +This line of text is 50 characters in length 259 +This line of text is 50 characters in length 260 +This line of text is 50 characters in length 261 +This line of text is 50 characters in length 262 +This line of text is 50 characters in length 263 +This line of text is 50 characters in length 264 +This line of text is 50 characters in length 265 +This line of text is 50 characters in length 266 +This line of text is 50 characters in length 267 +This line of text is 50 characters in length 268 +This line of text is 50 characters in length 269 +This line of text is 50 characters in length 270 +This line of text is 50 characters in length 271 +This line of text is 50 characters in length 272 +This line of text is 50 characters in length 273 +This line of text is 50 characters in length 274 +This line of text is 50 characters in length 275 +This line of text is 50 characters in length 276 +This line of text is 50 characters in length 277 +This line of text is 50 characters in length 278 +This line of text is 50 characters in length 279 +This line of text is 50 characters in length 280 +This line of text is 50 characters in length 281 +This line of text is 50 characters in length 282 +This line of text is 50 characters in length 283 +This line of text is 50 characters in length 284 +This line of text is 50 characters in length 285 +This line of text is 50 characters in length 286 +This line of text is 50 characters in length 287 +This line of text is 50 characters in length 288 +This line of text is 50 characters in length 289 +This line of text is 50 characters in length 290 +This line of text is 50 characters in length 291 +This line of text is 50 characters in length 292 +This line of text is 50 characters in length 293 +This line of text is 50 characters in length 294 +This line of text is 50 characters in length 295 +This line of text is 50 characters in length 296 +This line of text is 50 characters in length 297 +This line of text is 50 characters in length 298 +This line of text is 50 characters in length 299 +This line of text is 50 characters in length 300 +This line of text is 50 characters in length 301 +This line of text is 50 characters in length 302 +This line of text is 50 characters in length 303 +This line of text is 50 characters in length 304 +This line of text is 50 characters in length 305 +This line of text is 50 characters in length 306 +This line of text is 50 characters in length 307 +This line of text is 50 characters in length 308 +This line of text is 50 characters in length 309 +This line of text is 50 characters in length 310 +This line of text is 50 characters in length 311 +This line of text is 50 characters in length 312 +This line of text is 50 characters in length 313 +This line of text is 50 characters in length 314 +This line of text is 50 characters in length 315 +This line of text is 50 characters in length 316 +This line of text is 50 characters in length 317 +This line of text is 50 characters in length 318 +This line of text is 50 characters in length 319 +This line of text is 50 characters in length 320 +This line of text is 50 characters in length 321 +This line of text is 50 characters in length 322 +This line of text is 50 characters in length 323 +This line of text is 50 characters in length 324 +This line of text is 50 characters in length 325 +This line of text is 50 characters in length 326 +This line of text is 50 characters in length 327 +This line of text is 50 characters in length 328 +This line of text is 50 characters in length 329 +This line of text is 50 characters in length 330 +This line of text is 50 characters in length 331 +This line of text is 50 characters in length 332 +This line of text is 50 characters in length 333 +This line of text is 50 characters in length 334 +This line of text is 50 characters in length 335 +This line of text is 50 characters in length 336 +This line of text is 50 characters in length 337 +This line of text is 50 characters in length 338 +This line of text is 50 characters in length 339 +This line of text is 50 characters in length 340 +This line of text is 50 characters in length 341 +This line of text is 50 characters in length 342 +This line of text is 50 characters in length 343 +This line of text is 50 characters in length 344 +This line of text is 50 characters in length 345 +This line of text is 50 characters in length 346 +This line of text is 50 characters in length 347 +This line of text is 50 characters in length 348 +This line of text is 50 characters in length 349 +This line of text is 50 characters in length 350 +This line of text is 50 characters in length 351 +This line of text is 50 characters in length 352 +This line of text is 50 characters in length 353 +This line of text is 50 characters in length 354 +This line of text is 50 characters in length 355 +This line of text is 50 characters in length 356 +This line of text is 50 characters in length 357 +This line of text is 50 characters in length 358 +This line of text is 50 characters in length 359 +This line of text is 50 characters in length 360 +This line of text is 50 characters in length 361 +This line of text is 50 characters in length 362 +This line of text is 50 characters in length 363 +This line of text is 50 characters in length 364 +This line of text is 50 characters in length 365 +This line of text is 50 characters in length 366 +This line of text is 50 characters in length 367 +This line of text is 50 characters in length 368 +This line of text is 50 characters in length 369 +This line of text is 50 characters in length 370 +This line of text is 50 characters in length 371 +This line of text is 50 characters in length 372 +This line of text is 50 characters in length 373 +This line of text is 50 characters in length 374 +This line of text is 50 characters in length 375 +This line of text is 50 characters in length 376 +This line of text is 50 characters in length 377 +This line of text is 50 characters in length 378 +This line of text is 50 characters in length 379 +This line of text is 50 characters in length 380 +This line of text is 50 characters in length 381 +This line of text is 50 characters in length 382 +This line of text is 50 characters in length 383 +This line of text is 50 characters in length 384 +This line of text is 50 characters in length 385 +This line of text is 50 characters in length 386 +This line of text is 50 characters in length 387 +This line of text is 50 characters in length 388 +This line of text is 50 characters in length 389 +This line of text is 50 characters in length 390 +This line of text is 50 characters in length 391 +This line of text is 50 characters in length 392 +This line of text is 50 characters in length 393 +This line of text is 50 characters in length 394 +This line of text is 50 characters in length 395 +This line of text is 50 characters in length 396 +This line of text is 50 characters in length 397 +This line of text is 50 characters in length 398 +This line of text is 50 characters in length 399 diff --git a/test/java/io/NegativeInitSize.java b/test/java/io/NegativeInitSize.java new file mode 100644 index 0000000000..272014e59f --- /dev/null +++ b/test/java/io/NegativeInitSize.java @@ -0,0 +1,87 @@ +/* + * Copyright 1998 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 4015701 4127654 + @summary Test if the constructor would detect + illegal arguments. +*/ + +import java.io.*; + +public class NegativeInitSize { + public static void main(String[] args) throws Exception { + try { + ByteArrayOutputStream bos = new ByteArrayOutputStream(-1); + } catch (IllegalArgumentException e) { + } catch (Exception e){ + System.out.println(e.getMessage()); + throw new Exception + ("ByteArrayOutputStream failed to detect negative init size"); + } + CharArrayReader CAR = new CharArrayReader("test".toCharArray()); + try { + PushbackReader pbr = new PushbackReader(CAR, -1); + } catch (IllegalArgumentException e) { + } catch (Exception e) { + System.out.println(e.getClass().getName()); + throw new Exception + ("PushbackReader failed to detect negative init size"); + } + + try { + PushbackInputStream pbis = new PushbackInputStream(null, -1); + } catch (IllegalArgumentException e) { + } catch (Exception e) { + throw new Exception + ("PushbackInputStream failed to detect negative init size"); + } + + ByteArrayOutputStream goodbos = new ByteArrayOutputStream(); + try { + BufferedOutputStream bos = new BufferedOutputStream(goodbos, -1); + } catch (IllegalArgumentException e) { + } catch (Exception e) { + throw new Exception + ("BufferedOutputStream failed to detect negative init size"); + } + + byte[] ba = { 123 }; + ByteArrayInputStream goodbis = new ByteArrayInputStream(ba); + try { + BufferedInputStream bis = new BufferedInputStream(goodbis, -1); + } catch (IllegalArgumentException e) { + } catch (Exception e) { + throw new Exception + ("BufferedInputStream failed to detect negative init size"); + } + + try { + CharArrayWriter caw = new CharArrayWriter(-1); + } catch (IllegalArgumentException e) { + } catch (Exception e) { + throw new Exception + ("CharArrayWriter failed to detect negative init size"); + } + } +} diff --git a/test/java/io/ObjectInputStream/ResolveProxyClass.java b/test/java/io/ObjectInputStream/ResolveProxyClass.java new file mode 100644 index 0000000000..b8f3835ab8 --- /dev/null +++ b/test/java/io/ObjectInputStream/ResolveProxyClass.java @@ -0,0 +1,104 @@ +/* + * Copyright 1999 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 4258644 + * @summary ObjectInputStream's default implementation of its protected + * resolveProxyClass method is specified to pass the first non-null class + * loader up the execution stack to the Proxy.getProxyClass method when + * it creates the specified proxy class; this test makes sure that it does + * that in situations where it hadn't in the past, such as if the defining + * loaders of the interfaces were all strict ancestors of the first + * non-null loader up the stack. + * @author Peter Jones + * + * @build ResolveProxyClass + * @run main ResolveProxyClass + */ + +import java.lang.reflect.*; +import java.io.*; + +public class ResolveProxyClass { + + /* + * This class is a dummy ObjectInputStream subclass that allows the + * test code to access ObjectInputStream's protected resolveProxyClass + * method directly. + */ + private static class TestObjectInputStream extends ObjectInputStream { + + TestObjectInputStream() throws IOException { + super(); + } + + protected Class resolveProxyClass(String[] interfaces) + throws IOException, ClassNotFoundException + { + return super.resolveProxyClass(interfaces); + } + } + + public static void main(String[] args) { + + System.err.println("\nRegression test for bug 4258644\n"); + + try { + + /* + * Set this thread's context class loader to null, so that the + * resolveProxyClass implementation cannot cheat by guessing that + * the context class loader is the appropriate loader to pass to + * the Proxy.getProxyClass method. + */ + Thread.currentThread().setContextClassLoader(null); + + /* + * Expect the proxy class to be defined in the system class + * loader, because that is the defining loader of this test + * code, and it should be the first loader on the stack when + * ObjectInputStream.resolveProxyClass gets executed. + */ + ClassLoader expectedLoader = ClassLoader.getSystemClassLoader(); + + TestObjectInputStream in = new TestObjectInputStream(); + Class proxyClass = in.resolveProxyClass( + new String[] { Runnable.class.getName() }); + ClassLoader proxyLoader = proxyClass.getClassLoader(); + System.err.println("proxy class \"" + proxyClass + + "\" defined in loader: " + proxyLoader); + + if (proxyLoader != expectedLoader) { + throw new RuntimeException( + "proxy class defined in loader: " + proxyLoader); + } + + System.err.println("\nTEST PASSED"); + + } catch (Throwable e) { + System.err.println("\nTEST FAILED:"); + e.printStackTrace(); + throw new RuntimeException("TEST FAILED: " + e.toString()); + } + } +} diff --git a/test/java/io/OutputStream/WriteParams.java b/test/java/io/OutputStream/WriteParams.java new file mode 100644 index 0000000000..ef0f165fa0 --- /dev/null +++ b/test/java/io/OutputStream/WriteParams.java @@ -0,0 +1,169 @@ +/* + * Copyright 1998-1999 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 1267039 1267043 4193729 + * @summary Check for correct handling of parameters to + * XXXXOutputStream.write(b, off, len). + * + */ + +import java.io.*; +import java.util.zip.DeflaterOutputStream; + +public class WriteParams { + + /* check for correct handling of different values of off and len */ + public static void doTest(OutputStream out) throws Exception { + + int off[] = {-1, -1, 0, 0, 33, 33, 0, 32, 32, 4, 1, 0, -1, + Integer.MAX_VALUE, 1, Integer.MIN_VALUE, + Integer.MIN_VALUE, 1}; + int len[] = {-1, 0, -1, 33, 0, 4, 32, 0, 4, 16, 31, 0, + Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, + 1, -1, Integer.MIN_VALUE}; + boolean results[] = { false, false, false, false, false, false, + true, true, false, true, true, true, false, + false, false, false, false, false}; + int numCases = off.length; + byte b[] = new byte[32]; + int numBad = 0; + + for(int i = 0; i < numCases; i++) { + try { + out.write(b , off[i] , len[i]); + } catch (IndexOutOfBoundsException aiobe) { + if (results[i]) { + System.err.println("Error:IndexOutOfBoundsException thrown"+ + " for write(b, " + off[i] + " " + len[i] + + " ) on " + out + "\nb.length = 32"); + numBad++; + } else { + /* System.err.println("PassE: " + off[i] + " " + len[i]); */ + } + continue; + } catch (OutOfMemoryError ome) { + System.err.println("Error: OutOfMemoryError in write(b, " + + off[i] + " " + len[i] + " ) on " + out + + "\nb.length = 32"); + numBad++; + continue; + } + if (!results[i]) { + System.err.println("Error:No IndexOutOfBoundsException thrown"+ + " for write(b, " + off[i] + " " + len[i] + + " ) on " + out + "\nb.length = 32"); + numBad++; + } else { + /* System.err.println("Pass: " + off[i] + " " + len[i]); */ + } + } + + if (numBad > 0) { + throw new RuntimeException(out + " Failed " + numBad + " cases"); + } else { + System.err.println("Successfully completed bounds tests on " + out); + } + } + + /* check for correct handling of null b */ + public static void doTest1(OutputStream out) throws Exception { + byte b[] = null; + try { + out.write(b, 0, 32); + } catch (NullPointerException npe) { + System.err.println("SuccessFully completed null b test on " + out); + return; + } + throw new RuntimeException(out + " Failed null b test"); + } + + public static void main(String args[]) throws Exception{ + /* initialise stuff here */ + File fn = new File("x.WriteBounds"); + FileOutputStream fout = new FileOutputStream(fn); + for (int i = 0; i < 32; i++) { + fout.write(i); + } + fout.close(); + + byte b[] = new byte[64]; + for(int i = 0; i < 64; i++) { + b[i] = 1; + } + + /* test for different output streams */ + FileOutputStream fos = new FileOutputStream(fn); + doTest(fos); + doTest1(fos); + fos.close(); + + ObjectOutputStream oos = new ObjectOutputStream(new MyOutputStream()); + doTest(oos); + doTest1(oos); + oos.close(); + + BufferedOutputStream bos = + new BufferedOutputStream(new MyOutputStream()); + doTest(bos); + doTest1(bos); + bos.close(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + doTest(baos); + doTest1(baos); + baos.close(); + + DataOutputStream dos = new DataOutputStream(new MyOutputStream()); + doTest(dos); + doTest1(dos); + dos.close(); + + PipedInputStream pis = new PipedInputStream(); + PipedOutputStream pos = new PipedOutputStream(); + pos.connect(pis); + doTest(pos); + doTest1(pos); + pos.close(); + + DeflaterOutputStream dfos = new DeflaterOutputStream(new MyOutputStream()); + doTest(dfos); + doTest1(dfos); + dfos.close(); + + /* cleanup */ + fn.delete(); + + } +} + +/* An OutputStream class used in the above tests */ +class MyOutputStream extends OutputStream { + + public MyOutputStream() { + } + + public void write(int b) throws IOException { + } +} diff --git a/test/java/io/OutputStreamWriter/BoundsCheck.java b/test/java/io/OutputStreamWriter/BoundsCheck.java new file mode 100644 index 0000000000..341ba63f5e --- /dev/null +++ b/test/java/io/OutputStreamWriter/BoundsCheck.java @@ -0,0 +1,72 @@ +/* + * Copyright 1999 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 4221901 + * @summary Ensure that negative offset or negative len parameter for + * write(String str, int off, int len) throws + * IndexOutOfBoundsException. + */ + +import java.io.*; + +public class BoundsCheck { + public static void main(String args[]) throws Exception { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + OutputStreamWriter osw = new OutputStreamWriter(bos); + String data = "Data to be written"; + char cdata[] = {'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'}; + + boolean caughtException = false; + try { + osw.write(data, -3, 5); + throw new RuntimeException("Test failed for negative offset"); + } catch (IndexOutOfBoundsException e){ } + + try { + osw.write(data, 3, -5); + throw new RuntimeException("Test failed for negative length"); + } catch (IndexOutOfBoundsException e){ } + + try { + osw.write(data, 3, 75); + throw new RuntimeException("Test failed for len+off > str.length"); + } catch (IndexOutOfBoundsException e){ } + + try { + osw.write(cdata, -3, 5); + throw new RuntimeException("Test failed for negative offset"); + } catch (IndexOutOfBoundsException e){ } + + try { + osw.write(cdata, 3, -5); + throw new RuntimeException("Test failed for negative length"); + } catch (IndexOutOfBoundsException e){ } + + try { + osw.write(cdata, 3, 75); + throw new RuntimeException("Test failed for len+off > str.length"); + } catch (IndexOutOfBoundsException e){ } + } +} diff --git a/test/java/io/OutputStreamWriter/Encode.java b/test/java/io/OutputStreamWriter/Encode.java new file mode 100644 index 0000000000..7e71ca161f --- /dev/null +++ b/test/java/io/OutputStreamWriter/Encode.java @@ -0,0 +1,75 @@ +/* + * 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 4802209 + * @summary check that the right utf-8 encoder is used + */ + +import java.io.*; +import java.net.*; + +public class Encode implements Runnable { + public static void main(String args[]) throws Exception { + new Encode(); + } + + Encode() throws Exception { + ss = new ServerSocket(0); + (new Thread(this)).start(); + String toEncode = "\uD800\uDC00 \uD801\uDC01 "; + String enc1 = URLEncoder.encode(toEncode, "UTF-8"); + byte bytes[] = {}; + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + InputStreamReader reader = new InputStreamReader( bais, "8859_1"); + String url = "http://localhost:" + Integer.toString(ss.getLocalPort()) + + "/missing.nothtml"; + HttpURLConnection uc = (HttpURLConnection)new URL(url).openConnection(); + uc.connect(); + String enc2 = URLEncoder.encode(toEncode, "UTF-8"); + if (!enc1.equals(enc2)) + throw new RuntimeException("test failed"); + uc.disconnect(); + } + + ServerSocket ss; + + public void run() { + try { + Socket s = ss.accept(); + BufferedReader in = new BufferedReader( + new InputStreamReader(s.getInputStream())); + String req = in.readLine(); + PrintStream out = new PrintStream(new BufferedOutputStream( + s.getOutputStream())); + out.print("HTTP/1.1 403 Forbidden\r\n"); + out.print("\r\n"); + out.flush(); + s.close(); + ss.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/test/java/io/OutputStreamWriter/NullCreate.java b/test/java/io/OutputStreamWriter/NullCreate.java new file mode 100644 index 0000000000..668c11141e --- /dev/null +++ b/test/java/io/OutputStreamWriter/NullCreate.java @@ -0,0 +1,45 @@ +/* + * Copyright 1998 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 4149935 + * @summary Create with a null stream should throw an exception + */ + +import java.io.*; + +public class NullCreate { + + public static void main(String args[]) + { + try{ + OutputStreamWriter osw = new OutputStreamWriter(null); + } catch (NullPointerException e){ + // No problem - null create argument caught + return; + } + throw new RuntimeException("Create with null did not throw an error"); + } + +} diff --git a/test/java/io/OutputStreamWriter/TestWrite.java b/test/java/io/OutputStreamWriter/TestWrite.java new file mode 100644 index 0000000000..f5dd5dda2d --- /dev/null +++ b/test/java/io/OutputStreamWriter/TestWrite.java @@ -0,0 +1,56 @@ +/* + * Copyright 1998 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 4066847 4147276 4131647 + * @summary Check for flush of output buffer before concluding it is too small + */ + +import java.io.*; + +public class TestWrite { + + public static void main(String args[]) + throws Exception + { + ByteArrayOutputStream bos; + OutputStreamWriter osw; + byte[] array; + + try{ + bos = new ByteArrayOutputStream(); + osw = new OutputStreamWriter(bos, "EUCJIS"); + osw.write('a'); + for(int count = 0; count < 10000; ++count) + osw.write('\u3042'); // Hiragana + osw.close(); + array = bos.toByteArray(); + } catch (UnsupportedEncodingException e){ + System.err.println("Unsupported encoding - EUCJIS. ext " + + " may not be properly installed. ext is " + + " required for the test to run properly "); + throw new Exception("Environment is incorrect"); + } + } +} diff --git a/test/java/io/OutputStreamWriter/WriteAfterClose.java b/test/java/io/OutputStreamWriter/WriteAfterClose.java new file mode 100644 index 0000000000..a9bfcd6c88 --- /dev/null +++ b/test/java/io/OutputStreamWriter/WriteAfterClose.java @@ -0,0 +1,112 @@ +/* + * Copyright 1998-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 4143651 5085148 + * + * @summary Test if Writer methods will check if the stream + * has been closed. + */ + +import java.io.*; + +public class WriteAfterClose { + + static boolean failed = false; + + static void testWrite(Writer wtr) throws Exception { + + // These tests could be tighted to only check for a particular + // kind of exception, but in 1.2beta4 StringWriter and + // other writers throw RuntimeExceptions + char[] cbuf = new char[2]; + wtr.close(); + System.out.println("Class " + wtr.getClass().getName()); + + try { + wtr.write('a'); + System.out.println("FAILED: Allows char write on a closed stream"); + failed = true; + } catch (Exception e) { + } + + try { + wtr.write(cbuf, 0, 1); + System.out.println("FAILED: Allows buffer write on a closed stream"); + failed = true; + } catch (Exception e) { + } + + try { + wtr.write(cbuf, 0, 0); + System.out.println("FAILED: Allows empty write on a closed stream"); + failed = true; + } catch (Exception e) { + } + + try { + wtr.write("a"); + System.out.println("FAILED: Allows string write on a closed stream"); + failed = true; + } catch (Exception e) { + } + + try { + wtr.write("a", 0, 1); + System.out.println("FALIED: Allows string buf write on a closed stream"); + failed = true; + } catch (Exception e) { + } + + try { + wtr.flush(); + System.out.println("FAILED: Allows flushing writer on a closed stream"); + failed = true; + } catch (Exception e) { + } + + wtr.close(); + } + + public static void main(String argv[]) throws Exception { + StringWriter sw = new StringWriter(); + testWrite(new BufferedWriter(sw)); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + OutputStreamWriter osw = new OutputStreamWriter(bos); + testWrite(osw); + + File f = new File(System.getProperty("test.dir", "."), + "NewFile"); + f.createNewFile(); + f.deleteOnExit(); + FileWriter fr = new FileWriter(f); + testWrite(fr); + + if (failed) { + throw new Exception("The test failed because one of the" + + " writer operation{s} failed. Check the messages"); + } + } +} diff --git a/test/java/io/PipedInputStream/CloseAndAvailableRC.java b/test/java/io/PipedInputStream/CloseAndAvailableRC.java new file mode 100644 index 0000000000..0965345451 --- /dev/null +++ b/test/java/io/PipedInputStream/CloseAndAvailableRC.java @@ -0,0 +1,107 @@ +/* + * 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 4499763 + * @summary Check for race condition between close and available + */ + +import java.io.*; + +/* + * Note: this is a probabalistic test and will not always fail on + * a workspace where the race condition can occur. However it should + * never fail on a workspace where the bug has been fixed. + */ +public class CloseAndAvailableRC { + public static void main(final String[] args) throws Exception { + CloseAndAvailableRC rc = new CloseAndAvailableRC(); + rc.go(); + } + + private PipedInputStream inPipe = null; + private PipedOutputStream outPipe = null; + private Thread sink = null; + private volatile boolean stop = false; + private volatile boolean stopTest = false; + + private void go() throws Exception { + for (long i=0; i<2000; i++) { + if (stopTest) { + cleanup(); + throw new RuntimeException("Test failed"); + } + resetPipes(); + System.err.println("Closing..."); + inPipe.close(); + } + cleanup(); + } + + // Cleanup old threads + private void cleanup() throws Exception { + if (sink != null) { + stop = true; + sink.interrupt(); + try { + sink.join(); + } catch (InterruptedException e) { + } + stop = false; + // Input Stream will have been closed already + outPipe.close(); + } + } + + private void resetPipes() throws Exception { + cleanup(); + + // Init pipe; Note: output never read + inPipe = new PipedInputStream(); + outPipe = new PipedOutputStream(inPipe); + + // Put stuff in pipe so that available() > 0 + for (byte b = 0; b < 10; b++) + outPipe.write(b); + + sink = new Sink(); + sink.start(); + } + + private class Sink extends Thread { + public void run() { + while (!stop) { + try { + final int num = inPipe.available(); + if (num < 0) { + // Bug detected; stop the test + stopTest = true; + } + } catch (final IOException e) { + System.err.println("Error on available:" + e.getMessage()); + e.printStackTrace(System.err); + } + } + } + } +} diff --git a/test/java/io/PipedInputStream/ClosedWriter.java b/test/java/io/PipedInputStream/ClosedWriter.java new file mode 100644 index 0000000000..3c8edeafcb --- /dev/null +++ b/test/java/io/PipedInputStream/ClosedWriter.java @@ -0,0 +1,64 @@ +/* + * Copyright 1998 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 4130880 + * @summary reading inputstream from child process throws + * io exception: Write end dead + * + */ + +import java.io.*; + +public class ClosedWriter implements Runnable { + static PipedInputStream is; + static PipedOutputStream os; + + public void run() { + try { + os.write(0); + os.write(0); + os.write(0); + os.write(0); + os.write(0); + os.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws Exception { + is = new PipedInputStream(); + os = new PipedOutputStream(); + is.connect(os); + + Thread t = new Thread(new ClosedWriter()); + t.start(); + + // this should just exit cleanly but the bug causes an exception + // to be thrown on the last read. + while (is.read() != -1) { + } + } +} diff --git a/test/java/io/PipedInputStream/Constructors.java b/test/java/io/PipedInputStream/Constructors.java new file mode 100644 index 0000000000..57b98c2696 --- /dev/null +++ b/test/java/io/PipedInputStream/Constructors.java @@ -0,0 +1,86 @@ +/* + * 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 4028462 + * @summary Test for new constructors that set the pipe size + */ + +import java.io.*; +public class Constructors extends Thread { + + static PipedOutputStream out; + static PipedInputStream in; + static int totalToWrite = (8 * 1024); + static int pipeSize = totalToWrite; + + public void run() { + try { + for (int times = (totalToWrite / pipeSize); times > 0; times--) { + System.out.println("Pipe Input stream reading..."); + int read = in.read(new byte[pipeSize]); + System.out.println("read: " + read); + if (read < pipeSize) { + throw new Exception("Pipe Size is not set to:" + pipeSize); + } + } + } catch (Throwable e) { + System.out.println("Pipe Input stream exception:"); + e.printStackTrace(); + } finally { + System.out.println("Pipe Input stream done."); + } + } + + public static void main(String args[]) throws Exception { + + in = new PipedInputStream(pipeSize); + out = new PipedOutputStream(in); + testPipe(); + + out = new PipedOutputStream(); + in = new PipedInputStream(out, pipeSize); + testPipe(); + } + + + private static void testPipe() throws Exception { + Constructors reader = new Constructors(); + reader.start(); + + try { + System.out.println("Pipe Output stream started."); + out.write(new byte[totalToWrite]); + } catch (Throwable e) { + System.out.println("Pipe Output stream exception:"); + e.printStackTrace(); + } finally { + out.close(); + System.out.println("Waiting for Pipe Input stream..."); + reader.join(); + in.close(); + System.out.println("Done."); + } + } +} diff --git a/test/java/io/PipedInputStream/FasterWriter.java b/test/java/io/PipedInputStream/FasterWriter.java new file mode 100644 index 0000000000..034c6e808a --- /dev/null +++ b/test/java/io/PipedInputStream/FasterWriter.java @@ -0,0 +1,62 @@ +/* + * Copyright 1998 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 4131126 + * @summary read throws io exception: Write end dead when there still + * is data available in the pipe. + * + */ + +import java.io.*; + +public class FasterWriter implements Runnable { + static PipedInputStream is; + static PipedOutputStream os; + + public void run() { + try { + os.write(0); + os.write(0); + os.write(0); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) throws Exception { + is = new PipedInputStream(); + os = new PipedOutputStream(is); + + Thread t = new Thread(new FasterWriter()); + t.start(); + t.join(); + + try { + is.read(); + } catch (IOException e) { + throw new Exception("Cannot read remaining data in the pipe"); + } + } +} diff --git a/test/java/io/PipedInputStream/WriterLoop.java b/test/java/io/PipedInputStream/WriterLoop.java new file mode 100644 index 0000000000..7356bfafb8 --- /dev/null +++ b/test/java/io/PipedInputStream/WriterLoop.java @@ -0,0 +1,85 @@ +/* + * 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 6219755 + * @summary Write end loops infinitely when the + * buffer is full and the read end has closed. + */ + +import java.io.*; + +public class WriterLoop extends Thread { + + static PipedOutputStream out; + static PipedInputStream in; + + public void run() { + try { + System.out.println("Writer started."); + + // without the fix, this test will hang at this point, + // i.e inside the call to write() + out.write(new byte[64*1024]); + } catch (Throwable e) { + + // with the fix an IOException is caught + System.out.println("Writer exception:"); + e.printStackTrace(); + } finally { + System.out.println("Writer done."); + } + } + + public static void main(String args[]) throws Exception { + in = new PipedInputStream(); + out = new PipedOutputStream(in); + WriterLoop writer = new WriterLoop(); + writer.start(); + + try { + System.out.println("Reader reading..."); + in.read(new byte[2048]); + + System.out.println("Reader closing stream..."); + in.close(); + + System.out.println("Reader sleeping 3 seconds..."); + Thread.sleep(3000); + } catch (Throwable e) { + System.out.println("Reader exception:"); + e.printStackTrace(); + } finally { + System.out.println("Active threads:"); + Thread[] threads = new Thread[Thread.activeCount()]; + Thread.enumerate(threads); + for (int i = 0; i < threads.length; i++) { + System.out.println(" " + threads[i]); + } + System.out.println("Waiting for writer..."); + writer.join(); + System.out.println("Done."); + } + } +} diff --git a/test/java/io/PipedOutputStream/ClosedWrite.java b/test/java/io/PipedOutputStream/ClosedWrite.java new file mode 100644 index 0000000000..55fcb6a319 --- /dev/null +++ b/test/java/io/PipedOutputStream/ClosedWrite.java @@ -0,0 +1,53 @@ +/* + * Copyright 1998 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 1267258 + * @summary Check for IOException upon write on closed stream. + * + */ + +import java.io.*; + +/** + * This class tests to see if an IOException is thrown when + * an attempt is made to write to a closed PipedOutputStream. + */ + +public class ClosedWrite { + + public static void main(String[] argv) throws Exception { + PipedOutputStream os = new PipedOutputStream(); + PipedInputStream is = new PipedInputStream(); + os.connect(is); + os.close(); + try { + os.write(10); + throw new + RuntimeException("No IOException upon write on closed Stream"); + } catch(IOException e) { + System.err.println("Test passed: IOException thrown"); + } + } +} diff --git a/test/java/io/PipedOutputStream/DeadReader.java b/test/java/io/PipedOutputStream/DeadReader.java new file mode 100644 index 0000000000..bd03e03b57 --- /dev/null +++ b/test/java/io/PipedOutputStream/DeadReader.java @@ -0,0 +1,78 @@ +/* + * Copyright 1998 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 1267045 + * @summary Make sure write will fail if reading + * end thread is dead. + * + */ + + +import java.io.*; + +public class DeadReader { + + public static void main(String[] argv) throws Exception { + PipedOutputStream os = new PipedOutputStream(); + PipedInputStream is = new PipedInputStream(); + is.connect(os); + + // create reader thread + LazyReader lr = new LazyReader(is); + + os.write(new byte[1000]); + + lr.start(); + while (lr.isAlive()) { + Thread.sleep(100); + } + + try{ + os.write(27); + throw new Exception + ("Test failed: shouldn't be able to write"); + } catch (IOException e) { + // test passed + } + } +} + +class LazyReader extends Thread { + private PipedInputStream snk; + private int delay; + + public LazyReader(PipedInputStream snk) { + this.snk = snk; + } + + public void run() { + try { + snk.read(); + } catch (Exception e) { + System.err.println("Test failed: unexpected exception"); + } + return; + } +} diff --git a/test/java/io/PipedOutputStream/MultipleConnect.java b/test/java/io/PipedOutputStream/MultipleConnect.java new file mode 100644 index 0000000000..750ee9f28f --- /dev/null +++ b/test/java/io/PipedOutputStream/MultipleConnect.java @@ -0,0 +1,46 @@ +/* + * Copyright 1998 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 1266814 + * @summary Check for IOException upon multiple connects. + * + */ + +import java.io.*; + +public class MultipleConnect { + + public static void main(String[] argv) throws Exception { + PipedOutputStream os = new PipedOutputStream(); + PipedOutputStream os2 = new PipedOutputStream(); + PipedInputStream is = new PipedInputStream(); + os.connect(is); + try { + is.connect(os2); + throw new Exception("Test failed: IOException expected"); + } catch(IOException e) { + } + } +} diff --git a/test/java/io/PipedOutputStream/NotConnected.java b/test/java/io/PipedOutputStream/NotConnected.java new file mode 100644 index 0000000000..e815b0fd4d --- /dev/null +++ b/test/java/io/PipedOutputStream/NotConnected.java @@ -0,0 +1,57 @@ +/* + * Copyright 1998 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 1267038 + * @summary Check for IOException upon read/write on unconnected stream. + * + */ + + +import java.io.*; + +public class NotConnected { + public static void main( String[] argv ) throws Exception { + PipedInputStream i = new PipedInputStream(); + PipedOutputStream o = new PipedOutputStream(); + boolean readPassed = false; + boolean writePassed = false; + + try { + i.read(); + } catch (IOException e) { + readPassed = true; + } + + try { + o.write(10); + } catch (IOException e) { + writePassed = true; + } + + if (!readPassed || !writePassed) { + throw new Exception("Test failed: IOException not thrown" ); + } + } +} diff --git a/test/java/io/PipedOutputStream/WriteAfterClose.java b/test/java/io/PipedOutputStream/WriteAfterClose.java new file mode 100644 index 0000000000..7c72aa4286 --- /dev/null +++ b/test/java/io/PipedOutputStream/WriteAfterClose.java @@ -0,0 +1,46 @@ +/* + * Copyright 1998 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 4143704 + @summary Test if write throws exception after reader + closes the pipe. +*/ + + + +import java.io.*; + +public class WriteAfterClose { + public static void main(String argv[]) throws Exception { + PipedInputStream in = new PipedInputStream(); + PipedOutputStream out = new PipedOutputStream(in); + + in.close(); + try { + out.write('a'); + throw new Exception("Should not allow write after close"); + } catch (IOException e) { + } + } +} diff --git a/test/java/io/PipedReader/Constructors.java b/test/java/io/PipedReader/Constructors.java new file mode 100644 index 0000000000..cb44e80f45 --- /dev/null +++ b/test/java/io/PipedReader/Constructors.java @@ -0,0 +1,86 @@ +/* + * 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 4028462 + * @summary Test for new constructors that set the pipe size + */ + +import java.io.*; +public class Constructors extends Thread { + + static PipedWriter out; + static PipedReader in; + static int totalToWrite = (8 * 1024); + static int pipeSize = totalToWrite; + + public void run() { + try { + for (int times = (totalToWrite / pipeSize); times > 0; times--) { + System.out.println("Reader reading..."); + int read = in.read(new char[pipeSize]); + System.out.println("read: " + read); + if (read < pipeSize) { + throw new Exception("Pipe Size is not set to:" + pipeSize); + } + } + } catch (Throwable e) { + System.out.println("Reader exception:"); + e.printStackTrace(); + } finally { + System.out.println("Reader done."); + } + } + + public static void main(String args[]) throws Exception { + + in = new PipedReader(pipeSize); + out = new PipedWriter(in); + testPipe(); + + out = new PipedWriter(); + in = new PipedReader(out, pipeSize); + testPipe(); + } + + + private static void testPipe() throws Exception { + Constructors reader = new Constructors(); + reader.start(); + + try { + System.out.println("Writer started."); + out.write(new char[totalToWrite]); + } catch (Throwable e) { + System.out.println("Writer exception:"); + e.printStackTrace(); + } finally { + out.close(); + System.out.println("Waiting for reader..."); + reader.join(); + in.close(); + System.out.println("Done."); + } + } +} diff --git a/test/java/io/PipedReader/ReadToArray.java b/test/java/io/PipedReader/ReadToArray.java new file mode 100644 index 0000000000..94ec051571 --- /dev/null +++ b/test/java/io/PipedReader/ReadToArray.java @@ -0,0 +1,46 @@ +/* + * Copyright 1998 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 4101576 + @summary Test if read(byte[], int, int) works correctly. +*/ + +import java.io.*; + +public class ReadToArray { + public static void main(String[] args) throws Exception { + PipedWriter pw = new PipedWriter(); + PipedReader pr = new PipedReader(pw); + char[] cbuf = {'a', 'a', 'a', 'a'}; + + pw.write('b'); + // read 'b' and put it to position 2 + pr.read(cbuf, 2, 1); + + if (cbuf[2] != 'b') { + throw new Exception + ("Read character to wrong position: 2nd character should be b"); + } + } +} diff --git a/test/java/io/PipedReader/Ready.java b/test/java/io/PipedReader/Ready.java new file mode 100644 index 0000000000..c0e6bee02e --- /dev/null +++ b/test/java/io/PipedReader/Ready.java @@ -0,0 +1,47 @@ +/* + * Copyright 1998 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 4140433 4140438 + @summary Test if ready works correctly. +*/ + +import java.io.*; + +public class Ready { + public static void main(String[] args) throws Exception { + PipedWriter pw = new PipedWriter(); + PipedReader pr = new PipedReader(pw); + + pw.write("input characters"); + if (!pr.ready()) { + throw new Exception("ready() should return true"); + } + pr.close(); + try { + pr.ready(); + throw new Exception("ready() should throw an exception"); + } catch (IOException e) { + } + } +} diff --git a/test/java/io/PipedWriter/ConnectAfterReaderClose.java b/test/java/io/PipedWriter/ConnectAfterReaderClose.java new file mode 100644 index 0000000000..976eefa2ab --- /dev/null +++ b/test/java/io/PipedWriter/ConnectAfterReaderClose.java @@ -0,0 +1,44 @@ +/* + * Copyright 1999 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 4207916 + @summary Test if connect throws exception after reader + closes the pipe. +*/ + + + +import java.io.*; + +public class ConnectAfterReaderClose { + public static void main(String argv[]) throws Exception { + PipedReader pr = new PipedReader(); + pr.close(); + try { + PipedWriter pw = new PipedWriter(pr); + throw new Exception("Should not allow connect after close"); + } catch (IOException e) { + } + } +} diff --git a/test/java/io/PipedWriter/FlushAfterClose.java b/test/java/io/PipedWriter/FlushAfterClose.java new file mode 100644 index 0000000000..0a04ab99e3 --- /dev/null +++ b/test/java/io/PipedWriter/FlushAfterClose.java @@ -0,0 +1,45 @@ +/* + * Copyright 1999 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 4207959 + @summary Test if flush throws exception after writer + calls close. +*/ + + + +import java.io.*; + +public class FlushAfterClose { + public static void main(String argv[]) throws Exception { + PipedReader pr = new PipedReader(); + PipedWriter pw = new PipedWriter(pr); + pw.close(); + try { + pw.flush(); + throw new Exception("Should not allow flush after close"); + } catch (IOException e) { + } + } +} diff --git a/test/java/io/PipedWriter/WriteAfterReaderClose.java b/test/java/io/PipedWriter/WriteAfterReaderClose.java new file mode 100644 index 0000000000..a161ddbf3f --- /dev/null +++ b/test/java/io/PipedWriter/WriteAfterReaderClose.java @@ -0,0 +1,46 @@ +/* + * Copyright 1998 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 4140956 + @summary Test if write throws exception after reader + closes the pipe. +*/ + + + +import java.io.*; + +public class WriteAfterReaderClose { + public static void main(String argv[]) throws Exception { + PipedReader pr = new PipedReader(); + PipedWriter pw = new PipedWriter(pr); + + pr.close(); + try { + pw.write('a'); + throw new Exception("Should not allow write after close"); + } catch (IOException e) { + } + } +} diff --git a/test/java/io/PrintStream/CheckError.java b/test/java/io/PrintStream/CheckError.java new file mode 100644 index 0000000000..caa0809354 --- /dev/null +++ b/test/java/io/PrintStream/CheckError.java @@ -0,0 +1,62 @@ +/* + * 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 4213822 + * @summary Test that checkError() returns a correct value + * when a PrintWriter is wrapped with another + * PrintWriter. + */ + +import java.io.*; + +public class CheckError { + + public static void main(String[] args) throws Exception { + + File file = new File(System.getProperty("test.dir", "."), + "junkie.out"); + file.deleteOnExit(); + + FileOutputStream fos = new FileOutputStream(file); + PrintStream pps = new PrintStream( + new PrintStream(fos)); + boolean passTest1 = false; + + fos.close(); + pps.println("Hello World!"); + + if (pps.checkError()) { + System.out.println("Correct: An error occured in the" + + " underlying Stream"); + passTest1 = true; + } + pps.close(); + + if (!passTest1) { + throw new Exception("CheckError() returned an incorrect value" + + " when the error has occured in the underlying Stream"); + } + } +} diff --git a/test/java/io/PrintStream/ClearErrorStream.java b/test/java/io/PrintStream/ClearErrorStream.java new file mode 100644 index 0000000000..655bc75290 --- /dev/null +++ b/test/java/io/PrintStream/ClearErrorStream.java @@ -0,0 +1,67 @@ +/* + * 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 4491255 + * @summary Test for a new protected method PrintStream.clearError() + * to reset the internal error state + */ + +import java.io.*; + +public class ClearErrorStream extends PrintStream { + + public ClearErrorStream(OutputStream out, boolean autoFlush) { + super(out, autoFlush); + } + + public static void main(String[] args) throws Exception { + + File f = new File(System.getProperty("test.dir", "."), + "print-stream.out"); + f.deleteOnExit(); + + ClearErrorStream out = new ClearErrorStream( + new BufferedOutputStream( + new FileOutputStream(f)), + true); + out.println("Hello World!"); + out.close(); + out.println("Writing after close"); + + if (out.checkError()) { + System.out.println("An error occured"); + out.clearError(); + + if (!out.checkError()) { + System.out.println("Error status cleared"); + } else { + throw new Exception("Error Status unchanged"); + } + } + else { + System.out.println(" No error occured"); + } + } +} diff --git a/test/java/io/PrintStream/EncodingConstructor.java b/test/java/io/PrintStream/EncodingConstructor.java new file mode 100644 index 0000000000..fab64a6ba7 --- /dev/null +++ b/test/java/io/PrintStream/EncodingConstructor.java @@ -0,0 +1,54 @@ +/* + * Copyright 2000 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 4378278 + * @summary java.io.PrintStream(..., String encoding) constructor + */ + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + + +public class EncodingConstructor { + + public static void main(String args[]) throws Exception { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(bo, false, "UTF-8"); + String s = "xyzzy"; + int n = s.length(); + ps.print(s); + ps.close(); + byte[] ba = bo.toByteArray(); + if (ba.length != n) + throw new Exception("Length mismatch: " + n + " " + ba.length); + for (int i = 0; i < n; i++) { + if (ba[i] != (byte)s.charAt(i)) + throw new Exception("Content mismatch: " + + i + " " + + Integer.toString(ba[i]) + " " + + Integer.toString(s.charAt(i))); + } + } + +} diff --git a/test/java/io/PrintStream/NullConstructor.java b/test/java/io/PrintStream/NullConstructor.java new file mode 100644 index 0000000000..ec31b29253 --- /dev/null +++ b/test/java/io/PrintStream/NullConstructor.java @@ -0,0 +1,42 @@ +/* + * Copyright 1998-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 1265548 + @summary PrintStream should not accept a null output stream in its + constructor +*/ + +import java.io.*; + +public class NullConstructor { + + public static void main(String args[]) throws Exception { + try { + PrintStream ps = new PrintStream((OutputStream) null); + } catch (Exception e) { + return; + } + throw new Exception("PrintStream does not catch null constructor"); + } +} diff --git a/test/java/io/PrintStream/OversynchronizedTest.java b/test/java/io/PrintStream/OversynchronizedTest.java new file mode 100644 index 0000000000..f7d0b3dfa1 --- /dev/null +++ b/test/java/io/PrintStream/OversynchronizedTest.java @@ -0,0 +1,93 @@ +/* + * 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 4905777 + @summary PrintStream.println(Object) oversynchronized, can deadlock +*/ + +import java.io.PrintStream; + +public class OversynchronizedTest extends Thread { + private static TestObj testObj = new TestObj("This is a test."); + private static int loopNum = 100; + + public void run() { + for(int i=0; i<loopNum; i++) { + testObj.test(); + + //passing an object to System.out.println might cause deadlock + //if the object has a synchronized toString() method. + //using System.out.println(testObj.toString()) won't have a problem + System.out.println(testObj); + } + } + + public static void main(String args[]) throws Exception { + // should no NullPointerException + System.out.println((Object)null); + + // over synch test + int num = 5; + + OversynchronizedTest[] t = new OversynchronizedTest[num]; + for(int i=0; i<num; i++) { + t[i] = new OversynchronizedTest(); + t[i].start(); + } + + for(int i=0; i <num; i++) { + t[i].join(); + } + + System.out.println("Test completed."); + } +} + +class TestObj { + String mStr; + + TestObj(String str) { + mStr = str; + } + + synchronized void test() { + try { + long t = Math.round(Math.random()*10); + Thread.currentThread().sleep(t); + } catch (InterruptedException e) { + // jtreg timeout? + // Only jtreg will interrupt this thread so it knows what to do: + e.printStackTrace(); + } + + //the following line might cause hang if there is System.out.println(testObj) + //called by other threads. + System.out.println("In test()."); + } + + synchronized public String toString() { + System.out.println("Calling toString\n"); + return mStr; + } +} diff --git a/test/java/io/PrintWriter/CheckError.java b/test/java/io/PrintWriter/CheckError.java new file mode 100644 index 0000000000..c91aad4912 --- /dev/null +++ b/test/java/io/PrintWriter/CheckError.java @@ -0,0 +1,85 @@ +/* + * 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 4213822 + * @summary Test that checkError() returns a correct value + * when a PrintWriter is wrapped with another + * PrintWriter. + */ + +import java.io.*; + +public class CheckError { + public static void main(String[] args) throws Exception { + + boolean passTest1 = false; + File file = new File(System.getProperty("test.dir", "."), + "junkie.out"); + + FileWriter fw = new FileWriter(file); + + PrintWriter ppw = new PrintWriter( + new PrintWriter(fw)); + + fw.close(); + ppw.println("Hello World!"); + + file.deleteOnExit(); + + if (ppw.checkError()) { + System.out.println("Correct: An error occured in the" + + " underlying writer"); + passTest1 = true; + } + ppw.close(); + + // Test when the underlying stream is a PrintStream + FileOutputStream fos = new FileOutputStream(file); + PrintWriter pps = new PrintWriter( + new PrintStream(fos)); + + fos.close(); + pps.println("Hello World!"); + + if (pps.checkError()) { + System.out.println("Correct: An error occured in the" + + " underlying Stream"); + } else { + if (!passTest1) { + throw new Exception("CheckError() returned an incorrect value" + + " when error occured in the underlying Stream" + + " and when error occured in the underlying writer"); + } else { + throw new Exception("CheckError() returned an incorrect value" + + " when the error has occured in the underlying Stream"); + } + } + if (!passTest1) { + throw new Exception("CheckError() returned an incorrect value" + + " when the error has occured in the underlying Writer"); + } + pps.close(); + } +} diff --git a/test/java/io/PrintWriter/ClearErrorWriter.java b/test/java/io/PrintWriter/ClearErrorWriter.java new file mode 100644 index 0000000000..9ac02f718e --- /dev/null +++ b/test/java/io/PrintWriter/ClearErrorWriter.java @@ -0,0 +1,66 @@ +/* + * 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 4491255 + * @summary Test for a new protected method PrintWriter.clearError() + * to reset its internal error state + */ + +import java.io.*; + +public class ClearErrorWriter extends PrintWriter { + + + public ClearErrorWriter(Writer w, boolean autoFlush) { + super(w, autoFlush); + } + + public static void main(String[] args) throws Exception { + + File f = new File(System.getProperty("test.dir", "."), + "print-writer.out"); + f.deleteOnExit(); + ClearErrorWriter out = new ClearErrorWriter(new BufferedWriter( + new FileWriter(f)), + true); + out.println("Hello World!"); + out.close(); + out.println("Writing after close"); + + if (out.checkError()) { + System.out.println("An error occured"); + out.clearError(); + + if (!out.checkError()) { + System.out.println("Error status cleared"); + } else { + throw new Exception("Error Status unchanged"); + } + } + else { + System.out.println(" No error occured"); + } + } +} diff --git a/test/java/io/PrintWriter/OpsAfterClose.java b/test/java/io/PrintWriter/OpsAfterClose.java new file mode 100644 index 0000000000..048132bd79 --- /dev/null +++ b/test/java/io/PrintWriter/OpsAfterClose.java @@ -0,0 +1,89 @@ +/* + * 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 5085148 + * @summary Test if PrintWriter methods check if the stream + * has been closed. + */ + +import java.io.*; + +public enum OpsAfterClose { + + WRITE_BUF { boolean check(PrintWriter w) { + char buf[] = new char[2]; + w.write(buf); + return w.checkError(); + } }, + + WRITE_BUF_OFF { boolean check(PrintWriter w) { + char buf[] = new char[2]; + int len = 1; + w.write(buf, 0, len); + return w.checkError(); + } }, + WRITE_INT { boolean check(PrintWriter w) { + w.write(1); + return w.checkError(); + } }, + WRITE_STR { boolean check(PrintWriter w) { + String s = "abc"; + w.write(s); + return w.checkError(); + } }, + WRITE_STR_OFF { boolean check(PrintWriter w) { + String s = "abc"; + w.write(s, 0, s.length()); + return w.checkError(); + } }; + + abstract boolean check(PrintWriter w); + + public static void main(String args[]) throws Exception { + + System.out.println("Testing PrintWriter"); + boolean failed = false; + boolean result = false; + File f = new File(System.getProperty("test.dir", "."), + "print-writer.out"); + f.deleteOnExit(); + + for (OpsAfterClose op : OpsAfterClose.values()) { + PrintWriter pw = new PrintWriter( + new FileWriter(f)); + pw.close(); + result = op.check(pw); + if (!result) { + failed = true; + } + System.out.println(op + ":" + result); + } + if (failed) { + throw new Exception( + "Test failed for the failed operation{s} " + + "above for the PrintWriter"); + } + } +} diff --git a/test/java/io/PrintWriter/OversynchronizedTest.java b/test/java/io/PrintWriter/OversynchronizedTest.java new file mode 100644 index 0000000000..f95decff47 --- /dev/null +++ b/test/java/io/PrintWriter/OversynchronizedTest.java @@ -0,0 +1,96 @@ +/* + * 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 4905777 + @summary PrintWriter.println(Object) oversynchronized, can deadlock +*/ + +import java.io.PrintWriter; + +public class OversynchronizedTest extends Thread { + private static PrintWriter writer = new PrintWriter(System.out); + private static TestObj testObj = new TestObj("This is a test.", writer); + private static int loopNum = 100; + + public void run() { + for(int i=0; i<loopNum; i++) { + testObj.test(); + + //passing an object to PrintWriter.println might cause deadlock + //if the object has a synchronized toString() method. + //using PrintWriter.println(testObj.toString()) won't have a problem + writer.println(testObj); + } + } + + public static void main(String args[]) throws Exception { + // should no NullPointerException + writer.println((Object)null); + + int num = 5; + + OversynchronizedTest[] t = new OversynchronizedTest[num]; + for(int i=0; i<num; i++) { + t[i] = new OversynchronizedTest(); + t[i].start(); + } + + for(int i=0; i <num; i++) { + t[i].join(); + } + + System.out.println("Test completed"); + } +} + +class TestObj { + String mStr; + + TestObj(String str, PrintWriter writer) { + mStr = str; + this.writer = writer; + } + + synchronized void test() { + try { + long t = Math.round(Math.random()*10); + Thread.currentThread().sleep(t); + } catch (InterruptedException e) { + // jtreg timeout? + // Only jtreg will interrupt this thread so it knows what to do: + e.printStackTrace(); + } + + //the following line might cause hang if there is PrintWriter.println(testObj) + //called by other threads. + writer.println("In test()."); + } + + synchronized public String toString() { + writer.println("Calling toString\n"); + return mStr; + } + + private PrintWriter writer; +} diff --git a/test/java/io/PrintWriter/SubClass.java b/test/java/io/PrintWriter/SubClass.java new file mode 100644 index 0000000000..c2d9537d08 --- /dev/null +++ b/test/java/io/PrintWriter/SubClass.java @@ -0,0 +1,64 @@ +/* + * Copyright 1998 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 4103356 4121985 + @summary Test new subclassing features of PrintWriter + */ + +import java.io.*; + + +public class SubClass { + + + static class PW extends PrintWriter { + + PW(Writer out) { + super(out); + } + + public void println() { + try { + out.write("[EOL]"); + } catch (IOException x) { + setError(); + } + super.println(); + } + + } + + + public static void main(String[] args) throws Exception { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PW(sw); + pw.println("Hello"); + pw.close(); + String s = sw.toString(); + System.err.print(s); + if (!s.equals("Hello[EOL]" + System.getProperty("line.separator"))) + throw new Exception("Subclass broken"); + } + +} diff --git a/test/java/io/PushbackInputStream/Available.java b/test/java/io/PushbackInputStream/Available.java new file mode 100644 index 0000000000..9ba4742aa1 --- /dev/null +++ b/test/java/io/PushbackInputStream/Available.java @@ -0,0 +1,69 @@ +/* + * Copyright 1997 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 4017414 + @summary Check for correct implementation of PushbackInputStream.available + */ + +import java.io.*; + + + +public class Available{ + + private static void dotest(PushbackInputStream in , int expected) + throws Exception + { + + int got = in.available(); + System.err.println("available must be " + expected + " , got : " + got); + if (got != expected) { + throw new + RuntimeException("Unexpected number of bytes available in the PushBackInputStream"); + } + + } + + + + public static void main(String args[]) throws Exception{ + + PushbackInputStream in = new + PushbackInputStream(new ByteArrayInputStream(new byte[10]),5); + + dotest(in , 10); + + in.read(); + dotest(in , 9); + + in.unread(20); + dotest(in , 10); + + in.unread(20); + dotest(in , 11); + + } + +} diff --git a/test/java/io/PushbackInputStream/ClosedStream.java b/test/java/io/PushbackInputStream/ClosedStream.java new file mode 100644 index 0000000000..9dcc8c5590 --- /dev/null +++ b/test/java/io/PushbackInputStream/ClosedStream.java @@ -0,0 +1,52 @@ +/* + * Copyright 1998 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 4017193 + @summary Test PushbackInputStream close method */ + +import java.io.*; + +/** + * This class tests to see if PushbackInputStream closes + * properly + */ + +public class ClosedStream { + + public static void main( String argv[] ) throws Exception { + byte[] data = {30,40}; + int b1,b2; + PushbackInputStream in = new PushbackInputStream( + new ByteArrayInputStream(data)); + in.unread(20); + in.close(); + + try { + in.read(); //IOException must be thrown here + throw new RuntimeException("No exception during read on closed stream"); + } catch (IOException e) { + System.err.println("Test passed: IOException is thrown"); + } + } +} diff --git a/test/java/io/PushbackInputStream/MarkReset.java b/test/java/io/PushbackInputStream/MarkReset.java new file mode 100644 index 0000000000..65e98bcb60 --- /dev/null +++ b/test/java/io/PushbackInputStream/MarkReset.java @@ -0,0 +1,57 @@ +/* + * Copyright 1999-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 4283413 4171233 + * @summary Make sure that the mark() and reset() methods behave as expected. + */ + +import java.io.*; + + +public class MarkReset { + public static void main(String args[]) throws Exception { + + boolean expOccurred = false; + byte data[] = {90, 91, 92, 93, 94, 95, 96, 97}; + PushbackInputStream in = + new PushbackInputStream(new ByteArrayInputStream(data)); + in.mark(-5); + in.mark(6); + in.mark(Integer.MAX_VALUE); + try { + in.reset(); + throw new RuntimeException("Expected exception not thrown"); + } catch (IOException e) { + // Correct result + } + in.read(); + in.read(); + try { + in.reset(); + throw new RuntimeException("Expected exception not thrown"); + } catch (IOException e) { + // Correct result + } + } +} diff --git a/test/java/io/PushbackInputStream/Skip.java b/test/java/io/PushbackInputStream/Skip.java new file mode 100644 index 0000000000..c92f3f9c04 --- /dev/null +++ b/test/java/io/PushbackInputStream/Skip.java @@ -0,0 +1,77 @@ +/* + * Copyright 1997 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 4017196 + @summary Test for correct implementation of PushbackInputStream.skip + */ + +import java.io.*; + +public class Skip { + + private static void dotest(PushbackInputStream in, int expected) + throws Exception + { + int one, two, last, got; + + in.unread(4); + in.unread(5); + in.unread(6); + in.skip(2); + if (in.read() != 4) { + throw new Exception("Failed the n < pushed back bytes case"); + } + System.err.println("Passed the n < pushed back bytes case"); + one = in.read(); + two = in.read(); + + if (two == 7) { + in.unread(two); + two = 0; + } + in.skip(2); + last = in.read(); + got = (one + two + last); + System.err.println("Expected " + expected + " got " + got); + if (expected != got) { + throw new Exception("Expected " + expected + " got " + got); + } + } + + + public static void main(String args[]) throws Exception { + byte[] data1 = {1, 7, 1, 0, 4}; + byte[] data2 = {1, 1, 1, 1, 5}; + byte[] data3 = {1, 7, 1, 3, 6}; + PushbackInputStream in; + + in = new PushbackInputStream(new ByteArrayInputStream(data1), 3); + dotest(in, 1); + in = new PushbackInputStream(new ByteArrayInputStream(data2), 3); + dotest(in, 7); + in = new PushbackInputStream(new ByteArrayInputStream(data3), 3); + dotest(in, 4); + } + +} diff --git a/test/java/io/PushbackReader/MarkReset.java b/test/java/io/PushbackReader/MarkReset.java new file mode 100644 index 0000000000..3ca4c166cf --- /dev/null +++ b/test/java/io/PushbackReader/MarkReset.java @@ -0,0 +1,65 @@ +/* + * Copyright 1998 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 4149941 + @summary mark and reset should throw an exception even when the + underlying stream supports the operations. + +*/ + + +import java.io.*; + +public class MarkReset { + + public static void main(String args[]) throws Exception { + CharArrayReader car = new CharArrayReader(new char[32]); + PushbackReader pb = new PushbackReader(car); + boolean markResult = testMark(pb); + boolean resetResult = testReset(pb); + if ((!markResult) || (!resetResult)) + throw new Exception("Mark and reset should not be supported"); + } + + static boolean testMark(PushbackReader pb){ + try{ + pb.mark(100); + } catch (IOException e) { + return true; // Passed the test successfully + } + System.err.println("Mark error"); + return false; // Failed + } + + static boolean testReset(PushbackReader pb){ + try{ + pb.reset(); + } catch (IOException e) { + return true; // Passed the test successfully + } + System.err.println("Reset error"); + return false; // Failed + } + +} diff --git a/test/java/io/PushbackReader/Skip.java b/test/java/io/PushbackReader/Skip.java new file mode 100644 index 0000000000..6c88cf29c2 --- /dev/null +++ b/test/java/io/PushbackReader/Skip.java @@ -0,0 +1,69 @@ +/* + * 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 4398210 + * @summary check skip method after pushing data back + * + */ + +import java.io.*; + +public class Skip { + + public static void main(String args[]) throws Exception { + test1(); + } + + private static void test1() throws Exception { + char[] buf = new char[20]; + for (int i=0; i<20; i++) + buf[i] = (char)i; + CharArrayReader car = new CharArrayReader(buf); + PushbackReader pr = new PushbackReader(car, 10); + check(pr.read(), 0); + // Check skip without unread chars present + pr.skip(1); + check(pr.read(), 2); + pr.unread(2); + pr.unread(1); + // Check skip over and beyond unread chars + pr.skip(4); + check(pr.read(), 5); + check(pr.read(), 6); + pr.unread(6); + pr.unread(5); + // Check skip within unread chars + pr.skip(1); + check(pr.read(), 6); + check(pr.read(), 7); + // Check skip after unread chars have been used + pr.skip(3); + check(pr.read(), 11); + } + + private static void check (int i, int j) { + if (i != j) + throw new RuntimeException("Test failed"); + } +} diff --git a/test/java/io/RandomAccessFile/Close.java b/test/java/io/RandomAccessFile/Close.java new file mode 100644 index 0000000000..0126660332 --- /dev/null +++ b/test/java/io/RandomAccessFile/Close.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 4710771 + * @summary Test RandomAccessFile.close + */ + +import java.io.*; +import java.nio.channels.*; + +public class Close { + public static void main(String[] args) throws Exception { + File f = File.createTempFile("blah", null); + f.deleteOnExit(); + RandomAccessFile raf = new RandomAccessFile(f, "r"); + FileChannel channel = raf.getChannel(); + raf.close(); + if (channel.isOpen()) { + throw new RuntimeException("Channel not closed"); + } + } +} diff --git a/test/java/io/RandomAccessFile/EOF.java b/test/java/io/RandomAccessFile/EOF.java new file mode 100644 index 0000000000..86a96ffc3b --- /dev/null +++ b/test/java/io/RandomAccessFile/EOF.java @@ -0,0 +1,46 @@ +/* + * Copyright 1997 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 4017497 + @summary Check that read returns -1 on EOF, as specified + */ + +import java.io.*; + +public class EOF { + + public static void main(String[] args) throws IOException { + byte buf[] = new byte[100]; + int n; + String dir = System.getProperty("test.src", "."); + RandomAccessFile raf = new RandomAccessFile(new File(dir, "EOF.java"), "r"); + for (;;) { + n = raf.read(buf, 0, buf.length); + if (n <= 0) break; + } + if (n != -1) + throw new RuntimeException("Expected -1 for EOF, got " + n); + } + +} diff --git a/test/java/io/RandomAccessFile/OpenSync.java b/test/java/io/RandomAccessFile/OpenSync.java new file mode 100644 index 0000000000..f925b97ae9 --- /dev/null +++ b/test/java/io/RandomAccessFile/OpenSync.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 + * @summary Unit test for RandomAccessFile open-sync modes + */ + +import java.io.*; + + +public class OpenSync { + + static PrintStream log = System.err; + + public static void main(String[] args) throws Exception { + + File blah = File.createTempFile("OpenSync", null); + blah.deleteOnExit(); + + String[] badModes = { "d", "s", "rd", "rs", "rwx", "foo" }; + for (int i = 0; i < badModes.length; i++) { + String mode = badModes[i]; + try { + new RandomAccessFile(blah, mode); + } catch (IllegalArgumentException x) { + log.println("Mode \"" + mode +"\": Thrown as expected: " + + x.getClass().getName()); + log.println(" " + x.getMessage()); + continue; + } + throw new Exception("Exception not thrown for illegal mode " + + mode); + } + + new RandomAccessFile(blah, "rw").close(); + new RandomAccessFile(blah, "r").close(); + + String hi = "Hello, world!"; + RandomAccessFile raf = new RandomAccessFile(blah, "rws"); + raf.writeUTF(hi); + raf.close(); + + raf = new RandomAccessFile(blah, "rwd"); + if (!raf.readUTF().equals(hi)) + throw new Exception("File content mismatch"); + raf.close(); + + } + +} diff --git a/test/java/io/RandomAccessFile/OpsAfterClose.java b/test/java/io/RandomAccessFile/OpsAfterClose.java new file mode 100644 index 0000000000..d1f2b4c01e --- /dev/null +++ b/test/java/io/RandomAccessFile/OpsAfterClose.java @@ -0,0 +1,158 @@ +/** + * @test + * @bug 6359397 + * @summary Test if RandomAccessFile methods will check if the stream + * has been closed. + */ + +import java.io.*; + +public enum OpsAfterClose { + + READ { boolean check(RandomAccessFile r) { + try { + r.read(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + + READ_BUF { boolean check(RandomAccessFile r) { + try { + byte buf[] = new byte[2]; + int len = 1; + r.read(buf, 0, len); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + GET_CHANNEL { boolean check(RandomAccessFile r) { + r.getChannel(); + return true; + } }, + GET_FD { boolean check(RandomAccessFile r) { + try { + r.getFD(); + return true; + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return false; + } + } }, + GET_FILE_PTR { boolean check(RandomAccessFile r) { + try { + r.getFilePointer(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + GET_LENGTH { boolean check(RandomAccessFile r) { + try { + r.length(); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + SEEK { boolean check(RandomAccessFile r) { + try { + r.seek(1); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + SET_LENGTH { boolean check(RandomAccessFile r) { + try { + r.setLength(1); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + SKIP_BYTES { boolean check(RandomAccessFile r) { + try { + r.skipBytes(1); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + WRITE { boolean check(RandomAccessFile r) { + try { + r.write(1); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + WRITE_BUF { boolean check(RandomAccessFile r) { + try { + byte buf[] = new byte[2]; + int len = 1; + r.write(buf, 0, len); + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; + } + return false; + } }, + CLOSE { boolean check(RandomAccessFile r) { + try { + r.close(); + return true; // No Exception thrown on windows + } catch (IOException io) { + System.out.print("Excep Msg: "+ io.getMessage() + ", "); + return true; // Exception thrown on solaris and linux + } + } }; + + abstract boolean check(RandomAccessFile r); + + public static void main(String args[]) throws Exception { + + boolean failed = false; + + File f = new File(System.getProperty("test.dir", "."), + "raf.txt"); + f.createNewFile(); + f.deleteOnExit(); + + RandomAccessFile raf = new RandomAccessFile(f, "rw"); + if (testRandomAccessFile(raf)) { + throw new Exception("Test failed for some of the operation{s}" + + " on RandomAccessFile, check the messages"); + } + } + + private static boolean testRandomAccessFile(RandomAccessFile r) + throws Exception { + r.close(); + boolean failed = false; + boolean result; + System.out.println("Testing File:" + r); + for (OpsAfterClose op : OpsAfterClose.values()) { + result = op.check(r); + if (!result) { + failed = true; + } + System.out.println(op + ":" + result); + } + if (failed) { + System.out.println("Test failed for the failed operation{s}" + + " above for the RandomAccessFile:" + r); + } + return failed; + } +} diff --git a/test/java/io/RandomAccessFile/ParameterCheck.java b/test/java/io/RandomAccessFile/ParameterCheck.java new file mode 100644 index 0000000000..6b01c4947c --- /dev/null +++ b/test/java/io/RandomAccessFile/ParameterCheck.java @@ -0,0 +1,156 @@ +/* + * Copyright 1997 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 4030253 4030278 4030243 + @summary Test for correct parameter checking in read(byte[], int, int), + readFully(byte[], int, int) and write(byte[], int, int) of RandomAccessFile + */ + +import java.io.*; + +public class ParameterCheck { + + static int off[] = {-1, -1, 0, 0, 33, 33, 0, 32, + 32, 4, 1, 0, -1, Integer.MAX_VALUE, 1}; + static int len[] = {-1, 0, -1, 33, 0, 4, 32, + 0, 4, 16, 31, 0, Integer.MAX_VALUE, + Integer.MAX_VALUE, Integer.MAX_VALUE}; + static boolean results[] = { false, false, false, false, false, false, + true, true, false, true, true, true, false, + false, false }; + static int numBad = 0; + + private static void doTest(String method) throws Exception { + File fn = new File("x.ParameterCheck"); + + try { + byte b[] = new byte[32]; + int numCases = off.length; + int[] got = new int[numCases]; + int numGood = 0; + FileOutputStream fout = new FileOutputStream(fn); + for (int i = 0; i < 32; i++) { + fout.write(i); + } + fout.close(); + RandomAccessFile raf = new RandomAccessFile(fn , "rw"); + + System.err.println("-----------------------------" + + "-----------------------------"); + System.err.println("\nRandomAccessFile." + method + + "\nTotal test cases = " + (off.length+1)); + System.err.println("-----------------------------" + + "-----------------------------"); + for(int i = 0; i < numCases; i++) { + try { + if (method.equals("readFully")) { + raf.readFully(b , off[i] , len[i]); + } + if (method.equals("read")) { + raf.read(b , off[i] , len[i]); + } + if (method.equals("write")) { + raf.write(b , off[i] , len[i]); + } + raf.seek(0); + } catch(IndexOutOfBoundsException aiobe) { + if (results[i]) { + printErr(method , numGood, + i, "java.lang.IndexOutOfBoundsException"); + } else { + numGood++; + } + continue; + } catch(OutOfMemoryError ome) { + printErr(method, numGood, + i, "java.lang.OutOfMemoryError"); + continue; + } + + if (results[i]) { + numGood++; + } + else { + printErr(method, numGood, + i, "No java.lang.IndexOutOfBoundsException"); + } + + } + + raf.seek(0); + boolean thrown = false; + try { + if (method.equals("readFully")) { + raf.readFully(null, 1, 2); + } + if (method.equals("read")) { + raf.read(null, 1, 2); + } + if (method.equals("write")) { + raf.write(null, 1, 2); + } + + } catch(NullPointerException npe) { + numGood++; + thrown = true; + } + if (!thrown) { + printErr(method, numGood, -1, + "no NullPointerException for null b"); + } + + System.err.println("\nTotal passed = " + numGood); + System.err.println("-----------------------------" + + "-----------------------------"); + } finally { + fn.delete(); + } + + } + + private static void printErr(String method, int numGood, + int i, String expStr) { + numBad++; + System.err.println("\nNumber passed so far = " + numGood + + "\nUnexpected " + expStr); + if ( i < 0 ) { + System.err.println("for case : b = null"); + } else { + System.err.println("for case : b.length = " + 32 + + " off = " + off[i] + + " len = " + len[i]); + } + } + + public static void main(String argv[]) throws Exception{ + doTest("read"); + doTest("readFully"); + doTest("write"); + + if (numBad > 0) { + throw new RuntimeException("Failed " + numBad + " tests"); + } + } +} diff --git a/test/java/io/RandomAccessFile/ReadLine.java b/test/java/io/RandomAccessFile/ReadLine.java new file mode 100644 index 0000000000..2af58bab7a --- /dev/null +++ b/test/java/io/RandomAccessFile/ReadLine.java @@ -0,0 +1,60 @@ +/* + * Copyright 1997 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 1238814 + @summary check for correct implementation of RandomAccessFile.readLine + */ + +import java.io.*; + +public class ReadLine { + + public static void main(String args[]) throws Exception { + File fn = new File("x.ReadLine"); + RandomAccessFile raf = new RandomAccessFile(fn,"rw"); + String line; + int ctr = 1; + String expected; + + raf.writeBytes + ("ln1\rln2\r\nln3\nln4\rln5\r\nln6\n\rln8\r\rln10\n\nln12\r\r\nln14"); + raf.seek(0); + + while ((line=raf.readLine()) != null) { + if ((ctr == 7) || (ctr == 9) || + (ctr == 11) || (ctr == 13)) { + expected = ""; + } else { + expected = "ln" + ctr; + } + if (!line.equals(expected)) { + throw new Exception("Expected \"" + expected + "\"" + + ", read \"" + line + "\""); + } + ctr++; + } + System.err.println("Successfully completed test!"); + } + +} diff --git a/test/java/io/RandomAccessFile/ReadWritePrimitives.java b/test/java/io/RandomAccessFile/ReadWritePrimitives.java new file mode 100644 index 0000000000..2fafcbaed4 --- /dev/null +++ b/test/java/io/RandomAccessFile/ReadWritePrimitives.java @@ -0,0 +1,152 @@ +/* + * Copyright 1998 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 4092350 + @summary Verify that reads and writes of primitives are correct + */ + +// The bug mentioned is actually a performance bug that prompted +// changes in the methods to write primitives +import java.io.*; + +import java.io.*; + +public class ReadWritePrimitives { + + public static void main(String args[]) throws IOException { + long start, finish; + start = System.currentTimeMillis(); + testShort(); + finish = System.currentTimeMillis(); + // System.err.println("Time taken="+(finish-start)); + start = System.currentTimeMillis(); + testChar(); + finish = System.currentTimeMillis(); + // System.err.println("Time taken="+(finish-start)); + start = System.currentTimeMillis(); + testInt(); + finish = System.currentTimeMillis(); + // System.err.println("Time taken="+(finish-start)); + start = System.currentTimeMillis(); + testLong(); + finish = System.currentTimeMillis(); + // System.err.println("Time taken="+(finish-start)); + } + + private static void testShort() throws IOException { + File fh = new File(System.getProperty("test.dir", "."), + "x.ReadWriteGenerated"); + RandomAccessFile f = new RandomAccessFile(fh,"rw"); + for(int i = 0; i < 10000; i++){ + f.writeShort((short)i); + } + f.writeShort((short)65535); + f.close(); + f = new RandomAccessFile(fh,"r"); + for(int i = 0; i < 10000; i++) { + short r = f.readShort(); + if (r != ((short)i)) { + System.err.println("An error occurred. Read:" + r + + " i:" + ((short)i)); + throw new IOException("Bad read from a writeShort"); + } + } + short rmax = f.readShort(); + if (rmax != ((short)65535)) { + System.err.println("An error occurred. Read:" + rmax); + throw new IOException("Bad read from a writeShort"); + } + f.close(); + } + + private static void testChar() throws IOException { + File fh = new File(System.getProperty("test.dir", "."), + "x.ReadWriteGenerated"); + RandomAccessFile f = new RandomAccessFile(fh,"rw"); + for(int i = 0; i < 10000; i++){ + f.writeChar((char)i); + } + f.close(); + f = new RandomAccessFile(fh,"r"); + for(int i = 0; i < 10000; i++) { + char r = f.readChar(); + if (r != ((char)i)){ + System.err.println("An error occurred. Read:" + r + + " i:" + ((char) i)); + throw new IOException("Bad read from a writeChar"); + } + } + f.close(); + } + + + private static void testInt() throws IOException { + File fh = new File(System.getProperty("test.dir", "."), + "x.ReadWriteGenerated"); + RandomAccessFile f = new RandomAccessFile(fh,"rw"); + for(int i = 0; i < 10000; i++){ + f.writeInt((short)i); + } + f.writeInt(Integer.MAX_VALUE); + f.close(); + f = new RandomAccessFile(fh, "r"); + for(int i = 0; i < 10000; i++) { + int r = f.readInt(); + if (r != i){ + System.err.println("An error occurred. Read:" + r + + " i:" + i); + throw new IOException("Bad read from a writeInt"); + } + } + int rmax = f.readInt(); + if (rmax != Integer.MAX_VALUE){ + System.err.println("An error occurred. Read:" + rmax); + throw new IOException("Bad read from a writeInt"); + } + f.close(); + } + + private static void testLong() throws IOException { + File fh = new File(System.getProperty("test.dir", "."), + "x.ReadWriteGenerated"); + RandomAccessFile f = new RandomAccessFile(fh,"rw"); + for(int i = 0; i < 10000; i++){ + f.writeLong(123456789L * (long)i); + } + f.close(); + f = new RandomAccessFile(fh,"r"); + for(int i = 0; i < 10000; i++){ + long r = f.readLong(); + if (r != (((long) i) * 123456789L) ) { + System.err.println("An error occurred. Read:" + r + + " i" + ((long) i)); + + throw new IOException("Bad read from a writeInt"); + } + } + f.close(); + + } + +} diff --git a/test/java/io/RandomAccessFile/Seek.java b/test/java/io/RandomAccessFile/Seek.java new file mode 100644 index 0000000000..72dcbbfe5f --- /dev/null +++ b/test/java/io/RandomAccessFile/Seek.java @@ -0,0 +1,49 @@ +/* + * Copyright 1998 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 4140804 + @summary Test if seek will throw exception given a + negative offset. +*/ + + + +import java.io.*; + +public class Seek +{ + public static void main(String argv[]) throws Exception + { + String dir = System.getProperty("test.src", "."); + RandomAccessFile raf = new RandomAccessFile + (new File(dir, "Seek.java"), "r"); + + try { + raf.seek(-10); + throw new Exception + ("Should have thrown an IOException when seek offset is < 0"); + } catch (IOException e) { + } + } +} diff --git a/test/java/io/RandomAccessFile/SetLength.java b/test/java/io/RandomAccessFile/SetLength.java new file mode 100644 index 0000000000..fdf1497064 --- /dev/null +++ b/test/java/io/RandomAccessFile/SetLength.java @@ -0,0 +1,82 @@ +/* + * Copyright 1997 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 General tests of the setLength method -- Should migrate to 1.2 JCK + */ + +import java.io.*; + + +public class SetLength { + + static void fail(String s) { + throw new RuntimeException(s); + } + + static void go(File fn, int max) throws IOException { + int chunk = max / 4; + long i; + RandomAccessFile f; + + f = new RandomAccessFile(fn, "rw"); + f.setLength(2 * chunk); + if (f.length() != 2 * chunk) fail("Length not increased to " + (2 * chunk)); + if ((i = f.getFilePointer()) != 0) fail("File pointer shifted to " + i); + byte[] buf = new byte[max]; + f.write(buf); + if (f.length() != max) fail("Write didn't work"); + if (f.getFilePointer() != max) fail("File pointer inconsistent"); + f.setLength(3 * chunk); + if (f.length() != 3 * chunk) fail("Length not reduced to " + 3 * chunk); + if (f.getFilePointer() != 3 * chunk) fail("File pointer not shifted to " + (3 * chunk)); + f.seek(1 * chunk); + if (f.getFilePointer() != 1 * chunk) fail("File pointer not shifted to " + (1 * chunk)); + f.setLength(2 * chunk); + if (f.length() != 2 * chunk) fail("Length not reduced to " + (2 * chunk)); + if (f.getFilePointer() != 1 * chunk) fail("File pointer not shifted to " + (1 * chunk)); + f.close(); + } + + public static void main(String[] args) throws IOException { + File fn = new File("x.SetLength"); + try { + go(fn, 20); + fn.delete(); + go(fn, 64 * 1024); + RandomAccessFile f = new RandomAccessFile(fn, "r"); + boolean thrown = false; + try { + f.setLength(3); + } catch (IOException x) { + thrown = true; + } + if (!thrown) fail("setLength succeeded on a file opened read-only"); + f.close(); + } + finally { + fn.delete(); + } + } + +} diff --git a/test/java/io/RandomAccessFile/WriteBytesChars.java b/test/java/io/RandomAccessFile/WriteBytesChars.java new file mode 100644 index 0000000000..0440222daf --- /dev/null +++ b/test/java/io/RandomAccessFile/WriteBytesChars.java @@ -0,0 +1,77 @@ +/* + * Copyright 1997 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 4074388 + @summary Check for correct implementation of RandomAccessFile.writeBytes + and writeChars. + */ + +import java.io.*; + +public class WriteBytesChars { + + public static void main(String args[]) throws Exception { + String towrite; + char[] buf = new char[80]; + byte[] b = new byte[80]; + File fn = new File("x.WriteBytesChars"); + + try{ + RandomAccessFile raf = new RandomAccessFile(fn , "rw");; + for (int i = 0; i < 80; i++) { + buf[i] = 'a'; + } + towrite = new String(buf); + + raf.writeBytes(towrite); + raf.seek(0); + raf.read(b); + + System.out.println("RandomAccessFile.writeBytes"); + if (towrite.equals(new String(b))) { + System.err.println("Test succeeded."); + } else { + throw new + RuntimeException("RandomAccessFile.writeBytes, wrong result"); + } + + raf.seek(0); + raf.writeChars(towrite); + raf.seek(0); + for (int i = 0; i < 80; i++) { + buf[i] = raf.readChar(); + } + + System.out.println("RandomAccessFile.writeChars"); + if (towrite.equals(new String(buf))) { + System.err.println("Test succeeded."); + } else { + throw new + RuntimeException("RandomAccessFile.writeChars, wrong result"); + } + } finally { + fn.delete(); + } + } +} diff --git a/test/java/io/RandomAccessFile/WriteUTF.java b/test/java/io/RandomAccessFile/WriteUTF.java new file mode 100644 index 0000000000..dd518225bb --- /dev/null +++ b/test/java/io/RandomAccessFile/WriteUTF.java @@ -0,0 +1,61 @@ +/* + * Copyright 1997 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 4018515 + @summary Make sure that writeUTF throws a UTFDataFormatException when the + output string is too long + */ + +import java.io.*; + + +public class WriteUTF { + + public static void main(String[] args) throws IOException { + + RandomAccessFile f; + File fn = new File("x.WriteUTF"); + + String s = "\uffff"; + for (int i = 0; i < 16; i++) + s += s; + System.err.println("String length " + s.length()); + + try { + f = new RandomAccessFile(fn, "rw"); + try { + f.writeUTF(s); + } + catch (UTFDataFormatException x) { + return; + } + throw new RuntimeException("UTFDataFormatException not thrown"); + } + finally { + fn.delete(); + } + + } + +} diff --git a/test/java/io/RandomAccessFile/skipBytes/SkipBytes.java b/test/java/io/RandomAccessFile/skipBytes/SkipBytes.java new file mode 100644 index 0000000000..4ae5bdf8ca --- /dev/null +++ b/test/java/io/RandomAccessFile/skipBytes/SkipBytes.java @@ -0,0 +1,110 @@ +/* + * Copyright 1997 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 4027717 + @summary Check for correct implementation of RandomAccessFile.skipBytes + */ + + +import java.io.*; + +public class SkipBytes{ + + + /* + * doTest attempts to skip num_to_skip bytes in raf starting from position 0. + * It also does a read after the skip to check if EOF has been reached + * correctly or incorrectly. + */ + + + private static void doTest(RandomAccessFile raf, int start, int num_to_skip) + throws Exception + { + + raf.seek(start); + + long cur_ptr = raf.getFilePointer(); + int length = (int) raf.length(); + System.err.println("\nCurrent pointer = " + cur_ptr + " length = " + + length + " num_to_skip = " + num_to_skip); + + //Do the Skip test + int num_skipped = raf.skipBytes(num_to_skip); + System.err.println("After skipBytes -- no. skipped = " + num_skipped); + + // if num_to_skip is negative do the negative skip test + if (num_to_skip <= 0) { + if (num_skipped != 0){ + System.err.println("Negative Skip Test Failed"); + throw new RuntimeException("Negative Skip Test Failed"); + } + else { + System.err.println("Negative Skip Test Succeeded"); + } + } + + cur_ptr = raf.getFilePointer(); + System.err.println("Current pointer = " + cur_ptr); + + // Check if skip has gone beyond EOF. + if (cur_ptr > length) { + System.err.println("Past EOF Skip Test Failed"); + throw new RuntimeException("Past EOF Skip Test Failed"); + } + else { + System.err.println("Past EOF Skip Test Succeeded"); + } + + // do read test + int byte_read = raf.read(); + if ( (cur_ptr == length) && + (byte_read != -1) ) { + System.err.println("byte_read = " + byte_read + + " Read Test Failed ......"); + throw new RuntimeException("Read Test Failed"); + } + else { + System.err.println("byte_read = " + byte_read + + " Read Test Succeeded"); + } + + } + + public static void main(String[] args) throws Exception { + + RandomAccessFile raf = new RandomAccessFile("input.txt" , "rw"); + int length = (int)raf.length(); + + doTest(raf , 0 , 2*length); + doTest(raf , 0 , length); + doTest(raf , 0 , length/2); + doTest(raf , length/2 , -2); + doTest(raf , length , 0); + doTest(raf , 0 , -1); + + } + +} diff --git a/test/java/io/RandomAccessFile/skipBytes/input.txt b/test/java/io/RandomAccessFile/skipBytes/input.txt new file mode 100644 index 0000000000..a5024189d8 --- /dev/null +++ b/test/java/io/RandomAccessFile/skipBytes/input.txt @@ -0,0 +1,3 @@ +foo +goo +moo diff --git a/test/java/io/Reader/NullLock.java b/test/java/io/Reader/NullLock.java new file mode 100644 index 0000000000..aeb83ef0cb --- /dev/null +++ b/test/java/io/Reader/NullLock.java @@ -0,0 +1,63 @@ +/* + * Copyright 1998 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 4152455 + @summary A null lock in the create must throw an exception +*/ + + + +import java.io.*; + +public class NullLock { + public static void main(String argv[]) throws Exception { + if (!testBufferedReader()) + throw new Exception("Buffered Reader constructor: " + + "Null argument must throw an exception"); + if (!testBufferedWriter()) + throw new Exception("BufferedWriter constructor: " + + " Null arg must throw an exception"); + } + + static boolean testBufferedReader(){ + try { + InputStreamReader isr = null; + BufferedReader br = new BufferedReader(isr); + } catch(NullPointerException e) { + return true; + } + return false; + } + + static boolean testBufferedWriter(){ + try { + OutputStreamWriter isr = null; + BufferedWriter br = new BufferedWriter(isr); + } catch(NullPointerException e) { + return true; + } + return false; + } + +} diff --git a/test/java/io/Reader/OpsAfterClose.java b/test/java/io/Reader/OpsAfterClose.java new file mode 100644 index 0000000000..9876f311d5 --- /dev/null +++ b/test/java/io/Reader/OpsAfterClose.java @@ -0,0 +1,207 @@ +/* + * 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 5085148 4143651 + * @summary Test if Reader methods will check if the stream + * has been closed. + */ + +import java.io.*; + +public enum OpsAfterClose { + + READ { boolean check(Reader r) { + try { + r.read(); + } catch (IOException io) { + return true; + } + return false; + } }, + + READ_BUF { boolean check(Reader r) { + try { + char buf[] = new char[2]; + int len = 1; + r.read(buf, 0, len); + } catch (IOException io) { + return true; + } + return false; + } }, + READY { boolean check(Reader r) { + try { + r.ready(); + } catch (IOException io) { + return true; + } + return false; + } }, + MARK { boolean check(Reader r) { + try { + r.mark(1); + } catch (IOException io) { + return true; + } + return false; + } }, + SKIP { boolean check(Reader r) { + try { + r.skip(1); + } catch (IOException io) { + return true; + } + return false; + } }, + RESET { boolean check(Reader r) { + try { + r.reset(); + } catch (IOException io) { + return true; + } + return false; + } }, + CLOSE { boolean check(Reader r) { + try { + r.close(); + } catch (IOException io) { + return false; + } + return true; + } }; + + abstract boolean check(Reader r); + + public static void main(String args[]) throws Exception { + + boolean failed = false; + + BufferedReader br = new BufferedReader( + new StringReader("abc def ghi")); + if (testReader(br)) { + failed = true; + } + + CharArrayReader car = new CharArrayReader(new char[2]); + if (testReader(car)) { + failed = true; + } + + PushbackReader pbr = new PushbackReader( + new CharArrayReader(new char[2])); + if (testReader(pbr)) { + failed = true; + } + if (testPushbackReader(pbr)) { + failed = true; + } + + StringReader sr = new StringReader("abc def ghi"); + if (testReader(sr)) { + failed = true; + } + + InputStreamReader isr = new InputStreamReader( + new ByteArrayInputStream("abc".getBytes())); + if (testReader(isr)) { + failed = true; + } + + LineNumberReader lnr = new LineNumberReader( + new StringReader("abc def ghi")); + if (testReader(lnr)) { + failed = true; + } + + File f = new File(System.getProperty("test.dir", "."), + "NewFile"); + f.createNewFile(); + f.deleteOnExit(); + + FileReader fr = new FileReader(f); + if (testReader(fr)) { + failed = true; + } + + PipedWriter pw = new PipedWriter(); + PipedReader pr = new PipedReader(pw); + if (testReader(pr)) { + failed = true; + } + if (failed) { + throw new Exception("Test failed for some of the operation{s}" + + " on some of the reader{s}, check the messages"); + } + } + + private static boolean testReader(Reader r) throws Exception { + r.close(); + boolean failed = false; + boolean result; + System.out.println("Testing reader:" + r); + for (OpsAfterClose op : OpsAfterClose.values()) { + result = op.check(r); + if (!result) { + failed = true; + } + System.out.println(op + ":" + result); + } + if (failed) { + System.out.println("Test failed for the failed operation{s}" + + " above for the Reader:" + r); + } + return failed; + } + + private static boolean testPushbackReader(PushbackReader pr) + throws Exception { + boolean failed = false; + try { + pr.unread(1); + System.out.println("Test failed for unread(int):" + pr); + failed = true; + } catch (IOException io) { + System.out.println("UNREAD(int):true"); + } + + char buf[] = new char[2]; + try { + pr.unread(buf, 0, 2); + System.out.println("Test failed for unread(buf, offset, len):" + + pr); + failed = true; + } catch (IOException io) { + System.out.println("UNREAD(buf, offset, len):true"); + } + try { + pr.unread(buf); + System.out.println("Test failed for unread(char[] buf):" + pr); + failed = true; + } catch (IOException io) { + System.out.println("UNREAD(buf):true"); + } + return failed; + } +} diff --git a/test/java/io/Reader/ReadParams.java b/test/java/io/Reader/ReadParams.java new file mode 100644 index 0000000000..b3abbee0d6 --- /dev/null +++ b/test/java/io/Reader/ReadParams.java @@ -0,0 +1,99 @@ +/* + * Copyright 1998 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 4127657 + * @summary Check for correct handling of parameters to + * XXXXReader.read(b, off, len). + * + */ + +import java.io.*; + +public class ReadParams { + static int values[] = {Integer.MIN_VALUE, -1, 0, 1, 4, 16, 31, + 32, 33, Integer.MAX_VALUE}; + static char b[][] = {null, new char[32]}; + + static void test(Reader rdr) throws Exception { + int i = 0, j = 0, k = 0; + boolean nullPtr = false, indexOutBnd = false; + + for (i = 0; i < b.length; i++) { + for ( j = 0; j < values.length; j++) { + for ( k = 0; k < values.length; k++) { + + nullPtr = (b[i] == null); + + int bufLen = nullPtr ? 0 : b[i].length; + indexOutBnd = ((values[j] + values[k]) < 0) + ||(values[j] < 0) + || (values[j] > bufLen) + || (values[k] < 0) + || ((values[j] + values[k]) > bufLen); + + try { + rdr.read(b[i], values[j], values[k]); + } catch (NullPointerException e) { + if (!nullPtr) { + throw new Exception + ("should not throw NullPointerException" + i + " " +j + " " + k); + } + continue; + } catch (IndexOutOfBoundsException e) { + if (!indexOutBnd) { + throw new Exception + ("should not throw IndexOutOfBoundsException"); + } + continue; + } + + if (nullPtr || indexOutBnd) { + throw new Exception("Should have thrown an exception"); + } + } + } + } + } + + public static void main(String args[]) throws Exception{ + StringReader sr = new StringReader(new String(new byte[512])); + test(sr); + + test(new BufferedReader(sr)); + + test(new CharArrayReader(new char[8])); + + InputStreamReader ir = new InputStreamReader + (new ByteArrayInputStream(new byte[512])); + test(ir); + + test(new PushbackReader(sr, 2)); + + PipedWriter pw = new PipedWriter(); + PipedReader pir = new PipedReader(pw); + pw.write(new char[512], 0, 512); + test(pir); + } +} diff --git a/test/java/io/Reader/Skip.java b/test/java/io/Reader/Skip.java new file mode 100644 index 0000000000..2ed4b3fa60 --- /dev/null +++ b/test/java/io/Reader/Skip.java @@ -0,0 +1,46 @@ +/* + * Copyright 1998 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 4134311 + @summary Test if skip works correctly +*/ + + + +import java.io.*; + +public class Skip { + public static void main(String argv[]) throws Exception { + File f = new File(System.getProperty("test.src", "."), + "SkipInput.txt"); + FileReader fr = new FileReader(f); + long nchars = 8200; + long actual = fr.skip(nchars); + + if (actual > nchars) { + throw new Exception + ("Should skip " + nchars + ", but skipped " +actual+" chars"); + } + } +} diff --git a/test/java/io/Reader/SkipInput.txt b/test/java/io/Reader/SkipInput.txt new file mode 100644 index 0000000000..c690b80da9 --- /dev/null +++ b/test/java/io/Reader/SkipInput.txt @@ -0,0 +1,400 @@ +This line of text is 50 characters in length 0 +This line of text is 50 characters in length 1 +This line of text is 50 characters in length 2 +This line of text is 50 characters in length 3 +This line of text is 50 characters in length 4 +This line of text is 50 characters in length 5 +This line of text is 50 characters in length 6 +This line of text is 50 characters in length 7 +This line of text is 50 characters in length 8 +This line of text is 50 characters in length 9 +This line of text is 50 characters in length 10 +This line of text is 50 characters in length 11 +This line of text is 50 characters in length 12 +This line of text is 50 characters in length 13 +This line of text is 50 characters in length 14 +This line of text is 50 characters in length 15 +This line of text is 50 characters in length 16 +This line of text is 50 characters in length 17 +This line of text is 50 characters in length 18 +This line of text is 50 characters in length 19 +This line of text is 50 characters in length 20 +This line of text is 50 characters in length 21 +This line of text is 50 characters in length 22 +This line of text is 50 characters in length 23 +This line of text is 50 characters in length 24 +This line of text is 50 characters in length 25 +This line of text is 50 characters in length 26 +This line of text is 50 characters in length 27 +This line of text is 50 characters in length 28 +This line of text is 50 characters in length 29 +This line of text is 50 characters in length 30 +This line of text is 50 characters in length 31 +This line of text is 50 characters in length 32 +This line of text is 50 characters in length 33 +This line of text is 50 characters in length 34 +This line of text is 50 characters in length 35 +This line of text is 50 characters in length 36 +This line of text is 50 characters in length 37 +This line of text is 50 characters in length 38 +This line of text is 50 characters in length 39 +This line of text is 50 characters in length 40 +This line of text is 50 characters in length 41 +This line of text is 50 characters in length 42 +This line of text is 50 characters in length 43 +This line of text is 50 characters in length 44 +This line of text is 50 characters in length 45 +This line of text is 50 characters in length 46 +This line of text is 50 characters in length 47 +This line of text is 50 characters in length 48 +This line of text is 50 characters in length 49 +This line of text is 50 characters in length 50 +This line of text is 50 characters in length 51 +This line of text is 50 characters in length 52 +This line of text is 50 characters in length 53 +This line of text is 50 characters in length 54 +This line of text is 50 characters in length 55 +This line of text is 50 characters in length 56 +This line of text is 50 characters in length 57 +This line of text is 50 characters in length 58 +This line of text is 50 characters in length 59 +This line of text is 50 characters in length 60 +This line of text is 50 characters in length 61 +This line of text is 50 characters in length 62 +This line of text is 50 characters in length 63 +This line of text is 50 characters in length 64 +This line of text is 50 characters in length 65 +This line of text is 50 characters in length 66 +This line of text is 50 characters in length 67 +This line of text is 50 characters in length 68 +This line of text is 50 characters in length 69 +This line of text is 50 characters in length 70 +This line of text is 50 characters in length 71 +This line of text is 50 characters in length 72 +This line of text is 50 characters in length 73 +This line of text is 50 characters in length 74 +This line of text is 50 characters in length 75 +This line of text is 50 characters in length 76 +This line of text is 50 characters in length 77 +This line of text is 50 characters in length 78 +This line of text is 50 characters in length 79 +This line of text is 50 characters in length 80 +This line of text is 50 characters in length 81 +This line of text is 50 characters in length 82 +This line of text is 50 characters in length 83 +This line of text is 50 characters in length 84 +This line of text is 50 characters in length 85 +This line of text is 50 characters in length 86 +This line of text is 50 characters in length 87 +This line of text is 50 characters in length 88 +This line of text is 50 characters in length 89 +This line of text is 50 characters in length 90 +This line of text is 50 characters in length 91 +This line of text is 50 characters in length 92 +This line of text is 50 characters in length 93 +This line of text is 50 characters in length 94 +This line of text is 50 characters in length 95 +This line of text is 50 characters in length 96 +This line of text is 50 characters in length 97 +This line of text is 50 characters in length 98 +This line of text is 50 characters in length 99 +This line of text is 50 characters in length 100 +This line of text is 50 characters in length 101 +This line of text is 50 characters in length 102 +This line of text is 50 characters in length 103 +This line of text is 50 characters in length 104 +This line of text is 50 characters in length 105 +This line of text is 50 characters in length 106 +This line of text is 50 characters in length 107 +This line of text is 50 characters in length 108 +This line of text is 50 characters in length 109 +This line of text is 50 characters in length 110 +This line of text is 50 characters in length 111 +This line of text is 50 characters in length 112 +This line of text is 50 characters in length 113 +This line of text is 50 characters in length 114 +This line of text is 50 characters in length 115 +This line of text is 50 characters in length 116 +This line of text is 50 characters in length 117 +This line of text is 50 characters in length 118 +This line of text is 50 characters in length 119 +This line of text is 50 characters in length 120 +This line of text is 50 characters in length 121 +This line of text is 50 characters in length 122 +This line of text is 50 characters in length 123 +This line of text is 50 characters in length 124 +This line of text is 50 characters in length 125 +This line of text is 50 characters in length 126 +This line of text is 50 characters in length 127 +This line of text is 50 characters in length 128 +This line of text is 50 characters in length 129 +This line of text is 50 characters in length 130 +This line of text is 50 characters in length 131 +This line of text is 50 characters in length 132 +This line of text is 50 characters in length 133 +This line of text is 50 characters in length 134 +This line of text is 50 characters in length 135 +This line of text is 50 characters in length 136 +This line of text is 50 characters in length 137 +This line of text is 50 characters in length 138 +This line of text is 50 characters in length 139 +This line of text is 50 characters in length 140 +This line of text is 50 characters in length 141 +This line of text is 50 characters in length 142 +This line of text is 50 characters in length 143 +This line of text is 50 characters in length 144 +This line of text is 50 characters in length 145 +This line of text is 50 characters in length 146 +This line of text is 50 characters in length 147 +This line of text is 50 characters in length 148 +This line of text is 50 characters in length 149 +This line of text is 50 characters in length 150 +This line of text is 50 characters in length 151 +This line of text is 50 characters in length 152 +This line of text is 50 characters in length 153 +This line of text is 50 characters in length 154 +This line of text is 50 characters in length 155 +This line of text is 50 characters in length 156 +This line of text is 50 characters in length 157 +This line of text is 50 characters in length 158 +This line of text is 50 characters in length 159 +This line of text is 50 characters in length 160 +This line of text is 50 characters in length 161 +This line of text is 50 characters in length 162 +This line of text is 50 characters in length 163 +This line of text is 50 characters in length 164 +This line of text is 50 characters in length 165 +This line of text is 50 characters in length 166 +This line of text is 50 characters in length 167 +This line of text is 50 characters in length 168 +This line of text is 50 characters in length 169 +This line of text is 50 characters in length 170 +This line of text is 50 characters in length 171 +This line of text is 50 characters in length 172 +This line of text is 50 characters in length 173 +This line of text is 50 characters in length 174 +This line of text is 50 characters in length 175 +This line of text is 50 characters in length 176 +This line of text is 50 characters in length 177 +This line of text is 50 characters in length 178 +This line of text is 50 characters in length 179 +This line of text is 50 characters in length 180 +This line of text is 50 characters in length 181 +This line of text is 50 characters in length 182 +This line of text is 50 characters in length 183 +This line of text is 50 characters in length 184 +This line of text is 50 characters in length 185 +This line of text is 50 characters in length 186 +This line of text is 50 characters in length 187 +This line of text is 50 characters in length 188 +This line of text is 50 characters in length 189 +This line of text is 50 characters in length 190 +This line of text is 50 characters in length 191 +This line of text is 50 characters in length 192 +This line of text is 50 characters in length 193 +This line of text is 50 characters in length 194 +This line of text is 50 characters in length 195 +This line of text is 50 characters in length 196 +This line of text is 50 characters in length 197 +This line of text is 50 characters in length 198 +This line of text is 50 characters in length 199 +This line of text is 50 characters in length 200 +This line of text is 50 characters in length 201 +This line of text is 50 characters in length 202 +This line of text is 50 characters in length 203 +This line of text is 50 characters in length 204 +This line of text is 50 characters in length 205 +This line of text is 50 characters in length 206 +This line of text is 50 characters in length 207 +This line of text is 50 characters in length 208 +This line of text is 50 characters in length 209 +This line of text is 50 characters in length 210 +This line of text is 50 characters in length 211 +This line of text is 50 characters in length 212 +This line of text is 50 characters in length 213 +This line of text is 50 characters in length 214 +This line of text is 50 characters in length 215 +This line of text is 50 characters in length 216 +This line of text is 50 characters in length 217 +This line of text is 50 characters in length 218 +This line of text is 50 characters in length 219 +This line of text is 50 characters in length 220 +This line of text is 50 characters in length 221 +This line of text is 50 characters in length 222 +This line of text is 50 characters in length 223 +This line of text is 50 characters in length 224 +This line of text is 50 characters in length 225 +This line of text is 50 characters in length 226 +This line of text is 50 characters in length 227 +This line of text is 50 characters in length 228 +This line of text is 50 characters in length 229 +This line of text is 50 characters in length 230 +This line of text is 50 characters in length 231 +This line of text is 50 characters in length 232 +This line of text is 50 characters in length 233 +This line of text is 50 characters in length 234 +This line of text is 50 characters in length 235 +This line of text is 50 characters in length 236 +This line of text is 50 characters in length 237 +This line of text is 50 characters in length 238 +This line of text is 50 characters in length 239 +This line of text is 50 characters in length 240 +This line of text is 50 characters in length 241 +This line of text is 50 characters in length 242 +This line of text is 50 characters in length 243 +This line of text is 50 characters in length 244 +This line of text is 50 characters in length 245 +This line of text is 50 characters in length 246 +This line of text is 50 characters in length 247 +This line of text is 50 characters in length 248 +This line of text is 50 characters in length 249 +This line of text is 50 characters in length 250 +This line of text is 50 characters in length 251 +This line of text is 50 characters in length 252 +This line of text is 50 characters in length 253 +This line of text is 50 characters in length 254 +This line of text is 50 characters in length 255 +This line of text is 50 characters in length 256 +This line of text is 50 characters in length 257 +This line of text is 50 characters in length 258 +This line of text is 50 characters in length 259 +This line of text is 50 characters in length 260 +This line of text is 50 characters in length 261 +This line of text is 50 characters in length 262 +This line of text is 50 characters in length 263 +This line of text is 50 characters in length 264 +This line of text is 50 characters in length 265 +This line of text is 50 characters in length 266 +This line of text is 50 characters in length 267 +This line of text is 50 characters in length 268 +This line of text is 50 characters in length 269 +This line of text is 50 characters in length 270 +This line of text is 50 characters in length 271 +This line of text is 50 characters in length 272 +This line of text is 50 characters in length 273 +This line of text is 50 characters in length 274 +This line of text is 50 characters in length 275 +This line of text is 50 characters in length 276 +This line of text is 50 characters in length 277 +This line of text is 50 characters in length 278 +This line of text is 50 characters in length 279 +This line of text is 50 characters in length 280 +This line of text is 50 characters in length 281 +This line of text is 50 characters in length 282 +This line of text is 50 characters in length 283 +This line of text is 50 characters in length 284 +This line of text is 50 characters in length 285 +This line of text is 50 characters in length 286 +This line of text is 50 characters in length 287 +This line of text is 50 characters in length 288 +This line of text is 50 characters in length 289 +This line of text is 50 characters in length 290 +This line of text is 50 characters in length 291 +This line of text is 50 characters in length 292 +This line of text is 50 characters in length 293 +This line of text is 50 characters in length 294 +This line of text is 50 characters in length 295 +This line of text is 50 characters in length 296 +This line of text is 50 characters in length 297 +This line of text is 50 characters in length 298 +This line of text is 50 characters in length 299 +This line of text is 50 characters in length 300 +This line of text is 50 characters in length 301 +This line of text is 50 characters in length 302 +This line of text is 50 characters in length 303 +This line of text is 50 characters in length 304 +This line of text is 50 characters in length 305 +This line of text is 50 characters in length 306 +This line of text is 50 characters in length 307 +This line of text is 50 characters in length 308 +This line of text is 50 characters in length 309 +This line of text is 50 characters in length 310 +This line of text is 50 characters in length 311 +This line of text is 50 characters in length 312 +This line of text is 50 characters in length 313 +This line of text is 50 characters in length 314 +This line of text is 50 characters in length 315 +This line of text is 50 characters in length 316 +This line of text is 50 characters in length 317 +This line of text is 50 characters in length 318 +This line of text is 50 characters in length 319 +This line of text is 50 characters in length 320 +This line of text is 50 characters in length 321 +This line of text is 50 characters in length 322 +This line of text is 50 characters in length 323 +This line of text is 50 characters in length 324 +This line of text is 50 characters in length 325 +This line of text is 50 characters in length 326 +This line of text is 50 characters in length 327 +This line of text is 50 characters in length 328 +This line of text is 50 characters in length 329 +This line of text is 50 characters in length 330 +This line of text is 50 characters in length 331 +This line of text is 50 characters in length 332 +This line of text is 50 characters in length 333 +This line of text is 50 characters in length 334 +This line of text is 50 characters in length 335 +This line of text is 50 characters in length 336 +This line of text is 50 characters in length 337 +This line of text is 50 characters in length 338 +This line of text is 50 characters in length 339 +This line of text is 50 characters in length 340 +This line of text is 50 characters in length 341 +This line of text is 50 characters in length 342 +This line of text is 50 characters in length 343 +This line of text is 50 characters in length 344 +This line of text is 50 characters in length 345 +This line of text is 50 characters in length 346 +This line of text is 50 characters in length 347 +This line of text is 50 characters in length 348 +This line of text is 50 characters in length 349 +This line of text is 50 characters in length 350 +This line of text is 50 characters in length 351 +This line of text is 50 characters in length 352 +This line of text is 50 characters in length 353 +This line of text is 50 characters in length 354 +This line of text is 50 characters in length 355 +This line of text is 50 characters in length 356 +This line of text is 50 characters in length 357 +This line of text is 50 characters in length 358 +This line of text is 50 characters in length 359 +This line of text is 50 characters in length 360 +This line of text is 50 characters in length 361 +This line of text is 50 characters in length 362 +This line of text is 50 characters in length 363 +This line of text is 50 characters in length 364 +This line of text is 50 characters in length 365 +This line of text is 50 characters in length 366 +This line of text is 50 characters in length 367 +This line of text is 50 characters in length 368 +This line of text is 50 characters in length 369 +This line of text is 50 characters in length 370 +This line of text is 50 characters in length 371 +This line of text is 50 characters in length 372 +This line of text is 50 characters in length 373 +This line of text is 50 characters in length 374 +This line of text is 50 characters in length 375 +This line of text is 50 characters in length 376 +This line of text is 50 characters in length 377 +This line of text is 50 characters in length 378 +This line of text is 50 characters in length 379 +This line of text is 50 characters in length 380 +This line of text is 50 characters in length 381 +This line of text is 50 characters in length 382 +This line of text is 50 characters in length 383 +This line of text is 50 characters in length 384 +This line of text is 50 characters in length 385 +This line of text is 50 characters in length 386 +This line of text is 50 characters in length 387 +This line of text is 50 characters in length 388 +This line of text is 50 characters in length 389 +This line of text is 50 characters in length 390 +This line of text is 50 characters in length 391 +This line of text is 50 characters in length 392 +This line of text is 50 characters in length 393 +This line of text is 50 characters in length 394 +This line of text is 50 characters in length 395 +This line of text is 50 characters in length 396 +This line of text is 50 characters in length 397 +This line of text is 50 characters in length 398 +This line of text is 50 characters in length 399 diff --git a/test/java/io/Reader/SkipNegative.java b/test/java/io/Reader/SkipNegative.java new file mode 100644 index 0000000000..3f5e4ab3fd --- /dev/null +++ b/test/java/io/Reader/SkipNegative.java @@ -0,0 +1,47 @@ +/* + * Copyright 1998 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 4150442 + @summary Skip must throw an exception for negative args +*/ + + + +import java.io.*; + +public class SkipNegative { + public static void main(String argv[]) throws Exception { + File f = new File(System.getProperty("test.src", "."), + "SkipInput.txt"); + FileReader fr = new FileReader(f); + long nchars = -1L; + try { + long actual = fr.skip(nchars); + } catch(IllegalArgumentException e){ + // Negative argument caught + return; + } + throw new Exception("Skip should not accept negative values"); + } +} diff --git a/test/java/io/SequenceInputStream/ConstructorNull.java b/test/java/io/SequenceInputStream/ConstructorNull.java new file mode 100644 index 0000000000..15516ccd67 --- /dev/null +++ b/test/java/io/SequenceInputStream/ConstructorNull.java @@ -0,0 +1,55 @@ +/* + * Copyright 1998 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 4016189 + * @summary Test operation of nextStream method of SIS + * + */ + +import java.io.*; + +/** + * This class tests to see if java.io.SequenceInputStream + * nextStream() method operates properly when some of the + * streams it is given on input are null + */ + +public class ConstructorNull { + + public static void main( String[] argv ) throws Exception { + byte[] data = {10,20}; + int b1,b2; + ByteArrayInputStream is = new ByteArrayInputStream(data); + + try { + SequenceInputStream sis = new SequenceInputStream(null,is); + int b = sis.read(); + throw new RuntimeException("No exception with null stream"); + } catch(NullPointerException e) { + System.err.println("Test passed: NullPointerException thrown"); + } + + } +} diff --git a/test/java/io/Serializable/ClassCastExceptionDetail/Read.java b/test/java/io/Serializable/ClassCastExceptionDetail/Read.java new file mode 100644 index 0000000000..2f18c78a55 --- /dev/null +++ b/test/java/io/Serializable/ClassCastExceptionDetail/Read.java @@ -0,0 +1,62 @@ +/* + * 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. + */ + +/* + * @bug 4511532 + * @summary Verify that the message string of a ClassCastException thrown by + * ObjectInputStream when attempting to assign a value to a field of + * an incompatible type contains the names of the value's class, the + * field's declaring class, the field's type, and the field itself. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 0L; + private Float bar; +} + +class Gub extends Foo {} + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("tmp.ser")); + try { + oin.readObject(); + throw new Error("readObject should not succeed"); + } catch (ClassCastException e) { + String s = e.getMessage(); + System.out.println("ClassCastException message: " + s); + if (s == null || + s.indexOf(Foo.class.getName()) == -1 || + s.indexOf(Integer.class.getName()) == -1 || + s.indexOf(Float.class.getName()) == -1 || + s.indexOf(Gub.class.getName()) == -1 || + s.indexOf("bar") == -1) + { + throw new Error("ClassNotFoundException message incomplete"); + } + } + } +} diff --git a/test/java/io/Serializable/ClassCastExceptionDetail/Write.java b/test/java/io/Serializable/ClassCastExceptionDetail/Write.java new file mode 100644 index 0000000000..3f71f965e5 --- /dev/null +++ b/test/java/io/Serializable/ClassCastExceptionDetail/Write.java @@ -0,0 +1,56 @@ +/* + * 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 4511532 + * + * @clean Write Read Foo Gub + * @compile Write.java + * @run main Write + * @clean Write Read Foo Gub + * @compile Read.java + * @run main Read + * + * @summary Verify that the message string of a ClassCastException thrown by + * ObjectInputStream when attempting to assign a value to a field of + * an incompatible type contains the names of the value's class, the + * field's declaring class, the field's type, and the field itself. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 0L; + private Integer bar = new Integer(0); +} + +class Gub extends Foo {} + +public class Write { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("tmp.ser")); + oout.writeObject(new Gub()); + oout.close(); + } +} diff --git a/test/java/io/Serializable/GetField/Read.java b/test/java/io/Serializable/GetField/Read.java new file mode 100644 index 0000000000..2eec7f7365 --- /dev/null +++ b/test/java/io/Serializable/GetField/Read.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. + */ + +/* + * @bug 4402830 + * @summary Verify that the ObjectInputStream.GetField API works properly for + * serialized fields which don't exist in the receiving object. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 0L; + int blargh; + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + ObjectInputStream.GetField fields = in.readFields(); + if (! fields.defaulted("blargh")) { + throw new Error(); + } + try { + fields.defaulted("nonexistant"); + throw new Error(); + } catch (IllegalArgumentException ex) { + } + if ((fields.get("z", false) != true) || + (fields.get("b", (byte) 0) != 5) || + (fields.get("c", '0') != '5') || + (fields.get("s", (short) 0) != 5) || + (fields.get("i", 0) != 5) || + (fields.get("j", 0l) != 5) || + (fields.get("f", 0.0f) != 5.0f) || + (fields.get("d", 0.0) != 5.0) || + (! fields.get("str", null).equals("5"))) + { + throw new Error(); + } + } +} + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("tmp.ser")); + oin.readObject(); + oin.close(); + } +} diff --git a/test/java/io/Serializable/GetField/Read2.java b/test/java/io/Serializable/GetField/Read2.java new file mode 100644 index 0000000000..33aac89b24 --- /dev/null +++ b/test/java/io/Serializable/GetField/Read2.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. + */ + +/* + * @bug 4427881 + * @summary Verify that the ObjectInputStream.GetField API works properly for + * serialized fields which exist in the receiving object. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 0L; + + boolean z; + byte b; + char c; + short s; + int i; + long j; + float f; + double d; + String str; + Object extra; + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + ObjectInputStream.GetField fields = in.readFields(); + if ((fields.get("z", false) != true) || + (fields.get("b", (byte) 0) != 5) || + (fields.get("c", '0') != '5') || + (fields.get("s", (short) 0) != 5) || + (fields.get("i", 0) != 5) || + (fields.get("j", 0l) != 5) || + (fields.get("f", 0.0f) != 5.0f) || + (fields.get("d", 0.0) != 5.0) || + (! fields.get("str", null).equals("5"))) + { + throw new Error(); + } + } +} + +public class Read2 { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("tmp.ser")); + oin.readObject(); + oin.close(); + } +} diff --git a/test/java/io/Serializable/GetField/Write.java b/test/java/io/Serializable/GetField/Write.java new file mode 100644 index 0000000000..3ef3faa045 --- /dev/null +++ b/test/java/io/Serializable/GetField/Write.java @@ -0,0 +1,65 @@ +/* + * 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 4402830 4427881 + * + * @clean Write Read Read2 Foo + * @compile Write.java + * @run main Write + * @clean Write Foo + * @compile Read.java + * @run main Read + * @clean Read Foo + * @compile Read2.java + * @run main Read2 + * @clean Read2 Foo + * + * @summary Verify proper basic functionality of the + * ObjectInputStream.GetField API + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 0L; + + boolean z = true; + byte b = 5; + char c = '5'; + short s = 5; + int i = 5; + long j = 5; + float f = 5.0f; + double d = 5.0; + String str = "5"; +} + +public class Write { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("tmp.ser")); + oout.writeObject(new Foo()); + oout.close(); + } +} diff --git a/test/java/io/Serializable/InvalidClassException/noargctor/DefaultPackage.java b/test/java/io/Serializable/InvalidClassException/noargctor/DefaultPackage.java new file mode 100644 index 0000000000..ccc181e7fc --- /dev/null +++ b/test/java/io/Serializable/InvalidClassException/noargctor/DefaultPackage.java @@ -0,0 +1,200 @@ +/* + * Copyright 1998 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 4093279 + * @compile DefaultPackage.java + * @run main DefaultPackage + * @summary Raise InvalidClassException if 1st NonSerializable superclass' no-arg constructor is not accessible. This test verifies default package access. + */ +import java.io.*; + +class DefaultPackagePublicConstructor { + public DefaultPackagePublicConstructor() { + } +}; + +class DefaultPackageProtectedConstructor { + protected DefaultPackageProtectedConstructor() { + } +}; + +class DefaultPackageDefaultAccessConstructor { + DefaultPackageDefaultAccessConstructor() { + } +}; + +class DefaultPackagePrivateConstructor { + private DefaultPackagePrivateConstructor() { + } + + /* need to have at least one protected constructor to extend this class.*/ + protected DefaultPackagePrivateConstructor(int i) { + } +}; + +class DefaultPublicSerializable +extends DefaultPackagePublicConstructor implements Serializable +{ + int field1 = 5; +}; + +class DefaultProtectedSerializable +extends DefaultPackageProtectedConstructor implements Serializable +{ + int field1 = 5; +}; + +class DefaultAccessSerializable +extends DefaultPackageDefaultAccessConstructor implements Serializable +{ + int field1 = 5; +}; + +class DefaultPrivateSerializable +extends DefaultPackagePrivateConstructor implements Serializable +{ + int field1 = 5; + + DefaultPrivateSerializable() { + super(1); + } +}; + +class ExternalizablePublicConstructor implements Externalizable { + public ExternalizablePublicConstructor() { + } + public void writeExternal(ObjectOutput out) throws IOException { + } + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException + { + } +}; + +class ExternalizableProtectedConstructor implements Externalizable { + protected ExternalizableProtectedConstructor() { + } + public void writeExternal(ObjectOutput out) throws IOException { + } + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException + { + } +}; + +class ExternalizableAccessConstructor implements Externalizable { + ExternalizableAccessConstructor() { + } + public void writeExternal(ObjectOutput out) throws IOException { + } + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException + { + } +}; + +class ExternalizablePrivateConstructor implements Externalizable { + private ExternalizablePrivateConstructor() { + } + public ExternalizablePrivateConstructor(int i) { + } + public void writeExternal(ObjectOutput out) throws IOException { + } + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException + { + } +}; + + +public class DefaultPackage { + public static void main(String args[]) + throws IOException, ClassNotFoundException + { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(baos); + out.writeObject(new DefaultPublicSerializable()); + out.writeObject(new DefaultProtectedSerializable()); + out.writeObject(new DefaultAccessSerializable()); + out.writeObject(new DefaultPrivateSerializable()); + + InputStream is = new ByteArrayInputStream(baos.toByteArray()); + ObjectInputStream in = new ObjectInputStream(is); + /* (DefaultPublicSerializable) */ in.readObject(); + /* (DefaultProtectedSerializable) */ in.readObject(); + /* (DefaultAcccessSerializable) */ in.readObject(); + try { + /* (DefaultPrivateSerializable) */ in.readObject(); + throw new Error("Expected InvalidClassException reading DefaultPrivateSerialziable"); + } catch (InvalidClassException e) { + } + in.close(); + + baos.reset(); + out = new ObjectOutputStream(baos); + out.writeObject(new ExternalizablePublicConstructor()); + + in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + /* (ExternalizablePublicConstructor) */ in.readObject(); + in.close(); + + baos.reset(); + out = new ObjectOutputStream(baos); + out.writeObject(new ExternalizableProtectedConstructor()); + + + in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + try { + /* (ExternalizableProtectedConstructor) */ in.readObject(); + throw new Error("Expected InvalidClassException reading ExternalizableProtectedConstructor"); + } catch (InvalidClassException e) { + } + in.close(); + + baos.reset(); + out = new ObjectOutputStream(baos); + out.writeObject(new ExternalizableAccessConstructor()); + + in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + try { + /* (ExternalizableAccessConstructor) */ in.readObject(); + throw new Error("Expected InvalidClassException reading ExternalizableAccessConstructor"); + } catch (InvalidClassException e) { + } + in.close(); + + baos.reset(); + out = new ObjectOutputStream(baos); + out.writeObject(new ExternalizablePrivateConstructor(2)); + + in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + try { + /* (ExternalizablePrivateConstructor) */ in.readObject(); + throw new Error("Expected InvalidClassException reading ExternalizablePrivateConstructor"); + } catch (InvalidClassException e) { + } + out.close(); + in.close(); + } +} diff --git a/test/java/io/Serializable/InvalidClassException/noargctor/NonSerialize/PackageCtor.java b/test/java/io/Serializable/InvalidClassException/noargctor/NonSerialize/PackageCtor.java new file mode 100644 index 0000000000..a2fa0d9f13 --- /dev/null +++ b/test/java/io/Serializable/InvalidClassException/noargctor/NonSerialize/PackageCtor.java @@ -0,0 +1,35 @@ +/* + * Copyright 1998 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. + */ + +/* + * @bug 4093279 + */ + +package NonSerializable; + +public class PackageCtor { + PackageCtor() { + } + public PackageCtor(int l) { + } +}; diff --git a/test/java/io/Serializable/InvalidClassException/noargctor/NonSerialize/PrivateCtor.java b/test/java/io/Serializable/InvalidClassException/noargctor/NonSerialize/PrivateCtor.java new file mode 100644 index 0000000000..c38c948886 --- /dev/null +++ b/test/java/io/Serializable/InvalidClassException/noargctor/NonSerialize/PrivateCtor.java @@ -0,0 +1,36 @@ +/* + * Copyright 1998 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. + */ + +/* + * @bug 4093279 + */ + +package NonSerializable; + +public class PrivateCtor { + private PrivateCtor() { + } + /* need to have at least one protected constructor to extend this class.*/ + public PrivateCtor(int i) { + } +}; diff --git a/test/java/io/Serializable/InvalidClassException/noargctor/NonSerialize/ProtectedCtor.java b/test/java/io/Serializable/InvalidClassException/noargctor/NonSerialize/ProtectedCtor.java new file mode 100644 index 0000000000..7c7198054d --- /dev/null +++ b/test/java/io/Serializable/InvalidClassException/noargctor/NonSerialize/ProtectedCtor.java @@ -0,0 +1,33 @@ +/* + * Copyright 1998 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. + */ + +/* + * @bug 4093279 + */ + +package NonSerializable; + +public class ProtectedCtor { + protected ProtectedCtor() { + } +}; diff --git a/test/java/io/Serializable/InvalidClassException/noargctor/NonSerialize/PublicCtor.java b/test/java/io/Serializable/InvalidClassException/noargctor/NonSerialize/PublicCtor.java new file mode 100644 index 0000000000..5b9868deb9 --- /dev/null +++ b/test/java/io/Serializable/InvalidClassException/noargctor/NonSerialize/PublicCtor.java @@ -0,0 +1,33 @@ +/* + * Copyright 1998 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. + */ + +/* + * @bug 4093279 + */ + +package NonSerializable; + +public class PublicCtor { + public PublicCtor() { + } +}; diff --git a/test/java/io/Serializable/InvalidClassException/noargctor/Serialize/SamePackageCtor.java b/test/java/io/Serializable/InvalidClassException/noargctor/Serialize/SamePackageCtor.java new file mode 100644 index 0000000000..6c3db03d89 --- /dev/null +++ b/test/java/io/Serializable/InvalidClassException/noargctor/Serialize/SamePackageCtor.java @@ -0,0 +1,33 @@ +/* + * Copyright 1998 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. + */ + +/* + * @bug 4093279 + */ + +package Serialize; + +public class SamePackageCtor { + SamePackageCtor() { + } +}; diff --git a/test/java/io/Serializable/InvalidClassException/noargctor/Serialize/SubclassAcrossPackage.java b/test/java/io/Serializable/InvalidClassException/noargctor/Serialize/SubclassAcrossPackage.java new file mode 100644 index 0000000000..513955de01 --- /dev/null +++ b/test/java/io/Serializable/InvalidClassException/noargctor/Serialize/SubclassAcrossPackage.java @@ -0,0 +1,239 @@ +/* + * Copyright 1998 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. + */ + +/* + * @bug 4093279 + * REMOVED test, build and run tag since could not get this to work. + * Test is run via shell script, run.sh. + */ + +package Serialize; + +import java.io.*; + +class PublicSerializable +extends NonSerializable.PublicCtor implements Serializable +{ + int field1 = 5; +}; + +class ProtectedSerializable +extends NonSerializable.ProtectedCtor implements Serializable +{ + int field1 = 5; +}; + +class DifferentPackageSerializable +extends NonSerializable.PackageCtor implements Serializable +{ + int field1 = 5; + DifferentPackageSerializable() { + super(1); + } +}; + +class SamePackageSerializable +extends Serialize.SamePackageCtor implements Serializable +{ + SamePackageSerializable() { + } +}; + +class SamePackageProtectedCtor { + protected SamePackageProtectedCtor() { + } +}; + +class SamePackageProtectedSerializable +extends Serialize.SamePackageProtectedCtor implements Serializable +{ + SamePackageProtectedSerializable() { + } +}; + + +class SamePackagePrivateCtor { + private SamePackagePrivateCtor() { + } + public SamePackagePrivateCtor(int l) { + } +}; + +class SamePackagePrivateSerializable +extends Serialize.SamePackagePrivateCtor implements Serializable +{ + SamePackagePrivateSerializable() { + super(1); + } +}; + +class PrivateSerializable +extends NonSerializable.PrivateCtor implements Serializable +{ + int field1 = 5; + + PrivateSerializable() { + super(1); + } +}; + +class ExternalizablePublicCtor implements Externalizable { + public ExternalizablePublicCtor() { + } + public void writeExternal(ObjectOutput out) throws IOException { + } + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException + { + } +}; + +class ExternalizableProtectedCtor implements Externalizable { + protected ExternalizableProtectedCtor() { + } + public void writeExternal(ObjectOutput out) throws IOException { + } + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException + { + } +}; + +class ExternalizablePackageCtor implements Externalizable { + ExternalizablePackageCtor() { + } + public void writeExternal(ObjectOutput out) throws IOException { + } + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException + { + } +}; + +class ExternalizablePrivateCtor implements Externalizable { + private ExternalizablePrivateCtor() { + } + public ExternalizablePrivateCtor(int i) { + } + public void writeExternal(ObjectOutput out) throws IOException { + } + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException + { + } +}; + + +public class SubclassAcrossPackage { + public static void main(String args[]) + throws IOException, ClassNotFoundException + { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(baos); + out.writeObject(new PublicSerializable()); + out.writeObject(new ProtectedSerializable()); + out.writeObject(new SamePackageSerializable()); + out.writeObject(new SamePackageProtectedSerializable()); + out.writeObject(new DifferentPackageSerializable()); + + InputStream is = new ByteArrayInputStream(baos.toByteArray()); + ObjectInputStream in = new ObjectInputStream(is); + /* (PublicSerializable)*/ in.readObject(); + /* (ProtectedSerializable) */ in.readObject(); + /* (SamePackageSerializable) */ in.readObject(); + /* (SamePackageProtectedSerializable) */ in.readObject(); + try { + /* (DifferentPackageSerializable) */ in.readObject(); + } catch (InvalidClassException e) { + } + in.close(); + + baos.reset(); + out = new ObjectOutputStream(baos); + out.writeObject(new PrivateSerializable()); + in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + try { + /* (PrivateSerializable) */ in.readObject(); + throw new Error("Expected InvalidClassException reading PrivateSerialziable"); + } catch (InvalidClassException e) { + } + in.close(); + + baos.reset(); + out = new ObjectOutputStream(baos); + out.writeObject(new SamePackagePrivateSerializable()); + in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + try { + /* (SamePackagePrivateSerializable) */ in.readObject(); + throw new Error("Expected InvalidClassException reading PrivateSerialziable"); + } catch (InvalidClassException e) { + } + in.close(); + + baos.reset(); + out = new ObjectOutputStream(baos); + out.writeObject(new ExternalizablePublicCtor()); + + in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + /* (ExternalizablePublicCtor) */ in.readObject(); + in.close(); + + baos.reset(); + out = new ObjectOutputStream(baos); + out.writeObject(new ExternalizableProtectedCtor()); + + + in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + try { + /* (ExternalizableProtectedCtor) */ in.readObject(); + throw new Error("Expected InvalidClassException reading ExternalizableProtectedCtor"); + } catch (InvalidClassException e) { + } + in.close(); + + baos.reset(); + out = new ObjectOutputStream(baos); + out.writeObject(new ExternalizablePackageCtor()); + + in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + try { + /* (ExternalizablePackageCtor) */ in.readObject(); + throw new Error("Expected InvalidClassException reading ExternalizablePackageCtor"); + } catch (InvalidClassException e) { + } + in.close(); + + baos.reset(); + out = new ObjectOutputStream(baos); + out.writeObject(new ExternalizablePrivateCtor(2)); + + in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + try { + /* (ExternalizablePrivateCtor) */ in.readObject(); + throw new Error("Expected InvalidClassException reading ExternalizablePrivateCtor"); + } catch (InvalidClassException e) { + } + out.close(); + in.close(); + } +} diff --git a/test/java/io/Serializable/InvalidClassException/noargctor/Test.java b/test/java/io/Serializable/InvalidClassException/noargctor/Test.java new file mode 100644 index 0000000000..aa3f6b0555 --- /dev/null +++ b/test/java/io/Serializable/InvalidClassException/noargctor/Test.java @@ -0,0 +1,40 @@ +/* + * Copyright 1998-2000 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 4093279 + * @summary Validate accessibility checking to NonSerializable superclass constuctor. + * @library NonSerialize Serialize + * @compile NonSerialize/PrivateCtor.java NonSerialize/ProtectedCtor.java NonSerialize/PackageCtor.java NonSerialize/PublicCtor.java + * @compile Serialize/SubclassAcrossPackage.java Serialize/SamePackageCtor.java + * @run main Test + */ +import java.io.*; +import Serialize.SubclassAcrossPackage; +public class Test { + public static void main(String[] args) + throws IOException, ClassNotFoundException { + Serialize.SubclassAcrossPackage.main(args); + } +} diff --git a/test/java/io/Serializable/NPEProvoker/NPEProvoker.java b/test/java/io/Serializable/NPEProvoker/NPEProvoker.java new file mode 100644 index 0000000000..542342b1d0 --- /dev/null +++ b/test/java/io/Serializable/NPEProvoker/NPEProvoker.java @@ -0,0 +1,78 @@ +/* + * 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 6541870 + * @summary this test checks that ObjectInputStream throws an IOException + * instead of a NullPointerException when deserializing an ArrayList + * of Externalizables if there is an IOException while deserializing + * one of these Externalizables. + * + * @author Andrey Ozerov + */ + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectInputStream; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; +import java.util.ArrayList; + +public class NPEProvoker implements java.io.Externalizable { + private String test = "test"; + + public void readExternal(ObjectInput in) throws IOException, + ClassNotFoundException + { + throw new IOException(); //io exception for whatever reason + } + + public void writeExternal(ObjectOutput out) throws IOException { + out.writeObject(test); + } + + public static void main(String[] args) { + System.err.println("\n Regression test for bug 6541870\n"); + try { + ArrayList<NPEProvoker> list = new ArrayList<NPEProvoker>(); + list.add(new NPEProvoker()); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(list); + + ObjectInputStream ois = + new ObjectInputStream(new ByteArrayInputStream( + baos.toByteArray())); + ois.readObject(); + throw new Error(); + } catch (IOException e) { + System.err.println("\nTEST PASSED"); + } catch (ClassNotFoundException e) { + throw new Error(); + } catch (NullPointerException e) { + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/NoClassDefFoundErrorTrap/NoClassDefFoundErrorTrap.java b/test/java/io/Serializable/NoClassDefFoundErrorTrap/NoClassDefFoundErrorTrap.java new file mode 100644 index 0000000000..fd659a5afa --- /dev/null +++ b/test/java/io/Serializable/NoClassDefFoundErrorTrap/NoClassDefFoundErrorTrap.java @@ -0,0 +1,112 @@ +/* + * Copyright 1999 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 4205440 + * @summary When ObjectInputStream.inputClassDescriptor calls its protected + * resolveClass, if a NoClassDefFoundError is thrown, that Error should be + * propagated to the caller, instead of being trapped and transformed into + * a ClassNotFoundException for the class being resolved. + * @author Peter Jones + * + * @build NoClassDefFoundErrorTrap + * @run main NoClassDefFoundErrorTrap + */ + +import java.io.*; + +public class NoClassDefFoundErrorTrap { + + private static NoClassDefFoundError ncdfe; + + public interface Bar {} + public static class Foo implements Bar, java.io.Serializable {} + + /** + * Test subclass of ObjectInputStream that overrides resolveClass + * to throw a NoClassDefFoundError if our test class "Foo" is to + * be resolved. + */ + public static class TestObjectInputStream extends ObjectInputStream { + + public TestObjectInputStream(InputStream in) + throws IOException + { + super(in); + } + + protected Class resolveClass(ObjectStreamClass desc) + throws IOException, ClassNotFoundException + { + String name = desc.getName(); + + if (name.equals(Foo.class.getName())) { + ncdfe = new NoClassDefFoundError("Bar"); + throw ncdfe; + } else { + return super.resolveClass(desc); + } + } + } + + public static void main(String[] args) { + + System.err.println("\nRegression test for bug 4205440\n"); + + try { + /* + * Serialize a Foo instance to a byte array. + */ + Foo foo = new Foo(); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(bout); + out.writeObject(foo); + byte[] stream = bout.toByteArray(); + + /* + * Deserialize the Foo instance using our test subclass of + * ObjectInputStream that will throw NoClassDefFoundError. + */ + ByteArrayInputStream bin = new ByteArrayInputStream(stream); + ObjectInputStream in = new TestObjectInputStream(bin); + + /* + * The test succeeds if we get the NoClassDefFoundError. + */ + try { + in.readObject(); + } catch (NoClassDefFoundError e) { + if (e == ncdfe) { + System.err.println("TEST PASSED: " + e.toString()); + } else { + throw e; + } + } + + } catch (Exception e) { + System.err.println("\nTEST FAILED:"); + e.printStackTrace(); + throw new RuntimeException("TEST FAILED: " + e.toString()); + } + } +} diff --git a/test/java/io/Serializable/PutField/Read.java b/test/java/io/Serializable/PutField/Read.java new file mode 100644 index 0000000000..ec1af04cbf --- /dev/null +++ b/test/java/io/Serializable/PutField/Read.java @@ -0,0 +1,65 @@ +/* + * 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. + */ + +/* + * @summary Verify that the ObjectOutputStream.PutField API works as + * advertised. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 0L; + + boolean z; + byte b; + char c; + short s; + int i; + long j; + float f; + double d; + String str; +} + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("tmp.ser")); + Foo foo = (Foo) oin.readObject(); + oin.close(); + + if ((! foo.z) || + (foo.b != 5) || + (foo.c != '5') || + (foo.s != 5) || + (foo.i != 5) || + (foo.j != 5) || + (foo.f != 5.0f) || + (foo.d != 5.0) || + (! foo.str.equals("5"))) + { + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/PutField/Read2.java b/test/java/io/Serializable/PutField/Read2.java new file mode 100644 index 0000000000..78bc955e26 --- /dev/null +++ b/test/java/io/Serializable/PutField/Read2.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. + */ + +/* + * @bug 4453723 + * @summary Verify that ObjectOutputStream.PutField.write() works for objects + * that do not define primitive serializable fields. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 0L; + String s1, s2; +} + +public class Read2 { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("tmp.ser")); + Foo foo = (Foo) oin.readObject(); + oin.close(); + + if (!(foo.s1.equals("qwerty") && foo.s2.equals("asdfg"))) { + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/PutField/Write.java b/test/java/io/Serializable/PutField/Write.java new file mode 100644 index 0000000000..0fcc13be14 --- /dev/null +++ b/test/java/io/Serializable/PutField/Write.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 + * + * @clean Write Read Foo + * @compile Write.java + * @run main Write + * @clean Write Read Foo + * @compile Read.java + * @run main Read + * + * @summary Verify that the ObjectOutputStream.PutField API works as + * advertised. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 0L; + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("z", boolean.class), + new ObjectStreamField("b", byte.class), + new ObjectStreamField("c", char.class), + new ObjectStreamField("s", short.class), + new ObjectStreamField("i", int.class), + new ObjectStreamField("j", long.class), + new ObjectStreamField("f", float.class), + new ObjectStreamField("d", double.class), + new ObjectStreamField("str", String.class), + }; + + private void writeObject(ObjectOutputStream out) throws IOException { + ObjectOutputStream.PutField fields = out.putFields(); + fields.put("z", true); + fields.put("b", (byte) 5); + fields.put("c", '5'); + fields.put("s", (short) 5); + fields.put("i", 5); + fields.put("j", 5l); + fields.put("f", 5.0f); + fields.put("d", 5.0); + fields.put("str", "5"); + out.writeFields(); + } +} + +public class Write { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("tmp.ser")); + oout.writeObject(new Foo()); + oout.close(); + } +} diff --git a/test/java/io/Serializable/PutField/Write2.java b/test/java/io/Serializable/PutField/Write2.java new file mode 100644 index 0000000000..bd62e03a20 --- /dev/null +++ b/test/java/io/Serializable/PutField/Write2.java @@ -0,0 +1,62 @@ +/* + * 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 4453723 + * + * @clean Write2 Read2 Foo + * @compile Write2.java + * @run main Write2 + * @clean Write2 Read2 Foo + * @compile Read2.java + * @run main Read2 + * + * @summary Verify that ObjectOutputStream.PutField.write() works for objects + * that do not define primitive serializable fields. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 0L; + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("s1", String.class), + new ObjectStreamField("s2", String.class) + }; + + private void writeObject(ObjectOutputStream out) throws IOException { + ObjectOutputStream.PutField fields = out.putFields(); + fields.put("s1", "qwerty"); + fields.put("s2", "asdfg"); + fields.write(out); + } +} + +public class Write2 { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("tmp.ser")); + oout.writeObject(new Foo()); + oout.close(); + } +} diff --git a/test/java/io/Serializable/accessConstants/AccessConstants.java b/test/java/io/Serializable/accessConstants/AccessConstants.java new file mode 100644 index 0000000000..4575a3b0e7 --- /dev/null +++ b/test/java/io/Serializable/accessConstants/AccessConstants.java @@ -0,0 +1,44 @@ +/* + * Copyright 1998 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 4067964 +@clean AccessConstants +@build AccessConstants +@summary Verify that ObjectStreamConstants is public accessible. + This test will not compile pre-JDK 1.2. +*/ + +import java.io.ObjectStreamConstants; + +public class AccessConstants { + public static void main(String[] args) { + byte[] ref = new byte[4]; + ref[0] = ObjectStreamConstants.TC_BASE; + ref[1] = ObjectStreamConstants.TC_NULL; + ref[2] = ObjectStreamConstants.TC_REFERENCE; + ref[3] = ObjectStreamConstants.TC_CLASSDESC; + int version = ObjectStreamConstants.PROTOCOL_VERSION_1; + } +} diff --git a/test/java/io/Serializable/arraySuidConflict/Foo.java b/test/java/io/Serializable/arraySuidConflict/Foo.java new file mode 100644 index 0000000000..f9e80365f7 --- /dev/null +++ b/test/java/io/Serializable/arraySuidConflict/Foo.java @@ -0,0 +1,32 @@ +/* + * 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. + */ + +/* + * @bug 4490677 + * @summary Verify that array serialVersionUID conflicts caused by changes in + * package scope do not cause deserialization to fail. + */ + +public class Foo implements java.io.Serializable { + private static final long serialVersionUID = 0L; +} diff --git a/test/java/io/Serializable/arraySuidConflict/Read.java b/test/java/io/Serializable/arraySuidConflict/Read.java new file mode 100644 index 0000000000..ff62cc8188 --- /dev/null +++ b/test/java/io/Serializable/arraySuidConflict/Read.java @@ -0,0 +1,43 @@ +/* + * 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. + */ + +/* + * @bug 4490677 + * @summary Verify that array serialVersionUID conflicts caused by changes in + * package scope do not cause deserialization to fail. + */ + +import java.io.*; + +class Foo { + private static final long serialVersionUID = 0L; +} + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("tmp.ser")); + Foo[] obj = (Foo[]) oin.readObject(); + oin.close(); + } +} diff --git a/test/java/io/Serializable/arraySuidConflict/Write.java b/test/java/io/Serializable/arraySuidConflict/Write.java new file mode 100644 index 0000000000..b7a06ce6db --- /dev/null +++ b/test/java/io/Serializable/arraySuidConflict/Write.java @@ -0,0 +1,47 @@ +/* + * 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 4490677 + * + * @clean Write Read Foo + * @compile Write.java Foo.java + * @run main Write + * @clean Write Read Foo + * @compile Read.java + * @run main Read + * + * @summary Verify that array serialVersionUID conflicts caused by changes in + * package scope do not cause deserialization to fail. + */ + +import java.io.*; + +public class Write { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("tmp.ser")); + oout.writeObject(new Foo[0]); + oout.close(); + } +} diff --git a/test/java/io/Serializable/auditStreamSubclass/AuditStreamSubclass.java b/test/java/io/Serializable/auditStreamSubclass/AuditStreamSubclass.java new file mode 100644 index 0000000000..f58978a1ca --- /dev/null +++ b/test/java/io/Serializable/auditStreamSubclass/AuditStreamSubclass.java @@ -0,0 +1,136 @@ +/* + * Copyright 2000 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 4311940 + * @summary Verify that unauthorized ObjectOutputStream and ObjectInputStream + * cannot be constructed if they override security-sensitive non-final + * methods. + */ +import java.io.*; + +class GoodOOS1 extends ObjectOutputStream { + GoodOOS1(OutputStream out) throws IOException { super(out); } +} + +class GoodOOS2 extends GoodOOS1 { + GoodOOS2(OutputStream out) throws IOException { super(out); } +} + +class BadOOS1 extends ObjectOutputStream { + BadOOS1(OutputStream out) throws IOException { super(out); } + public PutField putFields() throws IOException { return null; } +} + +class BadOOS2 extends ObjectOutputStream { + BadOOS2(OutputStream out) throws IOException { super(out); } + public void writeUnshared(Object obj) throws IOException {} +} + +class BadOOS3 extends GoodOOS1 { + BadOOS3(OutputStream out) throws IOException { super(out); } + public void writeUnshared(Object obj) throws IOException {} +} + + +class GoodOIS1 extends ObjectInputStream { + GoodOIS1(InputStream in) throws IOException { super(in); } +} + +class GoodOIS2 extends GoodOIS1 { + GoodOIS2(InputStream in) throws IOException { super(in); } +} + +class BadOIS1 extends ObjectInputStream { + BadOIS1(InputStream in) throws IOException { super(in); } + public GetField readFields() throws IOException, ClassNotFoundException { + return null; + } +} + +class BadOIS2 extends ObjectInputStream { + BadOIS2(InputStream in) throws IOException { super(in); } + public Object readUnshared() throws IOException, ClassNotFoundException { + return null; + } +} + +class BadOIS3 extends GoodOIS1 { + BadOIS3(InputStream in) throws IOException { super(in); } + public Object readUnshared() throws IOException, ClassNotFoundException { + return null; + } +} + +public class AuditStreamSubclass { + public static void main(String[] args) throws Exception { + if (System.getSecurityManager() == null) { + System.setSecurityManager(new SecurityManager()); + } + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.flush(); + byte[] buf = bout.toByteArray(); + + new GoodOOS1(bout); + new GoodOOS2(bout); + new GoodOIS1(new ByteArrayInputStream(buf)); + new GoodOIS2(new ByteArrayInputStream(buf)); + + try { + new BadOOS1(bout); + throw new Error(); + } catch (SecurityException ex) { + } + + try { + new BadOOS2(bout); + throw new Error(); + } catch (SecurityException ex) { + } + + try { + new BadOOS3(bout); + throw new Error(); + } catch (SecurityException ex) { + } + + try { + new BadOIS1(new ByteArrayInputStream(buf)); + throw new Error(); + } catch (SecurityException ex) { + } + + try { + new BadOIS2(new ByteArrayInputStream(buf)); + throw new Error(); + } catch (SecurityException ex) { + } + + try { + new BadOIS3(new ByteArrayInputStream(buf)); + throw new Error(); + } catch (SecurityException ex) { + } + } +} diff --git a/test/java/io/Serializable/available/Available.java b/test/java/io/Serializable/available/Available.java new file mode 100644 index 0000000000..fed7739c63 --- /dev/null +++ b/test/java/io/Serializable/available/Available.java @@ -0,0 +1,88 @@ +/* + * 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 4400571 + * @summary Verify that ObjectInputStream.available() functions properly when + * called at the beginning of a data block, and that it does not + * attempt any read operations that may potentially block. + */ + +import java.io.*; + +public class Available { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout; + ByteArrayOutputStream bout; + byte[] buf; + + // write stream containing short data block + oout = new ObjectOutputStream(bout = new ByteArrayOutputStream()); + oout.write(new byte[100]); + oout.close(); + buf = bout.toByteArray(); + + // 4 byte stream header + 2 byte block header + data + if ((getAvailable(buf, 4) != 0) || (getAvailable(buf, 5) != 0)) { + throw new Error(); + } + for (int i = 0; i < 100; i++) { + if (getAvailable(buf, 6 + i) != i) { + throw new Error(); + } + } + + // write stream containing long data block + oout = new ObjectOutputStream(bout = new ByteArrayOutputStream()); + oout.write(new byte[500]); + oout.close(); + buf = bout.toByteArray(); + + // 4 byte stream header + 5 byte block header + data + for (int i = 4; i < 9; i++) { + if (getAvailable(buf, i) != 0) { + throw new Error(); + } + } + for (int i = 0; i < 500; i++) { + if (getAvailable(buf, 9 + i) != i) { + throw new Error(); + } + } + } + + /** + * Given a byte array containing a serialized stream, creates a copy of the + * given data truncated to the specified length, then returns the result of + * a call to available() on an ObjectInputStream created on top of the + * truncated data. As a side effect, a StreamCorrupted or EOFException + * will get thrown if the available() call attempts to read past the + * underlying stream's available data. + */ + static int getAvailable(byte[] data, int truncateLen) throws IOException { + byte[] trunc = new byte[truncateLen]; + System.arraycopy(data, 0, trunc, 0, truncateLen); + return new ObjectInputStream( + new ByteArrayInputStream(trunc)).available(); + } +} diff --git a/test/java/io/Serializable/backRefCNFException/Read.java b/test/java/io/Serializable/backRefCNFException/Read.java new file mode 100644 index 0000000000..c1ddcad322 --- /dev/null +++ b/test/java/io/Serializable/backRefCNFException/Read.java @@ -0,0 +1,50 @@ +/* + * Copyright 2000 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. + */ + +/* + * @bug 4312433 + * @summary Verify that reading a back reference to a previously skipped value + * whose class is not available will throw a ClassNotFoundException + */ + +import java.io.*; + +class A implements Serializable { + private static final long serialVersionUID = 0L; + // field b skipped +} + +// class B not available + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("tmp.ser")); + oin.readObject(); + try { + oin.readObject(); + throw new Error("back reference read succeeded"); + } catch (ClassNotFoundException ex) { + } + } +} diff --git a/test/java/io/Serializable/backRefCNFException/Write.java b/test/java/io/Serializable/backRefCNFException/Write.java new file mode 100644 index 0000000000..897ef1394e --- /dev/null +++ b/test/java/io/Serializable/backRefCNFException/Write.java @@ -0,0 +1,58 @@ +/* + * Copyright 2000 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 4312433 + * + * @clean Write Read A B + * @compile Write.java + * @run main Write + * @clean Write Read A B + * @compile Read.java + * @run main Read + * + * @summary Verify that reading a back reference to a previously skipped value + * whose class is not available will throw a ClassNotFoundException + */ + +import java.io.*; + +class A implements Serializable { + private static final long serialVersionUID = 0L; + B b = new B(); +} + +class B implements Serializable { // class not present on reading side + private static final long serialVersionUID = 0L; +} + +public class Write { + public static void main(String[] args) throws Exception { + A a = new A(); + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("tmp.ser")); + oout.writeObject(a); + oout.writeObject(a.b); + oout.close(); + } +} diff --git a/test/java/io/Serializable/badSerialPersistentField/BadSerialPersistentField.java b/test/java/io/Serializable/badSerialPersistentField/BadSerialPersistentField.java new file mode 100644 index 0000000000..6b213e4e2e --- /dev/null +++ b/test/java/io/Serializable/badSerialPersistentField/BadSerialPersistentField.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 4387368 + * @summary Verify that object whose class declared a serial persistent field + * that does not match any actual field cannot be serialized via + * default serialization. + */ + +import java.io.*; + +class A implements Serializable { + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("nonexistent", int.class) + }; +} + +class B implements Serializable { + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("mismatched", int.class) + }; + private float mismatched; +} + +class C implements Serializable { + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("existent", int.class) + }; + private int existent; +} + +public class BadSerialPersistentField { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout; + + oout = new ObjectOutputStream(bout); + try { + oout.writeObject(new A()); + throw new Error(); + } catch (InvalidClassException ex) { + } + + oout = new ObjectOutputStream(bout); + try { + oout.writeObject(new B()); + throw new Error(); + } catch (InvalidClassException ex) { + } + + oout = new ObjectOutputStream(bout); + oout.writeObject(new C()); + } +} diff --git a/test/java/io/Serializable/badSerialVersionUID/BadSerialVersionUID.java b/test/java/io/Serializable/badSerialVersionUID/BadSerialVersionUID.java new file mode 100644 index 0000000000..a297fad476 --- /dev/null +++ b/test/java/io/Serializable/badSerialVersionUID/BadSerialVersionUID.java @@ -0,0 +1,82 @@ +/* + * 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 4431318 + * @summary Verify that when serialVersionUID is declared with a type other + * than long, values that can be promoted to long will be used, and + * those that can't be will be ignored (but will not result in + * unchecked exceptions). + */ + +import java.io.*; + +class Z implements Serializable { + private static final boolean serialVersionUID = false; +} + +class B implements Serializable { + private static final byte serialVersionUID = 5; +} + +class C implements Serializable { + private static final char serialVersionUID = 5; +} + +class S implements Serializable { + private static final short serialVersionUID = 5; +} + +class I implements Serializable { + private static final int serialVersionUID = 5; +} + +class F implements Serializable { + private static final float serialVersionUID = 5.0F; +} + +class D implements Serializable { + private static final double serialVersionUID = 5.0; +} + +class L implements Serializable { + private static final Object serialVersionUID = "5"; +} + + +public class BadSerialVersionUID { + public static void main(String[] args) throws Exception { + Class[] ignore = { Z.class, F.class, D.class, L.class }; + Class[] convert = { B.class, C.class, S.class, I.class }; + + for (int i = 0; i < ignore.length; i++) { + ObjectStreamClass.lookup(ignore[i]).getSerialVersionUID(); + } + for (int i = 0; i < convert.length; i++) { + ObjectStreamClass desc = ObjectStreamClass.lookup(convert[i]); + if (desc.getSerialVersionUID() != 5L) { + throw new Error(); + } + } + } +} diff --git a/test/java/io/Serializable/badSubstByReplace/BadSubstByReplace.java b/test/java/io/Serializable/badSubstByReplace/BadSubstByReplace.java new file mode 100644 index 0000000000..b18e3890fe --- /dev/null +++ b/test/java/io/Serializable/badSubstByReplace/BadSubstByReplace.java @@ -0,0 +1,76 @@ +/* + * Copyright 1997-1998 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 + * @clean A B Container ReplacerObjectOutputStream + * @summary Verify that ClassCastException is thrown when deserializing + * an object and one of its object fields is incompatibly replaced + * by either replaceObject/resolveObject. + * + */ +import java.io.*; + +class A implements Serializable {} + +class B implements Serializable {} + +class Container implements Serializable { + A a = new A(); +} + +class ReplacerObjectOutputStream extends ObjectOutputStream { + static B b = new B(); + public ReplacerObjectOutputStream(OutputStream out) throws IOException { + super(out); + enableReplaceObject(true); + } + + protected Object replaceObject(Object obj) throws IOException { + if(obj instanceof A) { + System.err.println("replaceObject(" + obj.toString() + ") with " + + b.toString()); + return b; + } else return obj; + } +} + +public class BadSubstByReplace { + public static void main(String args[]) throws IOException, ClassNotFoundException { + Container c = new Container(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ReplacerObjectOutputStream out = new ReplacerObjectOutputStream(baos); + out.writeObject(c); + out.close(); + ObjectInputStream in = + new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + try { + c = (Container)in.readObject(); // throws IllegalArgumentException. + throw new Error("Should have thrown ClassCastException"); + } catch ( ClassCastException e) { + System.err.println("Caught expected exception " + e.toString()); + e.printStackTrace(); + } finally { + in.close(); + } + } +} diff --git a/test/java/io/Serializable/checkModifiers/CheckModifiers.java b/test/java/io/Serializable/checkModifiers/CheckModifiers.java new file mode 100644 index 0000000000..ee0883ba9c --- /dev/null +++ b/test/java/io/Serializable/checkModifiers/CheckModifiers.java @@ -0,0 +1,245 @@ +/* + * Copyright 1999 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 4214888 + * @clean CheckModifiers TestClass1 TestClass2 + * @build CheckModifiers + * @run main CheckModifiers + * @summary Make sure that serialpersistentFields data member is used to + * represent tyhe serializable fields only if it has the modfiers + * static, final, private and the type is ObjectStreamField. + * No need to check for static, as ObjectStreamField class is not + * serializable. + * + */ + +import java.io.*; +class TestClass1 implements Serializable { + // Missing the "final" modifier + private static ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("field1", Integer.class), + new ObjectStreamField("field2", Double.TYPE), + }; + + Integer field1; + double field2; + int field3; + String field4; + + public TestClass1(Integer f1, double f2, int f3, String f4) { + field1 = f1; + field2 = f2; + field3 = f3; + field4 = f4; + } + + private void readObject(ObjectInputStream ois) + throws IOException, ClassNotFoundException { + ObjectInputStream.GetField pfields = ois.readFields(); + + field1 = (Integer) pfields.get("field1", new Integer(100)); + field2 = pfields.get("field2", 99.99); + + /* These fields must be present in the stream */ + try { + field3 = pfields.get("field3", 99); + System.out.println("Passes test 1a"); + } catch(IllegalArgumentException e) { + throw new Error("data field: field3 not in the persistent stream"); + } + try { + field4 = (String) pfields.get("field4", "Default string"); + System.out.println("Passes test 1b"); + } catch(IllegalArgumentException e) { + throw new Error("data field: field4 not in the persistent stream"); + } + } +}; + + +class TestClass2 implements Serializable { + // public instead of private + public static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("field1", Integer.class), + new ObjectStreamField("field2", Double.TYPE), + }; + + Integer field1; + double field2; + int field3; + String field4; + + public TestClass2(Integer f1, double f2, int f3, String f4) { + field1 = f1; + field2 = f2; + field3 = f3; + field4 = f4; + } + + private void readObject(ObjectInputStream ois) + throws IOException, ClassNotFoundException { + ObjectInputStream.GetField pfields = ois.readFields(); + + field1 = (Integer) pfields.get("field1", new Integer(100)); + field2 = pfields.get("field2", 99.99); + + /* These fields must be present in the stream */ + try { + field3 = pfields.get("field3", 99); + System.out.println("Passes test 2a"); + } catch(IllegalArgumentException e) { + throw new Error("data field: field3 not in the persistent stream"); + } + try { + field4 = (String) pfields.get("field4", "Default string"); + System.out.println("Passes test 2b"); + } catch(IllegalArgumentException e) { + throw new Error("data field: field4 not in the persistent stream"); + } + } +}; + +class TestClass3 implements Serializable{ + // Not of type ObjectStreamField + private final String[] serialPersistentFields = {"Foo","Foobar"};; + Integer field1; + double field2; + int field3; + String field4; + + public TestClass3(Integer f1, double f2, int f3, String f4) { + field1 = f1; + field2 = f2; + field3 = f3; + field4 = f4; + } + + private void readObject(ObjectInputStream ois) + throws IOException, ClassNotFoundException { + ObjectInputStream.GetField pfields = ois.readFields(); + + field1 = (Integer) pfields.get("field1", new Integer(100)); + field2 = pfields.get("field2", 99.99); + field3 = pfields.get("field3", 99); + field4 = (String) pfields.get("field4", "Default string"); + + try { + String[] tserialPersistentFields = + (String[])pfields.get("serialPersistentFields", null); + System.out.println("Passes test 3"); + } catch(IllegalArgumentException e) { + throw new Error("non-static field: " + + "serialPersistentFields must be in the persistent stream"); + } + } +}; + +class TestClass4 implements Serializable { + // Correct format + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("field1", Integer.class), + new ObjectStreamField("field2", Double.TYPE), + }; + + Integer field1; + double field2; + int field3; + String field4; + + public TestClass4(Integer f1, double f2, int f3, String f4) { + field1 = f1; + field2 = f2; + field3 = f3; + field4 = f4; + } + + private void readObject(ObjectInputStream ois) + throws IOException, ClassNotFoundException { + ObjectInputStream.GetField pfields = ois.readFields(); + + field1 = (Integer) pfields.get("field1", new Integer(100)); + field2 = pfields.get("field2", 99.99); + + try { + field3 = pfields.get("field3", 99); + throw new Error("data field: field3 in the persistent stream"); + } catch(IllegalArgumentException e) { + System.out.println("Passes test 4a"); + } + try { + field4 = (String) pfields.get("field4", "Default string"); + throw new Error("data field: field4 in the persistent stream"); + } catch(IllegalArgumentException e) { + System.out.println("Passes test 4b"); + } + } +}; + +public class CheckModifiers { + public static void main(String[] args) + throws ClassNotFoundException, IOException{ + TestClass1 tc1 = new TestClass1(new Integer(100), 25.56, 2000, + new String("Test modifiers of serialPersistentFields")); + + TestClass2 tc2 = new TestClass2(new Integer(100), 25.56, 2000, + new String("Test modifiers of serialPersistentFields")); + + TestClass3 tc3 = new TestClass3(new Integer(100), 25.56, 2000, + new String("Test Type of serialPersistentFields")); + + TestClass4 tc4 = new TestClass4(new Integer(100), 25.56, 2000, + new String("Test modifiers of serialPersistentFields")); + + + FileOutputStream fos = new FileOutputStream("fields.ser"); + ObjectOutputStream oos = new ObjectOutputStream(fos); + + System.out.println("Writing obj 1"); + oos.writeObject(tc1); + System.out.println("Writing obj 2"); + oos.writeObject(tc2); + System.out.println("Writing obj 3"); + oos.writeObject(tc3); + System.out.println("Writing obj 4"); + oos.writeObject(tc4); + + FileInputStream fis = new FileInputStream("fields.ser"); + ObjectInputStream ois = new ObjectInputStream(fis); + + + System.out.println("Test modifiers for serialPeristentFields "); + System.out.println("---------------------------------------- "); + System.out.println("Declaration missing final modifier"); + ois.readObject(); + System.out.println(); + System.out.println("Declaration with public instead of private access"); + ois.readObject(); + System.out.println(); + System.out.println("Declaration with different type"); + ois.readObject(); + System.out.println(); + System.out.println("Declaration as in specification"); + ois.readObject(); + } +}; diff --git a/test/java/io/Serializable/class/NonSerialA_1.java b/test/java/io/Serializable/class/NonSerialA_1.java new file mode 100644 index 0000000000..ae055942c0 --- /dev/null +++ b/test/java/io/Serializable/class/NonSerialA_1.java @@ -0,0 +1,27 @@ +/* + * Copyright 1998 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. + */ + + +public class A { + int field1; +}; diff --git a/test/java/io/Serializable/class/NonSerialA_2.java b/test/java/io/Serializable/class/NonSerialA_2.java new file mode 100644 index 0000000000..f86c8c9b4e --- /dev/null +++ b/test/java/io/Serializable/class/NonSerialA_2.java @@ -0,0 +1,27 @@ +/* + * Copyright 1998 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. + */ + +public class A { + int field1; + int field2; +}; diff --git a/test/java/io/Serializable/class/SerialA.java b/test/java/io/Serializable/class/SerialA.java new file mode 100644 index 0000000000..9ce3836722 --- /dev/null +++ b/test/java/io/Serializable/class/SerialA.java @@ -0,0 +1,28 @@ +/* + * Copyright 1998 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. + */ + +import java.io.Serializable; + +public class A implements Serializable { + int field1; +}; diff --git a/test/java/io/Serializable/class/SerialA_1.java b/test/java/io/Serializable/class/SerialA_1.java new file mode 100644 index 0000000000..9ce3836722 --- /dev/null +++ b/test/java/io/Serializable/class/SerialA_1.java @@ -0,0 +1,28 @@ +/* + * Copyright 1998 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. + */ + +import java.io.Serializable; + +public class A implements Serializable { + int field1; +}; diff --git a/test/java/io/Serializable/class/SerialA_2.java b/test/java/io/Serializable/class/SerialA_2.java new file mode 100644 index 0000000000..a6d5adf516 --- /dev/null +++ b/test/java/io/Serializable/class/SerialA_2.java @@ -0,0 +1,31 @@ +/* + * Copyright 1998 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. + */ + +import java.io.Serializable; + +public class A implements Serializable { + static final long serialVersionUID = 746945609796141988L; + + int field1; + int field2; +}; diff --git a/test/java/io/Serializable/class/SerialA_3.java b/test/java/io/Serializable/class/SerialA_3.java new file mode 100644 index 0000000000..bd97924eda --- /dev/null +++ b/test/java/io/Serializable/class/SerialA_3.java @@ -0,0 +1,31 @@ +/* + * Copyright 1998 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. + */ + +import java.io.Serializable; + +/* THis class is purposely not compatible with previous versions of class.*/ +public class A implements Serializable { + int field1; + int field2; + int field3; +}; diff --git a/test/java/io/Serializable/class/Test.java b/test/java/io/Serializable/class/Test.java new file mode 100644 index 0000000000..971ec89ba5 --- /dev/null +++ b/test/java/io/Serializable/class/Test.java @@ -0,0 +1,78 @@ +/* + * Copyright 1998-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. + */ + +/* + * @bug 4075221 + * @summary Enable serialize of nonSerializable Class descriptor. + */ + +import java.io.*; + +class Test { + public static void main(String args[]) throws Exception { + File f = new File("tmp.ser"); + if (args[0].compareTo("-s") == 0) { + FileOutputStream of = new FileOutputStream(f); + ObjectOutputStream oos = new ObjectOutputStream(of); + Class cl = Class.forName(args[1]); + oos.writeObject(cl); + if (ObjectStreamClass.lookup(cl) != null) + oos.writeObject(cl.newInstance()); + oos.close(); + System.out.println("Serialized Class " + cl.getName()); + } else if (args[0].compareTo("-de") == 0) { + FileInputStream inf = new FileInputStream(f); + ObjectInputStream ois = new ObjectInputStream(inf); + Class cl = null; + try { + cl = (Class)ois.readObject(); + throw new Error("Expected InvalidClassException to be thrown"); + } catch (InvalidClassException e) { + System.out.println("Caught expected exception DeSerializing class " + e.getMessage()); + } + ois.close(); + } else if (args[0].compareTo("-doe") == 0) { + FileInputStream inf = new FileInputStream(f); + ObjectInputStream ois = new ObjectInputStream(inf); + Class cl = null; + cl = (Class)ois.readObject(); + try { + ois.readObject(); + throw new Error("Expected InvalidClassException to be thrown"); + } catch (InvalidClassException e) { + System.out.println("Caught expected exception DeSerializing class " + e.getMessage()); + } + ois.close(); + } else if (args[0].compareTo("-d") == 0) { + FileInputStream inf = new FileInputStream(f); + ObjectInputStream ois = new ObjectInputStream(inf); + Class cl = (Class)ois.readObject(); + try { + ois.readObject(); + } catch (EOFException e) { + } + ois.close(); + System.out.println("DeSerialized Class " + cl.getName()); + } + } +} diff --git a/test/java/io/Serializable/class/run.sh b/test/java/io/Serializable/class/run.sh new file mode 100644 index 0000000000..33c8255a15 --- /dev/null +++ b/test/java/io/Serializable/class/run.sh @@ -0,0 +1,129 @@ +# +# Copyright 1998-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 4075221 +# @run shell/timeout=300 run.sh +# @summary Enable serialize of nonSerializable Class descriptor. + +set -ex + +if [ "${TESTJAVA}" = "" ] +then + echo "TESTJAVA not set. Test cannot execute. Failed." + exit 1 +fi + +if [ "${TESTSRC}" = "" ] +then +TESTSRC="." +fi + +${TESTJAVA}/bin/javac -d . ${TESTSRC}/Test.java + +echo Write NonSerial1, Read NonSerial1 +rm -f A.java +cp ${TESTSRC}/NonSerialA_1.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -s A +${TESTJAVA}/bin/java Test -d +echo + +echo Write NonSerial1, Read NonSerial2 +rm -f A.java +cp ${TESTSRC}/NonSerialA_1.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -s A +rm -f A.java +cp ${TESTSRC}/NonSerialA_2.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -d +echo + +echo Write NonSerial1, Read Serial1 +rm -f A.java +cp ${TESTSRC}/NonSerialA_1.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -s A +rm -f A.java +cp ${TESTSRC}/SerialA_1.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -d +echo + +echo Write Serial1, Read NonSerial1 +rm -f A.java +cp ${TESTSRC}/SerialA_1.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -s A +rm -f A.java +cp ${TESTSRC}/NonSerialA_1.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -doe +echo + +echo Write Serial1, Read Serial2 +rm -f A.java +cp ${TESTSRC}/SerialA_1.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -s A +rm -f A.java +cp ${TESTSRC}/SerialA_2.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -d +echo + +echo Write Serial2, Read Serial1 +rm -f A.java +cp ${TESTSRC}/SerialA_2.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -s A +rm -f A.java +cp ${TESTSRC}/SerialA_1.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -d +echo + +echo Write Serial1, Read Serial3 +rm -f A.java +cp ${TESTSRC}/SerialA_1.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -s A +rm -f A.java +cp ${TESTSRC}/SerialA_3.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -de +echo + +echo Write Serial3, Read Serial1 +rm -f A.java +cp ${TESTSRC}/SerialA_3.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -s A +rm -f A.java +cp ${TESTSRC}/SerialA_1.java A.java +${TESTJAVA}/bin/javac A.java +${TESTJAVA}/bin/java Test -de +echo + +echo Passed diff --git a/test/java/io/Serializable/classDescFlagConflict/Foo.java b/test/java/io/Serializable/classDescFlagConflict/Foo.java new file mode 100644 index 0000000000..9fd4f24394 --- /dev/null +++ b/test/java/io/Serializable/classDescFlagConflict/Foo.java @@ -0,0 +1,36 @@ +/* + * 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. + */ + +/* + * @bug 4632671 + * @summary Verify that reading an object whose class descriptor has both + * SC_SERIALIZABLE and SC_EXTERNALIZABLE bits set results in an + * InvalidClassException. + */ +import java.io.*; + +public class Foo implements Externalizable { + public void writeExternal(ObjectOutput out) throws IOException {} + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException {} +} diff --git a/test/java/io/Serializable/classDescFlagConflict/Foo.ser b/test/java/io/Serializable/classDescFlagConflict/Foo.ser Binary files differnew file mode 100644 index 0000000000..f759371ef8 --- /dev/null +++ b/test/java/io/Serializable/classDescFlagConflict/Foo.ser diff --git a/test/java/io/Serializable/classDescFlagConflict/Read.java b/test/java/io/Serializable/classDescFlagConflict/Read.java new file mode 100644 index 0000000000..d3e650e5a9 --- /dev/null +++ b/test/java/io/Serializable/classDescFlagConflict/Read.java @@ -0,0 +1,52 @@ +/* + * 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 4632671 + * @summary Verify that reading an object whose class descriptor has both + * SC_SERIALIZABLE and SC_EXTERNALIZABLE bits set results in an + * InvalidClassException. + * + * @build Foo + * @run main/othervm Read + */ +import java.io.*; + +public class Read { + public static void main(String[] args) throws Exception { + try { + /* + * Foo.ser contains a doctored serialized representation of an + * instance of class Foo, in which both SC_SERIALIZABLE and + * SC_EXTERNALIZABLE flags have been set for Foo's class + * descriptor. + */ + File f = new File(System.getProperty("test.src", "."), "Foo.ser"); + new ObjectInputStream(new FileInputStream(f)).readObject(); + throw new Error( + "read succeeded for object whose class descriptor has " + + "both SC_SERIALIZABLE and SC_EXTERNALIZABLE flags set"); + } catch (InvalidClassException e) { + } + } +} diff --git a/test/java/io/Serializable/classDescGetField/GetField.java b/test/java/io/Serializable/classDescGetField/GetField.java new file mode 100644 index 0000000000..88438c654b --- /dev/null +++ b/test/java/io/Serializable/classDescGetField/GetField.java @@ -0,0 +1,52 @@ +/* + * Copyright 1999 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 4180735 + * @clean Foo GetField + * @build GetField + * @run main GetField + * + * @summary Make sure that getField() of ObjectStreamClass works correctly for + * object types. + */ +import java.io.*; + +public class GetField implements Serializable{ + String str; + int i; + + public static void main(String[] args) throws Exception { + ObjectStreamClass cl = ObjectStreamClass.lookup(GetField.class); + if (cl == null) + throw new RuntimeException("Cannot resolve class : GetField"); + + if (cl.getField("str") == null) + throw new RuntimeException( + "ObjectStreamClass.getField() failed for object type"); + + if (cl.getField("i") == null) + throw new RuntimeException( + "ObjectStreamClass.getField() failed for primitive type"); + } +} diff --git a/test/java/io/Serializable/classDescHooks/CNFException.java b/test/java/io/Serializable/classDescHooks/CNFException.java new file mode 100644 index 0000000000..95f33ec323 --- /dev/null +++ b/test/java/io/Serializable/classDescHooks/CNFException.java @@ -0,0 +1,65 @@ +/* + * 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 4931314 + * @summary Verify that a ClassNotFoundException thrown by the + * readClassDescriptor method is reflected to the caller as an + * InvalidClassException with the ClassNotFoundException as its cause. + */ + +import java.io.*; + +class CNFInputStream extends ObjectInputStream { + + CNFInputStream(InputStream in) throws IOException { + super(in); + } + + protected ObjectStreamClass readClassDescriptor() + throws IOException, ClassNotFoundException + { + throw new ClassNotFoundException("foobar"); + } +} + +public class CNFException { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(new Integer(5)); + oout.close(); + ObjectInputStream oin = + new CNFInputStream(new ByteArrayInputStream(bout.toByteArray())); + try { + oin.readObject(); + throw new Error("expected InvalidClassException"); + } catch (InvalidClassException e) { + Throwable cause = e.getCause(); + if (!(cause instanceof ClassNotFoundException)) { + throw new Error( + "expected ClassNotFoundException as cause, not " + cause); + } + } + } +} diff --git a/test/java/io/Serializable/classDescHooks/ClassDescHooks.java b/test/java/io/Serializable/classDescHooks/ClassDescHooks.java new file mode 100644 index 0000000000..b655b03217 --- /dev/null +++ b/test/java/io/Serializable/classDescHooks/ClassDescHooks.java @@ -0,0 +1,139 @@ +/* + * Copyright 1999 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 4227189 + * @summary Ensure that class descriptor read, write hooks exist, are backwards + * compatible, and work as advertised. + */ + +import java.io.*; +import java.util.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 1L; + Short s = new Short((short) 1); + Integer i = new Integer(2); + Long l = new Long(3); + + public boolean equals(Object obj) { + if (obj instanceof Foo) { + Foo ofoo = (Foo) obj; + return s.equals(ofoo.s) && i.equals(ofoo.i) && l.equals(ofoo.l); + } + return false; + } +} + +class CustomOutputStream extends ObjectOutputStream { + + boolean hookCalled = false; + + CustomOutputStream(OutputStream out) throws IOException { + super(out); + useProtocolVersion(PROTOCOL_VERSION_2); + } + + protected void writeClassDescriptor(ObjectStreamClass desc) + throws IOException + { + writeUTF(desc.getName()); + hookCalled = true; + } +} + +class CustomInputStream extends ObjectInputStream { + + boolean hookCalled = false; + + CustomInputStream(InputStream in) throws IOException { + super(in); + } + + protected ObjectStreamClass readClassDescriptor() + throws IOException, ClassNotFoundException + { + hookCalled = true; + return ObjectStreamClass.lookup(Class.forName(readUTF())); + } +} + +public class ClassDescHooks implements ObjectStreamConstants { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout; + ByteArrayInputStream bin; + ObjectOutputStream oout; + ObjectInputStream oin; + FileInputStream fin; + File foof; + CustomOutputStream cout; + CustomInputStream cin; + + // test for backwards compatibility + bout = new ByteArrayOutputStream(); + foof = new File(System.getProperty("test.src", "."), "Foo.ser"); + fin = new FileInputStream(foof); + while (fin.available() > 0) + bout.write(fin.read()); + byte[] buf1 = bout.toByteArray(); + + bout = new ByteArrayOutputStream(); + oout = new ObjectOutputStream(bout); + Foo foo = new Foo(); + oout.writeObject(foo); + oout.flush(); + byte[] buf2 = bout.toByteArray(); + + if (! Arrays.equals(buf1, buf2)) + throw new Error("Incompatible stream format (write)"); + + fin = new FileInputStream(foof); + oin = new ObjectInputStream(fin); + Foo foocopy = (Foo) oin.readObject(); + if (! foo.equals(foocopy)) + throw new Error("Incompatible stream format (read)"); + + // make sure write hook not called when old protocol in use + bout = new ByteArrayOutputStream(); + cout = new CustomOutputStream(bout); + cout.useProtocolVersion(PROTOCOL_VERSION_1); + cout.writeObject(foo); + if (cout.hookCalled) + throw new Error("write descriptor hook should not be called"); + + // write custom class descriptor representations + bout = new ByteArrayOutputStream(); + cout = new CustomOutputStream(bout); + cout.writeObject(foo); + cout.flush(); + bin = new ByteArrayInputStream(bout.toByteArray()); + cin = new CustomInputStream(bin); + foocopy = (Foo) cin.readObject(); + if (! cout.hookCalled) + throw new Error("write descriptor hook never called"); + if (! cin.hookCalled) + throw new Error("read descriptor hook never called"); + if (! foo.equals(foocopy)) + throw new Error("serialization failed when hooks active"); + } +} diff --git a/test/java/io/Serializable/classDescHooks/ExternLoopback.java b/test/java/io/Serializable/classDescHooks/ExternLoopback.java new file mode 100644 index 0000000000..e8b2b3797d --- /dev/null +++ b/test/java/io/Serializable/classDescHooks/ExternLoopback.java @@ -0,0 +1,122 @@ +/* + * 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 4461737 + * @summary Verify that serialization functions properly for externalizable + * classes if ObjectInputStream.readClassDescriptor() returns a local + * class descriptor. + */ + +import java.io.*; +import java.util.*; + +class LoopbackOutputStream extends ObjectOutputStream { + LinkedList descs; + + LoopbackOutputStream(OutputStream out, LinkedList descs) + throws IOException + { + super(out); + this.descs = descs; + } + + protected void writeClassDescriptor(ObjectStreamClass desc) + throws IOException + { + descs.add(desc); + } +} + +class LoopbackInputStream extends ObjectInputStream { + LinkedList descs; + + LoopbackInputStream(InputStream in, LinkedList descs) throws IOException { + super(in); + this.descs = descs; + } + + protected ObjectStreamClass readClassDescriptor() + throws IOException, ClassNotFoundException + { + return (ObjectStreamClass) descs.removeFirst(); + } +} + +public class ExternLoopback implements Externalizable { + + String a, b, c; + + public ExternLoopback() { + } + + ExternLoopback(String a, String b, String c) { + this.a = a; + this.b = b; + this.c = c; + } + + public void writeExternal(ObjectOutput out) throws IOException { + out.writeBoolean(false); + out.writeObject(a); + out.writeObject(b); + out.writeObject(c); + } + + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException + { + in.readBoolean(); + a = (String) in.readObject(); + b = (String) in.readObject(); + c = (String) in.readObject(); + } + + public boolean equals(Object obj) { + if (!(obj instanceof ExternLoopback)) { + return false; + } + ExternLoopback other = (ExternLoopback) obj; + return streq(a, other.a) && streq(b, other.b) && streq(c, other.c); + } + + static boolean streq(String s1, String s2) { + return (s1 != null) ? s1.equals(s2) : (s2 == null); + } + + public static void main(String[] args) throws Exception { + ExternLoopback lb = new ExternLoopback("foo", "bar", "baz"); + LinkedList descs = new LinkedList(); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + LoopbackOutputStream lout = new LoopbackOutputStream(bout, descs); + lout.writeObject(lb); + lout.close(); + + LoopbackInputStream lin = new LoopbackInputStream( + new ByteArrayInputStream(bout.toByteArray()), descs); + ExternLoopback lbcopy = (ExternLoopback) lin.readObject(); + if (!lb.equals(lbcopy)) { + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/classDescHooks/Foo.ser b/test/java/io/Serializable/classDescHooks/Foo.ser Binary files differnew file mode 100644 index 0000000000..96be5f2304 --- /dev/null +++ b/test/java/io/Serializable/classDescHooks/Foo.ser diff --git a/test/java/io/Serializable/classDescHooks/Loopback.java b/test/java/io/Serializable/classDescHooks/Loopback.java new file mode 100644 index 0000000000..26ca42ef48 --- /dev/null +++ b/test/java/io/Serializable/classDescHooks/Loopback.java @@ -0,0 +1,89 @@ +/* + * 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 4461299 + * @summary Verify that serialization functions properly if + * ObjectInputStream.readClassDescriptor() returns a local class + * descriptor for which the serialVersionUID has not yet been + * calculated. + */ + +import java.io.*; +import java.util.*; + +class LoopbackOutputStream extends ObjectOutputStream { + LinkedList descs; + + LoopbackOutputStream(OutputStream out, LinkedList descs) + throws IOException + { + super(out); + this.descs = descs; + } + + protected void writeClassDescriptor(ObjectStreamClass desc) + throws IOException + { + descs.add(desc); + } +} + +class LoopbackInputStream extends ObjectInputStream { + LinkedList descs; + + LoopbackInputStream(InputStream in, LinkedList descs) throws IOException { + super(in); + this.descs = descs; + } + + protected ObjectStreamClass readClassDescriptor() + throws IOException, ClassNotFoundException + { + return (ObjectStreamClass) descs.removeFirst(); + } +} + +public class Loopback implements Serializable { + String str; + + Loopback(String str) { + this.str = str; + } + + public static void main(String[] args) throws Exception { + Loopback lb = new Loopback("foo"); + LinkedList descs = new LinkedList(); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + LoopbackOutputStream lout = new LoopbackOutputStream(bout, descs); + lout.writeObject(lb); + lout.close(); + + LoopbackInputStream lin = new LoopbackInputStream( + new ByteArrayInputStream(bout.toByteArray()), descs); + Loopback lbcopy = (Loopback) lin.readObject(); + if (!lb.str.equals(lbcopy.str)) { + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/clearHandleTable/ClearHandleTable.java b/test/java/io/Serializable/clearHandleTable/ClearHandleTable.java new file mode 100644 index 0000000000..4fb634262a --- /dev/null +++ b/test/java/io/Serializable/clearHandleTable/ClearHandleTable.java @@ -0,0 +1,66 @@ +/* + * Copyright 2000 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 4332184 + * @summary Ensure that ObjectOutputStream properly releases strong references + * to written objects when reset() is called. + */ + +import java.io.*; +import java.lang.ref.WeakReference; +import java.util.ArrayList; + +public class ClearHandleTable { + public static void main(String[] args) throws Exception { + final int nreps = 100; + ObjectOutputStream oout = + new ObjectOutputStream(new ByteArrayOutputStream()); + WeakReference[] refs = new WeakReference[nreps]; + + for (int i = 0; i < nreps; i++) { + String str = new String("blargh"); + oout.writeObject(str); + refs[i] = new WeakReference(str); + } + + oout.reset(); + exhaustMemory(); + + for (int i = 0; i < nreps; i++) { + if (refs[i].get() != null) { + throw new Error("failed to garbage collect object " + i); + } + } + } + + static void exhaustMemory() { + ArrayList blob = new ArrayList(); + try { + for (;;) { + blob.add(new int[0xFFFF]); + } + } catch (OutOfMemoryError e) { + } + } +} diff --git a/test/java/io/Serializable/concurrentClassDescLookup/ConcurrentClassDescLookup.java b/test/java/io/Serializable/concurrentClassDescLookup/ConcurrentClassDescLookup.java new file mode 100644 index 0000000000..c56ad43561 --- /dev/null +++ b/test/java/io/Serializable/concurrentClassDescLookup/ConcurrentClassDescLookup.java @@ -0,0 +1,138 @@ +/* + * 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 Verify that concurrent class descriptor lookups function properly, + * even when class descriptor initialization is slow or throws an + * exception. + */ + +import java.io.*; + +class Good implements Serializable { + static { + try { Thread.sleep(1000); } catch (InterruptedException ex) {} + } +} + +class Bad implements Serializable { + // explicit suid triggers class initialization during classdesc lookup + private static final long serialVersionUID = 0xBAD; + static { + try { Thread.sleep(1000); } catch (InterruptedException ex) {} + if ("foo".equals("foo")) { + throw new RuntimeException(); + } + } +} + +class SuccessfulLookup extends Thread { + Class cl; + long suid; + Object barrier; + boolean ok; + + SuccessfulLookup(Class cl, long suid, Object barrier) { + this.cl = cl; + this.suid = suid; + this.barrier = barrier; + } + + public void run() { + synchronized (barrier) { + try { barrier.wait(); } catch (InterruptedException ex) {} + } + for (int i = 0; i < 100; i++) { + if (ObjectStreamClass.lookup(cl).getSerialVersionUID() != suid) { + return; + } + } + ok = true; + } +} + +class FailingLookup extends Thread { + Class cl; + Object barrier; + boolean ok; + + FailingLookup(Class cl, Object barrier) { + this.cl = cl; + this.barrier = barrier; + } + + public void run() { + synchronized (barrier) { + try { barrier.wait(); } catch (InterruptedException ex) {} + } + for (int i = 0; i < 100; i++) { + try { + ObjectStreamClass.lookup(cl); + return; + } catch (Throwable th) { + } + } + ok = true; + } +} + +public class ConcurrentClassDescLookup { + public static void main(String[] args) throws Exception { + ClassLoader loader = ConcurrentClassDescLookup.class.getClassLoader(); + Class cl = Class.forName("Good", false, loader); + Object barrier = new Object(); + SuccessfulLookup[] slookups = new SuccessfulLookup[50]; + for (int i = 0; i < slookups.length; i++) { + slookups[i] = + new SuccessfulLookup(cl, 6319710844400051132L, barrier); + slookups[i].start(); + } + Thread.sleep(1000); + synchronized (barrier) { + barrier.notifyAll(); + } + for (int i = 0; i < slookups.length; i++) { + slookups[i].join(); + if (!slookups[i].ok) { + throw new Error(); + } + } + + cl = Class.forName("Bad", false, loader); + FailingLookup[] flookups = new FailingLookup[50]; + for (int i = 0; i < flookups.length; i++) { + flookups[i] = new FailingLookup(cl, barrier); + flookups[i].start(); + } + Thread.sleep(1000); + synchronized (barrier) { + barrier.notifyAll(); + } + for (int i = 0; i < slookups.length; i++) { + flookups[i].join(); + if (!flookups[i].ok) { + throw new Error(); + } + } + } +} diff --git a/test/java/io/Serializable/corruptedUTFConsumption/CorruptedUTFConsumption.java b/test/java/io/Serializable/corruptedUTFConsumption/CorruptedUTFConsumption.java new file mode 100644 index 0000000000..3155b3a4ca --- /dev/null +++ b/test/java/io/Serializable/corruptedUTFConsumption/CorruptedUTFConsumption.java @@ -0,0 +1,84 @@ +/* + * 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 4450867 + * @summary Although technically the behavior of ObjectInputStream following a + * UTFDataFormatException is unspecified, verify that + * ObjectInputStream consumes at most the expected number of utf + * bytes, even if the last byte(s) of the utf string indicate that the + * string overflows its expected length. + */ + +import java.io.*; +import java.util.Random; + +public class CorruptedUTFConsumption { + + static Random rand = new Random(System.currentTimeMillis()); + + public static void main(String[] args) throws Exception { + StringBuffer sbuf = new StringBuffer(); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + DataOutputStream dout = new DataOutputStream(bout); + + for (int i = 0; i < 1200; i++) { + sbuf.append(i % 10); + bout.reset(); + dout.writeUTF(sbuf.toString()); + byte[] utf = bout.toByteArray(); + + // set last byte to first byte of 2-char sequence + utf[utf.length - 1] = (byte) (0xC0 | rand.nextInt() & 0x1F); + checkConsume(utf); + + // set last byte to first byte of 3-char sequence + utf[utf.length - 1] = (byte) (0xE0 | rand.nextInt() & 0x0F); + checkConsume(utf); + + if (utf.length >= 4) { // don't touch utf length bytes + // set last 2 bytes to first, second byte of 3-char sequence + utf[utf.length - 2] = (byte) (0xE0 | rand.nextInt() & 0x0F); + utf[utf.length - 1] = (byte) (0x80 | rand.nextInt() & 0x3F); + checkConsume(utf); + } + } + } + + static void checkConsume(byte[] utf) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.write(utf); + oout.writeByte(0); // leave one byte of padding + oout.close(); + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + try { + oin.readUTF(); + throw new Error(); + } catch (UTFDataFormatException ex) { + } + // if readUTF consumed padding byte, readByte will throw EOFException + oin.readByte(); + } +} diff --git a/test/java/io/Serializable/defaultDataEnd/DefaultDataEnd.java b/test/java/io/Serializable/defaultDataEnd/DefaultDataEnd.java new file mode 100644 index 0000000000..b5eee2861a --- /dev/null +++ b/test/java/io/Serializable/defaultDataEnd/DefaultDataEnd.java @@ -0,0 +1,149 @@ +/* + * 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 4360508 + * @summary Verify that a custom readObject() method reading in data written + * via default serialization cannot read past the end of the default + * data. + */ + +import java.io.*; + +class A implements Serializable { + int i1 = 1, i2 = 2; + String s1 = "foo", s2 = "bar"; + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + if (in.read() != -1) { + throw new Error(); + } + try { + in.readInt(); + throw new Error(); + } catch (EOFException ex) { + } + try { + in.readObject(); + throw new Error(); + } catch (OptionalDataException ex) { + if (!ex.eof) { + throw new Error(); + } + } + try { + in.readUnshared(); + throw new Error(); + } catch (OptionalDataException ex) { + if (!ex.eof) { + throw new Error(); + } + } + } +} + +class B implements Serializable { + int i1 = 1, i2 = 2; + String s1 = "foo", s2 = "bar"; + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.readFields(); + try { + in.readObject(); + throw new Error(); + } catch (OptionalDataException ex) { + if (!ex.eof) { + throw new Error(); + } + } + try { + in.readUnshared(); + throw new Error(); + } catch (OptionalDataException ex) { + if (!ex.eof) { + throw new Error(); + } + } + if (in.read() != -1) { + throw new Error(); + } + try { + in.readInt(); + throw new Error(); + } catch (EOFException ex) { + } + } +} + +class C implements Serializable { + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + try { + in.readObject(); + throw new Error(); + } catch (OptionalDataException ex) { + if (!ex.eof) { + throw new Error(); + } + } + try { + in.readUnshared(); + throw new Error(); + } catch (OptionalDataException ex) { + if (!ex.eof) { + throw new Error(); + } + } + if (in.read() != -1) { + throw new Error(); + } + try { + in.readInt(); + throw new Error(); + } catch (EOFException ex) { + } + } +} + +public class DefaultDataEnd { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(new A()); + oout.writeObject(new B()); + oout.writeObject(new C()); + oout.close(); + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + oin.readObject(); + oin.readObject(); + oin.readObject(); + } +} diff --git a/test/java/io/Serializable/defaultReadObjectCNFException/DefaultReadObjectCNFException.java b/test/java/io/Serializable/defaultReadObjectCNFException/DefaultReadObjectCNFException.java new file mode 100644 index 0000000000..5d94f90782 --- /dev/null +++ b/test/java/io/Serializable/defaultReadObjectCNFException/DefaultReadObjectCNFException.java @@ -0,0 +1,80 @@ +/* + * 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 4662327 + * @summary Verify that ObjectInputStream.defaultReadObject() throws a + * ClassNotFoundException if any of the non-primitive field values it + * reads in are tagged with ClassNotFoundExceptions. + */ + +import java.io.*; + +class Foo implements Serializable { + Object obj = new Bar(); + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + if (obj == null) { + throw new Error( + "ClassNotFoundException masked by defaultReadObject()"); + } + } +} + +class Bar implements Serializable {} + +class TestObjectInputStream extends ObjectInputStream { + TestObjectInputStream(InputStream in) throws IOException { super(in); } + + protected Class resolveClass(ObjectStreamClass desc) + throws IOException, ClassNotFoundException + { + if (desc.getName().equals(Bar.class.getName())) { + throw new ClassNotFoundException(); + } + return super.resolveClass(desc); + } +} + +public class DefaultReadObjectCNFException { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(new Foo()); + oout.writeObject("after"); + oout.close(); + ObjectInputStream oin = new TestObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + try { + oin.readObject(); + } catch (ClassNotFoundException e) { + // expected + } + if (!oin.readObject().equals("after")) { + throw new Error("subsequent object corrupted"); + } + } +} diff --git a/test/java/io/Serializable/defaulted/GetFieldRead.java b/test/java/io/Serializable/defaulted/GetFieldRead.java new file mode 100644 index 0000000000..c4541f2034 --- /dev/null +++ b/test/java/io/Serializable/defaulted/GetFieldRead.java @@ -0,0 +1,111 @@ +/* + * Copyright 1999 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. + */ + +/* + * @bug 4180735 + * @summary Make sure that fields that are defaulted can be of primitive and + * object type. + * + */ + +import java.io.*; +class TestClass implements Serializable { + public static final Integer DEFAULT_OBJECT_I = new Integer(99); + public static final Foo DEFAULT_OBJECT_F = new Foo(); + private static final long serialVersionUID=5748652654655279289L; + + // Fields to be serialized. + private final static ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("objectI", Integer.class), + new ObjectStreamField("primitiveI", Integer.TYPE), + new ObjectStreamField("foo", Foo.class) + }; + + Integer objectI; + int primitiveI; + Foo foo; + + public TestClass(Foo f, Integer I, int i) { + foo = f; + objectI = I; + primitiveI = i; + } + + /** + * Verify GetField.defaulted("fieldName") works for primitive and + * object fields. + */ + private void readObject(ObjectInputStream in) + throws ClassNotFoundException, IOException + { + ObjectInputStream.GetField pfields = in.readFields(); + primitiveI = pfields.get("primitiveI", 99); + System.out.println("The primitiveI : " + primitiveI); + + objectI = (Integer)pfields.get("objectI", DEFAULT_OBJECT_I); + System.out.println("The ObjectI : " + objectI); + + foo = (Foo)pfields.get("foo", DEFAULT_OBJECT_F); + System.out.println("The foo : " + foo); + + try { + boolean b = pfields.defaulted("primitiveI"); + System.out.println("Defaulted prim : " + b); + if (b == false) { + throw new Error("Bad return value for defaulted() with " + + "primitive type fields"); + } + + b = pfields.defaulted("objectI"); + System.out.println("Defaulted ObjectI : " + b); + if (b == true) { + throw new Error("Bad return value for defaulted() with " + + "object type fields"); + } + + b = pfields.defaulted("foo"); + System.out.println("Defaulted Foo : " + b); + if (b == false) { + throw new Error("Bad return value for defaulted() with " + + "object type fields"); + } + + } catch (IllegalArgumentException e) { + System.out.println("Exception " + e.getMessage() + + ": handled calling " + + "GetField.defaulted(\"fieldName referring to an object\")"); + throw e; + } + } +}; + +public class GetFieldRead { + public static void main(String[] args) + throws ClassNotFoundException, IOException + { + FileInputStream fis = new FileInputStream("data.ser"); + ObjectInputStream in = new ObjectInputStream(fis); + TestClass obj = (TestClass) in.readObject(); + in.close(); + } +}; diff --git a/test/java/io/Serializable/defaulted/GetFieldWrite.java b/test/java/io/Serializable/defaulted/GetFieldWrite.java new file mode 100644 index 0000000000..f4a8bfeed8 --- /dev/null +++ b/test/java/io/Serializable/defaulted/GetFieldWrite.java @@ -0,0 +1,89 @@ +/* + * Copyright 1999-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 4180735 + * + * @clean GetFieldWrite Foo TestClass + * @build GetFieldWrite + * @run main GetFieldWrite + * @clean GetFieldRead TestClass + * @build GetFieldRead + * @run main GetFieldRead + * + * @summary Make sure that fields that are defaulted can be of primitive and + * object type. + * + */ + +import java.io.*; +class TestClass implements Serializable { + + private static final long serialVersionUID = 5748652654655279289L; + + // Fields to be serialized. + private final static ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("objectI", Integer.class)}; + + Integer objectI; + int primitiveI; + Foo foo; + + public TestClass(Foo f, Integer I, int i) { + foo = f; + objectI = I; + primitiveI = i; + } +}; + +public class GetFieldWrite { + public static void main(String[] args) + throws ClassNotFoundException, IOException + { + FileOutputStream fos = new FileOutputStream("data.ser"); + ObjectOutput out = new ObjectOutputStream(fos); + out.writeObject(new TestClass(new Foo(100, 200), new Integer(100), + 200)); + out.close(); + } +}; + +/* + * Test class to be used as data field + */ +class Foo implements Serializable{ + int a; + int b; + public Foo() { + a = 10; b= 20; + } + + public Foo(int a1, int b1) + { + a = a1; b = b1; + } + + public String toString() { + return new String("a = " + a + " b = " + b); + } +} diff --git a/test/java/io/Serializable/duplicateSerialFields/Setup.java b/test/java/io/Serializable/duplicateSerialFields/Setup.java new file mode 100644 index 0000000000..e2bd78c474 --- /dev/null +++ b/test/java/io/Serializable/duplicateSerialFields/Setup.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. + */ + +/* + * @bug 4764280 + * @summary Verify that if a serializable class declares multiple + * serialPersistentFields that share the same name, calling + * ObjectStreamClass.lookup() for that class will not result in an + * InternalError, and that attempts at default serialization or + * deserialization of such a class will result in + * InvalidClassExceptions. + */ + +import java.io.*; + +class A implements Serializable { + private static final long serialVersionUID = 0L; + int i; +} + +class B implements Serializable { + private static final long serialVersionUID = 0L; + int i; +} + +public class Setup { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("a.ser")); + oout.writeObject(new A()); + oout.close(); + + oout = new ObjectOutputStream(new FileOutputStream("b.ser")); + oout.writeObject(new B()); + oout.close(); + } +} diff --git a/test/java/io/Serializable/duplicateSerialFields/Test.java b/test/java/io/Serializable/duplicateSerialFields/Test.java new file mode 100644 index 0000000000..3e602768ed --- /dev/null +++ b/test/java/io/Serializable/duplicateSerialFields/Test.java @@ -0,0 +1,99 @@ +/* + * 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 4764280 + * + * @clean Setup Test A B + * @compile Setup.java + * @run main Setup + * @clean Setup A B + * @compile Test.java + * @run main Test + * + * @summary Verify that if a serializable class declares multiple + * serialPersistentFields that share the same name, calling + * ObjectStreamClass.lookup() for that class will not result in an + * InternalError, and that attempts at default serialization or + * deserialization of such a class will result in + * InvalidClassExceptions. + */ + +import java.io.*; + +class A implements Serializable { + private static final long serialVersionUID = 0L; + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("i", int.class), + new ObjectStreamField("i", int.class) + }; + int i; +} + +class B implements Serializable { + private static final long serialVersionUID = 0L; + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("i", int.class), + new ObjectStreamField("i", String.class) + }; + int i; +} + +public class Test { + public static void main(String[] args) throws Exception { + + ObjectStreamClass.lookup(A.class); + ObjectStreamClass.lookup(B.class); + + ObjectOutputStream oout = + new ObjectOutputStream(new ByteArrayOutputStream()); + try { + oout.writeObject(new A()); + throw new Error( + "write of A should fail with InvalidClassException"); + } catch (InvalidClassException e) { + } + + oout = new ObjectOutputStream(new ByteArrayOutputStream()); + try { + oout.writeObject(new B()); + throw new Error( + "write of B should fail with InvalidClassException"); + } catch (InvalidClassException e) { + } + + try { + new ObjectInputStream(new FileInputStream("a.ser")).readObject(); + throw new Error( + "read of A should fail with InvalidClassException"); + } catch (InvalidClassException e) { + } + + try { + new ObjectInputStream(new FileInputStream("b.ser")).readObject(); + throw new Error( + "read of B should fail with InvalidClassException"); + } catch (InvalidClassException e) { + } + } +} diff --git a/test/java/io/Serializable/enum/array/Test.java b/test/java/io/Serializable/enum/array/Test.java new file mode 100644 index 0000000000..705de3a44d --- /dev/null +++ b/test/java/io/Serializable/enum/array/Test.java @@ -0,0 +1,72 @@ +/* + * 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 4838379 + * @summary Verify that serialization of enum constant arrays functions + * properly. + * + * @compile -source 1.5 Test.java + * @run main Test + */ + +import java.io.*; +import java.util.Arrays; + +enum Foo { klaatu, barada { int i = 1; }, nikto } + +public class Test { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + Foo[] fa = Foo.values(); + Object[] oa = Arrays.asList(fa).toArray(); + oout.writeObject(oa); + oout.writeObject(fa); + oout.close(); + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + Object[] oa2 = (Object[]) oin.readObject(); + if (!elementsIdentical(oa, oa2)) { + throw new Error("arrays differ: " + + Arrays.asList(oa) + ", " + Arrays.asList(oa2)); + } + Foo[] fa2 = (Foo[]) oin.readObject(); + if (!elementsIdentical(fa, fa2)) { + throw new Error("arrays differ: " + + Arrays.asList(fa) + ", " + Arrays.asList(fa2)); + } + } + + static boolean elementsIdentical(Object[] a1, Object[] a2) { + if (a1.length != a2.length) { + return false; + } + for (int i = 0; i < a1.length; i++) { + if (a1[i] != a2[i]) { + return false; + } + } + return true; + } +} diff --git a/test/java/io/Serializable/enum/badResolve/Read.java b/test/java/io/Serializable/enum/badResolve/Read.java new file mode 100644 index 0000000000..f4d38a78ad --- /dev/null +++ b/test/java/io/Serializable/enum/badResolve/Read.java @@ -0,0 +1,56 @@ +/* + * 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. + */ + +/* + * @bug 4838379 + * @summary Verify that enum classes present in a serialization stream cannot + * be resolved by the receiver to non-enum classes, and vice-versa. + */ + +import java.io.*; + +class EnumToNonEnum implements Serializable { + private static final long serialVersionUID = 0L; +} + +enum NonEnumToEnum { foo } + +public class Read { + public static void main(String[] args) throws Exception { + read("0.ser"); + read("1.ser"); + read("2.ser"); + read("3.ser"); + } + + static void read(String filename) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream(filename)); + try { + Object obj = oin.readObject(); + throw new Error("read of " + obj + " should not have succeeded"); + } catch (InvalidClassException e) { + System.out.println("caught expected exception " + e); + } + } +} diff --git a/test/java/io/Serializable/enum/badResolve/Write.java b/test/java/io/Serializable/enum/badResolve/Write.java new file mode 100644 index 0000000000..24e0242d5f --- /dev/null +++ b/test/java/io/Serializable/enum/badResolve/Write.java @@ -0,0 +1,59 @@ +/* + * 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 4838379 + * @summary Verify that enum classes present in a serialization stream cannot + * be resolved by the receiver to non-enum classes, and vice-versa. + * + * @compile -source 1.5 Write.java + * @run main Write + * @clean Write + * @compile -source 1.5 Read.java + * @run main Read + * @clean Read + */ + +import java.io.*; + +enum EnumToNonEnum { foo } + +class NonEnumToEnum implements Serializable { + private static final long serialVersionUID = 0L; +} + +public class Write { + public static void main(String[] args) throws Exception { + write(EnumToNonEnum.class, "0.ser"); + write(NonEnumToEnum.class, "1.ser"); + write(EnumToNonEnum.foo, "2.ser"); + write(new NonEnumToEnum(), "3.ser"); + } + + static void write(Object obj, String filename) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream(filename)); + oout.writeObject(obj); + oout.close(); + } +} diff --git a/test/java/io/Serializable/enum/basic/Test.java b/test/java/io/Serializable/enum/basic/Test.java new file mode 100644 index 0000000000..b8677750bb --- /dev/null +++ b/test/java/io/Serializable/enum/basic/Test.java @@ -0,0 +1,54 @@ +/* + * 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 4838379 + * @summary Verify that basic serialization of non-specialized enum constants + * functions properly. + * + * @compile -source 1.5 Test.java + * @run main Test + */ + +import java.io.*; + +enum Foo { klaatu, barada, nikto } + +public class Test { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + for (Foo f : Foo.values()) { + oout.writeObject(f); + } + oout.close(); + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + for (Foo f : Foo.values()) { + Object obj = oin.readObject(); + if (obj != f) { + throw new Error("expected " + f + ", got " + obj); + } + } + } +} diff --git a/test/java/io/Serializable/enum/classObject/Test.java b/test/java/io/Serializable/enum/classObject/Test.java new file mode 100644 index 0000000000..e0f6ea2bd9 --- /dev/null +++ b/test/java/io/Serializable/enum/classObject/Test.java @@ -0,0 +1,57 @@ +/* + * 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 4838379 + * @summary Verify that serialization of Class objects for enum types works + * properly. + * + * @compile -source 1.5 Test.java + * @run main Test + */ + +import java.io.*; + +enum Foo { foo, bar { int i = 0; }, baz { double d = 3.0; } } + +public class Test { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + Class[] classes = { Enum.class, Foo.foo.getClass(), + Foo.bar.getClass(), Foo.baz.getClass() }; + for (int i = 0; i < classes.length; i++) { + oout.writeObject(classes[i]); + } + oout.close(); + + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + for (int i = 0; i < classes.length; i++) { + Object obj = oin.readObject(); + if (obj != classes[i]) { + throw new Error("expected " + classes[i] + ", got " + obj); + } + } + } +} diff --git a/test/java/io/Serializable/enum/constantSubclasses/Read.java b/test/java/io/Serializable/enum/constantSubclasses/Read.java new file mode 100644 index 0000000000..35811199c4 --- /dev/null +++ b/test/java/io/Serializable/enum/constantSubclasses/Read.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. + */ + +/* + * @bug 4838379 + * @summary Verify that serialization of enum constants that are instances of + * constant-specific subclasses functions properly. + */ + +import java.io.*; + +enum Foo { + a, + b { byte b = 3; }, + c, + d { double d = 6.0; } +} + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("foo.ser")); + for (Foo f : Foo.values()) { + Object obj = oin.readObject(); + if (obj != f) { + throw new Error("expected " + f + ", got " + obj); + } + } + } +} diff --git a/test/java/io/Serializable/enum/constantSubclasses/Write.java b/test/java/io/Serializable/enum/constantSubclasses/Write.java new file mode 100644 index 0000000000..18dcfb5685 --- /dev/null +++ b/test/java/io/Serializable/enum/constantSubclasses/Write.java @@ -0,0 +1,55 @@ +/* + * 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 4838379 + * @summary Verify that serialization of enum constants that are instances of + * constant-specific subclasses functions properly. + * + * @compile -source 1.5 Write.java + * @run main Write + * @clean Write + * @compile -source 1.5 Read.java + * @run main Read + * @clean Read + */ + +import java.io.*; + +enum Foo { + a, + b, + c { int i = 5; }, + d { float f = 5.0f; } +} + +public class Write { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("foo.ser")); + for (Foo f : Foo.values()) { + oout.writeObject(f); + } + oout.close(); + } +} diff --git a/test/java/io/Serializable/enum/ignoreSerializationFields/Test.java b/test/java/io/Serializable/enum/ignoreSerializationFields/Test.java new file mode 100644 index 0000000000..2780a283e5 --- /dev/null +++ b/test/java/io/Serializable/enum/ignoreSerializationFields/Test.java @@ -0,0 +1,73 @@ +/* + * 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 4838379 + * @summary Verify that serialVersionUID and serialPersistentFields + * declarations made by enum types and constants are ignored. + * + * @compile -source 1.5 Test.java + * @run main Test + */ + +import java.io.*; +import java.util.Arrays; + +enum Foo { + + foo, + bar { + private static final long serialVersionUID = 2L; + // bar is implemented as an inner class instance, so the following + // declaration would cause a compile-time error + // private static final ObjectStreamField[] serialPersistentFields = { + // new ObjectStreamField("gub", Float.TYPE) + // }; + }; + + private static final long serialVersionUID = 1L; + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("blargh", Integer.TYPE) + }; +} + +public class Test { + public static void main(String[] args) throws Exception { + Class[] classes = + { Foo.class, Foo.foo.getClass(), Foo.bar.getClass() }; + for (int i = 0; i < classes.length; i++) { + ObjectStreamClass desc = ObjectStreamClass.lookup(classes[i]); + if (desc.getSerialVersionUID() != 0L) { + throw new Error( + classes[i] + " has non-zero serialVersionUID: " + + desc.getSerialVersionUID()); + } + ObjectStreamField[] fields = desc.getFields(); + if (fields.length > 0) { + throw new Error( + classes[i] + " has non-empty list of fields: " + + Arrays.asList(fields)); + } + } + } +} diff --git a/test/java/io/Serializable/enum/ignoreSerializationMethods/Test.java b/test/java/io/Serializable/enum/ignoreSerializationMethods/Test.java new file mode 100644 index 0000000000..39bde6e255 --- /dev/null +++ b/test/java/io/Serializable/enum/ignoreSerializationMethods/Test.java @@ -0,0 +1,90 @@ +/* + * 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 4838379 + * @summary Verify that custom serialization methods defined by enum types are + * not invoked during serialization or deserialization. + * + * @compile -source 1.5 Test.java + * @run main Test + */ + +import java.io.*; + +enum Foo { + + foo, + bar { + private void writeObject(ObjectOutputStream out) throws IOException { + throw new Error("bar.writeObject invoked"); + } + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + throw new Error("bar.readObject invoked"); + } + Object writeReplace() throws ObjectStreamException { + throw new Error("bar.writeReplace invoked"); + } + // readResolve cannot be defined until Enum.readResolve is removed + // Object readResolve() throws ObjectStreamException { + // throw new Error("bar.readResolve invoked"); + // } + }; + + private void writeObject(ObjectOutputStream out) throws IOException { + throw new Error("Foo.writeObject invoked"); + } + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + throw new Error("Foo.readObject invoked"); + } + Object writeReplace() throws ObjectStreamException { + throw new Error("Foo.writeReplace invoked"); + } + // readResolve cannot be defined until Enum.readResolve is removed + // Object readResolve() throws ObjectStreamException { + // throw new Error("Foo.readResolve invoked"); + // } +} + +public class Test { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + for (Foo f : Foo.values()) { + oout.writeObject(f); + } + oout.close(); + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + for (Foo f : Foo.values()) { + Object obj = oin.readObject(); + if (obj != f) { + throw new Error("expected " + f + ", got " + obj); + } + } + } +} diff --git a/test/java/io/Serializable/enum/mismatchedTypecode/Test.java b/test/java/io/Serializable/enum/mismatchedTypecode/Test.java new file mode 100644 index 0000000000..f050cd964d --- /dev/null +++ b/test/java/io/Serializable/enum/mismatchedTypecode/Test.java @@ -0,0 +1,88 @@ +/* + * 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 4838379 + * @summary Verify that TC_OBJECT followed by a class descriptor for an enum + * class results in an InvalidClassException, as does TC_ENUM followed + * by a class descriptor for a non-enum class. + * + * @compile -source 1.5 Test.java + * @run main Test + */ + +import java.io.*; + +enum Foo { bar } + +class TestObjectOutputStream extends ObjectOutputStream { + + static ObjectStreamClass fooDesc = ObjectStreamClass.lookup(Foo.class); + static ObjectStreamClass integerDesc = + ObjectStreamClass.lookup(Integer.class); + + TestObjectOutputStream(OutputStream out) throws IOException { + super(out); + } + + protected void writeClassDescriptor(ObjectStreamClass desc) + throws IOException + { + if (desc == fooDesc) { + super.writeClassDescriptor(integerDesc); + } else if (desc == integerDesc) { + super.writeClassDescriptor(fooDesc); + } else { + super.writeClassDescriptor(desc); + } + } +} + +public class Test { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new TestObjectOutputStream(bout); + oout.writeObject(Foo.bar); + oout.close(); + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + try { + Object obj = oin.readObject(); + throw new Error("read of " + obj + " should not have succeeded"); + } catch (InvalidClassException e) { + System.out.println("caught expected exception " + e); + } + + oout = new TestObjectOutputStream(bout = new ByteArrayOutputStream()); + oout.writeObject(new Integer(5)); + oout.close(); + oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + try { + Object obj = oin.readObject(); + throw new Error("read of " + obj + " should not have succeeded"); + } catch (InvalidClassException e) { + System.out.println("caught expected exception " + e); + } + } +} diff --git a/test/java/io/Serializable/enum/missingConstant/Read.java b/test/java/io/Serializable/enum/missingConstant/Read.java new file mode 100644 index 0000000000..5ab1090dfc --- /dev/null +++ b/test/java/io/Serializable/enum/missingConstant/Read.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. + */ + +/* + * @bug 4838379 + * @summary Verify that deserialization of an enum constant that does not exist + * on the receiving side results in an InvalidObjectException. + */ + +import java.io.*; + +enum Foo { foo, bar } + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("foo.ser")); + for (Foo f : Foo.values()) { + Object obj = oin.readObject(); + if (obj != f) { + throw new Error("expected " + f + ", got " + obj); + } + } + try { + Object obj = oin.readObject(); + throw new Error("read of " + obj + " should not succeed"); + } catch (InvalidObjectException e) { + System.out.println("caught expected exception: " + e); + } + } +} diff --git a/test/java/io/Serializable/enum/missingConstant/Write.java b/test/java/io/Serializable/enum/missingConstant/Write.java new file mode 100644 index 0000000000..2939520636 --- /dev/null +++ b/test/java/io/Serializable/enum/missingConstant/Write.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 4838379 + * @summary Verify that deserialization of an enum constant that does not exist + * on the receiving side results in an InvalidObjectException. + * + * @compile -source 1.5 Write.java + * @run main Write + * @clean Write + * @compile -source 1.5 Read.java + * @run main Read + * @clean Read + */ + +import java.io.*; + +enum Foo { foo, bar, baz } + +public class Write { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("foo.ser")); + for (Foo f : Foo.values()) { + oout.writeObject(f); + } + oout.close(); + } +} diff --git a/test/java/io/Serializable/enum/unshared/Test.java b/test/java/io/Serializable/enum/unshared/Test.java new file mode 100644 index 0000000000..c4bdde9bc0 --- /dev/null +++ b/test/java/io/Serializable/enum/unshared/Test.java @@ -0,0 +1,136 @@ +/* + * 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 4838379 + * @summary Verify that unshared write and read operations work properly with + * enum constants. + * + * @compile -source 1.5 Test.java + * @run main Test + */ + +import java.io.*; + +enum Foo { foo, bar, baz } + +abstract class WriteReadTest { + + abstract void write(ObjectOutputStream out) throws Exception; + abstract void read(ObjectInputStream in) throws Exception; + + void run() throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + write(oout); + oout.close(); + read(new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray()))); + } +} + +public class Test { + public static void main(String[] args) throws Exception { + WriteReadTest[] tests = { + new WriteReadTest() { + void write(ObjectOutputStream out) throws Exception { + out.writeObject(Foo.foo); + out.writeObject(Foo.foo); + } + void read(ObjectInputStream in) throws Exception { + Object obj = in.readObject(); + if (obj != Foo.foo) { + throw new Error( + "expected " + Foo.foo + " instead of " + obj); + } + try { + obj = in.readUnshared(); + throw new Error( + "read of " + obj + " should not have succeeded"); + } catch (ObjectStreamException e) { + System.out.println("caught expected exception " + e); + } + } + }, + new WriteReadTest() { + void write(ObjectOutputStream out) throws Exception { + out.writeObject(Foo.foo); + out.writeObject(Foo.foo); + } + void read(ObjectInputStream in) throws Exception { + Object obj = in.readUnshared(); + if (obj != Foo.foo) { + throw new Error( + "expected " + Foo.foo + " instead of " + obj); + } + try { + obj = in.readObject(); + throw new Error( + "read of " + obj + " should not have succeeded"); + } catch (ObjectStreamException e) { + System.out.println("caught expected exception " + e); + } + } + }, + new WriteReadTest() { + void write(ObjectOutputStream out) throws Exception { + out.writeObject(Foo.foo); + out.writeUnshared(Foo.foo); + } + void read(ObjectInputStream in) throws Exception { + Object obj = in.readUnshared(); + if (obj != Foo.foo) { + throw new Error( + "expected " + Foo.foo + " instead of " + obj); + } + obj = in.readUnshared(); + if (obj != Foo.foo) { + throw new Error( + "expected " + Foo.foo + " instead of " + obj); + } + } + }, + new WriteReadTest() { + void write(ObjectOutputStream out) throws Exception { + out.writeUnshared(Foo.foo); + out.writeObject(Foo.foo); + } + void read(ObjectInputStream in) throws Exception { + Object obj = in.readUnshared(); + if (obj != Foo.foo) { + throw new Error( + "expected " + Foo.foo + " instead of " + obj); + } + obj = in.readUnshared(); + if (obj != Foo.foo) { + throw new Error( + "expected " + Foo.foo + " instead of " + obj); + } + } + } + }; + for (int i = 0; i < tests.length; i++) { + tests[i].run(); + } + } +} diff --git a/test/java/io/Serializable/evolution/AddedExternField/ReadAddedField.java b/test/java/io/Serializable/evolution/AddedExternField/ReadAddedField.java new file mode 100644 index 0000000000..fa1cb5621c --- /dev/null +++ b/test/java/io/Serializable/evolution/AddedExternField/ReadAddedField.java @@ -0,0 +1,68 @@ +/* + * Copyright 1998-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. + */ + +/* + * @bug 4088176 + * @summary Evolution: read evolved class with new field of a non-existing Externalizable class. + */ + +import java.io.*; + +class A implements Serializable { + // Version 1.0 of class A. + private static final long serialVersionUID = 1L; + public int bar; + public D zoo; +} + +class D implements Serializable { + public int x; + D(int y) { + x = y; + } +} + +public class ReadAddedField { + public static void main(String args[]) + throws IOException, ClassNotFoundException + { + File f = new File("tmp.ser"); + ObjectInput in = + new ObjectInputStream(new FileInputStream(f)); + A a = (A)in.readObject(); + A b = (A)in.readObject(); + if (a.bar != 4) + throw new RuntimeException("a.bar does not equal 4, it equals " + + a.bar); + if (a.zoo.x != 22) + throw new RuntimeException("a.zoo.x does not equal 22 equals " + + a.zoo.x); + if (b.bar != 4) + throw new RuntimeException("b.bar does not equal 4, it equals " + + b.bar); + if (b.zoo.x != 22) + throw new RuntimeException("b.zoo.x does not equal 22 equals " + + b.zoo.x); + in.close(); + } +} diff --git a/test/java/io/Serializable/evolution/AddedExternField/WriteAddedField.java b/test/java/io/Serializable/evolution/AddedExternField/WriteAddedField.java new file mode 100644 index 0000000000..676492156b --- /dev/null +++ b/test/java/io/Serializable/evolution/AddedExternField/WriteAddedField.java @@ -0,0 +1,93 @@ +/* + * Copyright 1998-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 4088176 + * + * @clean A D NewExternFieldClass ReadAddedField WriteAddedField + * @compile WriteAddedField.java + * @run main WriteAddedField + * @clean A D NewExternFieldClass ReadAddedField WriteAddedField + * @compile ReadAddedField.java + * @run main ReadAddedField + * + * @summary Evolution: read evolved class with new field of a non-existing Externalizable class. + */ +import java.io.*; + +class NewExternFieldClass implements Externalizable { + byte l; + + public NewExternFieldClass() { + l = 0; + } + + public NewExternFieldClass(byte value) { + l = value; + } + + public void readExternal(ObjectInput s) + throws IOException, ClassNotFoundException + { + l = s.readByte(); + System.out.println("readExternal read " + l); + } + + public void writeExternal(ObjectOutput s) throws IOException + { + s.writeByte(l); + } +} + +class D implements Serializable { + public int x; + D(int y) { + x = y; + } +} + +class A implements Serializable { + // Version 1.1 of class A. Added superclass NewSerializableSuper. + private static final long serialVersionUID = 1L; + NewExternFieldClass foo; + D zoo; + + int bar; + A() { + bar = 4; + foo = new NewExternFieldClass((byte)66); + zoo = new D(22); + } +} + +public class WriteAddedField { + public static void main(String args[]) throws IOException { + A a = new A(); + File f = new File("tmp.ser"); + ObjectOutput out = + new ObjectOutputStream(new FileOutputStream(f)); + out.writeObject(a); + out.writeObject(new A()); + out.close(); + } +} diff --git a/test/java/io/Serializable/evolution/AddedExternField/run.sh b/test/java/io/Serializable/evolution/AddedExternField/run.sh new file mode 100644 index 0000000000..7159d29924 --- /dev/null +++ b/test/java/io/Serializable/evolution/AddedExternField/run.sh @@ -0,0 +1,33 @@ +# +# Copyright 1998 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. +# + +# +# @bug 4088176 +# @summary Test reading an evolved class serialization into the original class + +rm *.class tmp.ser +javac WriteAddedField.java +java WriteAddedField +rm *.class +javac ReadAddedField.java +java ReadAddedField diff --git a/test/java/io/Serializable/evolution/AddedField/ReadAddedField.java b/test/java/io/Serializable/evolution/AddedField/ReadAddedField.java new file mode 100644 index 0000000000..2b93e1d32a --- /dev/null +++ b/test/java/io/Serializable/evolution/AddedField/ReadAddedField.java @@ -0,0 +1,114 @@ +/* + * Copyright 1997-1999 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. + */ + +/* + * @bug 4088176 + * @build WriteAddedField ReadAddedField + * @run main ReadAddedField + * + * @summary Deserialize an evolved class with a new field, field type is new. + * + */ + +import java.io.*; + +class IncompatibleFieldClass implements Serializable { + private static long serialVersionUID = 4L; + int x = 5; +}; + +class A implements Serializable { + // Version 1.0 of class A. + private static final long serialVersionUID = 1L; + public int bar; +} + +/** Test serial persistent fields w/o using Alternate API. + */ +class B implements Serializable { + private static final long serialVersionUID = 2L; + int bar; + + B() { + bar = 4; + } +} + +/** Test serial persistent fields using Alternate API. + * Also make sure that optional data to non-existent classes can be skipped. + */ +class C implements Serializable { + private static final long serialVersionUID = 3L; + int bar; + + C() { + bar = 4; + } + + private void readObject(ObjectInputStream s) + throws IOException, ClassNotFoundException + { + s.defaultReadObject(); + } + + private void writeObject(ObjectOutputStream s) + throws IOException + { + s.defaultWriteObject(); + } +} + +public class ReadAddedField { + public static void main(String args[]) + throws IOException, ClassNotFoundException + { + File f = new File("tmp.ser"); + ObjectInput in = + new ObjectInputStream(new FileInputStream(f)); + A a = (A)in.readObject(); + if (a.bar != 4) + throw new RuntimeException("a.bar does not equal 4, it equals " + + a.bar); + B b = (B)in.readObject(); + if (b.bar != 4) + throw new RuntimeException("b.bar does not equal 4, it equals " + + b.bar); + C c = (C)in.readObject(); + if (c.bar != 4) + throw new RuntimeException("c.bar does not equal 4, it equals " + + c.bar); + A aa = (A)in.readObject(); + if (aa.bar != 4) + throw new RuntimeException("a.bar does not equal 4, it equals " + + aa.bar); + B bb = (B)in.readObject(); + if (bb.bar != 4) + throw new RuntimeException("b.bar does not equal 4, it equals " + + bb.bar); + C cc = (C)in.readObject(); + if (cc.bar != 4) + throw new RuntimeException("c.bar does not equal 4, it equals " + + cc.bar); + in.close(); + } +} diff --git a/test/java/io/Serializable/evolution/AddedField/WriteAddedField.java b/test/java/io/Serializable/evolution/AddedField/WriteAddedField.java new file mode 100644 index 0000000000..868a46fcc1 --- /dev/null +++ b/test/java/io/Serializable/evolution/AddedField/WriteAddedField.java @@ -0,0 +1,206 @@ +/* + * Copyright 1997-1999 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 4088176 + * @summary Deserialize an evolved class with a new field, field type is new. + * + * @clean A B C NewExternField NewFieldClass ReadAddedField WriteAddedField + * @compile WriteAddedField.java + * @run main WriteAddedField + * @clean A B C NewExternField NewFieldClass ReadAddedField WriteAddedField + * @compile ReadAddedField.java + * @run main ReadAddedField + + + */ +import java.io.*; + +class NewFieldClass implements Serializable { + int k; + + NewFieldClass(int value) { + k = value; + } +}; + +class IncompatibleFieldClass implements Serializable { + private static long serialVersionUID = 3L; + int x = 5; +}; + +class NewExternFieldClass implements Externalizable { + byte l; + + public NewExternFieldClass(int value) { + l = (byte)value; + } + + public void readExternal(ObjectInput s) + throws IOException, ClassNotFoundException + { + l = s.readByte(); + } + + public void writeExternal(ObjectOutput s) throws IOException + { + s.writeByte(l); + } +} + +class A implements Serializable { + // Version 1.1 of class A. Added superclass NewSerializableSuper. + private static final long serialVersionUID = 1L; + NewFieldClass foo; + NewFieldClass fooarray[]; + IncompatibleFieldClass boo; + IncompatibleFieldClass booarray[]; + /* Excluded due to Bug 4089540 + NewExternFieldClass abc; + NewExternFieldClass farray[]; + */ + int bar; + A() { + foo = new NewFieldClass(23); + fooarray = new NewFieldClass[24]; + for (int i = 0; i < fooarray.length; i++) + fooarray[i] = new NewFieldClass(i); + boo = new IncompatibleFieldClass(); + booarray = new IncompatibleFieldClass[24]; + for (int i = 0; i < booarray.length; i++) + booarray[i] = new IncompatibleFieldClass(); + bar = 4; + /* Excluded due to Bug 4089540 + abc = new NewExternFieldClass(66); + farray = new NewExternFieldClass[10]; + for (int k = 0; k < farray.length; k++) + farray[k] = new NewExternFieldClass(k); + */ + } +} + +/** Test serial persistent fields w/o using Alternate API. + */ +class B implements Serializable { + private static final long serialVersionUID = 2L; + NewFieldClass foo; + NewFieldClass[] array; + IncompatibleFieldClass boo; + IncompatibleFieldClass booarray[]; + transient NewExternFieldClass abc; + transient NewExternFieldClass farray[]; + int bar; + + B() { + foo = new NewFieldClass(12); + array = new NewFieldClass[12]; + for (int i = 0; i < array.length; i++) + array[i] = new NewFieldClass(i); + bar = 4; + abc = new NewExternFieldClass(66); + farray = new NewExternFieldClass[10]; + for (int k = 0; k < farray.length; k++) + farray[k] = new NewExternFieldClass(k); + } +} + +/** Test serial persistent fields using Alternate API. + * Also make sure that optional data to non-existent classes can be skipped. + */ +class C implements Serializable { + private static final long serialVersionUID = 3L; + NewFieldClass foo; + NewFieldClass[] array; + int bar; + transient NewExternFieldClass abc; + transient NewExternFieldClass farray[]; + + C() { + foo = new NewFieldClass(12); + array = new NewFieldClass[12]; + for (int i = 0; i < array.length; i++) + array[i] = new NewFieldClass(i); + bar = 4; + abc = new NewExternFieldClass(3); + farray = new NewExternFieldClass[10]; + for (int k = 0; k < farray.length; k++) + farray[k] = new NewExternFieldClass(k); + } + + private void readObject(ObjectInputStream s) + throws IOException, ClassNotFoundException + { + s.defaultReadObject(); + /* Excluded due to Bug 4089540 + abc = (NewExternFieldClass)fields.get("abc", null); + farray = (NewExternFieldClass[])fields.get("farray", null); + */ + + /* read optional data */ + NewFieldClass tmpfoo = (NewFieldClass)s.readObject(); + NewFieldClass[] tmparray= (NewFieldClass[])s.readObject(); + int tmpbar = s.readInt(); + /* Excluded due to Bug 4089540 + NewExternFieldClass tmpabc = (NewExternFieldClass)s.readObject(); + NewExternFieldClass[] tmpfarray = (NewExternFieldClass[])s.readObject(); + */ + } + + private void writeObject(ObjectOutputStream s) + throws IOException + { + s.defaultWriteObject(); + + /* write optional data */ + s.writeObject(foo); + s.writeObject(array); + s.writeInt(bar); + + /* Excluded due to Bug 4089540 + s.writeObject(abc); + s.writeObject(farray); + */ + } +} + + +public class WriteAddedField { + public static void main(String args[]) throws IOException { + A a = new A(); + B b = new B(); + C c = new C(); + File f = new File("tmp.ser"); + ObjectOutput out = + new ObjectOutputStream(new FileOutputStream(f)); + out.writeObject(a); + out.writeObject(b); + out.writeObject(c); + a = new A(); + b = new B(); + c = new C(); + out.writeObject(a); + out.writeObject(b); + out.writeObject(c); + out.close(); + } +} diff --git a/test/java/io/Serializable/evolution/AddedField/run b/test/java/io/Serializable/evolution/AddedField/run new file mode 100644 index 0000000000..aef9c0e109 --- /dev/null +++ b/test/java/io/Serializable/evolution/AddedField/run @@ -0,0 +1,31 @@ +# +# Copyright 1997 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. +# + +rm *.class tmp.ser +javac WriteAddedField.java +java WriteAddedField +rm *.class +javac ReadAddedField.java +java ReadAddedField +rm *.class + diff --git a/test/java/io/Serializable/evolution/AddedSuperClass/README b/test/java/io/Serializable/evolution/AddedSuperClass/README new file mode 100644 index 0000000000..5878c2facb --- /dev/null +++ b/test/java/io/Serializable/evolution/AddedSuperClass/README @@ -0,0 +1,17 @@ +#Here is the script I used to run this test. The "rm" are critical to +#the test. +java -version +javac WriteAddedSuperClass.java +java WriteAddedSuperClass +rm A.class AddedSuperClass.class +javac ReadAddedSuperClass.java +java ReadAddedSuperClass +rm A.class +javac WriteAddedSuperClass.java +java WriteAddedSuperClass +rm A.class AddedSuperClass.class +javac ReadAddedSuperClass2.java +java ReadAddedSuperClass2 + + + diff --git a/test/java/io/Serializable/evolution/AddedSuperClass/ReadAddedSuperClass.java b/test/java/io/Serializable/evolution/AddedSuperClass/ReadAddedSuperClass.java new file mode 100644 index 0000000000..8b942b6f96 --- /dev/null +++ b/test/java/io/Serializable/evolution/AddedSuperClass/ReadAddedSuperClass.java @@ -0,0 +1,61 @@ +/* + * Copyright 1997-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. + */ + +/* + * @bug 4070080 + * + * @build WriteAddedSuperClass ReadAddedSuperClass + * @run main ReadAddedSuperClass + * @summary Test reading an evolved class serialization into the original class + * version. Class evolved by adding a superclass. + * This is a compatible class evolution. + * + * Part a of test serializes an instance of an evolved class to a serialization stream. + * Part b of test deserializes the serialization stream into an instance of + * the original class. + * + * Description of failure: + * + * If you delete AddedSuperClass.class before running this test, + * both JDK 1.1.x and 1.2 result in ClassNotFoundException for class + * AddedSuperClass. If the .class file is not deleted, 1.2 does not + * fail. However, JDK 1.1.4 core dumps dereferencing a null class handle + * in the native method for inputClassDescriptor. + */ + +import java.io.*; + +class A implements Serializable { + // Version 1.0 of class A. + private static final long serialVersionUID = 1L; +} + +public class ReadAddedSuperClass { + public static void main(String args[]) throws IOException, ClassNotFoundException { + File f = new File("tmp.ser"); + ObjectInput in = + new ObjectInputStream(new FileInputStream(f)); + A a = (A)in.readObject(); + in.close(); + } +} diff --git a/test/java/io/Serializable/evolution/AddedSuperClass/ReadAddedSuperClass2.java b/test/java/io/Serializable/evolution/AddedSuperClass/ReadAddedSuperClass2.java new file mode 100644 index 0000000000..52f7b99311 --- /dev/null +++ b/test/java/io/Serializable/evolution/AddedSuperClass/ReadAddedSuperClass2.java @@ -0,0 +1,62 @@ +/* + * Copyright 1997-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. + */ + +/* + * @bug 4070080 + * + * @build WriteAddedSuperClass ReadAddedSuperClass2 + * @run main ReadAddedSuperClass2 + * @summary 2nd part of test deserializes the serialization stream into an + * instance of the original class WHEN the AddedSuperClass exists + * locally. + * + * Description of failure: + * + * If you delete AddedSuperClass.class before running this test, + * both JDK 1.1.x and 1.2 result in ClassNotFoundException for class + * AddedSuperClass. If the .class file is not deleted, 1.2 does not + * fail. However, JDK 1.1.4 core dumps dereferencing a null class handle + * in the native method for inputClassDescriptor. + */ + +import java.io.*; + +class AddedSuperClass implements Serializable { + // Needed at least one field to recreate failure. + int field; +} + +class A implements Serializable { + // Version 1.0 of class A. + private static final long serialVersionUID = 1L; +} + +public class ReadAddedSuperClass2 { + public static void main(String args[]) throws IOException, ClassNotFoundException { + File f = new File("tmp.ser"); + ObjectInput in = + new ObjectInputStream(new FileInputStream(f)); + A a = (A)in.readObject(); + in.close(); + } +} diff --git a/test/java/io/Serializable/evolution/AddedSuperClass/WriteAddedSuperClass.java b/test/java/io/Serializable/evolution/AddedSuperClass/WriteAddedSuperClass.java new file mode 100644 index 0000000000..9eae4a6fe1 --- /dev/null +++ b/test/java/io/Serializable/evolution/AddedSuperClass/WriteAddedSuperClass.java @@ -0,0 +1,73 @@ +/* + * Copyright 1997-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 4070080 + * + * @summary Test reading an evolved class serialization into the original class + * version. Class evolved by adding a superclass. + * + * @clean A WriteAddedSuperClass ReadAddedSuperClass ReadAddedSuperClass2 + * @compile WriteAddedSuperClass.java + * @run main WriteAddedSuperClass + * @clean A AddedSuperClass + * @compile ReadAddedSuperClass.java + * @run main ReadAddedSuperClass + * @clean A + * @compile WriteAddedSuperClass.java + * @run main WriteAddedSuperClass + * @clean A AddedSuperClass + * @compile ReadAddedSuperClass2.java + * @run main ReadAddedSuperClass2 + * + */ + + /* + * Part a of test serializes an instance of an evolved class to a serialization stream. + * Part b of test deserializes the serialization stream into an instance of + * the original class. + * + */ + +import java.io.*; + +class AddedSuperClass implements Serializable { + // Needed at least one field to recreate failure. + int field; +} + +class A extends AddedSuperClass implements Serializable { + // Version 1.1 of class A. Added superclass NewSerializableSuper. + private static final long serialVersionUID = 1L; +} + +public class WriteAddedSuperClass { + public static void main(String args[]) throws IOException { + A a = new A(); + File f = new File("tmp.ser"); + ObjectOutput out = + new ObjectOutputStream(new FileOutputStream(f)); + out.writeObject(a); + out.close(); + } +} diff --git a/test/java/io/Serializable/evolution/RenamePackage/extension/ExtendedObjectInputStream.java b/test/java/io/Serializable/evolution/RenamePackage/extension/ExtendedObjectInputStream.java new file mode 100644 index 0000000000..62ea5fbac0 --- /dev/null +++ b/test/java/io/Serializable/evolution/RenamePackage/extension/ExtendedObjectInputStream.java @@ -0,0 +1,77 @@ +/* + * Copyright 1998 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. + */ + +package extension; + +import java.util.Hashtable; +import java.io.*; + +public class ExtendedObjectInputStream extends ObjectInputStream { + + static private Hashtable renamedClassMap; + + public ExtendedObjectInputStream(InputStream si) + throws IOException, StreamCorruptedException + { + super(si); + } + + protected Class resolveClass(ObjectStreamClass v) + throws IOException, ClassNotFoundException + { + if (renamedClassMap != null) { + // System.out.println("resolveClass(" + v.getName() + ")"); + Class newClass = (Class)renamedClassMap.get(v.getName()); + if (newClass != null) { + v = ObjectStreamClass.lookup(newClass); + } + } + return super.resolveClass(v); + } + + static public void addRenamedClassName(String oldName, String newName) + throws ClassNotFoundException + { + Class cl = null; + + if (renamedClassMap == null) + renamedClassMap = new Hashtable(10); + if (newName.startsWith("[L")) { + // System.out.println("Array processing"); + Class componentType = + Class.forName(newName.substring(2)); + //System.out.println("ComponentType=" + componentType.getName()); + Object dummy = + java.lang.reflect.Array.newInstance(componentType, 3); + + cl = dummy.getClass(); + // System.out.println("Class=" + cl.getName()); + } + else + cl = Class.forName(newName); + //System.out.println("oldName=" + oldName + + // " newName=" + cl.getName()); + renamedClassMap.put(oldName, cl); + } + +} diff --git a/test/java/io/Serializable/evolution/RenamePackage/install/SerialDriver.java b/test/java/io/Serializable/evolution/RenamePackage/install/SerialDriver.java new file mode 100644 index 0000000000..03092f1ad3 --- /dev/null +++ b/test/java/io/Serializable/evolution/RenamePackage/install/SerialDriver.java @@ -0,0 +1,142 @@ +/* + * Copyright 1998-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. + */ + +/* + * + * @bug 4087295 + * @build install/SerialDriver.java test/SerialDriver.java extension/ExtendedObjectInputStream.java + * @summary Enable resolveClass() to accommodate package renaming. + * This fix enables one to implement a resolveClass method that maps a + * Serialiazable class within a serialization stream to the same class + * in a different package within the JVM runtime. See run shell script + * for instructions on how to run this test. + */ + +package install; + +import java.io.*; +import extension.ExtendedObjectInputStream; + +public class SerialDriver implements Serializable { + private static final long serialVersionUID = 1L; + + String name; + SerialDriver next; + transient Object objarray[]; + + public SerialDriver() { + name = "<terminator>"; + next = null; + } + + public SerialDriver(String name, SerialDriver next) { + this.name = name; + this.next = next; + } + + static boolean serialize; + static boolean deserialize; + + public static void main(String args[]) throws Exception { + SerialDriver obj = new SerialDriver("SerialDriver_2", + new SerialDriver()); + SerialDriver[] array = new SerialDriver[5]; + for (int i = 0; i < array.length; i++) + array[i] = new SerialDriver("SerialDriver_1_" + i, new SerialDriver()); + + /* + * see if we are serializing or deserializing. + * The ability to deserialize or serialize allows + * us to see the bidirectional readability and writeability + */ + if (args.length == 1) { + if (args[0].equals("-d")) { + deserialize = true; + } else if (args[0].equals("-s")) { + serialize = true; + } else { + usage(); + throw new Exception("incorrect command line arguments"); + } + } else { + usage(); + throw new Exception("incorrect command line arguments"); + } + + File f = new File("stream.ser"); + if (serialize) { + // Serialize the subclass + try { + FileOutputStream fo = new FileOutputStream(f); + ObjectOutputStream so = new ObjectOutputStream(fo); + so.writeObject(obj); + /* Skip arrays since they do not work with rename yet. + The serialVersionUID changes due to the name change + and there is no way to set the serialVersionUID for an + array. */ + so.writeObject(array); + so.flush(); + } catch (Exception e) { + System.out.println(e); + throw e; + } + } + if (deserialize) { + // Deserialize the subclass + try { + FileInputStream fi = new FileInputStream(f); + ExtendedObjectInputStream si = + new ExtendedObjectInputStream(fi); + si.addRenamedClassName("test.SerialDriver", "install.SerialDriver"); + si.addRenamedClassName("[Ltest.SerialDriver;", + "[Linstall.SerialDriver"); + obj = (SerialDriver) si.readObject(); + array = (SerialDriver[]) si.readObject(); + si.close(); + } catch (Exception e) { + System.out.println(e); + throw e; + } + System.out.println(); + System.out.println("Printing deserialized class: "); + System.out.println(); + System.out.println(obj.toString()); + System.out.println(); + } + } + + + public String toString() { + String nextString = next != null ? next.toString() : "<null>"; + return "name =" + name + " next = <" + nextString + ">"; + } + + /** + * Prints out the usage + */ + static void usage() { + System.out.println("Usage:"); + System.out.println(" -s (in order to serialize)"); + System.out.println(" -d (in order to deserialize)"); + } +} diff --git a/test/java/io/Serializable/evolution/RenamePackage/run.sh b/test/java/io/Serializable/evolution/RenamePackage/run.sh new file mode 100644 index 0000000000..2f194c0612 --- /dev/null +++ b/test/java/io/Serializable/evolution/RenamePackage/run.sh @@ -0,0 +1,98 @@ +# +# Copyright 1998-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 4087295 4785472 +# @summary Enable resolveClass() to accommodate package renaming. +# This fix enables one to implement a resolveClass method that maps a +# Serialiazable class within a serialization stream to the same class +# in a different package within the JVM runtime. See run shell script +# for instructions on how to run this test. + + +if [ "${TESTJAVA}" = "" ] +then + echo "TESTJAVA not set. Test cannot execute. Failed." + exit 1 +fi + + +OS=`uname -s` +# Need to determine the classpath separator and filepath separator based on the +# operating system. +case "$OS" in +SunOS | Linux ) + PS=":" ;; +Windows* ) + PS=";" ;; +* ) + echo "Unrecognized system!" + exit 1 ;; +esac + +JAVA=${TESTJAVA}/bin/java +JAVAC=${TESTJAVA}/bin/javac +MKDIR=mkdir +RDEL="rm -r" + +if [ -d ${TESTCLASSES}/oclasses ] +then + ${RDEL} ${TESTCLASSES}/oclasses +fi +if [ -d ${TESTCLASSES}/nclasses ] +then + ${RDEL} ${TESTCLASSES}/nclasses +fi +if [ -d ${TESTCLASSES}/share ] +then + ${RDEL} ${TESTCLASSES}/share +fi +if [ -f ${TESTCLASSES}/stream.ser ] +then + ${RDEL} ${TESTCLASSES}/stream.ser +fi + +mkdir ${TESTCLASSES}/oclasses +mkdir ${TESTCLASSES}/share +mkdir ${TESTCLASSES}/nclasses + +# Build sources +set -e +${JAVAC} -d ${TESTCLASSES}/share ${TESTSRC}/extension/ExtendedObjectInputStream.java +CLASSPATH=${TESTCLASSES}/share; export CLASSPATH; +${JAVAC} -d ${TESTCLASSES}/oclasses ${TESTSRC}/test/SerialDriver.java +CLASSPATH=${TESTCLASSES}/share; export CLASSPATH; +${JAVAC} -d ${TESTCLASSES}/nclasses ${TESTSRC}/install/SerialDriver.java + +# Run Case 1. Map test.SerialDriver within stream to install.SerialDriver. +CLASSPATH=${TESTCLASSES}/oclasses${PS}${TESTCLASSES}/share; export CLASSPATH; +${JAVA} test.SerialDriver -s +CLASSPATH=${TESTCLASSES}/nclasses${PS}${TESTCLASSES}/share; export CLASSPATH; +${JAVA} install.SerialDriver -d +rm stream.ser + +# Run Case 2. Map install.SerialDriver within stream to test.SerialDriver. +CLASSPATH=${TESTCLASSES}/nclasses${PS}${TESTCLASSES}/share; export CLASSPATH; +${JAVA} install.SerialDriver -s +CLASSPATH=${TESTCLASSES}/oclasses${PS}${TESTCLASSES}/share; export CLASSPATH; +${JAVA} test.SerialDriver -d diff --git a/test/java/io/Serializable/evolution/RenamePackage/test/SerialDriver.java b/test/java/io/Serializable/evolution/RenamePackage/test/SerialDriver.java new file mode 100644 index 0000000000..99d04d779f --- /dev/null +++ b/test/java/io/Serializable/evolution/RenamePackage/test/SerialDriver.java @@ -0,0 +1,137 @@ +/* + * Copyright 1998-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. + */ + +/* + * + * @bug 4087295 + * @build install/SerialDriver.java test/SerialDriver.java extension/ExtendedObjectInputStream.java + * @summary Enable resolveClass() to accommodate package renaming. + * This fix enables one to implement a resolveClass method that maps a + * Serialiazable class within a serialization stream to the same class + * in a different package within the JVM runtime. See run shell script + * for instructions on how to run this test. + */ + +package test; + +import java.io.*; +import extension.ExtendedObjectInputStream; + +public class SerialDriver implements Serializable { + private static final long serialVersionUID = 1L; + String name; + SerialDriver next; + + public SerialDriver() { + name = "<terminator>"; + next = null; + } + + public SerialDriver(String name, SerialDriver next) { + this.name = name; + this.next = next; + } + + static boolean serialize = false; + static boolean deserialize = false; + + public static void main(String args[]) throws Exception { + SerialDriver obj = new SerialDriver("SerialDriver_1", new SerialDriver()); + SerialDriver[] array = new SerialDriver[5]; + for (int i = 0; i < array.length; i++) + array[i] = new SerialDriver("SerialDriver_1_" + i, new SerialDriver()); + + /* + * see if we are serializing or deserializing. + * The ability to deserialize or serialize allows + * us to see the bidirectional readability and writeability + */ + if (args.length == 1) { + if (args[0].equals("-d")) { + deserialize = true; + } else if (args[0].equals("-s")) { + serialize = true; + } else { + usage(); + throw new Exception("incorrect command line arguments"); + } + } else { + usage(); + throw new Exception("incorrect command line arguments"); + } + + File f = new File("stream.ser"); + if (serialize) { + // Serialize the subclass + try { + FileOutputStream fo = new FileOutputStream(f); + ObjectOutputStream so = new ObjectOutputStream(fo); + so.writeObject(obj); + /* Comment out since renaming arrays does not work + since it changes the serialVersionUID. */ + so.writeObject(array); + so.flush(); + } catch (Exception e) { + System.out.println(e); + throw e; + } + } + if (deserialize) { + // Deserialize the subclass + try { + FileInputStream fi = new FileInputStream(f); + ExtendedObjectInputStream si = new ExtendedObjectInputStream(fi); + si.addRenamedClassName("install.SerialDriver", + "test.SerialDriver"); + si.addRenamedClassName("[Linstall.SerialDriver;", + "[Ltest.SerialDriver"); + obj = (SerialDriver) si.readObject(); + array = (SerialDriver[]) si.readObject(); + si.close(); + } catch (Exception e) { + System.out.println(e); + throw e; + } + System.out.println(); + System.out.println("Printing deserialized class: "); + System.out.println(); + System.out.println(obj.toString()); + System.out.println(); + } + } + + + public String toString() { + String nextString = next != null ? next.toString() : "<null>"; + return "name =" + name + " next = <" + nextString + ">"; + } + + /** + * Prints out the usage + */ + static void usage() { + System.out.println("Usage:"); + System.out.println(" -s (in order to serialize)"); + System.out.println(" -d (in order to deserialize)"); + } +} diff --git a/test/java/io/Serializable/expectedStackTrace/ExpectedStackTrace.java b/test/java/io/Serializable/expectedStackTrace/ExpectedStackTrace.java new file mode 100644 index 0000000000..024e8a3827 --- /dev/null +++ b/test/java/io/Serializable/expectedStackTrace/ExpectedStackTrace.java @@ -0,0 +1,108 @@ +/* + * 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 6317435 + * @summary Verify that stack trace contains a proper cause of + * InvalidClassException (methods: checkSerialize, + * checkDeserialize or checkDefaultSerialize) + * + * @author Andrey Ozerov + * + */ +import java.io.*; + +class NotSerializableObject { + private String m_str; + private Integer m_int; + + public NotSerializableObject(String m_str, Integer m_int) { + this.m_str = m_str; + this.m_int = m_int; + } +} + +class SerializableObject extends NotSerializableObject + implements Serializable +{ + + public SerializableObject(String m_str, Integer m_int) { + super(m_str, m_int); + } + + public SerializableObject() { + super("test", 10); + } +} + +public class ExpectedStackTrace { + private static final String SER_METHOD_NAME = "checkSerializable"; + + public static final void main(String[] args) throws Exception { + System.err.println("\nRegression test for CR6317435"); + checkSerializable(getObject()); + } + + private static Object getObject() throws Exception { + ObjectStreamClass osc = + ObjectStreamClass.lookup(SerializableObject.class); + SerializableObject initObj = + (SerializableObject) osc.forClass().newInstance(); + return initObj; + } + + private static void checkSerializable(Object initObj) throws Exception { + try { + // Serialize to a byte array + ByteArrayOutputStream bos = new ByteArrayOutputStream() ; + ObjectOutputStream out = new ObjectOutputStream(bos) ; + out.writeObject(initObj); + out.close(); + + // Get the bytes of the serialized object + byte[] buf = bos.toByteArray(); + + // Deserialize from a byte array + ByteArrayInputStream bais = new ByteArrayInputStream(buf); + ObjectInputStream in = new ObjectInputStream(bais); + SerializableObject finObj = (SerializableObject) in.readObject(); + in.close(); + throw new Error(); + } catch(ObjectStreamException ex) { + StackTraceElement[] stes = ex.getStackTrace(); + boolean found = false; + for (int i = 0; i<stes.length-1; i++) { + StackTraceElement ste = stes[i]; + String nme = ste.getMethodName(); + if (nme.equals(SER_METHOD_NAME)) { + found = true; + } + } + if (found) { + System.err.println("\nTEST PASSED"); + } else { + throw new Error(); + } + } + } +} diff --git a/test/java/io/Serializable/explicitCNFException/ExplicitCNFException.java b/test/java/io/Serializable/explicitCNFException/ExplicitCNFException.java new file mode 100644 index 0000000000..aa8505fb61 --- /dev/null +++ b/test/java/io/Serializable/explicitCNFException/ExplicitCNFException.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 4407956 + * @summary Verify that ClassNotFoundExceptions explicitly constructed and + * thrown from with custom readObject/readExternal methods are + * propagated properly. + */ + +import java.io.*; + +class A implements Serializable { + private void readObject(ObjectInputStream in) + throws ClassNotFoundException, IOException + { + throw new ClassNotFoundException(); + } +} + +class B implements Externalizable { + public B() {} + + public void writeExternal(ObjectOutput out) throws IOException {} + + public void readExternal(ObjectInput in) + throws ClassNotFoundException, IOException + { + throw new ClassNotFoundException(); + } +} + +public class ExplicitCNFException { + public static void main(String[] args) throws Exception { + test(new A()); + test(new Object[]{ new A() }); + test(new B()); + test(new Object[]{ new B() }); + } + + static void test(Object obj) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.useProtocolVersion(ObjectStreamConstants.PROTOCOL_VERSION_2); + oout.writeObject(obj); + oout.close(); + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + try { + oin.readObject(); + throw new Error(); // should not succeed + } catch (ClassNotFoundException ex) { + } + } +} diff --git a/test/java/io/Serializable/fieldTypeString/Read.java b/test/java/io/Serializable/fieldTypeString/Read.java new file mode 100644 index 0000000000..1b5da8a457 --- /dev/null +++ b/test/java/io/Serializable/fieldTypeString/Read.java @@ -0,0 +1,66 @@ +/* + * 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. + */ + +/* + * @bug 4404696 + * @summary Verify that serialization does not require matching type strings + * for non-primitive fields. + * + * NOTE: This test should be removed if it is determined that serialization + * *should* consider type strings when matching non-primitive fields. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 0L; + String obj; // writer defines this field as type Object +} + +class Bar implements Serializable { + private static final long serialVersionUID = 0L; + short q; // writer defines this field as type int +} + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("foo.ser")); + Foo foo = (Foo) oin.readObject(); + if (! foo.obj.equals("foo")) { + throw new Error(); + } + try { + oin.readObject(); + throw new Error(); + } catch (ClassCastException ex) { + } + + oin = new ObjectInputStream(new FileInputStream("bar.ser")); + try { + oin.readObject(); + throw new Error(); + } catch (InvalidClassException ex) { + } + } +} diff --git a/test/java/io/Serializable/fieldTypeString/Write.java b/test/java/io/Serializable/fieldTypeString/Write.java new file mode 100644 index 0000000000..fa59bf3faf --- /dev/null +++ b/test/java/io/Serializable/fieldTypeString/Write.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 4404696 + * + * @clean Write Read Foo Bar + * @compile Write.java + * @run main Write + * @clean Write Read Foo Bar + * @compile Read.java + * @run main Read + * + * @summary Verify that serialization does not require matching type strings + * for non-primitive fields. + * + * NOTE: This test should be removed if it is determined that serialization + * *should* consider type strings when matching non-primitive fields. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 0L; + Object obj; + + Foo(Object obj) { + this.obj = obj; + } +} + +class Bar implements Serializable { + private static final long serialVersionUID = 0L; + int q; +} + +public class Write { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("foo.ser")); + oout.writeObject(new Foo("foo")); + oout.writeObject(new Foo(new Integer(0))); + oout.close(); + + oout = new ObjectOutputStream(new FileOutputStream("bar.ser")); + oout.writeObject(new Bar()); + oout.close(); + } +} diff --git a/test/java/io/Serializable/finalFields/FinalFields.java b/test/java/io/Serializable/finalFields/FinalFields.java new file mode 100644 index 0000000000..09b2c4484e --- /dev/null +++ b/test/java/io/Serializable/finalFields/FinalFields.java @@ -0,0 +1,71 @@ +/* + * Copyright 1999 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 4174797 + * @summary Ensure that ObjectInputStream can set final fields. + */ + +import java.io.*; + +class Foo implements Serializable { + final int i; + + Foo(int i) { + this.i = i; + } + + public boolean equals(Object obj) { + if (! (obj instanceof Foo)) + return false; + Foo f = (Foo) obj; + return (i == f.i); + } +} + +public class FinalFields { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout; + ByteArrayInputStream bin; + ObjectOutputStream oout; + ObjectInputStream oin; + Foo f1, f2, f1copy, f2copy; + + bout = new ByteArrayOutputStream(); + oout = new ObjectOutputStream(bout); + f1 = new Foo(1); + f2 = new Foo(2); + + oout.writeObject(f1); + oout.writeObject(f2); + oout.flush(); + + bin = new ByteArrayInputStream(bout.toByteArray()); + oin = new ObjectInputStream(bin); + f1copy = (Foo) oin.readObject(); + f2copy = (Foo) oin.readObject(); + + if (! (f1.equals(f1copy) && f2.equals(f2copy))) + throw new Error("copies don't match originals"); + } +} diff --git a/test/java/io/Serializable/getSuidClinitError/GetSuidClinitError.java b/test/java/io/Serializable/getSuidClinitError/GetSuidClinitError.java new file mode 100644 index 0000000000..ceb2198569 --- /dev/null +++ b/test/java/io/Serializable/getSuidClinitError/GetSuidClinitError.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 4482966 + * @summary Verify that ObjectStreamClass.getSerialVersionUID() will not mask + * Errors (other than NoSuchMethodError) triggered by JNI query for + * static initializer method. + */ + +import java.io.*; + +class A implements Serializable { + static { + // compiler prohibits direct throw + throwMe(new RuntimeException("blargh")); + } + + static void throwMe(RuntimeException ex) throws RuntimeException { + throw ex; + } +} + +class B implements Serializable { +} + +class C implements Serializable { + static { System.out.println("C.<clinit>"); } +} + +class B1 extends B { +} + +class B2 extends B { + static { System.out.println("B2.<clinit>"); } +} + +class C1 extends C { +} + +class C2 extends C { + static { System.out.println("C2.<clinit>"); } +} + +public class GetSuidClinitError { + public static void main(String[] args) throws Exception { + Class cl = Class.forName( + "A", false, GetSuidClinitError.class.getClassLoader()); + for (int i = 0; i < 2; i++) { + try { + ObjectStreamClass.lookup(cl).getSerialVersionUID(); + throw new Error(); + } catch (ExceptionInInitializerError er) { + } catch (NoClassDefFoundError er) { + /* + * er _should_ be an ExceptionInInitializerError; however, + * hotspot currently throws a NoClassDefFoundError in this + * case, which runs against the JNI spec. For the purposes of + * testing this fix, however, permit either. + */ + System.out.println("warning: caught " + er + + " instead of ExceptionInInitializerError"); + } + } + + Class[] cls = new Class[] { + B.class, B1.class, B2.class, + C.class, C1.class, C2.class + }; + long[] suids = new long[] { // 1.3.1 default serialVersionUIDs + 369445310364440919L, 7585771686008346939L, -8952923334200087495L, + 3145821251853463625L, 327577314910517070L, -92102021266426451L + }; + for (int i = 0; i < cls.length; i++) { + if (ObjectStreamClass.lookup(cls[i]).getSerialVersionUID() != + suids[i]) + { + throw new Error(); + } + } + } +} diff --git a/test/java/io/Serializable/illegalHandle/Test.java b/test/java/io/Serializable/illegalHandle/Test.java new file mode 100644 index 0000000000..f3fb4a3766 --- /dev/null +++ b/test/java/io/Serializable/illegalHandle/Test.java @@ -0,0 +1,58 @@ +/* + * Copyright 2000 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 4357979 + * @summary Verify that ObjectInputStream throws a StreamCorruptedException if + * it reads in an out-of-bounds handle value. + */ + +import java.io.*; + +public class Test { + public static void main(String[] args) throws Exception { + String base = System.getProperty("test.src", "."); + + /* + * Files negativeHandle.ser and tooHighHandle.ser each contain a + * serialized String object followed by an illegal handle + */ + File f = new File(base, "negativeHandle.ser"); + ObjectInputStream oin = new ObjectInputStream(new FileInputStream(f)); + oin.readObject(); + try { + oin.readObject(); + throw new Error("negative handle read should not succeed"); + } catch (StreamCorruptedException ex) { + } + + f = new File(base, "tooHighHandle.ser"); + oin = new ObjectInputStream(new FileInputStream(f)); + oin.readObject(); + try { + oin.readObject(); + throw new Error("too-high handle read should not succeed"); + } catch (StreamCorruptedException ex) { + } + } +} diff --git a/test/java/io/Serializable/illegalHandle/negativeHandle.ser b/test/java/io/Serializable/illegalHandle/negativeHandle.ser Binary files differnew file mode 100644 index 0000000000..627c6e8601 --- /dev/null +++ b/test/java/io/Serializable/illegalHandle/negativeHandle.ser diff --git a/test/java/io/Serializable/illegalHandle/tooHighHandle.ser b/test/java/io/Serializable/illegalHandle/tooHighHandle.ser Binary files differnew file mode 100644 index 0000000000..0894b05fdd --- /dev/null +++ b/test/java/io/Serializable/illegalHandle/tooHighHandle.ser diff --git a/test/java/io/Serializable/inactiveRegistration/InactiveRegistration.java b/test/java/io/Serializable/inactiveRegistration/InactiveRegistration.java new file mode 100644 index 0000000000..f52db59815 --- /dev/null +++ b/test/java/io/Serializable/inactiveRegistration/InactiveRegistration.java @@ -0,0 +1,49 @@ +/* + * Copyright 2000 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 4400609 + * @summary Verify that ObjectInputStream.registerValidation() throws a + * NotActiveException when invoked on inactive stream. + */ + +import java.io.*; + +public class InactiveRegistration { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject("foo"); + oout.close(); + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + try { + oin.registerValidation(new ObjectInputValidation() { + public void validateObject() throws InvalidObjectException {} + }, 0); + throw new Error( + "registerValidation should fail on inactive stream"); + } catch (NotActiveException ex) { + } + } +} diff --git a/test/java/io/Serializable/longString/LongString.java b/test/java/io/Serializable/longString/LongString.java new file mode 100644 index 0000000000..02fb95f3cf --- /dev/null +++ b/test/java/io/Serializable/longString/LongString.java @@ -0,0 +1,84 @@ +/* + * Copyright 1999 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 4217676 + * @summary Ensure that object streams support serialization of long strings + * (strings whose UTF representation > 64k in length) + */ + +import java.io.*; +import java.util.*; + +public class LongString { + public static void main(String[] args) throws Exception { + Random rand = new Random(System.currentTimeMillis()); + ByteArrayOutputStream bout; + ByteArrayInputStream bin; + ObjectOutputStream oout; + ObjectInputStream oin; + FileInputStream fin; + File mesgf; + + // generate a long random string + StringBuffer sbuf = new StringBuffer(); + for (int i = 0; i < 100000; i++) + sbuf.append((char) rand.nextInt(Character.MAX_VALUE + 1)); + String str = sbuf.toString(); + + // write and read long string + bout = new ByteArrayOutputStream(); + oout = new ObjectOutputStream(bout); + oout.writeObject(str); + oout.flush(); + bin = new ByteArrayInputStream(bout.toByteArray()); + oin = new ObjectInputStream(bin); + String strcopy = (String) oin.readObject(); + if (! str.equals(strcopy)) + throw new Error("deserialized long string not equal to original"); + + // test backwards compatibility + String mesg = "Message in golden file"; + bout = new ByteArrayOutputStream(); + oout = new ObjectOutputStream(bout); + oout.writeObject(mesg); + oout.flush(); + byte[] buf1 = bout.toByteArray(); + + mesgf = new File(System.getProperty("test.src", "."), "mesg.ser"); + fin = new FileInputStream(mesgf); + bout = new ByteArrayOutputStream(); + while (fin.available() > 0) + bout.write(fin.read()); + byte[] buf2 = bout.toByteArray(); + + if (! Arrays.equals(buf1, buf2)) + throw new Error("incompatible string format (write)"); + + fin = new FileInputStream(mesgf); + oin = new ObjectInputStream(fin); + String mesgcopy = (String) oin.readObject(); + if (! mesg.equals(mesgcopy)) + throw new Error("incompatible string format (read)"); + } +} diff --git a/test/java/io/Serializable/longString/mesg.ser b/test/java/io/Serializable/longString/mesg.ser Binary files differnew file mode 100644 index 0000000000..0835e64a1d --- /dev/null +++ b/test/java/io/Serializable/longString/mesg.ser diff --git a/test/java/io/Serializable/lookupAnyInvocation/LookupAnyInvocation.java b/test/java/io/Serializable/lookupAnyInvocation/LookupAnyInvocation.java new file mode 100644 index 0000000000..a68f74288e --- /dev/null +++ b/test/java/io/Serializable/lookupAnyInvocation/LookupAnyInvocation.java @@ -0,0 +1,43 @@ +/* + * 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 4413615 + * @summary Verify that ObjectStreamClass.lookupAny() returns a non-null + * descriptor for class which doesn't implement java.io.Serializable + * interface at all. + */ + +import java.io.*; + +class Foo { +} + +public class LookupAnyInvocation { + public static final void main(String[] args) { + ObjectStreamClass descs = ObjectStreamClass.lookupAny(Foo.class); + if (descs == null) { + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/lookupInterfaceDesc/LookupInterfaceDesc.java b/test/java/io/Serializable/lookupInterfaceDesc/LookupInterfaceDesc.java new file mode 100644 index 0000000000..84419aef56 --- /dev/null +++ b/test/java/io/Serializable/lookupInterfaceDesc/LookupInterfaceDesc.java @@ -0,0 +1,63 @@ +/* + * 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 4402227 + * @summary Verify that ObjectStreamClass.lookup() functions properly + * for interfaces. + */ + +import java.io.*; + +interface Foo extends Serializable { + static final long serialVersionUID = 0xCAFE; +} + +interface Bar extends Externalizable { + static final long serialVersionUID = 0xBABE; +} + +interface Gub { +} + +public class LookupInterfaceDesc { + public static void main(String[] args) throws Exception { + ObjectStreamClass desc = ObjectStreamClass.lookup(Foo.class); + if ((desc.getSerialVersionUID() != Foo.serialVersionUID) || + (desc.getFields().length != 0)) + { + throw new Error(); + } + + desc = ObjectStreamClass.lookup(Bar.class); + if ((desc.getSerialVersionUID() != Bar.serialVersionUID) || + (desc.getFields().length != 0)) + { + throw new Error(); + } + + if (ObjectStreamClass.lookup(Gub.class) != null) { + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/maskSyntheticModifier/Foo.class b/test/java/io/Serializable/maskSyntheticModifier/Foo.class Binary files differnew file mode 100644 index 0000000000..1777af8b13 --- /dev/null +++ b/test/java/io/Serializable/maskSyntheticModifier/Foo.class diff --git a/test/java/io/Serializable/maskSyntheticModifier/Foo.java b/test/java/io/Serializable/maskSyntheticModifier/Foo.java new file mode 100644 index 0000000000..51265f2ec5 --- /dev/null +++ b/test/java/io/Serializable/maskSyntheticModifier/Foo.java @@ -0,0 +1,41 @@ +/* + * 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. + */ + +/* + * @bug 4897937 + * @summary Verify that the presence of the JVM_ACC_SYNTHETIC bit in the + * modifiers of fields and methods does not affect default + * serialVersionUID calculation. + */ + +/* + * This file is compiled with JDK 1.4.2 in order to obtain the Foo.class + * "golden file" used in the test, which contains a synthetic field and method + * for implementing the class literal reference. This file is not itself used + * directly by the test, but is kept here for reference. + */ +public class Foo implements java.io.Serializable { + Foo() { + Class cl = Integer.class; + } +} diff --git a/test/java/io/Serializable/maskSyntheticModifier/Test.java b/test/java/io/Serializable/maskSyntheticModifier/Test.java new file mode 100644 index 0000000000..59362cf78d --- /dev/null +++ b/test/java/io/Serializable/maskSyntheticModifier/Test.java @@ -0,0 +1,40 @@ +/* + * 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. + */ + +/* + * @bug 4897937 + * @summary Verify that the presence of the JVM_ACC_SYNTHETIC bit in the + * modifiers of fields and methods does not affect default + * serialVersionUID calculation. + */ + +import java.io.ObjectStreamClass; + +public class Test { + public static void main(String[] args) { + long suid = ObjectStreamClass.lookup(Foo.class).getSerialVersionUID(); + if (suid != 8027844768744011556L) { + throw new Error("incorrect serialVersionUID: " + suid); + } + } +} diff --git a/test/java/io/Serializable/maskSyntheticModifier/run.sh b/test/java/io/Serializable/maskSyntheticModifier/run.sh new file mode 100644 index 0000000000..36ca440132 --- /dev/null +++ b/test/java/io/Serializable/maskSyntheticModifier/run.sh @@ -0,0 +1,45 @@ +# +# 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 4897937 +# @summary Verify that the presence of the JVM_ACC_SYNTHETIC bit in the +# modifiers of fields and methods does not affect default +# serialVersionUID calculation. + +if [ "${TESTJAVA}" = "" ] +then + echo "TESTJAVA not set. Test cannot execute. Failed." +exit 1 +fi + +if [ "${TESTSRC}" = "" ] +then + TESTSRC="." +fi + +set -ex +cp ${TESTSRC}/Foo.class . +${TESTJAVA}/bin/javac -d . ${TESTSRC}/Test.java +${TESTJAVA}/bin/java Test +rm -f *.class diff --git a/test/java/io/Serializable/misplacedArrayClassDesc/MisplacedArrayClassDesc.java b/test/java/io/Serializable/misplacedArrayClassDesc/MisplacedArrayClassDesc.java new file mode 100644 index 0000000000..332954308d --- /dev/null +++ b/test/java/io/Serializable/misplacedArrayClassDesc/MisplacedArrayClassDesc.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 6313687 + * @summary Verify that if the class descriptor for an ordinary object is the + * descriptor for an array class, an ObjectStreamException is thrown. + * + */ + +import java.io.*; + +class TestArray implements Serializable { + // size of array + private static final int ARR_SIZE = 5; + // serializable field + private String[] strArr = new String[ARR_SIZE]; + + public TestArray() { + for (int i = 0; i < ARR_SIZE; i++) { + strArr[i] = "test" + i; + } + } +} + +public class MisplacedArrayClassDesc { + public static final void main(String[] args) throws Exception { + System.err.println("\nRegression test for CR6313687"); + TestArray object = new TestArray(); + try { + // Serialize to a byte array + ByteArrayOutputStream bos = new ByteArrayOutputStream() ; + ObjectOutputStream out = new ObjectOutputStream(bos) ; + out.writeObject(object); + out.close(); + + // Get the bytes of the serialized object + byte[] buf = bos.toByteArray(); + for (int i = 0; i < buf.length; i++) { + if (buf[i] == ObjectOutputStream.TC_ARRAY) { + buf[i] = ObjectOutputStream.TC_OBJECT; + break; + } + } + + // Deserialize from a byte array + ByteArrayInputStream bais = new ByteArrayInputStream(buf); + ObjectInputStream in = new ObjectInputStream(bais); + TestArray ta = (TestArray) in.readObject(); + in.close(); + } catch (InstantiationError e) { + throw new Error(); + } catch (InvalidClassException e) { + System.err.println("\nTest passed"); + return; + } + throw new Error(); + } +} diff --git a/test/java/io/Serializable/modifyStaticFields/ModifyStaticFields.java b/test/java/io/Serializable/modifyStaticFields/ModifyStaticFields.java new file mode 100644 index 0000000000..b685d89254 --- /dev/null +++ b/test/java/io/Serializable/modifyStaticFields/ModifyStaticFields.java @@ -0,0 +1,58 @@ +/* + * Copyright 2000 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 4334623 + * @summary Verify that serialPersistentFields cannot be used to cause + * deserialization to set the value of a static field. + */ + +import java.io.*; + +public class ModifyStaticFields implements Serializable { + private static final ObjectStreamField[] serialPersistentFields = + new ObjectStreamField[] { new ObjectStreamField("str", String.class) }; + + static String str = "foo"; + + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(new ModifyStaticFields()); + oout.close(); + + String origStr = str; + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + oin.readObject(); + if (str != origStr) { + throw new Error("deserialization modified static field"); + } + } + + private void writeObject(ObjectOutputStream out) throws IOException { + ObjectOutputStream.PutField pf = out.putFields(); + pf.put("str", "bar"); + out.writeFields(); + } +} diff --git a/test/java/io/Serializable/nestedReplace/NestedReplace.java b/test/java/io/Serializable/nestedReplace/NestedReplace.java new file mode 100644 index 0000000000..bab866f99e --- /dev/null +++ b/test/java/io/Serializable/nestedReplace/NestedReplace.java @@ -0,0 +1,90 @@ +/* + * Copyright 1999 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 4217737 + * @clean NestedReplace A B C D + * @build NestedReplace + * @run main NestedReplace + * @summary Ensure that replacement objects can nominate their own replacements, + * so long as the replacement is not the same class as the + * just-replaced object. + * + */ + +import java.io.*; + +class A implements Serializable { + Object writeReplace() throws ObjectStreamException { + return new B(); + } +} + +class B implements Serializable { + Object writeReplace() throws ObjectStreamException { + return new C(); + } +} + +class C implements Serializable { + + static int writeReplaceCalled = 0; + + Object writeReplace() throws ObjectStreamException { + writeReplaceCalled++; + return new C(); + } + + Object readResolve() throws ObjectStreamException { + return new D(); + } +} + +class D implements Serializable { + Object readResolve() throws ObjectStreamException { + throw new Error("readResolve() called more than once"); + } +} + +public class NestedReplace { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout; + ObjectOutputStream oout; + ByteArrayInputStream bin; + ObjectInputStream oin; + Object obj; + + bout = new ByteArrayOutputStream(); + oout = new ObjectOutputStream(bout); + oout.writeObject(new A()); + oout.flush(); + bin = new ByteArrayInputStream(bout.toByteArray()); + oin = new ObjectInputStream(bin); + obj = oin.readObject(); + + if (! (obj instanceof D)) + throw new Error("Deserialized object is of wrong class"); + if (C.writeReplaceCalled != 1) + throw new Error("C.writeReplace() should only get called once"); + } +} diff --git a/test/java/io/Serializable/noSuchFieldClarification/NoSuchFieldClarification.java b/test/java/io/Serializable/noSuchFieldClarification/NoSuchFieldClarification.java new file mode 100644 index 0000000000..39ba9e465c --- /dev/null +++ b/test/java/io/Serializable/noSuchFieldClarification/NoSuchFieldClarification.java @@ -0,0 +1,112 @@ +/* + * 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 6323008 + * @summary this test verifies that exception from GetField.get method + * will be a more comprehensible + * + * @author Andrey Ozerov + * + */ + + import java.io.*; + + class TwoDPoint implements Serializable { + + private double radius; + private double angle; + + private static final ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("x", double.class), + new ObjectStreamField("y", double.class), + }; + + public TwoDPoint(double x, double y) { + this.radius = Math.sqrt(x*x+y*y); + this.angle = Math.atan2(y, x); + } + + public double getX() { + return radius * Math.cos(angle); + } + + public double getY() { + return radius * Math.sin(angle); + } + + public String toString() { + return "[TwoDPoint:x=" + this.getX() + ", y=" + this.getY() +"]"; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + ObjectOutputStream.PutField fields = out.putFields(); + fields.put("x", radius * Math.cos(angle)); + fields.put("y", radius * Math.sin(angle)); + out.writeFields(); + } + + private void readObject(ObjectInputStream in) + throws ClassNotFoundException, IOException + { + ObjectInputStream.GetField fields = in.readFields(); + double x = fields.get("x", 0); + double y = fields.get("y", 0.0); + + radius = Math.sqrt(x*x + y*y); + angle = Math.atan2(y, x); + } + + } + + public class NoSuchFieldClarification { + private static final String SUBSTRING1 = "x"; + private static final String SUBSTRING2 = int.class.toString(); + + public static void main(String[] args) throws IOException, + ClassNotFoundException + { + TwoDPoint point = new TwoDPoint(7, 67); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(point); + oout.close(); + byte[] ser = bout.toByteArray(); + ByteArrayInputStream bin = new ByteArrayInputStream(ser); + ObjectInputStream oin = new ObjectInputStream(bin); + try { + point = (TwoDPoint) oin.readObject(); + throw new Error(); + } catch(IllegalArgumentException exc) { + String msg = exc.getMessage(); + System.err.println("\nOriginal message : " + msg); + if (msg.trim().toLowerCase().lastIndexOf(SUBSTRING1) > 0 && + msg.trim().toLowerCase().lastIndexOf(SUBSTRING2) > 0) + { + System.err.println("\nTEST PASSED"); + } else { + throw new Error(); + } + } + } + } diff --git a/test/java/io/Serializable/nonserializable/ExceptionDetail.java b/test/java/io/Serializable/nonserializable/ExceptionDetail.java new file mode 100644 index 0000000000..92e9827460 --- /dev/null +++ b/test/java/io/Serializable/nonserializable/ExceptionDetail.java @@ -0,0 +1,59 @@ +/* + * 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 4403192 + * @summary Verify that serialization includes the offending class name in the + * message string of a NotSerializableException. + */ + +import java.io.*; + +public class ExceptionDetail { + public static void main(String[] args) throws Exception { + String className = ExceptionDetail.class.getName(); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + try { + oout.writeObject(new ExceptionDetail()); + throw new Error(); + } catch (NotSerializableException ex) { + if (ex.getMessage().indexOf(className) == -1) { + throw new Error(); + } + } + oout.close(); + + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + try { + oin.readObject(); + throw new Error(); + } catch (WriteAbortedException ex) { + if (ex.detail.getMessage().indexOf(className) == -1) { + throw new Error(); + } + } + oin.close(); + } +} diff --git a/test/java/io/Serializable/notAvailable/NotAvailable.java b/test/java/io/Serializable/notAvailable/NotAvailable.java new file mode 100644 index 0000000000..aa6006d8bf --- /dev/null +++ b/test/java/io/Serializable/notAvailable/NotAvailable.java @@ -0,0 +1,85 @@ +/* + * Copyright 1998 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 4085756 + * @summary Ensure readObject() works when InputStream.available() is not implemented. + * In JDK 1.1.x, Win32 System Console available() thows IOException + * to denote that it is not implemented. + */ + +import java.io.*; + +public class NotAvailable { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream baos; + ObjectOutput out; + try { + // Write class out + baos = new ByteArrayOutputStream(); + out = new ObjectOutputStream(baos); + out.writeObject(new Class1(22,33)); + out.writeObject(new Class1(22,33)); + out.flush(); + } catch (IOException e) { + e.printStackTrace(); + throw e; + } + + ObjectInputStream in = null; + try { + // Read it back + ByteArrayInputStream bois = + new ByteArrayInputStream(baos.toByteArray()) { + /* simulate available() not being implemented. */ + public int available() { + throw new Error("available() is not implemented"); + } + }; + in = new ObjectInputStream(bois); + Class1 cc1 = (Class1) in.readObject(); + Class1 cc2 = (Class1) in.readObject(); + } catch (IOException e) { + e.printStackTrace(); + throw e; + } catch (ClassNotFoundException e) { + e.printStackTrace(); + throw e; + } finally { + if (in != null) + in.close(); + if (out != null) + out.close(); + } + } +} + +class Class1 implements Serializable { + int a, b; + + public Class1(int aa, int bb) { + a = aa; + b = bb; + } +} diff --git a/test/java/io/Serializable/nullArgExceptionOrder/Test.java b/test/java/io/Serializable/nullArgExceptionOrder/Test.java new file mode 100644 index 0000000000..47daa6d45d --- /dev/null +++ b/test/java/io/Serializable/nullArgExceptionOrder/Test.java @@ -0,0 +1,77 @@ +/* + * 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 4771562 + * @summary Verify that if ObjectInputStream.read(byte[], int, int) is called + * with a null byte array and invalid offset/length values, a + * NullPointerException is thrown rather than an + * IndexOutOfBoundsException. + */ + +import java.io.*; + +public class Test { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + byte[] b = new byte[10]; + int[][] badBounds = + { { -1, -1}, { -1, 5 }, { 5, -1 }, { 100, 5 }, { 5, 100 } }; + + for (int i = 0; i < badBounds.length; i++) { + try { + oout.write(null, badBounds[i][0], badBounds[i][1]); + throw new Error(); + } catch (NullPointerException e) { + } + } + for (int i = 0; i < badBounds.length; i++) { + try { + oout.write(b, badBounds[i][0], badBounds[i][1]); + throw new Error(); + } catch (IndexOutOfBoundsException e) { + } + } + oout.write(b); + oout.flush(); + + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + for (int i = 0; i < badBounds.length; i++) { + try { + oin.read(null, badBounds[i][0], badBounds[i][1]); + throw new Error(); + } catch (NullPointerException e) { + } + } + for (int i = 0; i < badBounds.length; i++) { + try { + oin.read(b, badBounds[i][0], badBounds[i][1]); + throw new Error(); + } catch (IndexOutOfBoundsException e) { + } + } + oin.read(b); + } +} diff --git a/test/java/io/Serializable/oldTests/AnnotateClass.java b/test/java/io/Serializable/oldTests/AnnotateClass.java new file mode 100644 index 0000000000..032deef8a9 --- /dev/null +++ b/test/java/io/Serializable/oldTests/AnnotateClass.java @@ -0,0 +1,184 @@ +/* + * 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 + * @summary it is new version of old test which was + * /src/share/test/serialization/subtest.java + * This test verifies of invocation + * annotateClass/replaceObject methods + */ + +import java.io.*; + +public class AnnotateClass { + public static void main (String argv[]) { + System.err.println("\nRegression test for verification " + + "of invocation annotateClass/replaceObject " + + "methods \n"); + try { + FileOutputStream ostream = new FileOutputStream("subtest1.tmp"); + TestOutputStream p = new TestOutputStream(ostream); + + p.writeObject(System.out); + p.writeObject(System.err); + p.writeObject(new PrintStream(ostream)); + p.flush(); + ostream.close(); + + FileInputStream istream = new FileInputStream("subtest1.tmp"); + TestInputStream q = new TestInputStream(istream); + + PrintStream out = (PrintStream)q.readObject(); + PrintStream err = (PrintStream)q.readObject(); + Object other = q.readObject(); + if (out != System.out) { + System.err.println( + "\nTEST FAILED: System.out not read correctly"); + throw new Error(); + } + if (err != System.err) { + System.err.println( + "\nTEST FAILED: System.err not read correctly"); + throw new Error(); + } + if (other != null) { + System.err.println( + "\nTEST FAILED: Non-system PrintStream should have " + + "been written/read as null"); + throw new Error(); + } + System.err.println("\nTEST PASSED"); + } catch (Exception e) { + System.err.print("TEST FAILED: "); + e.printStackTrace(); + throw new Error(); + } + } +} + + + +/** ObjectOutputStream is extended to test the annotateClass() + * and replaceObject() subclassable methods. + * In annotateClass a magic string is written to the stream + * so that it can be verified in ObjectInputStream. + * replaceObject is used to subsititute a handle object for + * one of the standard PrintStreams (stdout or stderr). + */ +class TestOutputStream extends ObjectOutputStream { + /* Construct a new test stream */ + TestOutputStream(OutputStream out) throws IOException { + super(out); + enableReplaceObject(true); + } + + /* When any class is written, add a "magic" string + * that must be verified by the TestInputStream. + */ + protected void annotateClass(Class cl) throws IOException { + this.writeUTF("magic"); + } + + /* For each object of type PrintStream, substitute + * a StdStream handle object that encodes which + * of the standard print streams is being written. + * Other objects are written as themselves. + */ + protected Object replaceObject(Object obj) + throws IOException + { + /* For PrintStreams, like stdout and stderr, encode */ + if (obj instanceof PrintStream) { + return new StdStream((PrintStream)obj); + } + return obj; + } +} + +/** Reverse the effects of TestOutputStream. + */ +class TestInputStream extends ObjectInputStream { + + TestInputStream(InputStream in) throws IOException { + super(in); + enableResolveObject(true); + } + + /** Verify that the magic string was written to the stream + * Also use the default classname->class resolution. + */ + protected Class<?> resolveClass(ObjectStreamClass classdesc) + throws ClassNotFoundException, IOException + { + try { + String s = readUTF(); + if (!(s.equals("magic"))) { + System.err.println( + "\nTEST FAILED: Bad magic number"); + throw new Error(); + } + } catch (IOException ee) { + System.err.println( + "\nTEST FAILED: I/O Exception"); + throw new Error(); + } + return super.resolveClass(classdesc); + } + + /** If the object in the stream is a StdStream, + * get the mapping of it to the local System printstream and + * return it. + * Other objects are returned as themselves. + */ + protected Object resolveObject(Object obj) { + if (obj instanceof StdStream) { + return ((StdStream)obj).getStream(); + } + return obj; + } +} + +/* A holder class to map between standard print streams (stdout, stderr) + * and a small integer. + */ +class StdStream implements java.io.Serializable { + private int stream = 0; + + public StdStream(PrintStream s) { + if (s == System.out) { + stream = 1; + } else if (s == System.err) { + stream = 2; + } + } + + public PrintStream getStream() { + if (stream == 1) { + return System.out; + } else if (stream == 2) { + return System.err; + } else { + return null; + } + } +} diff --git a/test/java/io/Serializable/oldTests/ArrayFields.java b/test/java/io/Serializable/oldTests/ArrayFields.java new file mode 100644 index 0000000000..343d152573 --- /dev/null +++ b/test/java/io/Serializable/oldTests/ArrayFields.java @@ -0,0 +1,78 @@ +/* + * Copyright 2005-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 + * @summary it is a new version of an old test which was + * /src/share/test/serialization/piotest.java + * Test of serialization/deserialization + * of objects with fields of array type + * + * @build ArrayTest PrimitivesTest ArrayOpsTest + * @run main ArrayFields + */ + +import java.io.*; + +public class ArrayFields { + + public static void main (String argv[]) { + System.err.println("\nRegression test for testing of " + + "serialization/deserialization of objects with " + + "fields of array type\n"); + + try { + FileOutputStream ostream = new FileOutputStream("piotest4.tmp"); + ObjectOutputStream p = new ObjectOutputStream(ostream); + + ArrayTest array = new ArrayTest(); + p.writeObject(array); + p.flush(); + + FileInputStream istream = new FileInputStream("piotest4.tmp"); + ObjectInputStream q = new ObjectInputStream(istream); + + Object obj = null; + try { + obj = q.readObject(); + } catch (ClassCastException ee) { + System.err.println("\nTEST FAILED: An Exception occurred " + + ee.getMessage()); + System.err.println("\nBoolean array read as byte array" + + " could not be assigned to field z"); + throw new Error(); + } + + ArrayTest array_u = (ArrayTest)obj; + if (!array.equals(array_u)) { + System.out.println("\nTEST FAILED: Unpickling of objects " + + "with ArrayTest failed"); + throw new Error(); + } + System.err.println("\nTEST PASSED"); + } catch (Exception e) { + System.err.print("TEST FAILED: "); + e.printStackTrace(); + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/oldTests/ArrayOpsTest.java b/test/java/io/Serializable/oldTests/ArrayOpsTest.java new file mode 100644 index 0000000000..1aad2e7eba --- /dev/null +++ b/test/java/io/Serializable/oldTests/ArrayOpsTest.java @@ -0,0 +1,218 @@ +/* + * 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. + */ + +public class ArrayOpsTest { + public static boolean verify(int a[], int b[]) { + boolean result = true; + + if (a.length != b.length) { + System.err.println("\nInt array lengths differ: " + + a.length + " != " + b.length); + result = false; + } + + for (int i = 0; i < a.length; i++) { + if (a[i] != b[i]) { + System.err.println("\nInt array contents differ " + + "at index " + i + ": " + a[i] + " != " + b[i]); + result = false; + } + } + return result; + } + + public static boolean verify(byte a[], byte b[]) { + boolean result = true; + + if (a.length != b.length) { + System.err.println("\nByte array lengths differ: " + + a.length + " != " + b.length); + result = false; + } + + for (int i = 0; i < a.length; i++) { + if (a[i] != b[i]) { + System.err.println("\nByte array contents differ at index " + + i + ": " + a[i] + " != " + b[i]); + result = false; + } + } + return result; + } + + public static boolean verify(char a[], char b[]) { + boolean result = true; + + if (a.length != b.length) { + System.err.println("\nChar array lengths differ: " + + a.length + " != " + b.length); + result = false; + } + + for (int i = 0; i < a.length; i++) { + if (a[i] != b[i]) { + System.err.println("\nChar array contents differ at index " + + i + ": " + a[i] + " != " + b[i]); + result = false; + } + } + return result; + } + + public static boolean verify(short a[], short b[]) { + boolean result = true; + + if (a.length != b.length) { + System.err.println("\nShort array lengths differ: " + + a.length + " != " + b.length); + result = false; + } + + for (int i = 0; i < a.length; i++) { + if (a[i] != b[i]) { + System.err.println("\nShort array contents differ at index " + + i + ": " + a[i] + " != " + b[i]); + result = false; + } + } + return result; + } + + public static boolean verify(boolean a[], boolean b[]) { + boolean result = true; + + if (a.length != b.length) { + System.err.println("\nBoolean array lengths differ: " + + a.length + " != " + b.length); + result = false; + } + + for (int i = 0; i < a.length; i++) { + if (a[i] != b[i]) { + System.err.println("\nBoolean array contents differ at index " + + i + ": " + a[i] + " != " + b[i]); + result = false; + } + } + return result; + } + + public static boolean verify(float a[], float b[]) { + boolean result = true; + + if (a.length != b.length) { + System.err.println("\nFloat array lengths differ: " + + a.length + " != " + b.length); + result = false; + } + + for (int i = 0; i < a.length; i++) { + if (a[i] != b[i]) { + System.err.println("\nFloat array contents differ at index " + + i + ": " + a[i] + " != " + b[i]); + result = false; + } + } + return result; + } + + public static boolean verify(double a[], double b[]) { + boolean result = true; + + if (a.length != b.length) { + System.err.println("\nDouble array lengths differ: " + + a.length + " != " + b.length); + result = false; + } + + for (int i = 0; i < a.length; i++) { + if (a[i] != b[i]) { + System.err.println("\nDouble array contents differ at index " + + i + ": " + a[i] + " != " + b[i]); + result = false; + } + } + return result; + } + + public static boolean verify(long a[], long b[]) { + boolean result = true; + + if (a.length != b.length) { + System.err.println("\nLong array lengths differ: " + + a.length + " != " + b.length); + result = false; + } + + for (int i = 0; i < a.length; i++) { + if (a[i] != b[i]) { + System.err.println("\nLong array contents differ at index " + + i + ": " + a[i] + " != " + b[i]); + result = false; + } + } + return result; + } + + public static boolean verify(String a[], String b[]) { + boolean result = true; + + if (a.length != b.length) { + System.err.println("\nString array lengths differ: " + + a.length + " != " + b.length); + result = false; + } + + for (int i = 0; i < a.length; i++) { + if (!a[i].equals(b[i])) { + System.err.println("\nString array contents differ at index " + + i + ": " + a[i] + " != " + b[i]); + result = false; + } + } + return result; + } + + public static boolean verify(PrimitivesTest a[], PrimitivesTest b[]) { + boolean result = true; + + if (a.length != b.length) { + System.err.println("\nPrimitivesTest array lengths differ: " + + a.length + " != " + b.length); + result = false; + } + + for (int i = 0; i < a.length; i++) { + if (a[i] == null && b[i] == null) { + continue; + } + + if (!a[i].equals(b[i])) { + System.err.println("\nPrimitivesTest array contents differ at " + + "index " + i + ": " + a[i] + " != " + b[i]); + result = false; + } + } + return result; + } +} diff --git a/test/java/io/Serializable/oldTests/ArrayTest.java b/test/java/io/Serializable/oldTests/ArrayTest.java new file mode 100644 index 0000000000..587de36f35 --- /dev/null +++ b/test/java/io/Serializable/oldTests/ArrayTest.java @@ -0,0 +1,96 @@ +/* + * 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. + */ + +public class ArrayTest implements java.io.Serializable { + byte b[] = { 0, 1}; + short s[] = { 0, 1, 2}; + char c[] = { 'Z', 'Y', 'X'}; + int i[] = { 0, 1, 2, 3, 4}; + long l[] = { 0, 1, 2, 3, 4, 5}; + boolean z[] = new boolean[4]; + float f[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}; + double d[] = { 1.0d, 2.0d, 3.0d, 4.0d, 5.0d, 6.0d, 7.0d}; + String string[] = { "ABC", "DEF", "GHI", "JKL"}; + PrimitivesTest prim[] = { new PrimitivesTest(), new PrimitivesTest() } ; + + transient int ti[] = {99, 98, 97, 96}; + ArrayTest self = this; + + static int si[] = {9, 8, 7, 6, 4} ; + + public ArrayTest() { + z[0] = true; + z[1] = false; + z[2] = true; + z[3] = false; + } + + public boolean equals(ArrayTest other) { + boolean ret = true; + if (other == null) { + System.err.println("\nother Array is " + other); + return false; + } + if (!ArrayOpsTest.verify(i, other.i)) { + System.err.println("\nUnpickling of int array failed"); + ret = false; + } + if (!ArrayOpsTest.verify(b, other.b)) { + System.err.println("\nUnpickling of byte array failed"); + ret = false; + } + if (!ArrayOpsTest.verify(s, other.s)) { + System.err.println("\nUnpickling of short array failed"); + ret = false; + } + if (!ArrayOpsTest.verify(c, other.c)) { + System.err.println("\nUnpickling of char array failed"); + ret = false; + } + if (!ArrayOpsTest.verify(l, other.l)) { + System.err.println("\nUnpickling of long array failed"); + ret = false; + } + if (!ArrayOpsTest.verify(f, other.f)) { + System.err.println("\nUnpickling of float array failed"); + ret = false; + } + if (!ArrayOpsTest.verify(d, other.d)) { + System.err.println("\nUnpickling of double array failed"); + ret = false; + } + if (!ArrayOpsTest.verify(z, other.z)) { + System.err.println("\nUnpickling of boolean array failed"); + ret = false; + } + if (!ArrayOpsTest.verify(string, other.string)) { + System.err.println("\nUnpickling of String array failed"); + ret = false; + } + if (!ArrayOpsTest.verify(prim, other.prim)) { + System.err.println("\nUnpickling of Primitives array failed"); + ret = false; + } + return ret; + } +} diff --git a/test/java/io/Serializable/oldTests/ArraysOfArrays.java b/test/java/io/Serializable/oldTests/ArraysOfArrays.java new file mode 100644 index 0000000000..796e6fe568 --- /dev/null +++ b/test/java/io/Serializable/oldTests/ArraysOfArrays.java @@ -0,0 +1,212 @@ +/* + * 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 + * @summary it is new version of old test which was under + * /src/share/test/serialization/piotest.java + * Test of serialization/deserialization of + * objects as arrays of arrays + */ + +import java.io.*; + +public class ArraysOfArrays { + public static void main (String argv[]) { + System.err.println("\nRegression test for testing of " + + "serialization/deserialization of objects as " + + "arrays of arrays \n"); + + FileInputStream istream = null; + try { + FileOutputStream ostream = new FileOutputStream("piotest5.tmp"); + ObjectOutputStream p = new ObjectOutputStream(ostream); + + byte b[][] = {{ 0, 1}, {2,3}}; + p.writeObject((Object)b); + + short s[][] = {{ 0, 1, 2}, {3,4,5}}; + p.writeObject((Object)s); + + char c[][] = {{ 0, 1, 2, 3}, {4, 5, 6, 7}}; + p.writeObject((Object)c); + + int i[][] = {{ 0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}}; + p.writeObject((Object)i); + + long l[][] = {{ 0, 1, 2, 3, 4, 5}, {6,7,8,9,10,11}}; + p.writeObject((Object)l); + + boolean z[][] = new boolean[2][2]; + + z[0][0] = true; + z[0][1] = false; + z[1] = z[0]; // Use first row same as second + + p.writeObject((Object)z); + + float f[][] = {{ 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}, + { 1.1f, 2.1f, 3.1f, 4.1f, 5.1f, 6.1f}}; + p.writeObject((Object)f); + + double d[][] = {{ 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0d}, + { 1.1f, 2.1f, 3.1f, 4.1f, 5.1f, 6.1f, 7.1d}}; + p.writeObject((Object)d); + + Integer Int[][] = {{ new Integer(3), new Integer(2)}, + { new Integer(1), new Integer(0)}}; + p.writeObject((Object)Int); + + p.flush(); + + /* Now read them back and verify + */ + istream = new FileInputStream("piotest5.tmp"); + ObjectInputStream q = new ObjectInputStream(istream); + + byte b_u[][] = (byte [][]) (q.readObject()); + for (int ix = 0; ix < b_u.length; ix++) { + for(int iy = 0; iy < b_u[ix].length; iy++) { + if (b[ix][iy] != b_u[ix][iy]) { + System.err.println("\nByte array mismatch [" + + ix + "][" + iy + " expected " + b[ix][iy] + + " actual = " + b_u[ix][iy]); + throw new Error(); + } + } + } + + + short s_u[][] = (short [][])(q.readObject()); + for (int ix = 0; ix < b_u.length; ix++) { + for(int iy = 0; iy < b_u[ix].length; iy++) { + if (b[ix][iy] != b_u[ix][iy]) { + System.err.println("\nshort array mismatch [" + + ix + "][" + iy + " expected " + b[ix][iy] + + " actual = " + b_u[ix][iy]); + throw new Error(); + } + } + } + + char c_u[][] = (char [][])(q.readObject()); + for (int ix = 0; ix < b_u.length; ix++) { + for(int iy = 0; iy < b_u[ix].length; iy++) { + if (b[ix][iy] != b_u[ix][iy]) { + System.err.println("\nchar array mismatch [" + + ix + "][" + iy + " expected " + b[ix][iy] + + " actual = " + b_u[ix][iy]); + throw new Error(); + } + } + } + + int i_u[][] = (int [][])(q.readObject()); + for (int ix = 0; ix < b_u.length; ix++) { + for(int iy = 0; iy < b_u[ix].length; iy++) { + if (b[ix][iy] != b_u[ix][iy]) { + System.err.println("\nint array mismatch [" + + ix + "][" + iy + " expected " + b[ix][iy] + + " actual = " + b_u[ix][iy]); + throw new Error(); + } + } + } + + long l_u[][] = (long [][])(q.readObject()); + for (int ix = 0; ix < b_u.length; ix++) { + for(int iy = 0; iy < b_u[ix].length; iy++) { + if (b[ix][iy] != b_u[ix][iy]) { + System.err.println("\nlong array mismatch [" + + ix + "][" + iy + " expected " + b[ix][iy] + + " actual = " + b_u[ix][iy]); + throw new Error(); + } + } + } + + boolean z_u[][] = (boolean [][])(q.readObject()); + for (int ix = 0; ix < b_u.length; ix++) { + for(int iy = 0; iy < b_u[ix].length; iy++) { + if (b[ix][iy] != b_u[ix][iy]) { + System.err.println("\nboolean array mismatch [" + + ix + "][" + iy + " expected " + b[ix][iy] + + " actual = " + b_u[ix][iy]); + throw new Error(); + } + } + } + + float f_u[][] = (float [][])(q.readObject()); + for (int ix = 0; ix < b_u.length; ix++) { + for(int iy = 0; iy < b_u[ix].length; iy++) { + if (b[ix][iy] != b_u[ix][iy]) { + System.err.println("\nfloat array mismatch [" + + ix + "][" + iy + " expected " + b[ix][iy] + + " actual = " + b_u[ix][iy]); + throw new Error(); + } + } + } + + double d_u[][] = (double [][])(q.readObject()); + for (int ix = 0; ix < b_u.length; ix++) { + for(int iy = 0; iy < b_u[ix].length; iy++) { + if (b[ix][iy] != b_u[ix][iy]) { + System.err.println("\ndouble array mismatch [" + + ix + "][" + iy + " expected " + b[ix][iy] + + " actual = " + b_u[ix][iy]); + throw new Error(); + } + } + } + + Integer Int_u[][] = (Integer [][])(q.readObject()); + for (int ix = 0; ix < b_u.length; ix++) { + for(int iy = 0; iy < b_u[ix].length; iy++) { + if (b[ix][iy] != b_u[ix][iy]) { + System.err.println("\nInteger array mismatch [" + + ix + "][" + iy + " expected " + b[ix][iy] + + " actual = " + b_u[ix][iy]); + throw new Error(); + } + } + } + System.err.println("\nTEST PASSED"); + } catch (Exception e) { + System.err.print("TEST FAILED: "); + e.printStackTrace(); + + System.err.println("\nInput remaining"); + int ch; + try { + while ((ch = istream.read()) != -1) { + System.err.print("\n " +Integer.toString(ch, 16) + " "); + } + System.err.println("\n "); + } catch (Exception f) { + throw new Error(); + } + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/oldTests/BinaryTree.java b/test/java/io/Serializable/oldTests/BinaryTree.java new file mode 100644 index 0000000000..661e6eb9b8 --- /dev/null +++ b/test/java/io/Serializable/oldTests/BinaryTree.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 + * @summary it is new version of old test which was + * /src/share/test/serialization/piotest.java + * Test of serialization/deserialization of + * objects with BinaryTree types + */ + +import java.io.*; + +public class BinaryTree { + public static void main (String argv[]) { + System.err.println("\nRegression test for testing of " + + "serialization/deserialization of objects " + + "with BinaryTree types \n"); + + try { + FileOutputStream ostream = new FileOutputStream("piotest3.tmp"); + ObjectOutputStream p = new ObjectOutputStream(ostream); + + BinaryTreeTest base = new BinaryTreeTest(2); + p.writeObject(null); + p.writeObject(base); + p.flush(); + ostream.close(); + + FileInputStream istream = new FileInputStream("piotest3.tmp"); + ObjectInputStream q = new ObjectInputStream(istream); + + Object n = q.readObject(); + if (n != null) { + System.err.println("\nnull read as " + n); + } + BinaryTreeTest nbase = (BinaryTreeTest)q.readObject(); + if (!base.equals(nbase)) { + System.err.println("\nTEST FAILED: BinaryTree read " + + "incorrectly."); + throw new Error(); + } + System.err.println("\nTEST PASSED"); + } catch (Exception e) { + System.err.print("TEST FAILED: "); + e.printStackTrace(); + throw new Error(); + } + } +} + +class BinaryTreeTest implements java.io.Serializable { + public BinaryTreeTest left; + public BinaryTreeTest right; + public int id; + public int level; + + private static int count = 0; + + public BinaryTreeTest(int l) { + id = count++; + level = l; + if (l > 0) { + left = new BinaryTreeTest(l-1); + right = new BinaryTreeTest(l-1); + } + } + + public void print(int levels) { + for (int i = 0; i < level; i++) { + System.out.print(" "); + } + System.err.println("node " + id); + + if (level <= levels && left != null) { + left.print(levels); + } + + if (level <= levels && right != null) { + right.print(levels); + } + } + + public boolean equals(BinaryTreeTest other) { + if (other == null) { + return false; + } + + if (id != other.id) { + return false; + } + + if (left != null && !left.equals(other.left)) { + return false; + } + + if (right != null && !right.equals(other.right)) { + return false; + } + + return true; + } +} diff --git a/test/java/io/Serializable/oldTests/CheckForException.java b/test/java/io/Serializable/oldTests/CheckForException.java new file mode 100644 index 0000000000..c11bb5c875 --- /dev/null +++ b/test/java/io/Serializable/oldTests/CheckForException.java @@ -0,0 +1,164 @@ +/* + * 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 + * @summary it is new version of old test which was + * /src/share/test/serialization/psiotest.java + * Test pickling and unpickling an object with derived classes + * and using a read special to serialize the "middle" class, + * which raises NotSerializableException inside writeObject() + * and readObject() methods. + */ + +import java.io.*; + +public class CheckForException { + public static void main (String argv[]) { + System.err.println("\nRegression test of " + + "serialization/deserialization of " + + "complex objects which raise " + + "NotSerializableException inside " + + "writeObject() and readObject() methods.\n"); + + + FileInputStream istream = null; + try { + + FileOutputStream ostream = new FileOutputStream("psiotest3.tmp"); + ObjectOutputStream p = new ObjectOutputStream(ostream); + + /* Catch the expected exception and + * complain if it does not occur. + */ + TryPickleClass npc = new TryPickleClass(); + + NotSerializableException we = null; + try { + // Two objects of the same class that are used + // in cleanup test below + p.writeObject("test"); + p.writeObject("test2"); + p.writeObject(npc); + } catch (NotSerializableException e) { + we = e; + } + if (we == null) { + System.err.println("\nTEST FAILED: Write of NoPickleClass " + + "should have raised an exception"); + throw new Error(); + } + + p.flush(); + ostream.close(); + + istream = new FileInputStream("psiotest3.tmp"); + ObjectInputStream q = new ObjectInputStream(istream); + + /* Catch the expected exception and + * complain if it does not occur. + */ + TryPickleClass npc_u; + + NotSerializableException re = null; + try { + // Read the two objects, neither has a cleanup method + q.readObject(); + q.readObject(); + npc_u = (TryPickleClass)q.readObject(); + } catch (NotSerializableException e) { + re = e; + } + if (re == null) { + System.err.println("\nTEST FAILED: Read of NoPickleClass " + + "should have raised an exception"); + throw new Error(); + } + + istream.close(); + System.err.println("\nTEST PASSED"); + } catch (Exception e) { + System.err.print("TEST FAILED: "); + e.printStackTrace(); + throw new Error(); + } + } +} + +class PickleClass implements java.io.Serializable { + int ii = 17; + transient int tmp[]; + + private void writeObject(ObjectOutputStream pw) throws IOException { + pw.writeUTF("PickleClass"); + pw.writeInt(ii); + } + + private void readObject(ObjectInputStream pr) throws IOException { + tmp = new int[32]; + pr.readUTF(); + ii = pr.readInt(); + } + + private void readObjectCleanup(ObjectInputStream pr) { + System.err.println("\nPickleClass cleanup correctly called on abort."); + if (tmp != null) { + tmp = null; + } + } + +} + +class NoPickleClass extends PickleClass { + private void writeObject(ObjectOutputStream pw) + throws NotSerializableException + { + throw new NotSerializableException("NoPickleClass"); + } + + private void readObject(ObjectInputStream pr) + throws NotSerializableException + { + throw new NotSerializableException("NoPickleClass"); + } +} + +class TryPickleClass extends NoPickleClass { + int i = 7; + transient int tmp[]; + + private void writeObject(ObjectOutputStream pw) throws IOException { + pw.writeInt(i); + } + + private void readObject(ObjectInputStream pr) throws IOException { + tmp = new int[32]; + i = pr.readInt(); + } + + private void readObjectCleanup(ObjectInputStream pr) { + System.err.println("\nCleanup called on abort"); + if (tmp != null) { + tmp = null; + } + } +} diff --git a/test/java/io/Serializable/oldTests/CheckingEquality.java b/test/java/io/Serializable/oldTests/CheckingEquality.java new file mode 100644 index 0000000000..a05b6b91e5 --- /dev/null +++ b/test/java/io/Serializable/oldTests/CheckingEquality.java @@ -0,0 +1,234 @@ +/* + * 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 + * @summary it is new version of old test which was + * /src/share/test/serialization/psiotest.java + * Test pickling and unpickling an object with derived classes + * and using a read special to serialize the "middle" class. + * + */ + +import java.io.*; + +public class CheckingEquality { + public static void main (String argv[]) { + System.err.println("\nRegression test of " + + "serialization/deserialization of " + + "complex objects\n"); + + FileInputStream istream = null; + try { + + Thirdpsio objout = new Thirdpsio(); + objout.init(); + + FileOutputStream ostream = new FileOutputStream("psiotest1.tmp"); + ObjectOutputStream p = new ObjectOutputStream(ostream); + + p.writeObject(objout); + + p.flush(); + ostream.close(); + + istream = new FileInputStream("psiotest1.tmp"); + ObjectInputStream q = new ObjectInputStream(istream); + + Thirdpsio objin = (Thirdpsio)q.readObject(); + + if (!objout.equals(objin)) { + System.err.println( + "\nTEST FAILED: Original and read objects not equal."); + throw new Error(); + } + istream.close(); + System.err.println("\nTEST PASSED"); + } catch (Exception e) { + System.err.print("TEST FAILED: "); + e.printStackTrace(); + + System.err.println("\nInput remaining"); + int ch; + try { + while ((ch = istream.read()) != -1) { + System.out.print(Integer.toString(ch, 16) + " "); + } + System.err.println("\n"); + } catch (Exception f) { + throw new Error(); + } + throw new Error(); + } + } +} + +class Firstpsio implements java.io.Serializable { + String one; + int two; + float three[]; + + void init() { /* called only before writing */ + one = "one"; + two = 2; + three = new float[5]; + float f = 3.0f; + for (int i=0; i<5 ; i++) { + f += 0.11; + three[i] = f; + } + } + + /* Compare two first objects */ + boolean equals(Firstpsio other) { + boolean ret = true; + + if (!one.equals(other.one)) { + System.err.println("\nfirstpsio: expected " + one + + " actual " + other.one); + ret = false; + } + if (two != other.two) { + System.err.println("\nfirstpsio: expected " + two + + " actual " + other.two); + ret = false; + } + + for (int i = 0; i < three.length; i++ ) { + if (three[i] != other.three[i]) { + System.err.println("\nfirstpsio: three[" + i + "] expected " + + three[i] + " actual " + other.three[i]); + ret = false; + } + } + return ret; + } +} + +class Secondpsio extends Firstpsio { + String quatre; + int cinq; + + private void writeObject(ObjectOutputStream pw) throws IOException { + pw.writeObject(quatre); + pw.writeInt(cinq); + } + + private void readObject(ObjectInputStream pr) + throws StreamCorruptedException, IOException, ClassNotFoundException + { + if (one == null) { + System.err.println( + "\nTEST FAILED: Superclass not serialized when " + + "it should have been"); + throw new StreamCorruptedException("Superclass not serialized " + + "when it should have been"); + } + + quatre = (String)pr.readObject(); + cinq = pr.readInt(); + } + + boolean equals(Secondpsio other) { + boolean ret = super.equals(other); + + if (!quatre.equals(other.quatre)) { + System.err.println("\nsecondpsio: quatre expected " + quatre + + " actual " + other.quatre); + ret = false; + } + if (cinq != other.cinq) { + System.err.println("\nsecondpsio: cinq expected " + cinq + + " actual " + other.cinq); + ret = false; + } + return ret; + } + + /* called only before writing */ + void init() { + quatre = "4444"; + cinq = 5; + super.init(); + } +} + +class Thirdpsio extends Secondpsio { + + static String ign = "ignored"; + transient Object oh; + + int six; + + private static int seven[]; + protected byte eight = (byte)9; + final static byte dcare = (byte) 128; + private short nine = 8888; + long ten; + java.util.Enumeration zero; + + + boolean equals(Thirdpsio other) { + boolean ret = super.equals(other); + + if (six != other.six) { + System.err.println("\nthirdpsio six " + six + + " actual " + other.six); + ret = false; + } + if (eight != other.eight) { + System.err.println("\nthirdpsio eight - expected " + eight + + " actual " + other.eight); + ret = false; + } + if (nine != other.nine) { + System.err.println("\nthirdpsio nine - expected " + nine + + " actual " + other.nine); + ret = false; + } + if (ten != other.ten) { + System.err.println("\nthirdpsio ten - expected " + ten + + " actual " + other.ten); + ret = false; + } + if (zero != other.zero) { + System.err.println("\nthirdpsio zero - expected " + zero + + " actual " + other.zero); + ret = false; + } + return ret; + } + + /* called only before writing */ + void init() { + six = 666; + + int s7[] = { 7, 7, 7 }; + seven = s7; + eight = (byte)8; + nine = (short)9; + ten = (long)100000; + java.util.Enumeration em = null; /* default */ + + super.init(); + } +} diff --git a/test/java/io/Serializable/oldTests/CircularList.java b/test/java/io/Serializable/oldTests/CircularList.java new file mode 100644 index 0000000000..2bc8b3ccdf --- /dev/null +++ b/test/java/io/Serializable/oldTests/CircularList.java @@ -0,0 +1,73 @@ +/* + * 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 + * @summary it is new version of old test which was + * /src/share/test/serialization/piotest.java + * Test of serialization/deserialization of + * objects with CircularListType types + */ + +import java.io.*; + +public class CircularList { + public static void main (String argv[]) { + System.err.println("\nRegression test for testing of " + + "serialization/deserialization of " + + "objects with CirculalListType types \n"); + + try { + FileOutputStream ostream = new FileOutputStream("piotest7.tmp"); + ObjectOutputStream p = new ObjectOutputStream(ostream); + + CircularListTest.setup(); + p.writeObject(CircularListTest.list); + p.flush(); + + FileInputStream istream = new FileInputStream("piotest7.tmp"); + ObjectInputStream q = new ObjectInputStream(istream); + + CircularListTest cv = (CircularListTest)q.readObject(); + if (cv != cv.next) { + System.err.println("\nTEST FAILED: " + + "Circular List Test failed, next != self"); + throw new Error(); + } + System.err.println("\nTEST PASSED"); + } catch (Exception e) { + System.err.print("TEST FAILED: "); + e.printStackTrace(); + throw new Error(); + } + } +} + +class CircularListTest implements java.io.Serializable { + public CircularListTest next = null; + public static CircularListTest list = null; + + public static void setup() { + list = new CircularListTest(); + list.next = list; + } +} diff --git a/test/java/io/Serializable/oldTests/PrimitivesTest.java b/test/java/io/Serializable/oldTests/PrimitivesTest.java new file mode 100644 index 0000000000..c39726e5fd --- /dev/null +++ b/test/java/io/Serializable/oldTests/PrimitivesTest.java @@ -0,0 +1,50 @@ +/* + * 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. + */ + +public class PrimitivesTest implements java.io.Serializable { + byte b = 1; + char c = 'c'; + float f = 3.14159f; + long l = 3; + double d = 1.740; + int i = 4; + boolean z = true; + short s = 2; + transient int trans = 89; + PrimitivesTest self = this; + + public boolean equals(PrimitivesTest other) { + if (b != other.b || + c != other.c || + f != other.f || + l != other.l || + d != other.d || + i != other.i || + s != other.s || + z != other.z ) + { + return false; + } + return true; + } +} diff --git a/test/java/io/Serializable/oldTests/SerializeWithException.java b/test/java/io/Serializable/oldTests/SerializeWithException.java new file mode 100644 index 0000000000..93b93fde38 --- /dev/null +++ b/test/java/io/Serializable/oldTests/SerializeWithException.java @@ -0,0 +1,126 @@ +/* + * Copyright 2005-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 + * @summary it is a new version of an old test which was + * /src/share/test/serialization/piotest.java + * Test of serialization when there is + * exceptions on the I/O stream + * + * @build PrimitivesTest + * @run main SerializeWithException + */ + +import java.io.*; + +public class SerializeWithException { + public static void main (String argv[]) { + System.err.println("\nRegression test for testing of " + + "serialization when there is exceptions on the I/O stream \n"); + + try { + int i = 123456; + byte b = 12; + short s = 45; + char c = 'A'; + long l = 1234567890000L; + float f = 3.14159f; + double d = f*2; + boolean z = true; + String string = "The String"; + PrimitivesTest prim = new PrimitivesTest(); + + /* For each of the byte offsets from 0 to 100, + do the pickling but expect an exception */ + for (int offset = 0; offset < 200; offset++) { + ExceptionOutputStream ostream; + boolean expect_exception = false; + IOException exception = null; + + try { + expect_exception = true; + exception = null; + + ostream = new ExceptionOutputStream(); + ostream.setExceptionOffset(offset); + ObjectOutputStream p = new ObjectOutputStream(ostream); + + p.writeInt(i); + p.writeByte(b); + p.writeShort(s); + p.writeChar(c); + p.writeLong(l); + p.writeFloat(f); + p.writeDouble(d); + p.writeBoolean(z); + p.writeUTF(string); + p.writeObject(string); + + p.writeObject(prim); + p.flush(); + expect_exception = false; + } catch (IOException ee) { + exception = ee; + } + + if (expect_exception && exception == null) { + System.err.println("\nIOException did not occur at " + + "offset " + offset); + throw new Error(); + } + if (!expect_exception && exception != null) { + System.err.println("\n " + exception.toString() + + " not expected at offset " + offset); + throw new Error(); + } + } + System.err.println("\nTEST PASSED"); + } catch (Exception e) { + System.err.print("TEST FAILED: "); + e.printStackTrace(); + throw new Error(); + } + } +} + +class ExceptionOutputStream extends OutputStream { + private int exceptionOffset = 0; + private int currentOffset = 0; + + /** + * Writes a byte to the buffer. + * @param b the byte + */ + public void write(int b) throws IOException { + if (currentOffset >= exceptionOffset) { + throw new IOException("Debug exception"); + } + currentOffset++; + } + + + public void setExceptionOffset(int offset) { + exceptionOffset = offset; + currentOffset = 0; + } +} diff --git a/test/java/io/Serializable/oldTests/SimpleArrays.java b/test/java/io/Serializable/oldTests/SimpleArrays.java new file mode 100644 index 0000000000..52f33285c2 --- /dev/null +++ b/test/java/io/Serializable/oldTests/SimpleArrays.java @@ -0,0 +1,182 @@ +/* + * Copyright 2005-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 + * @summary it is a new version of an old test which was + * /src/share/test/serialization/piotest.java + * Test of serialization/deserialization of + * objects with Arrays types + * + * @build ArrayOpsTest PrimitivesTest + * @run main SimpleArrays + */ + +import java.io.*; + + +public class SimpleArrays { + public static void main (String argv[]) { + System.err.println("\nRegression test for testing of " + + "serialization/deserialization of objects with Arrays types\n"); + + FileInputStream istream = null; + try { + FileOutputStream ostream = new FileOutputStream("piotest2.tmp"); + ObjectOutputStream p = new ObjectOutputStream(ostream); + + byte b[] = { 0, 1}; + p.writeObject((Object)b); + + short s[] = { 0, 1, 2}; + p.writeObject((Object)s); + + char c[] = { 'A', 'B', 'C', 'D'}; + p.writeObject((Object)c); + + int i[] = { 0, 1, 2, 3, 4}; + p.writeObject((Object)i); + + long l[] = { 0, 1, 2, 3, 4, 5}; + p.writeObject((Object)l); + + boolean z[] = new boolean[4]; + z[0] = true; + z[1] = false; + z[2] = true; + z[3] = false; + p.writeObject(z); + + float f[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}; + p.writeObject((Object)f); + + double d[] = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0d}; + p.writeObject((Object)d); + + String string[] = { "A", "B", "C", "D"}; + p.writeObject((Object) string); + + PrimitivesTest prim[] = new PrimitivesTest[5]; + prim[0] = new PrimitivesTest(); + prim[1] = prim[0]; + prim[2] = new PrimitivesTest(); + prim[3] = prim[2]; + prim[4] = null; + p.writeObject((Object)prim); + + p.flush(); + + /* now read them back */ + istream = new FileInputStream("piotest2.tmp"); + ObjectInputStream q = new ObjectInputStream(istream); + + Object obj; + + byte b_u[] = (byte[])q.readObject(); + short s_u[] = (short[])q.readObject(); + char c_u[] = (char[])q.readObject(); + int i_u[] = (int[])q.readObject(); + long l_u[] = (long[])q.readObject(); + + /* This should be boolean, but they were serialized as bytes + */ + boolean z_u[] = null; + Object z_obj = null; + try { + z_obj = q.readObject(); + z_u = (boolean[])z_obj; + } catch (ClassCastException e) { + System.err.println("\nClassCastException " + e.getMessage()); + System.err.println("\nBoolean array read as " + + z_obj.getClass().getName()); + System.err.println("\nAn Exception occurred. " + + e.getMessage()); + z_u = z; + throw new Error(); + } + + float f_u[] = (float[])q.readObject(); + double d_u[] = (double[])q.readObject(); + String string_u[] = (String[])q.readObject(); + + PrimitivesTest prim_u[] = (PrimitivesTest[])q.readObject(); + + if (!ArrayOpsTest.verify(i, i_u)) { + System.err.println("\nUnpickling of int array failed"); + throw new Error(); + } + if (!ArrayOpsTest.verify(b, b_u)) { + System.err.println("\nUnpickling of byte array failed"); + throw new Error(); + } + if (!ArrayOpsTest.verify(s, s_u)) { + System.err.println("\nUnpickling of short array failed"); + throw new Error(); + } + if (!ArrayOpsTest.verify(c, c_u)) { + System.err.println("\nUnpickling of char array failed"); + throw new Error(); + } + if (!ArrayOpsTest.verify(l, l_u)) { + System.err.println("\nUnpickling of long array failed"); + throw new Error(); + } + if (!ArrayOpsTest.verify(f, f_u)) { + System.err.println("\nUnpickling of float array failed"); + throw new Error(); + } + if (!ArrayOpsTest.verify(d, d_u)) { + System.err.println("\nUnpickling of double array failed"); + throw new Error(); + } + if (!ArrayOpsTest.verify(z, z_u)) { + System.err.println("\nUnpickling of boolean array failed"); + throw new Error(); + } + if (!ArrayOpsTest.verify(string, string_u)) { + System.err.println("\nUnpickling of String array failed"); + throw new Error(); + } + if (!ArrayOpsTest.verify(prim, prim_u)) { + System.err.println("\nUnpickling of PrimitivesTest array " + + "failed"); + throw new Error(); + } + System.err.println("\nTEST PASSED"); + } catch (Exception e) { + System.err.print("TEST FAILED: "); + e.printStackTrace(); + + System.err.println("\nInput remaining"); + int ch; + try { + while ((ch = istream.read()) != -1) { + System.err.print("\n " + Integer.toString(ch, 16) + " "); + } + System.err.println("\n "); + } catch (Exception f) { + throw new Error(); + } + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/oldTests/ValidateClass.java b/test/java/io/Serializable/oldTests/ValidateClass.java new file mode 100644 index 0000000000..cd99a0e362 --- /dev/null +++ b/test/java/io/Serializable/oldTests/ValidateClass.java @@ -0,0 +1,133 @@ +/* + * 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 + * @summary it is new version of old test which was under + * /src/share/test/serialization/psiotest.java + * Test validation callbacks + */ + +import java.io.*; + +public class ValidateClass { + public static void main (String argv[]) { + System.err.println("\nRegression test for validation of callbacks \n"); + + FileInputStream istream = null; + try { + + FileOutputStream ostream = new FileOutputStream("psiotest4.tmp"); + ObjectOutputStream p = new ObjectOutputStream(ostream); + + /* Catch the expected exception and + * complain if it does not occur. + */ + + // Serialize a bunch of objects that will be validated when read + // Make a list of classes with intermingled priorities + Validator vc = new Validator(0, null); + vc = new Validator(2, vc); + vc = new Validator(0, vc); + vc = new Validator(3, vc); + vc = new Validator(Integer.MIN_VALUE, vc); + vc = new Validator(1, vc); + vc = new Validator(1, vc); + vc = new Validator(0, vc); + + p.writeObject(vc); + p.flush(); + ostream.close(); + + istream = new FileInputStream("psiotest4.tmp"); + ObjectInputStream q = new ObjectInputStream(istream); + + Validator vc_u; + + vc_u = (Validator)q.readObject(); + if (vc_u.validated != Integer.MIN_VALUE) { + System.err.println("\nTEST FAILED: Validation callbacks did " + + "not complete."); + throw new Error(); + } + istream.close(); + System.err.println("\nTEST PASSED"); + } catch (Exception e) { + System.err.print("TEST FAILED: "); + e.printStackTrace(); + throw new Error(); + } + } +} + +class MissingWriterClass implements java.io.Serializable { + int i = 77; + + private void writeObject(ObjectOutputStream pw) throws IOException { + pw.writeInt(i); + } +} + +class MissingReaderClass implements java.io.Serializable { + int i = 77; + + private void readObject(ObjectInputStream pr) throws IOException { + i = pr.readInt(); + } +} + + +class Validator implements ObjectInputValidation, java.io.Serializable { + static int validated = Integer.MAX_VALUE; // Last value validated + int priority; + Validator next = null; + + public Validator(int prio, Validator n) { + priority = prio; + next = n; + } + + // Handle serialization/deserialization + private void writeObject(ObjectOutputStream pw) throws IOException { + pw.writeInt(priority); + pw.writeObject(next); + } + + private void readObject(ObjectInputStream pr) + throws IOException, ClassNotFoundException + { + priority = pr.readInt(); + next = (Validator)pr.readObject(); + + pr.registerValidation(this, priority); + } + + public void validateObject() throws InvalidObjectException { + if (validated < priority) { + System.err.println("\nTEST FAILED: Validations called out " + + "of order: Previous priority: " + validated + " < " + + "new priority: " + priority); + throw new Error(); + } + validated = priority; + } +} diff --git a/test/java/io/Serializable/oldTests/WritePrimitive.java b/test/java/io/Serializable/oldTests/WritePrimitive.java new file mode 100644 index 0000000000..f00dce420f --- /dev/null +++ b/test/java/io/Serializable/oldTests/WritePrimitive.java @@ -0,0 +1,159 @@ +/* + * Copyright 2005-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 + * @summary it is a new version of an old test which was + * /src/share/test/serialization/piotest.java + * Test of serialization/deserialization of + * primitives + * + * @build PrimitivesTest + * @run main WritePrimitive + */ + +import java.io.*; + +public class WritePrimitive { + public static void main (String argv[]) { + System.err.println("\nRegression test for testing of " + + "serialization/deserialization of primitives \n"); + + FileInputStream istream = null; + try { + int i = 123456; + byte b = 12; + short s = 45; + char c = 'A'; + long l = 1234567890000L; + float f = 3.14159f; + double d = f*2; + boolean z = true; + String string = "The String"; + PrimitivesTest prim = new PrimitivesTest(); + + FileOutputStream ostream = new FileOutputStream("piotest1.tmp"); + ObjectOutputStream p = new ObjectOutputStream(ostream); + + p.writeInt(i); + p.writeByte(b); + p.writeShort(s); + p.writeChar(c); + p.writeLong(l); + p.writeFloat(f); + p.writeDouble(d); + p.writeBoolean(z); + p.writeUTF(string); + p.writeObject(string); + + p.writeObject(prim); + p.flush(); + + istream = new FileInputStream("piotest1.tmp"); + ObjectInputStream q = new ObjectInputStream(istream); + + int i_u = q.readInt(); + byte b_u = q.readByte(); + short s_u = q.readShort(); + char c_u = q.readChar(); + long l_u = q.readLong(); + float f_u = q.readFloat(); + double d_u = q.readDouble(); + boolean z_u = q.readBoolean(); + String string_utf = q.readUTF(); + String string_u = (String)q.readObject(); + if (i != i_u) { + System.err.println("\nint: expected " + i + " actual " +i_u); + throw new Error(); + } + if (b != b_u) { + System.err.println("\nbyte: expected " + b + " actual " +b_u); + throw new Error(); + } + if (s != s_u) { + System.err.println("\nshort: expected " + s + " actual " + + s_u); + throw new Error(); + } + if (c != c_u) { + System.err.println("\nchar: expected " + c + " actual " + + c_u); + throw new Error(); + } + if (l != l_u) { + System.err.println("\nlong: expected " + l + " actual " + + l_u); + throw new Error(); + } + if (f != f_u) { + System.err.println("\nfloat: expected " + f + " actual " + + f_u); + throw new Error(); + } + if (d != d_u) { + System.err.println("\ndouble: expected " + d + " actual " + + d_u); + throw new Error(); + } + if (z != z_u) { + System.err.println("\nboolean: expected " + z + " actual " + + z_u); + throw new Error(); + } + if (!string.equals(string_utf)) { + System.err.println("\nString: expected " + string + + " actual " + string_utf); + throw new Error(); + } + if (!string.equals(string_u)) { + System.err.println("\nString: expected " + string + + " actual " + string_u); + throw new Error(); + } + + PrimitivesTest prim_u = (PrimitivesTest)q.readObject(); + if (!prim.equals(prim_u)) { + System.err.println("\nTEST FAILED: Read primitive object " + + "correctly = " + false); + System.err.println("\n " + prim); + System.err.println("\n " + prim_u); + throw new Error(); + } + System.err.println("\nTEST PASSED"); + } catch (Exception e) { + System.err.print("TEST FAILED: "); + e.printStackTrace(); + + System.err.println("\nInput remaining"); + int ch; + try { + while ((ch = istream.read()) != -1) { + System.err.print("\n " + Integer.toString(ch, 16)+ " "); + } + System.out.println("\n "); + } catch (Exception f) { + throw new Error(); + } + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/optionalDataEnd/OptionalDataEnd.java b/test/java/io/Serializable/optionalDataEnd/OptionalDataEnd.java new file mode 100644 index 0000000000..a1af91905d --- /dev/null +++ b/test/java/io/Serializable/optionalDataEnd/OptionalDataEnd.java @@ -0,0 +1,79 @@ +/* + * 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 4402870 + * @summary Verify that an OptionalDataException with eof == true is thrown + * when a call to ObjectInputStream.readObject() attempts to read past + * the end of custom data. + */ + +import java.io.*; + +class Foo implements Serializable { + int reps; + + Foo(int reps) { + this.reps = reps; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + for (int i = 0; i < reps; i++) { + out.writeObject(new Integer(i)); + } + } + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + for (int i = 0; i < reps; i++) { + in.readObject(); + } + try { + in.readObject(); + throw new Error(); + } catch (OptionalDataException ex) { + if (! (ex.eof && (ex.length == 0))) { + throw new Error(); + } + } + } +} + +public class OptionalDataEnd { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(new Foo(5)); + oout.writeObject(new Foo(0)); + oout.close(); + + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + oin.readObject(); + oin.readObject(); + oin.close(); + } +} diff --git a/test/java/io/Serializable/packageAccess/A.java b/test/java/io/Serializable/packageAccess/A.java new file mode 100644 index 0000000000..603a07d65a --- /dev/null +++ b/test/java/io/Serializable/packageAccess/A.java @@ -0,0 +1,41 @@ +/* + * 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. + */ + +/* + * @bug 4765255 + * @summary Verify proper functioning of package equality checks used to + * determine accessibility of superclass constructor and inherited + * writeReplace/readResolve methods. + */ + +public class A { + + static boolean packagePrivateConstructorInvoked = false; + + A() { + packagePrivateConstructorInvoked = true; + } + + public A(int throwaway) { + } +} diff --git a/test/java/io/Serializable/packageAccess/B.java b/test/java/io/Serializable/packageAccess/B.java new file mode 100644 index 0000000000..bac31da7d7 --- /dev/null +++ b/test/java/io/Serializable/packageAccess/B.java @@ -0,0 +1,35 @@ +/* + * 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. + */ + +/* + * @bug 4765255 + * @summary Verify proper functioning of package equality checks used to + * determine accessibility of superclass constructor and inherited + * writeReplace/readResolve methods. + */ + +public class B extends A implements java.io.Serializable { + public B() { + super(0); + } +} diff --git a/test/java/io/Serializable/packageAccess/C.java b/test/java/io/Serializable/packageAccess/C.java new file mode 100644 index 0000000000..642180ea8c --- /dev/null +++ b/test/java/io/Serializable/packageAccess/C.java @@ -0,0 +1,41 @@ +/* + * 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. + */ + +/* + * @bug 4765255 + * @summary Verify proper functioning of package equality checks used to + * determine accessibility of superclass constructor and inherited + * writeReplace/readResolve methods. + */ + +import java.io.*; + +public class C implements Serializable { + Object writeReplace() throws ObjectStreamException { + throw new Error("package-private writeReplace called"); + } + + Object readResolve() throws ObjectStreamException { + throw new Error("package-private readResolve called"); + } +} diff --git a/test/java/io/Serializable/packageAccess/D.java b/test/java/io/Serializable/packageAccess/D.java new file mode 100644 index 0000000000..26fb800623 --- /dev/null +++ b/test/java/io/Serializable/packageAccess/D.java @@ -0,0 +1,32 @@ +/* + * 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. + */ + +/* + * @bug 4765255 + * @summary Verify proper functioning of package equality checks used to + * determine accessibility of superclass constructor and inherited + * writeReplace/readResolve methods. + */ + +public class D extends C implements java.io.Serializable { +} diff --git a/test/java/io/Serializable/packageAccess/Test.java b/test/java/io/Serializable/packageAccess/Test.java new file mode 100644 index 0000000000..df0cd8188d --- /dev/null +++ b/test/java/io/Serializable/packageAccess/Test.java @@ -0,0 +1,89 @@ +/* + * 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. + */ + +/* + * @bug 4765255 + * @summary Verify proper functioning of package equality checks used to + * determine accessibility of superclass constructor and inherited + * writeReplace/readResolve methods. + */ + +import java.io.*; +import java.net.*; + +public class Test { + + static Class bcl; + static Class dcl; + + public static void main(String[] args) throws Exception { + ClassLoader ldr = + new URLClassLoader(new URL[]{ new URL("file:foo.jar") }); + bcl = Class.forName("B", true, ldr); + dcl = Class.forName("D", true, ldr); + + Object b = bcl.newInstance(); + try { + swizzle(b); + throw new Error("expected InvalidClassException for class B"); + } catch (InvalidClassException e) { + System.out.println("caught " + e); + e.printStackTrace(); + } + if (A.packagePrivateConstructorInvoked) { + throw new Error("package private constructor of A invoked"); + } + + Object d = dcl.newInstance(); + swizzle(d); + } + + static void swizzle(Object obj) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(obj); + oout.close(); + ByteArrayInputStream bin = + new ByteArrayInputStream(bout.toByteArray()); + new TestObjectInputStream(bin).readObject(); + } +} + +class TestObjectInputStream extends ObjectInputStream { + TestObjectInputStream(InputStream in) throws IOException { + super(in); + } + + protected Class resolveClass(ObjectStreamClass desc) + throws IOException, ClassNotFoundException + { + String n = desc.getName(); + if (n.equals("B")) { + return Test.bcl; + } else if (n.equals("D")) { + return Test.dcl; + } else { + return super.resolveClass(desc); + } + } +} diff --git a/test/java/io/Serializable/packageAccess/run.sh b/test/java/io/Serializable/packageAccess/run.sh new file mode 100644 index 0000000000..11d3472162 --- /dev/null +++ b/test/java/io/Serializable/packageAccess/run.sh @@ -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 4765255 +# @summary Verify proper functioning of package equality checks used to +# determine accessibility of superclass constructor and inherited +# writeReplace/readResolve methods. + +if [ "${TESTJAVA}" = "" ] +then + echo "TESTJAVA not set. Test cannot execute. Failed." +exit 1 +fi + +if [ "${TESTSRC}" = "" ] +then + TESTSRC="." +fi + +set -ex + +${TESTJAVA}/bin/javac -d . ${TESTSRC}/A.java ${TESTSRC}/B.java \ + ${TESTSRC}/C.java ${TESTSRC}/D.java ${TESTSRC}/Test.java +${TESTJAVA}/bin/jar cf foo.jar B.class D.class +rm -f B.class D.class + +${TESTJAVA}/bin/java Test +rm -f *.class *.jar diff --git a/test/java/io/Serializable/parents/EvolvedClass.java b/test/java/io/Serializable/parents/EvolvedClass.java new file mode 100644 index 0000000000..55fb535e05 --- /dev/null +++ b/test/java/io/Serializable/parents/EvolvedClass.java @@ -0,0 +1,83 @@ +/* + * Copyright 1999 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. + */ + +/* + * @bug 4186885 + */ + +import java.io.*; + +public class EvolvedClass { + public static void main(String args[]) throws Exception{ + ASubClass corg = new ASubClass(1, "SerializedByEvolvedClass"); + ASubClass cnew = null; + + // Deserialize in to new class object + FileInputStream fi = new FileInputStream("parents.ser"); + ObjectInputStream si = new ObjectInputStream(fi); + cnew = (ASubClass) si.readObject(); + + System.out.println("Printing the deserialized class: "); + System.out.println(); + System.out.println(cnew); + } +} + + +/* During deserialization, the no-arg constructor of a serializable base class + * must not be invoked. + */ +class ASuperClass implements Serializable { + String name; + + ASuperClass() { + /* + * This method is not to be executed during deserialization for this + * example. Must call no-arg constructor of class Object which is the + * base class for ASuperClass. + */ + throw new Error("ASuperClass: Wrong no-arg constructor invoked"); + } + + ASuperClass(String name) { + this.name = new String(name); + } + + public String toString() { + return("Name: " + name); + } +} + +class ASubClass extends ASuperClass implements Serializable { + int num; + + private static final long serialVersionUID =6341246181948372513L; + ASubClass(int num, String name) { + super(name); + this.num = num; + } + + public String toString() { + return (super.toString() + "\nNum: " + num); + } +} diff --git a/test/java/io/Serializable/parents/OriginalClass.java b/test/java/io/Serializable/parents/OriginalClass.java new file mode 100644 index 0000000000..3a4828a616 --- /dev/null +++ b/test/java/io/Serializable/parents/OriginalClass.java @@ -0,0 +1,67 @@ +/* + * Copyright 1999 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 4186885 + * @clean OriginalClass EvolvedClass + * @build OriginalClass + * @run main OriginalClass + * @build EvolvedClass + * @run main EvolvedClass + * @summary To ensure that during deserializing classes, only the highest + * non-serializable class in the hierarchy has its no-arg constructor + * invoked. + * + */ + +import java.io.*; +public class OriginalClass { + + public static void main(String args[]) throws Exception{ + ASubClass corg = new ASubClass(1); + ASubClass cnew = null; + + // Serialize the subclass + FileOutputStream fo = new FileOutputStream("parents.ser"); + ObjectOutputStream so = new ObjectOutputStream(fo); + so.writeObject(corg); + so.flush(); + + System.out.println("Printing the serialized class: "); + System.out.println(); + System.out.println(corg); + } +} + + +class ASubClass implements Serializable { + int num; + + ASubClass(int num) { + this.num = num; + } + + public String toString() { + return ("\nNum: " + num); + } +} diff --git a/test/java/io/Serializable/partialClassDesc/PartialClassDesc.java b/test/java/io/Serializable/partialClassDesc/PartialClassDesc.java new file mode 100644 index 0000000000..355f06f108 --- /dev/null +++ b/test/java/io/Serializable/partialClassDesc/PartialClassDesc.java @@ -0,0 +1,61 @@ +/* + * Copyright 2000 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 4373844 + * @summary Verify that partially initialized ObjectStreamClass instances + * cannot be obtained from ObjectStreamClass.lookup() in the event + * that the target class is uninitializable. + */ + +import java.io.*; + +class A implements Serializable { + // existence of SVUID forces class initialization during classdesc init + private static final long serialVersionUID = 0L; + + static { + if ("foo".equals("foo")) { // force class initialization failure + throw new Error(); + } + } +} + +public class PartialClassDesc { + public static void main(String[] args) throws Exception { + Class cl = Class.forName( + "A", false, PartialClassDesc.class.getClassLoader()); + ObjectStreamClass desc = null; + try { + desc = ObjectStreamClass.lookup(cl); + } catch (Throwable th) { + } + try { + desc = ObjectStreamClass.lookup(cl); + } catch (Throwable th) { + } + if (desc != null) { + throw new Error("should not be able to obtain class descriptor"); + } + } +} diff --git a/test/java/io/Serializable/primitiveClasses/PrimitiveClasses.java b/test/java/io/Serializable/primitiveClasses/PrimitiveClasses.java new file mode 100644 index 0000000000..fe6453fa16 --- /dev/null +++ b/test/java/io/Serializable/primitiveClasses/PrimitiveClasses.java @@ -0,0 +1,56 @@ +/* + * 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. + */ + +/* @test + * @bug 4171142 4519050 + * @summary Verify that primitive classes can be serialized and deserialized. + */ + +import java.io.*; + +public class PrimitiveClasses { + public static void main(String[] args) throws Exception { + Class[] primClasses = new Class[] { + boolean.class, byte.class, char.class, short.class, + int.class, long.class, float.class, double.class, void.class + }; + + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + for (int i = 0; i < primClasses.length; i++) { + oout.writeObject(primClasses[i]); + } + oout.close(); + + ByteArrayInputStream bin = + new ByteArrayInputStream(bout.toByteArray()); + ObjectInputStream oin = new ObjectInputStream(bin); + for (int i = 0; i < primClasses.length; i++) { + Object obj = oin.readObject(); + if (obj != primClasses[i]) { + throw new Error( + "expected " + primClasses[i] + " instead of " + obj); + } + } + } +} diff --git a/test/java/io/Serializable/proxy/Basic.java b/test/java/io/Serializable/proxy/Basic.java new file mode 100644 index 0000000000..d8ef3d65b1 --- /dev/null +++ b/test/java/io/Serializable/proxy/Basic.java @@ -0,0 +1,119 @@ +/* + * Copyright 2000 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 Verifies basic correct functioning of proxy serialization. + */ + +import java.io.*; +import java.lang.reflect.*; +import java.util.Random; + +// proxy interfaces +interface Foo { int foo(); } +interface Bar { float bar(); } + +// dummy invocation handler +class Handler implements InvocationHandler, Serializable { + + static Method fooMethod, barMethod; + static { + try { + fooMethod = Foo.class.getDeclaredMethod("foo", new Class[0]); + barMethod = Bar.class.getDeclaredMethod("bar", new Class[0]); + } catch (NoSuchMethodException ex) { + throw new Error(); + } + } + + int foo; + float bar; + + Handler(int foo, float bar) { + this.foo = foo; + this.bar = bar; + } + + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable + { + if (method.equals(fooMethod)) { + return new Integer(foo); + } else if (method.equals(barMethod)) { + return new Float(bar); + } else { + throw new UnsupportedOperationException(); + } + } +} + +// ObjectInputStream incapable of resolving proxy classes +class ProxyBlindInputStream extends ObjectInputStream { + + ProxyBlindInputStream(InputStream in) throws IOException { super(in); } + + protected Class resolveProxyClass(String[] interfaces) + throws IOException, ClassNotFoundException + { + throw new ClassNotFoundException(); + } +} + +public class Basic { + public static void main(String[] args) throws Exception { + ClassLoader loader = ClassLoader.getSystemClassLoader(); + Class[] interfaces = new Class[] { Foo.class, Bar.class }; + Random rand = new Random(); + int foo = rand.nextInt(); + float bar = rand.nextFloat(); + ObjectOutputStream oout; + ObjectInputStream oin; + ByteArrayOutputStream bout; + Object proxy; + + + // test simple proxy write + read + bout = new ByteArrayOutputStream(); + oout = new ObjectOutputStream(bout); + oout.writeObject(Proxy.newProxyInstance( + loader, interfaces, new Handler(foo, bar))); + oout.close(); + + oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + proxy = oin.readObject(); + if ((((Foo) proxy).foo() != foo) || (((Bar) proxy).bar() != bar)) { + throw new Error(); + } + + + // test missing proxy class ClassNotFoundException + oin = new ProxyBlindInputStream( + new ByteArrayInputStream(bout.toByteArray())); + try { + oin.readObject(); + throw new Error(); + } catch (ClassNotFoundException ex) { + } + } +} diff --git a/test/java/io/Serializable/proxy/replace/ReadResolve.java b/test/java/io/Serializable/proxy/replace/ReadResolve.java new file mode 100644 index 0000000000..983362b008 --- /dev/null +++ b/test/java/io/Serializable/proxy/replace/ReadResolve.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +/* @summary Ensure that serialization invokes writeReplace/readResolve methods + * on dynamic proxies, just as with normal objects. + */ + +public interface ReadResolve { + public Object readResolve() throws java.io.ObjectStreamException; +} diff --git a/test/java/io/Serializable/proxy/replace/Resolved.java b/test/java/io/Serializable/proxy/replace/Resolved.java new file mode 100644 index 0000000000..8c43ca0274 --- /dev/null +++ b/test/java/io/Serializable/proxy/replace/Resolved.java @@ -0,0 +1,28 @@ +/* + * 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. + */ + +/* @summary Ensure that serialization invokes writeReplace/readResolve methods + * on dynamic proxies, just as with normal objects. + */ + +public interface Resolved {} diff --git a/test/java/io/Serializable/proxy/replace/Test.java b/test/java/io/Serializable/proxy/replace/Test.java new file mode 100644 index 0000000000..d78a17e86d --- /dev/null +++ b/test/java/io/Serializable/proxy/replace/Test.java @@ -0,0 +1,65 @@ +/* + * 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 Ensure that serialization invokes writeReplace/readResolve methods + * on dynamic proxies, just as with normal objects. + */ + +import java.io.*; +import java.lang.reflect.*; + +public class Test implements InvocationHandler, Serializable { + + static ClassLoader loader = Test.class.getClassLoader(); + + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable + { + String methName = method.getName(); + if (methName.equals("writeReplace")) { + return Proxy.newProxyInstance( + loader, new Class[] { ReadResolve.class }, this); + } else if (methName.equals("readResolve")) { + return Proxy.newProxyInstance( + loader, new Class[] { Resolved.class }, this); + } else if (method.getDeclaringClass() == Object.class) { + return method.invoke(this, args); + } else { + throw new Error(); + } + } + + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(Proxy.newProxyInstance( + loader, new Class[] { WriteReplace.class }, new Test())); + oout.close(); + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + if (!(oin.readObject() instanceof Resolved)) { + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/proxy/replace/WriteReplace.java b/test/java/io/Serializable/proxy/replace/WriteReplace.java new file mode 100644 index 0000000000..c385a882ef --- /dev/null +++ b/test/java/io/Serializable/proxy/replace/WriteReplace.java @@ -0,0 +1,30 @@ +/* + * 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. + */ + +/* @summary Ensure that serialization invokes writeReplace/readResolve methods + * on dynamic proxies, just as with normal objects. + */ + +public interface WriteReplace { + public Object writeReplace() throws java.io.ObjectStreamException; +} diff --git a/test/java/io/Serializable/proxy/skipMissing/Handler.java b/test/java/io/Serializable/proxy/skipMissing/Handler.java new file mode 100644 index 0000000000..aa2390893e --- /dev/null +++ b/test/java/io/Serializable/proxy/skipMissing/Handler.java @@ -0,0 +1,38 @@ +/* + * Copyright 2000 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. + */ + +/* + * @summary Verify that ObjectInputStream can skip over unresolvable serialized + * proxy instances. + */ + +import java.io.*; +import java.lang.reflect.*; + +class Handler implements InvocationHandler, Serializable { + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable + { + return null; + } +} diff --git a/test/java/io/Serializable/proxy/skipMissing/Read.java b/test/java/io/Serializable/proxy/skipMissing/Read.java new file mode 100644 index 0000000000..e51bf08145 --- /dev/null +++ b/test/java/io/Serializable/proxy/skipMissing/Read.java @@ -0,0 +1,68 @@ +/* + * Copyright 2000 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. + */ + +/* + * @summary Verify that ObjectInputStream can skip over unresolvable serialized + * proxy instances. + */ + +import java.io.*; +import java.lang.reflect.*; + +class A implements Serializable { + private static final long serialVersionUID = 0L; + String a; + String z; +} + +class B implements Serializable { + private static final long serialVersionUID = 0L; + String s; + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + // leave proxy object unconsumed + } +} + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = new ObjectInputStream( + new FileInputStream("tmp.ser")); + A a = (A) oin.readObject(); + if (! (a.a.equals("a") && a.z.equals("z"))) { + throw new Error("A fields corrupted"); + } + B b = (B) oin.readObject(); + if (! b.s.equals("s")) { + throw new Error("B fields corrupted"); + } + try { + oin.readObject(); + throw new Error("proxy read should not succeed"); + } catch (ClassNotFoundException ex) { + } + } +} diff --git a/test/java/io/Serializable/proxy/skipMissing/Write.java b/test/java/io/Serializable/proxy/skipMissing/Write.java new file mode 100644 index 0000000000..f613ba34f4 --- /dev/null +++ b/test/java/io/Serializable/proxy/skipMissing/Write.java @@ -0,0 +1,77 @@ +/* + * Copyright 2000 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 + * + * @clean Write Read A B I Handler + * @compile Write.java Handler.java + * @run main Write + * @clean Write Read A B I Handler + * @compile Read.java Handler.java + * @run main Read + * + * @summary Verify that ObjectInputStream can skip over unresolvable serialized + * proxy instances. + */ + +import java.io.*; +import java.lang.reflect.*; + +interface I {} // interface present only on writing side + +class A implements Serializable { + private static final long serialVersionUID = 0L; + String a = "a"; + Object proxy; + String z = "z"; + + A(Object proxy) { this.proxy = proxy; } +} + +class B implements Serializable { + private static final long serialVersionUID = 0L; + String s = "s"; + transient Object proxy; + + B(Object proxy) { this.proxy = proxy; } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + out.writeObject(proxy); + } +} + +public class Write { + public static void main(String[] args) throws Exception { + Object proxy = Proxy.newProxyInstance( + ClassLoader.getSystemClassLoader(), + new Class[] { I.class }, new Handler()); + ObjectOutputStream oout = new ObjectOutputStream( + new FileOutputStream("tmp.ser")); + oout.writeObject(new A(proxy)); + oout.reset(); + oout.writeObject(new B(proxy)); + oout.writeObject(proxy); + oout.close(); + } +} diff --git a/test/java/io/Serializable/readObjectNoData/Read.java b/test/java/io/Serializable/readObjectNoData/Read.java new file mode 100644 index 0000000000..d09a8a5a64 --- /dev/null +++ b/test/java/io/Serializable/readObjectNoData/Read.java @@ -0,0 +1,108 @@ +/* + * Copyright 2000 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. + */ + +/* + * @bug 4363844 + * @summary Verify that a custom readObjectNoData method, if defined properly + * by a serializable superclass, gets invoked during deserialization + * of a subclass instance whose serialized form omits a class + * descriptor corresponding to the superclass. + */ + +import java.io.*; + +/* Non-serializable superclass which defines readObjectNoData: + * readObjectNoData should not get called. + */ +class A { + private static final long serialVersionUID = 0L; + boolean aCalled = false; + private void readObjectNoData() throws ObjectStreamException { + aCalled = true; + } +} + +/* Serializable superclass which defines readObjectNoData with wrong signature: + * readObjectNoData should not get called. + */ +class B extends A implements Serializable { + private static final long serialVersionUID = 0L; + boolean bCalled = false; + private void readObjectNoData(int wrong) throws ObjectStreamException { + bCalled = true; + } +} + +/* Serializable superclass which defines readObjectNoData correctly, and is not + * listed in stream: readObjectNoData should get called. + */ +class C extends B { + private static final long serialVersionUID = 0L; + boolean cCalled = false; + private void readObjectNoData() throws ObjectStreamException { + cCalled = true; + } +} + +/* Serializable superclass which defines readObjectNoData correctly, but whose + * corresponding class descriptor is listed in stream: readObjectNoData should + * not get called. + */ +class D extends C { + private static final long serialVersionUID = 0L; + boolean dCalled = false; + private void readObjectNoData() throws ObjectStreamException { + dCalled = true; + } +} + +/* Serializable superclass which defines readObjectNoData with wrong access: + * readObjectNoData should not get called. + */ +class E extends D { + private static final long serialVersionUID = 0L; + boolean eCalled = false; + void readObjectNoData() throws ObjectStreamException { + eCalled = true; + } +} + +/* Instance class. + */ +class F extends E { + private static final long serialVersionUID = 0L; +} + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("tmp.ser")); + F f = (F) oin.readObject(); + if (f.aCalled || f.bCalled || f.dCalled || f.eCalled) { + throw new Error("readObjectNoData invoked erroneously"); + } + if (! f.cCalled) { + throw new Error("readObjectNoData not invoked"); + } + } +} diff --git a/test/java/io/Serializable/readObjectNoData/Write.java b/test/java/io/Serializable/readObjectNoData/Write.java new file mode 100644 index 0000000000..adae9c621c --- /dev/null +++ b/test/java/io/Serializable/readObjectNoData/Write.java @@ -0,0 +1,57 @@ +/* + * Copyright 2000 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 4363844 + * + * @clean Write Read A B C D E F + * @compile Write.java + * @run main Write + * @clean Write Read A B C D E F + * @compile Read.java + * @run main Read + * + * @summary Verify that a custom readObjectNoData method, if defined properly + * by a serializable superclass, gets invoked during deserialization + * of a subclass instance whose serialized form omits a class + * descriptor corresponding to the superclass. + */ + +import java.io.*; + +class D implements Serializable { + private static final long serialVersionUID = 0L; +} + +class F extends D { + private static final long serialVersionUID = 0L; +} + +public class Write { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("tmp.ser")); + oout.writeObject(new F()); + oout.close(); + } +} diff --git a/test/java/io/Serializable/readPastObject/ReadPastObject.java b/test/java/io/Serializable/readPastObject/ReadPastObject.java new file mode 100644 index 0000000000..be7f3cb493 --- /dev/null +++ b/test/java/io/Serializable/readPastObject/ReadPastObject.java @@ -0,0 +1,72 @@ +/* + * Copyright 1999 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 4253271 + * @summary Ensure that ObjectInputStream.readObject() is called, it doesn't + * read past the end of the object in the underlying stream. + */ + +import java.io.*; + +class LimitInputStream extends ByteArrayInputStream { + int limit; + + LimitInputStream(byte[] b) { + super(b); + limit = b.length; + } + + public int read() { + if (limit < 1) + throw new Error("limit exceeded"); + int c = super.read(); + if (c != -1) + limit--; + return c; + } + + public int read(byte[] b) { + return read(b, 0, b.length); + } + + public int read(byte[] b, int off, int len) { + if (limit < len) + throw new Error("limit exceeded"); + int n = super.read(b, off, len); + if (n != -1) + limit -= n; + return n; + } +} + +public class ReadPastObject { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject("foo"); + LimitInputStream lin = new LimitInputStream(bout.toByteArray()); + ObjectInputStream oin = new ObjectInputStream(lin); + System.out.println(oin.readObject()); + } +} diff --git a/test/java/io/Serializable/recursiveClassDescLookup/Test.java b/test/java/io/Serializable/recursiveClassDescLookup/Test.java new file mode 100644 index 0000000000..eed308d7b5 --- /dev/null +++ b/test/java/io/Serializable/recursiveClassDescLookup/Test.java @@ -0,0 +1,47 @@ +/* + * 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 4803747 + * @run main/timeout=20 Test + * @summary Verify that a nested call to ObjectStreamClass.lookup from within + * the static initializer of a serializable class will not cause + * deadlock. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 1L; + static { + ObjectStreamClass.lookup(Foo.class); + } +} + +public class Test { + public static void main(String[] args) throws Exception { + Class fooCl = Class.forName("Foo", false, Test.class.getClassLoader()); + ObjectStreamClass.lookup(fooCl); + System.out.println("done."); + } +} diff --git a/test/java/io/Serializable/replaceStringArray/ReplaceStringArray.java b/test/java/io/Serializable/replaceStringArray/ReplaceStringArray.java new file mode 100644 index 0000000000..de26291ed8 --- /dev/null +++ b/test/java/io/Serializable/replaceStringArray/ReplaceStringArray.java @@ -0,0 +1,186 @@ +/* + * Copyright 1998 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 + * @clean A SubstituteObjectOutputStream SubstituteObjectInputStream + * @bug 4099013 + * @summary Enable substitution of String and Array by ObjectStreams. + */ + +import java.io.*; +import java.lang.reflect.Array; + +class A implements Serializable { + String stringA; + String stringB; + String stringC; + String[] arrayOfString; + + A() { + stringA = "hello"; + stringB = "goodbye"; + stringC = stringA; + arrayOfString = new String[2]; + for (int i = 0; i < arrayOfString.length; i++) + arrayOfString[i] = new String("array element " + i); + } + + void report() { + System.out.println("stringA = " + stringA); + System.out.println("stringB = " + stringB); + System.out.println("stringC = " + stringC); + System.out.println("length of arrayOfString = " + + arrayOfString.length); + for (int i = 0; i < arrayOfString.length; i++) + System.out.println("arrayOfString[" + i + "]= " + + arrayOfString[i]); + } +} + +class SubstituteObjectOutputStream extends ObjectOutputStream { + public int numStringsReplaced = 0; + public int numArraysCounted = 0; + + public SubstituteObjectOutputStream(OutputStream out) throws IOException { + super(out); + enableReplaceObject(true); + } + + protected Object replaceObject(Object obj) throws IOException { + if (obj instanceof String) { + numStringsReplaced++; + return obj + "_WriteReplaced"; + } + if (obj.getClass().isArray()) { + Object[] array = (Object[]) obj; + /* Double the array. + * Initialize new array elements with original array. */ + Class arrayComponentType = array.getClass().getComponentType(); + Object[] newarray = + (Object[])Array.newInstance(arrayComponentType, + array.length * 2); + for (int i = 0; i < array.length; i++) + newarray[i] = array[i]; + for (int ni = array.length; ni < 2* array.length; ni++) + newarray[ni] = array[ni - array.length]; + numArraysCounted++; + obj = newarray; + } + return obj; + } +} + +class SubstituteObjectInputStream extends ObjectInputStream { + public int numStringsReplaced = 0; + public int numArraysCounted = 0; + + public SubstituteObjectInputStream(InputStream in) throws IOException { + super(in); + enableResolveObject(true); + } + + protected Object resolveObject(Object obj) throws IOException { + if (obj instanceof String) { + numStringsReplaced++; + return obj + "_ReadResolved"; + } + if (obj.getClass().isArray()) { + Object[] array = (Object[])obj; + + /* Double the array. + * Initialize new array elements with original array. */ + Class arrayComponentType = array.getClass().getComponentType(); + Object[] newarray = + (Object[])Array.newInstance(arrayComponentType, + array.length * 2); + for (int i = 0; i < array.length; i++) + newarray[i] = array[i]; + for (int ni = array.length; ni < 2* array.length; ni++) + newarray[ni] = array[ni - array.length]; + numArraysCounted++; + obj = newarray; + } + return obj; + } +} + +public class ReplaceStringArray { + public static void main(String args[]) throws IOException, ClassNotFoundException { + boolean verbose = false; + if (args.length >= 1 && args[0].compareTo("verbose") == 0) + verbose = true; + + + A a = new A(); + if (verbose) { + System.out.println("Value of Class A"); + a.report(); + System.out.println(""); + } + + + /* Serialize object a to bytestream. */ + if (verbose) { + System.out.println("Serialize A to SubstituteObjectOutputStream"); + System.out.println(""); + } + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + SubstituteObjectOutputStream out = new SubstituteObjectOutputStream(baos); + out.writeObject(a); + out.close(); + a = null; + + /* Validate that writeReplace called by SubstituteObjectOutputStream.*/ + boolean expectedResult = (out.numStringsReplaced == 4); + if (!expectedResult) + throw new Error("Expected " + 4 + " strings to be replaced during serialization;" + + " only " + out.numStringsReplaced + " strings were replaced."); + if (out.numArraysCounted != 1) + throw new Error("Expected 1 array during serialization; only " + + out.numArraysCounted + " arrays"); + + if (verbose) { + System.out.println("DeSerialize A from SubstituteObjectInputStream"); + System.out.println(""); + } + SubstituteObjectInputStream in = + new SubstituteObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + a = (A)in.readObject(); + in.close(); + + /* Validate that readResolve called by SubstituteObjectInputStream.*/ + if (in.numStringsReplaced != 4) + throw new Error("Expected 4 strings to be resolved during deserialization;" + + " only " + in.numStringsReplaced + " strings were resolved."); + if (in.numArraysCounted != 1) + throw new Error("Expected 1 array during deserialization; only " + + out.numArraysCounted + " arrays"); + if (a.arrayOfString.length != 8) + throw new Error("Expected a.arrayOfString.length to be 8, observed " + + a.arrayOfString.length); + if (verbose) { + System.out.println("Value of Class A after serialize/deserialize with writeReplace/readResolve"); + a.report(); + } + } +} diff --git a/test/java/io/Serializable/replaceWithNull/ReplaceWithNull.java b/test/java/io/Serializable/replaceWithNull/ReplaceWithNull.java new file mode 100644 index 0000000000..c7e79511f6 --- /dev/null +++ b/test/java/io/Serializable/replaceWithNull/ReplaceWithNull.java @@ -0,0 +1,53 @@ +/* + * Copyright 1997-1998 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 4065313 + * @clean A ReplaceWithNull MyObjectOutputStream + * @summary Ensure that it is okay to replace an object with null. + */ +import java.io.*; + +class A { } + +class MyObjectOutputStream extends ObjectOutputStream { + public MyObjectOutputStream(OutputStream out) throws IOException { + super(out); + enableReplaceObject(true); + } + protected Object replaceObject(Object obj) throws IOException { + if(obj instanceof A) return null; + else return obj; + } +} + +public class ReplaceWithNull { + public static void main(String args[]) throws IOException { + A a = new A(); + + MyObjectOutputStream out = + new MyObjectOutputStream(new ByteArrayOutputStream()); + out.writeObject(a); //raised NullPointerException. + out.close(); + } +} diff --git a/test/java/io/Serializable/resolveClass/MethodTest.java b/test/java/io/Serializable/resolveClass/MethodTest.java new file mode 100644 index 0000000000..7c227630ba --- /dev/null +++ b/test/java/io/Serializable/resolveClass/MethodTest.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 4413434 + * @summary Verify that generated java.lang.reflect implementation classes do + * not interfere with serialization's class resolution mechanism. + */ + +import java.io.*; +import java.lang.reflect.*; + +public class MethodTest implements Serializable { + public static void main(String[] args) throws Exception { + Method readObject = ObjectInputStream.class.getDeclaredMethod( + "readObject", new Class[0]); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(new MethodTest()); + oout.close(); + + for (int i = 0; i < 100; i++) { + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + readObject.invoke(oin, new Object[0]); + } + } +} diff --git a/test/java/io/Serializable/resolveClass/consTest/Boot.java b/test/java/io/Serializable/resolveClass/consTest/Boot.java new file mode 100644 index 0000000000..17ce00fe39 --- /dev/null +++ b/test/java/io/Serializable/resolveClass/consTest/Boot.java @@ -0,0 +1,37 @@ +/* + * 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. + */ + +/* + * @bug 4413434 + * @summary Verify that generated java.lang.reflect implementation classes do + * not interfere with serialization's class resolution mechanism. + */ + +import java.io.*; + +// this class should be loaded from bootclasspath +public class Boot { + public Boot(ObjectInputStream oin) throws Exception { + oin.readObject(); + } +} diff --git a/test/java/io/Serializable/resolveClass/consTest/Test.java b/test/java/io/Serializable/resolveClass/consTest/Test.java new file mode 100644 index 0000000000..e6a2f547f2 --- /dev/null +++ b/test/java/io/Serializable/resolveClass/consTest/Test.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. + */ + +/* + * @bug 4413434 + * @summary Verify that generated java.lang.reflect implementation classes do + * not interfere with serialization's class resolution mechanism. + */ + +import java.io.*; +import java.lang.reflect.*; + +public class Test implements Serializable { + public static void main(String[] args) throws Exception { + Constructor cons = Boot.class.getConstructor( + new Class[] { ObjectInputStream.class }); + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(new Test()); + oout.close(); + + for (int i = 0; i < 100; i++) { + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + cons.newInstance(new Object[]{ oin }); + } + } +} diff --git a/test/java/io/Serializable/resolveClass/consTest/run.sh b/test/java/io/Serializable/resolveClass/consTest/run.sh new file mode 100644 index 0000000000..dc097104ce --- /dev/null +++ b/test/java/io/Serializable/resolveClass/consTest/run.sh @@ -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 4413434 +# @summary Verify that generated java.lang.reflect implementation classes do +# not interfere with serialization's class resolution mechanism. + +if [ "${TESTJAVA}" = "" ] +then + echo "TESTJAVA not set. Test cannot execute. Failed." +exit 1 +fi + +if [ "${TESTSRC}" = "" ] +then + TESTSRC="." +fi + +set -ex + +rm -f *.class *.jar +${TESTJAVA}/bin/javac -d . ${TESTSRC}/Boot.java +${TESTJAVA}/bin/jar cf boot.jar *.class +rm -f *.class +${TESTJAVA}/bin/javac -classpath boot.jar -d . ${TESTSRC}/Test.java +${TESTJAVA}/bin/java -Xbootclasspath/a:boot.jar Test +rm -f *.class *.jar diff --git a/test/java/io/Serializable/resolveClass/deserializeButton/Foo.java b/test/java/io/Serializable/resolveClass/deserializeButton/Foo.java new file mode 100644 index 0000000000..d9980c073a --- /dev/null +++ b/test/java/io/Serializable/resolveClass/deserializeButton/Foo.java @@ -0,0 +1,60 @@ +/* + * 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. + */ + +/* + * @bug 4413434 + * @summary Verify that class loaded outside of application class loader is + * correctly resolved during deserialization when read in by custom + * readObject() method of a bootstrap class (in this case, + * java.awt.Button). + */ + +import java.awt.Button; +import java.awt.event.MouseAdapter; +import java.io.*; + +public class Foo implements Runnable { + + static class Adapter extends MouseAdapter implements Serializable {} + + public void run() { + try { + Button button = new Button(); + button.addMouseListener(new Adapter()); + + // iterate to trigger java.lang.reflect code generation + for (int i = 0; i < 100; i++) { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(button); + oout.close(); + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + oin.readObject(); + } + } catch (Exception ex) { + throw new Error( + "Error occured while (de)serializing Button: " + ex); + } + } +} diff --git a/test/java/io/Serializable/resolveClass/deserializeButton/Test.java b/test/java/io/Serializable/resolveClass/deserializeButton/Test.java new file mode 100644 index 0000000000..26a146fb21 --- /dev/null +++ b/test/java/io/Serializable/resolveClass/deserializeButton/Test.java @@ -0,0 +1,42 @@ +/* + * 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. + */ + +/* + * @bug 4413434 + * @summary Verify that class loaded outside of application class loader is + * correctly resolved during deserialization when read in by custom + * readObject() method of a bootstrap class (in this case, + * java.awt.Button). + */ + +import java.io.*; +import java.net.*; + +public class Test { + public static void main(String[] args) throws Exception { + ClassLoader ldr = + new URLClassLoader(new URL[]{ new URL("file:cb.jar") }); + Runnable r = (Runnable) Class.forName("Foo", true, ldr).newInstance(); + r.run(); + } +} diff --git a/test/java/io/Serializable/resolveClass/deserializeButton/run.sh b/test/java/io/Serializable/resolveClass/deserializeButton/run.sh new file mode 100644 index 0000000000..5d741fabb0 --- /dev/null +++ b/test/java/io/Serializable/resolveClass/deserializeButton/run.sh @@ -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 4413434 +# @summary Verify that class loaded outside of application class loader is +# correctly resolved during deserialization when read in by custom +# readObject() method of a bootstrap class (in this case, +# java.awt.Button). + +if [ "${TESTJAVA}" = "" ] +then + echo "TESTJAVA not set. Test cannot execute. Failed." +exit 1 +fi + +if [ "${TESTSRC}" = "" ] +then + TESTSRC="." +fi + +set -ex + +rm -f *.class *.jar +${TESTJAVA}/bin/javac -d . ${TESTSRC}/Foo.java +${TESTJAVA}/bin/jar cf cb.jar *.class +rm -f *.class +${TESTJAVA}/bin/javac -d . ${TESTSRC}/Test.java +${TESTJAVA}/bin/java Test +rm -f *.class *.jar diff --git a/test/java/io/Serializable/resolveClassException/ResolveClassException.java b/test/java/io/Serializable/resolveClassException/ResolveClassException.java new file mode 100644 index 0000000000..9f706ef40e --- /dev/null +++ b/test/java/io/Serializable/resolveClassException/ResolveClassException.java @@ -0,0 +1,83 @@ +/* + * Copyright 1999 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 4191941 + * @summary Ensure that original ClassNotFoundException thrown inside of + * ObjectInputStream.resolveClass() is preserved (and thrown). + */ + +import java.io.*; + +class BrokenObjectInputStream extends ObjectInputStream { + + static final String message = "bodega"; + + BrokenObjectInputStream(InputStream in) throws IOException { + super(in); + } + + protected Class resolveClass(ObjectStreamClass desc) + throws IOException, ClassNotFoundException + { + throw new ClassNotFoundException(message); + } +} + +public class ResolveClassException { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout; + ObjectOutputStream oout; + ByteArrayInputStream bin; + BrokenObjectInputStream oin; + Object obj; + + // write and read an object + obj = new Integer(5); + bout = new ByteArrayOutputStream(); + oout = new ObjectOutputStream(bout); + oout.writeObject(obj); + bin = new ByteArrayInputStream(bout.toByteArray()); + oin = new BrokenObjectInputStream(bin); + try { + oin.readObject(); + } catch (ClassNotFoundException e) { + if (! BrokenObjectInputStream.message.equals(e.getMessage())) + throw new Error("Original exception not preserved"); + } + + // write and read an array of objects + obj = new Integer[] { new Integer(5) }; + bout = new ByteArrayOutputStream(); + oout = new ObjectOutputStream(bout); + oout.writeObject(obj); + bin = new ByteArrayInputStream(bout.toByteArray()); + oin = new BrokenObjectInputStream(bin); + try { + oin.readObject(); + } catch (ClassNotFoundException e) { + if (! BrokenObjectInputStream.message.equals(e.getMessage())) + throw new Error("Original exception not preserved"); + } + } +} diff --git a/test/java/io/Serializable/resolveProxyClass/NonPublicInterface.java b/test/java/io/Serializable/resolveProxyClass/NonPublicInterface.java new file mode 100644 index 0000000000..fbf69fb198 --- /dev/null +++ b/test/java/io/Serializable/resolveProxyClass/NonPublicInterface.java @@ -0,0 +1,76 @@ +/* + * 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 4413817 + * @summary Verify that ObjectInputStream.resolveProxyClass can properly + * resolve a dynamic proxy class which implements a non-public + * interface not defined in the latest user defined class loader. + */ + +import java.io.*; +import java.lang.reflect.*; + +public class NonPublicInterface { + + static class Handler implements InvocationHandler, Serializable { + public Object invoke(Object obj, Method meth, Object[] args) { + return null; + } + } + + public static void main(String[] args) throws Exception { + Class nonPublic = null; + String[] nonPublicInterfaces = new String[] { + "java.awt.Conditional", + "java.util.zip.ZipConstants", + "javax.swing.GraphicsWrapper", + "javax.swing.JPopupMenu$Popup", + "javax.swing.JTable$Resizable2", + "javax.swing.JTable$Resizable3", + "javax.swing.ToolTipManager$Popup", + "sun.audio.Format", + "sun.audio.HaePlayable", + "sun.tools.agent.StepConstants", + }; + for (int i = 0; i < nonPublicInterfaces.length; i++) { + try { + nonPublic = Class.forName(nonPublicInterfaces[i]); + break; + } catch (ClassNotFoundException ex) { + } + } + if (nonPublic == null) { + throw new Error("couldn't find system non-public interface"); + } + + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(Proxy.newProxyInstance(nonPublic.getClassLoader(), + new Class[]{ nonPublic }, new Handler())); + oout.close(); + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + oin.readObject(); + } +} diff --git a/test/java/io/Serializable/sanityCheck/SanityCheck.java b/test/java/io/Serializable/sanityCheck/SanityCheck.java new file mode 100644 index 0000000000..7a6415afb2 --- /dev/null +++ b/test/java/io/Serializable/sanityCheck/SanityCheck.java @@ -0,0 +1,148 @@ +/* + * 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 Basic sanity check to test if default (de)serialization is + * transmitting values properly. + */ + +import java.io.*; +import java.util.*; + +class Item implements Serializable { + + static final int ARRAYLEN = 1000; + static final int STRLEN = 1000; + static Random rand = new Random(System.currentTimeMillis()); + + boolean z; + byte b; + char c; + short s; + int i; + float f; + long j; + double d; + + boolean[] zary; + byte[] bary; + char[] cary; + short[] sary; + int[] iary; + float[] fary; + long[] jary; + double[] dary; + + String str; + Object[] oary; + + Item() { + z = rand.nextBoolean(); + b = (byte) rand.nextInt(); + c = (char) rand.nextInt(); + s = (short) rand.nextInt(); + i = rand.nextInt(); + f = rand.nextFloat(); + j = rand.nextLong(); + d = rand.nextDouble(); + + zary = new boolean[ARRAYLEN]; + bary = new byte[ARRAYLEN]; + cary = new char[ARRAYLEN]; + sary = new short[ARRAYLEN]; + iary = new int[ARRAYLEN]; + fary = new float[ARRAYLEN]; + jary = new long[ARRAYLEN]; + dary = new double[ARRAYLEN]; + oary = new Object[ARRAYLEN]; + + for (int i = 0; i < ARRAYLEN; i++) { + zary[i] = rand.nextBoolean(); + bary[i] = (byte) rand.nextInt(); + cary[i] = (char) rand.nextInt(); + sary[i] = (short) rand.nextInt(); + iary[i] = rand.nextInt(); + fary[i] = rand.nextFloat(); + jary[i] = rand.nextLong(); + dary[i] = rand.nextDouble(); + oary[i] = new Integer(rand.nextInt()); + } + + char[] strChars = new char[STRLEN]; + for (int i = 0; i < STRLEN; i++) { + strChars[i] = (char) rand.nextInt(); + } + str = new String(strChars); + } + + public boolean equals(Object obj) { + if (!(obj instanceof Item)) { + return false; + } + Item other = (Item) obj; + + if ((z != other.z) || (b != other.b) || (c != other.c) || + (s != other.s) || (i != other.i) || (f != other.f) || + (j != other.j) || (d != other.d)) + { + return false; + } + + for (int i = 0; i < ARRAYLEN; i++) { + if ((zary[i] != other.zary[i]) || (bary[i] != other.bary[i]) || + (cary[i] != other.cary[i]) || (sary[i] != other.sary[i]) || + (iary[i] != other.iary[i]) || (fary[i] != other.fary[i]) || + (jary[i] != other.jary[i]) || (dary[i] != other.dary[i]) || + !oary[i].equals(other.oary[i])) + { + return false; + } + } + + if (!str.equals(other.str)) { + return false; + } + + return true; + } +} + +public class SanityCheck { + public static void main(String[] args) throws Exception { + for (int i = 0; i < 20; i++) { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + Item item = new Item(); + oout.writeObject(item); + oout.close(); + + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + Item itemcopy = (Item) oin.readObject(); + + if (! item.equals(itemcopy)) { + throw new Error(); + } + } + } +} diff --git a/test/java/io/Serializable/serialver/classpath/Test.java b/test/java/io/Serializable/serialver/classpath/Test.java new file mode 100644 index 0000000000..b6371708b0 --- /dev/null +++ b/test/java/io/Serializable/serialver/classpath/Test.java @@ -0,0 +1,35 @@ +/* + * Copyright 2000 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. + */ + +/* + * + * @bug 4035147 + * @sumary Simple java class for test purposes + */ + +package serialver; + +public class Test implements java.io.Serializable{ + int a; + int b; +} diff --git a/test/java/io/Serializable/serialver/classpath/run.sh b/test/java/io/Serializable/serialver/classpath/run.sh new file mode 100644 index 0000000000..aa3251e479 --- /dev/null +++ b/test/java/io/Serializable/serialver/classpath/run.sh @@ -0,0 +1,64 @@ +# +# 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. +# + +# @test +# @bug 4035147 4785472 +# @summary Test the use of the -classpath switch in the serialver application. +# @author Naveen Sanjeeva +# +# @build Test +# @run shell run.sh + +# set a few environment variables so that the shell-script can run stand-alone +# in the source directory + +if [ "${TESTSRC}" = "" ] ; then + TESTSRC="." +fi +if [ "${TESTCLASSES}" = "" ] ; then + TESTCLASSES="." +fi +if [ "${TESTJAVA}" = "" ] ; then + echo "TESTJAVA not set. Test cannot execute." + echo "FAILED!!!" + exit 1 +fi + +# set platform-dependent variables +OS=`uname -s` +case "$OS" in + SunOS | Linux ) + PS=":" ;; + Windows* ) + PS=";" ;; + * ) + echo "Unrecognized system!" + exit 1 ;; +esac + +# the test code + +echo "Using the classpath .${PS}${TESTCLASSES}" +${TESTJAVA}/bin/serialver -classpath ".${PS}${TESTCLASSES}" serialver.Test + +exit $? diff --git a/test/java/io/Serializable/serialver/nested/Test.java b/test/java/io/Serializable/serialver/nested/Test.java new file mode 100644 index 0000000000..96b6c5c702 --- /dev/null +++ b/test/java/io/Serializable/serialver/nested/Test.java @@ -0,0 +1,40 @@ +/* + * Copyright 2000 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. + */ + +/* + * + * @bug 4312217 + * @summary To test the use of nested class specification using the '.' + * notation instead of the '$' notation. + */ +package serialver; + +import java.io.*; + +public class Test implements Serializable { + public static class Test1 implements Serializable { + public static class Test2 implements Serializable{ + private static final long serialVersionUID = 100L; + } + } +} diff --git a/test/java/io/Serializable/serialver/nested/run.sh b/test/java/io/Serializable/serialver/nested/run.sh new file mode 100644 index 0000000000..57b0ca0a75 --- /dev/null +++ b/test/java/io/Serializable/serialver/nested/run.sh @@ -0,0 +1,64 @@ +# +# 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. +# + +# @test +# @bug 4312217 4785473 +# @summary Test the use of the -classpath switch in the serialver application. +# @author Naveen Sanjeeva +# +# @build Test +# @run shell run.sh + +# set a few environment variables so that the shell-script can run stand-alone +# in the source directory + +if [ "${TESTSRC}" = "" ] ; then + TESTSRC="." +fi +if [ "${TESTCLASSES}" = "" ] ; then + TESTCLASSES="." +fi +if [ "${TESTJAVA}" = "" ] ; then + echo "TESTJAVA not set. Test cannot execute." + echo "FAILED!!!" + exit 1 +fi + +# set platform-dependent variables +OS=`uname -s` +case "$OS" in + SunOS | Linux ) + PS=":" ;; + Windows* ) + PS=";" ;; + * ) + echo "Unrecognized system!" + exit 1 ;; +esac + +# the test code + +echo "Using the classpath .${PS}${TESTCLASSES}" +${TESTJAVA}/bin/serialver -classpath ".${PS}${TESTCLASSES}" 'serialver.Test.Test1.Test2' + +exit $? diff --git a/test/java/io/Serializable/skipToEndOfBlockData/SkipToEndOfBlockData.java b/test/java/io/Serializable/skipToEndOfBlockData/SkipToEndOfBlockData.java new file mode 100644 index 0000000000..14687ea794 --- /dev/null +++ b/test/java/io/Serializable/skipToEndOfBlockData/SkipToEndOfBlockData.java @@ -0,0 +1,143 @@ +/* + * Copyright 1999 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 4228592 + * @summary Ensure that ObjectInputStream properly skips over block data when a + * class that defines readObject() or readExternal() fails to read all + * of the data written by the corresponding writeObject() or + * writeExternal() method. + */ + +import java.io.*; + +class MismatchedRead implements Serializable { + int i; + float f; + + MismatchedRead(int i, float f) { + this.i = i; + this.f = f; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.writeInt(i); + out.writeFloat(f); + out.writeUTF("skip me"); + } + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + i = in.readInt(); + f = in.readFloat(); + } + + public boolean equals(Object obj) { + if (! (obj instanceof MismatchedRead)) + return false; + MismatchedRead other = (MismatchedRead) obj; + return (i == other.i && f == other.f); + } +} + +class MismatchedReadExternal implements Externalizable { + int i; + float f; + + public MismatchedReadExternal() { + this(0, (float) 0.0); + } + + MismatchedReadExternal(int i, float f) { + this.i = i; + this.f = f; + } + + public void writeExternal(ObjectOutput out) throws IOException { + out.writeInt(i); + out.writeFloat(f); + out.writeUTF("skip another"); + } + + public void readExternal(ObjectInput in) throws IOException { + i = in.readInt(); + f = in.readFloat(); + } + + public boolean equals(Object obj) { + if (! (obj instanceof MismatchedReadExternal)) + return false; + MismatchedReadExternal other = (MismatchedReadExternal) obj; + return (i == other.i && f == other.f); + } +} + +class InnocentBystander implements Serializable { + String s; + + InnocentBystander(String s) { + this.s = s; + } + + public boolean equals(Object obj) { + if (! (obj instanceof InnocentBystander)) + return false; + InnocentBystander other = (InnocentBystander) obj; + if (s != null) + return s.equals(other.s); + return (s == other.s); + } +} + +public class SkipToEndOfBlockData { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout; + ObjectInputStream oin; + ByteArrayOutputStream bout; + ByteArrayInputStream bin; + MismatchedRead mr, mrcopy; + MismatchedReadExternal mre, mrecopy; + InnocentBystander ib, ibcopy; + + bout = new ByteArrayOutputStream(); + oout = new ObjectOutputStream(bout); + mr = new MismatchedRead(1, (float) 2.34); + mre = new MismatchedReadExternal(5, (float) 6.78); + ib = new InnocentBystander("foo"); + + oout.writeObject(mr); + oout.writeObject(mre); + oout.writeObject(ib); + oout.flush(); + + bin = new ByteArrayInputStream(bout.toByteArray()); + oin = new ObjectInputStream(bin); + mrcopy = (MismatchedRead) oin.readObject(); + mrecopy = (MismatchedReadExternal) oin.readObject(); + ibcopy = (InnocentBystander) oin.readObject(); + + if (! (mr.equals(mrcopy) && mre.equals(mrecopy) && ib.equals(ibcopy))) + throw new Error("copy not equal to original"); + } +} diff --git a/test/java/io/Serializable/skipWriteObject/Read.java b/test/java/io/Serializable/skipWriteObject/Read.java new file mode 100644 index 0000000000..f56cc0c001 --- /dev/null +++ b/test/java/io/Serializable/skipWriteObject/Read.java @@ -0,0 +1,46 @@ +/* + * Copyright 2000 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. + */ + +/* + * @bug 4392325 + * @summary Ensure that ObjectInputStream can successfully skip over an object + * written using a class-defined writeObject method for which the + * class is not resolvable. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 0L; +} + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("tmp.ser")); + Object[] array = (Object[]) oin.readObject(); + if (! (array[0].equals("before") && array[2].equals("after"))) { + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/skipWriteObject/Write.java b/test/java/io/Serializable/skipWriteObject/Write.java new file mode 100644 index 0000000000..9f160a528e --- /dev/null +++ b/test/java/io/Serializable/skipWriteObject/Write.java @@ -0,0 +1,60 @@ +/* + * Copyright 2000 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 4392325 + * + * @clean Write Read Foo Bar + * @compile Write.java + * @run main Write + * @clean Write Read Foo Bar + * @compile Read.java + * @run main Read + * + * @summary Ensure that ObjectInputStream can successfully skip over an object + * written using a class-defined writeObject method for which the + * class is not resolvable. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final long serialVersionUID = 0L; + Bar b = new Bar(); +} + +class Bar implements Serializable { + int a, b; + private void writeObject(ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + } +} + +public class Write { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("tmp.ser")); + oout.writeObject(new Object[] { "before", new Foo(), "after" }); + oout.close(); + } +} diff --git a/test/java/io/Serializable/skippedObjCNFException/Read.java b/test/java/io/Serializable/skippedObjCNFException/Read.java new file mode 100644 index 0000000000..c986666bff --- /dev/null +++ b/test/java/io/Serializable/skippedObjCNFException/Read.java @@ -0,0 +1,51 @@ +/* + * Copyright 2000 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. + */ + +/* + * @bug 4313167 + * @summary Verify that ClassNotFoundExceptions caused by values referenced + * (perhaps transitively) by "skipped" fields will not cause + * deserialization failure. + */ + +import java.io.*; + +class A implements Serializable { + private static final long serialVersionUID = 0L; + // skipped fields b, c, ca +} + +class B implements Serializable { + private static final long serialVersionUID = 0L; + Object c; +} + +// class C not available + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("tmp.ser")); + oin.readObject(); + } +} diff --git a/test/java/io/Serializable/skippedObjCNFException/Write.java b/test/java/io/Serializable/skippedObjCNFException/Write.java new file mode 100644 index 0000000000..b866795370 --- /dev/null +++ b/test/java/io/Serializable/skippedObjCNFException/Write.java @@ -0,0 +1,65 @@ +/* + * Copyright 2000 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 4313167 + * + * @clean Write Read A B C + * @compile Write.java + * @run main Write + * @clean Write Read A B C + * @compile Read.java + * @run main Read + * + * @summary Verify that ClassNotFoundExceptions caused by values referenced + * (perhaps transitively) by "skipped" fields will not cause + * deserialization failure. + */ + +import java.io.*; + +class A implements Serializable { + private static final long serialVersionUID = 0L; + // all three following fields not present on reading side + B b = new B(); + C c = new C(); + Object ca = new Object[] { new C() }; +} + +class B implements Serializable { + private static final long serialVersionUID = 0L; + Object c = new C(); +} + +class C implements Serializable { // class not present on reading side + private static final long serialVersionUID = 0L; +} + +public class Write { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("tmp.ser")); + oout.writeObject(new A()); + oout.close(); + } +} diff --git a/test/java/io/Serializable/stopCustomDeserialization/Read.java b/test/java/io/Serializable/stopCustomDeserialization/Read.java new file mode 100644 index 0000000000..829028b189 --- /dev/null +++ b/test/java/io/Serializable/stopCustomDeserialization/Read.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. + */ + +/* + * @bug 4663191 + * @summary Verify that readObject and readObjectNoData methods will not be + * called on an object being deserialized if that object is already + * tagged with a ClassNotFoundException. + */ + +import java.io.*; + +class A implements Serializable { + private static final long serialVersionUID = 0L; + Object x; +} + +class B extends A { + private static final long serialVersionUID = 0L; + private void readObjectNoData() throws ObjectStreamException { + throw new Error("readObjectNoData called"); + } +} + +class C extends B { + private static final long serialVersionUID = 0L; + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + throw new Error("readObject called"); + } +} + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("tmp.ser")); + try { + oin.readObject(); + throw new Error("readObject should not succeed"); + } catch (ClassNotFoundException e) { + // expected + } + if (!oin.readObject().equals("after")) { + throw new Error("subsequent object corrupted"); + } + } +} diff --git a/test/java/io/Serializable/stopCustomDeserialization/Write.java b/test/java/io/Serializable/stopCustomDeserialization/Write.java new file mode 100644 index 0000000000..38ac5ecbf9 --- /dev/null +++ b/test/java/io/Serializable/stopCustomDeserialization/Write.java @@ -0,0 +1,61 @@ +/* + * 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 4663191 + * @summary Verify that readObject and readObjectNoData methods will not be + * called on an object being deserialized if that object is already + * tagged with a ClassNotFoundException. + * + * @clean Write Read A B C X + * @compile Write.java + * @run main Write + * @clean Write Read A B C X + * @compile Read.java + * @run main Read + */ + +import java.io.*; + +class A implements Serializable { + private static final long serialVersionUID = 0L; + Object x = new X(); +} + +class C extends A { + private static final long serialVersionUID = 0L; +} + +class X implements Serializable { + private static final long serialVersionUID = 0L; +} + +public class Write { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("tmp.ser")); + oout.writeObject(new C()); + oout.writeObject("after"); + oout.close(); + } +} diff --git a/test/java/io/Serializable/subclass/AbstractObjectInputStream.java b/test/java/io/Serializable/subclass/AbstractObjectInputStream.java new file mode 100644 index 0000000000..5312e25e29 --- /dev/null +++ b/test/java/io/Serializable/subclass/AbstractObjectInputStream.java @@ -0,0 +1,321 @@ +/* + * Copyright 1998-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. + */ + +/* + * + */ + +import java.io.*; +import java.util.Vector; +import java.util.Stack; +import java.util.Hashtable; +import java.lang.Math; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +/** + * This abstract class enables one to subclass ObjectInputStream + * for the purpose of re-implementing serialization while preserving the + * existing public serialization API. A complimentary subclass of + * AbstractObjectInputStream must also be implemented.<p> + * + * Since serialization must override java access rules in order to + * access private, protected and package accessible Serializable fields, + * only trusted classes are allowed to subclass AbstractObjectInputStream. + * Subclasses of AbstractObjectInputStream must define SerializablePermission + * "enableAbstractSubclass" within a security policy file or this + * constructor will throw a SecurityException. Implementations of this + * class should protect themselves from being subclassed in a way that will + * provide access to object references and other sensitive info. + * Specifically, readObjectOverride() should be made final. + * <p> + * + * A subclass of AbstractObjectInputStream deserializes primitive data and + * objects previously written by a subclass of AbstractObjectOutputStream. + * The subclass ensures that the types of all objects in the graph created + * from the stream match the classes present in the Java Virtual Machine. + * Classes are loaded as required using the standard mechanisms. <p> + * + * Only objects that support the java.io.Serializable or + * java.io.Externalizable interface can be read from streams. + * + * The method <STRONG>readObjectOverride</STRONG> is used to read an object + * from the stream. Java's safe casting should be used to get the + * desired type. In Java, strings and arrays are objects and are + * treated as objects during serialization. When read with readObject() + * they need to be cast to the expected type.<p> + * + * Primitive data types can be read from the stream using the appropriate + * method on DataInput. <p> + * + * The default deserialization mechanism for objects restores the + * contents of each field to the value and type it had when it was written. + * References to other objects cause those + * objects to be read from the stream as necessary. Graphs of objects + * are restored correctly using a reference sharing mechanism. New + * objects are always allocated when deserializing, which prevents + * existing objects from being overwritten. <p> + * + * Reading an object is analogous to running the constructors of a new + * object. Memory is allocated for the object and initialized to zero + * (NULL). No-arg constructors are invoked for the first non-serializable + * super class and then the fields of the serializable classes are + * restored from the stream starting with the serializable class closest to + * java.lang.object and finishing with the object's most specifiec + * class. <p> + * + * Classes control how they are serialized by implementing either the + * java.io.Serializable or java.io.Externalizable interfaces.<P> + * + * Implementing the Serializable interface allows object serialization + * to save and restore the entire state of the object and it allows + * classes to evolve between the time the stream is written and the time it is + * read. It automatically traverses references between objects, + * saving and restoring entire graphs. + * + * Serializable classes that require special handling during the + * serialization and deserialization process should implement both + * of these methods:<p> + * + * <PRE> + * private void writeObject(java.io.ObjectOutputStream stream) + * throws IOException; + * private void readObject(java.io.ObjectInputStream stream) + * throws IOException, ClassNotFoundException; + * </PRE><p> + * + * The readObject method is responsible for reading and restoring the + * state of the object for its particular class using data written to + * the stream by the corresponding writeObject method. The method + * does not need to concern itself with the state belonging to its + * superclasses or subclasses. State is restored by reading data from + * the ObjectInputStream for the individual fields and making + * assignments to the appropriate fields of the object. Reading + * primitive data types is supported by DataInput. <p> + * + * Serialization does not read or assign values to the fields of any + * object that does not implement the java.io.Serializable interface. + * Subclasses of Objects that are not serializable can be + * serializable. In this case the non-serializable class must have an + * accessible no-arg constructor to allow its fields to be initialized. + * In this case it is the responsibility of the subclass to save and restore + * the state of the non-serializable class. It is frequently the case that + * the fields of that class are accessible (public, package, or + * protected) or that there are get and set methods that can be used + * to restore the state. <p> + * + * Implementing the Externalizable interface allows the object to + * assume complete control over the contents and format of the object's + * serialized form. The methods of the Externalizable interface, + * writeExternal and readExternal, are called to save and restore the + * objects state. When implemented by a class they can write and read + * their own state using all of the methods of ObjectOutput and + * ObjectInput. It is the responsibility of the objects to handle any + * versioning that occurs. + * + * @author Joe Fialli + * + * @see java.io.ObjectInputStream + * @see java.io.DataInput + * @see java.io.Serializable + * @see java.io.Externalizable + * @see java.io.ext.AbstractObjectOutputStream + * @since JDK1.2 + */ +abstract public class AbstractObjectInputStream extends ObjectInputStream +{ + protected InputStream in; + /** + * Create an ObjectInputStream that reads from the specified InputStream.<p> + * + * Add the following line to the security policy file to enable + * subclassing. + * + * <PRE> + * permission SerializablePermission "enableAbstractSubclass" ; + * </PRE><p> + * + * @exception StreamCorruptedException The version or magic number are incorrect. + * @exception IOException An exception occurred in the underlying stream. + * @exception SecurityException if subclass does not have SerializablePermiision + * "enableAbstractSubclass". + */ + public AbstractObjectInputStream(InputStream in) + throws IOException, StreamCorruptedException + { + this.in = in; + } + + abstract public void close() throws IOException; + + /***************************************************************/ + /* Read an object from the stream. */ + + /** + * Read an object from the ObjectInputStream.<p> + * + * NOTE: The override method of this class should have the modifier final.<p> + * + * Default deserializing for a class can be + * overriden by defining a readObject method for the Serializable class. + * Objects referenced by this object are read transitively so + * that a complete equivalent graph of objects is reconstructed by + * readObject. <p> + * + * The root object is completely restored when all of its fields + * and the objects it references are completely restored. At this + * point the object validation callbacks are executed in order + * based on their registered priorities. The callbacks are + * registered by objects (in the readObject special methods) + * as they are individually restored. <p> + * + * For security's sake, any overrides of this method should be final. + * Serialization typically needs to disable java access rules + * to serialize private, protected and package accessible Serializable + * fields. This method gets called for ALL Serializable objects. + * + * @exception java.lang.ClassNotFoundException Class of a serialized object + * cannot be found. + * @exception InvalidClassException Something is wrong with a class used by + * serialization. + * @exception StreamCorruptedException Control information in the + * stream is inconsistent. + * @exception OptionalDataException Primitive data was found in the + * stream instead of objects. + * @exception IOException Any of the usual Input/Output related exceptions. + * + * @see java.io.ObjectInputStream#resolveObject(Object) + * @see java.io.Resolvable + * @see java.io.Externalizable + * @see java.io.ObjectInputValidation + * @see #registerValidation(ObjectInputValidation, int) + * @see java.io.ObjectInputStream#resolveClass(ObjectStreamClass) + */ + protected Object readObjectOverride() + throws OptionalDataException, ClassNotFoundException, IOException { + return null; + } + + /** + * Read the Serializable fields of the current object from this stream.<p> + * + * Note: The object being deserialized is not passed to this method. + * For security purposes, the initial implementation maintained + * the state of the last object to be read by readObject + * only allowed this method to be invoked for this object.<p> + * + * @exception NotActiveException Thrown if a readObject method is not + * active. + * @exception ClassNotFoundException if no corresponding local class can be + * found in the local JVM. + */ + abstract public void defaultReadObject() + throws IOException, ClassNotFoundException, NotActiveException; + + /** + * Enable allocation for subclass reimplementing serialization.<p> + * + * Note: Default allocation does not have the java access priviledges + * to invoke package and protected constructors.<p> + * + * Security alert: this JVM native method is private within ObjectInputStream; however, + * it was anticipated that re-implementors of serialization would need + * access to this method. Is this allocator considered a security problem? <p> + * + * @param ctorClass is the same class or a superclass of <STRONG>ofClass</STRONG> + * @param ofClass the type of the object to allocate. + * @return an object of <STRONG>ofClass</STRONG> type. + * + * @exception IllegalAccessException if no-arg constructor of + * <STRONG>ctorClass</STRONG> is not accessible from + * <STRONG>ofClass</STRONG>. + * @exception InstantiationException TBD. + */ + final protected native Object + allocateNewObject(Class ofClass, Class ctorClass) + throws InstantiationException, IllegalAccessException; + + /** + * Enable allocation for subclass reimplementing serialization.<p> + * + * Note: Default allocation does not have the java access priviledges + * to invoke package and protected constructors.<p> + * + * Security alert: this JVM native method is private within ObjectInputStream; however, + * it was anticipated that re-implementors of serialization would need + * access to this method. Is this allocator considered a security problem?<p> + * + * + * @exception IllegalAccessException TBD. + * @exception InstantiationException TBD. + */ + final protected native Object + allocateNewArray(Class componentClass, int length) + throws InstantiationException, IllegalAccessException; + + /** + * Reads the Serializable fields from the stream into a buffer + * and makes the fields available by name. + * + * @exception java.lang.ClassNotFoundException if the class of a serialized + * object could not be found. + * @exception IOException if an I/O error occurs. + * @exception NotActiveException if readObject() is not currently active. + */ + abstract public ObjectInputStream.GetField readFields() + throws IOException, ClassNotFoundException, NotActiveException; + + abstract protected boolean enableResolveObject(boolean enable) throws SecurityException; + + abstract public void registerValidation(ObjectInputValidation obj, + int prio) + throws NotActiveException, InvalidObjectException; + + + /****************************************************************/ + + /* Use DataInput methods to read primitive data from the stream. */ + + abstract public int read() throws IOException; + abstract public int read(byte[] data, int offset, int length) + throws IOException; + abstract public boolean readBoolean() throws IOException; + abstract public byte readByte() throws IOException; + abstract public int readUnsignedByte() throws IOException; + abstract public short readShort() throws IOException; + abstract public int readUnsignedShort() throws IOException; + abstract public char readChar() throws IOException; + abstract public int readInt() throws IOException; + abstract public long readLong() throws IOException; + abstract public float readFloat() throws IOException; + abstract public double readDouble() throws IOException; + abstract public void readFully(byte[] data) throws IOException; + abstract public void readFully(byte[] data, int offset, int size) throws IOException; + abstract public String readUTF() throws IOException; + abstract public int available() throws IOException; + abstract public int skipBytes(int len) throws IOException; + + /* @deprecated */ + abstract public String readLine() throws IOException; +}; diff --git a/test/java/io/Serializable/subclass/AbstractObjectOutputStream.java b/test/java/io/Serializable/subclass/AbstractObjectOutputStream.java new file mode 100644 index 0000000000..71a07e4798 --- /dev/null +++ b/test/java/io/Serializable/subclass/AbstractObjectOutputStream.java @@ -0,0 +1,253 @@ +/* + * Copyright 1998-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. + */ + +/* + * + * + */ + +import java.io.*; +import java.security.*; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.InvocationTargetException; +import java.io.IOException; +import java.io.OutputStream; +import java.io.ObjectOutputStream; + +/** + * This class provides a means for a subclass to re-implement Serialization + * while preserving the existing public API to Serialization. A complimentary + * subclass of AbstractObjectInputStream must also be implemented to + * deserializa the new implementation.<p> + * + * Since serialization must override java access rules in order to + * access private, protected and package accessible Serializable fields, + * only trusted classes are allowed to subclass AbstractObjectInputStream. + * Subclasses of AbstractObjectOututStream must have SerializablePermission + * "enableAbstractSubclass" or this constructor will throw a + * SecurityException.Implementations of this class should protect themselves + * from being subclassed in a way that will provide access to object + * references and other sensitive info. Specifically, writeObjectOverride() + * should be made final. + * + * A subclass of AbstractObjectOutputStream writes primitive data types + * and graphs of Java objects to an ObjectOutputStream. The objects can be read + * (reconstituted) using he complimentary subclass of AbstractObjectInputStream.<p> + * Persistent storage of objects can be accomplished by using a file for + * the stream. If the stream is a network socket stream, the objects can + * be reconstituted on another host or in another process. <p> + * + * Only objects that support the java.io.Serializable interface can be + * written to streams.<p> + * + * The method <STRONG>writeObjectOverride</STRONG> is used to write an object + * to the stream. Any object, including Strings and arrays, is + * written with writeObject. Multiple objects or primitives can be + * written to the stream. The objects must be read back from the + * corresponding subclass of AbstractObjectInputstream with the same types + * and in the same order as they were written.<p> + * + * Primitive data types can also be written to the stream using the + * appropriate methods from DataOutput. Strings can also be written + * using the writeUTF method.<p> + * + * The default serialization mechanism for an object is defined by + * defaultWriteObject(). References to other objects + * (except in transient or static fields) cause those objects to be + * written also. Multiple references to a single object are encoded + * using a reference sharing mechanism so that graphs of objects can + * be restored to the same shape as when the original was written. <p> + * + * Classes that require special handling during the serialization and deserialization + * process must implement special methods with these exact signatures: <p> + * + * <PRE> + * private void readObject(java.io.ObjectInputStream stream) + * throws IOException, ClassNotFoundException; + * private void writeObject(java.io.ObjectOutputStream stream) + * throws IOException + * </PRE><p> + * The writeObject method is responsible for writing the state of + * the object for its particular class so that the corresponding + * readObject method can restore it. + * The method does not need to concern itself with the + * state belonging to the object's superclasses or subclasses. + * State is saved by writing the individual fields to the ObjectOutputStream + * using the writeObject method or by using the methods for + * primitive data types supported by DataOutput. <p> + * + * Serialization does not write out the fields of any object that does + * not implement the java.io.Serializable interface. Subclasses of + * Objects that are not serializable can be serialized. In this case + * the non-serializable class must have a no-arg constructor to allow + * its fields to be initialized. In this case it is the + * responsibility of the subclass to save and restore the state of the + * non-serializable class. It is frequently the case that the fields + * of that class are accessible (public, package, or protected) or + * that there are get and set methods that can be used to restore the + * state. <p> + * + * Serialization of an object can be prevented by implementing writeObject + * and readObject methods that throw the NotSerializableException. + * The exception will be caught by the ObjectOutputStream and abort the + * serialization process. + * + * Implementing the Externalizable interface allows the object to + * assume complete control over the contents and format of the object's + * serialized form. The methods of the Externalizable interface, + * writeExternal and readExternal, are called to save and restore the + * objects state. When implemented by a class they can write and read + * their own state using all of the methods of ObjectOutput and + * ObjectInput. It is the responsibility of the objects to handle any + * versioning that occurs. + * + * @author Joe Fialli + * + * @see java.io.ObjectOutputStream + * @see java.io.DataOutput + * @see java.io.Serializable + * @see java.io.Externalizable + * @see java.io.Replaceable + * @see java.io.ext.AbstractObjectInputStream + * + * @since JDK1.2 + */ +abstract public class AbstractObjectOutputStream extends ObjectOutputStream +{ + protected OutputStream out; + /* Stream Management Methods. */ + + /** + * Creates an ObjectOutputStream that writes to the specified OutputStream. + * + * Add the following line to the security policy file to enable + * subclassing. + * + * <PRE> + * permission SerializablePermission "enableAbstractSubclass" ; + * </PRE><p> + * + * @exception IOException Any exception thrown by the underlying OutputStream. + * @see java.io.ObjectOutputStream#writeStreamHeader() + */ + public AbstractObjectOutputStream(OutputStream out) throws IOException { + this.out = out; + } + + abstract public void reset() throws IOException; + abstract protected void drain() throws IOException; + abstract public void close() throws IOException; + + /*******************************************************************/ + + /* Write Objects to Stream */ + + /** + * Write the specified object to a subclass of AbstractObjectOutputStream.<p> + * + * NOTE: The override method of this class should have the modifier final.<p> + * + * Default serialization for a class can be + * overridden by defining writeObject and the readObject methods + * for the Serializable class. Objects referenced by this object are + * written transitively so that a complete equivalent graph of objects + * can be reconstructed by an ObjectInputStream. <p> + * + * This method must implement the substitution semantics on the + * object to be written, write Externalizable objects with its classes + * override of writeExternal, and it must call annotateClass when + * writing an ObjectStreamClass to the stream. + * + * Exceptions can be thrown for problems with the OutputStream and + * for classes that should not be serialized. + * + * For security's sake, any overrides of this method should be final. + * Serialization typically needs to disable java access rules + * to serialize private, protected and package accessible Serializable + * fields. This method gets called for ALL Serializable objects. + * + * @exception InvalidClassException Something is wrong with a class used by + * serialization. + * @exception NotSerializableException Some object to be serialized does not + * implement the java.io.Serializable interface. + * @exception IOException Any exception thrown by the underlying OutputStream. + * @see java.io.Externalizable + * @see java.io.ObjectOutputStream#replaceObject(Object) + * @see java.io.Replaceable + * @see java.io.ObjectOutputStream#annotateClass(Class) + */ + protected void writeObjectOverride(Object obj) + throws IOException + { + } + + /** + * Write the Serializable fields of the current object to this stream.<p> + * + * Note: The object being serialized is not passed to this method. + * For security purposes, the initial implementation maintained + * the state of the last object to be passed to writeObject and + * only allowed this method to be invoked for this object.<p> + * + * @exception NotActiveException Thrown if a writeObject method is not + * active. + */ + abstract public void defaultWriteObject() throws IOException; + + /*************************************************************/ + /* Use the methods of PutField to map between Serializable fields + * and actual fields of a Serializable class. + */ + + abstract public ObjectOutputStream.PutField putFields() throws IOException; + + /** + * Note: The PutField being serialized is not passed to this method. + * For security purposes, the initial implementation maintained + * the state of the last putFields call and + * only allowed this method to be invoked for that PutFields object. + */ + abstract public void writeFields() throws IOException; + + abstract protected boolean enableReplaceObject(boolean enable) throws SecurityException; + + /*******************************************************************/ + /* Write Primitive Data to stream. DataOutput methods. */ + + abstract public void write(int data) throws IOException; + abstract public void write(byte b[]) throws IOException; + abstract public void write(byte b[], int off, int len) throws IOException; + abstract public void writeBoolean(boolean data) throws IOException; + abstract public void writeByte(int data) throws IOException; + abstract public void writeShort(int data) throws IOException; + abstract public void writeChar(int data) throws IOException; + abstract public void writeInt(int data) throws IOException; + abstract public void writeLong(long data) throws IOException; + abstract public void writeFloat(float data) throws IOException; + abstract public void writeDouble(double data) throws IOException; + abstract public void writeBytes(String data) throws IOException; + abstract public void writeChars(String data) throws IOException; + abstract public void writeUTF(String data) throws IOException; +}; diff --git a/test/java/io/Serializable/subclass/Allow.policy b/test/java/io/Serializable/subclass/Allow.policy new file mode 100644 index 0000000000..234de2c9d3 --- /dev/null +++ b/test/java/io/Serializable/subclass/Allow.policy @@ -0,0 +1,10 @@ +grant { + // "standard" properies that can be read by anyone + permission java.io.FilePermission "-","read,write,execute"; + permission java.io.SerializablePermission "enableSubstitution"; + permission java.io.SerializablePermission "enableSubclassImplementation"; + + // Needed to get access to private writeObjectMethod and + // to be able to call it. + permission java.lang.reflect.ReflectPermission "access"; +}; diff --git a/test/java/io/Serializable/subclass/Test.java b/test/java/io/Serializable/subclass/Test.java new file mode 100644 index 0000000000..0d1a6c7810 --- /dev/null +++ b/test/java/io/Serializable/subclass/Test.java @@ -0,0 +1,152 @@ +/* + * Copyright 1998 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 4100915 + * @summary Verify that [write/read]ObjectOverride methods get called. + * Test verifies that ALL methods to write an object can + * be overridden. Howver, the testing for reading an object + * is incomplete. Only test that readObjectOverride is called. + * An entire protocol would need to be implemented and written + * out before being able to test the input side of the API. + * + * Also, would be appropriate that this program verify + * that if SerializablePermission "enableSubclassImplamentation" + * is not in the security policy and security is enabled, that + * a security excepiton is thrown when constructing the + * ObjectOutputStream subclass. + * + * + * @compile AbstractObjectInputStream.java AbstractObjectOutputStream.java XObjectInputStream.java XObjectOutputStream.java Test.java + * @run main Test + */ + +import java.io.*; + +/** + * Test if customized readObject and writeObject are called. + */ +class B implements Serializable { + public int publicIntField; + static public int numWriteObjectCalled = 0; + B(int v) { + publicIntField = v; + } + private void writeObject(ObjectOutputStream os) throws IOException { + numWriteObjectCalled++; + os.defaultWriteObject(); + } + + private void readObject(ObjectInputStream is) + throws IOException, ClassNotFoundException + { + is.defaultReadObject(); + } + +}; + +/** + * Test PutFields interface. + */ + +class C implements Serializable { + public int xx1; + public int xx2; + final static ObjectStreamField[] serialPersistentFields = { + new ObjectStreamField("x1", Integer.TYPE), + new ObjectStreamField("x2", Integer.TYPE), + new ObjectStreamField("x3", Integer.TYPE), + new ObjectStreamField("x4", Integer.TYPE) + }; + C() { + xx1 = 300; + xx2 = 400; + } + + private void writeObject(ObjectOutputStream os) throws IOException { + ObjectOutputStream.PutField putFields = os.putFields(); + putFields.put("x1", xx1); + putFields.put("x2", xx2); + putFields.put("x3", xx1 * 2); + putFields.put("x4", xx2 * 2); + os.writeFields(); + } + +}; + + +class A implements Serializable { + public int publicIntField; + public long publicLongField; + public B publicBField; + public B[] publicBArray = { new B(4), new B(6)}; + public C publicCField; + + public A() { + publicIntField = 3; + publicLongField = 10L; + publicBField = new B(5); + publicCField = new C(); + } +}; + +public class Test { + static public void main(String argv[]) + throws IOException, ClassNotFoundException + { + boolean expectSecurityException = false; + + if (argv.length > 0 && + argv[0].compareTo("-expectSecurityException") == 0) + expectSecurityException = true; + + ByteArrayOutputStream baos = new ByteArrayOutputStream(20); + XObjectOutputStream os = null; + try { + os = new XObjectOutputStream(baos); + if (expectSecurityException) + throw new Error("Assertion failure. " + + "Expected a security exception on previous line."); + } catch (SecurityException e) { + if (expectSecurityException) + return; + else + throw e; + } + os.writeObject(new A()); + os.close(); + if (B.numWriteObjectCalled != 3) + throw new Error("Expected B.writeObject() to be called 3 times;" + + " observed only " + B.numWriteObjectCalled + " times"); + + XObjectInputStream is = + new XObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + try { + A a = (A)is.readObject(); + throw new Error("Expected readObjectOverride() to be called and throw IOException(not implemented)"); + } catch (IOException e) { + } + is.close(); + } +}; diff --git a/test/java/io/Serializable/subclass/XObjectInputStream.java b/test/java/io/Serializable/subclass/XObjectInputStream.java new file mode 100644 index 0000000000..960005bad7 --- /dev/null +++ b/test/java/io/Serializable/subclass/XObjectInputStream.java @@ -0,0 +1,328 @@ +/* + * Copyright 1998 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. + */ + +import java.io.*; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.InvocationTargetException; +import java.security.*; + +class XObjectInputStream extends AbstractObjectInputStream { + + XObjectInputStream(InputStream in) + throws IOException, StreamCorruptedException + { + super(in); + dis = new DataInputStream(in); + } + + final public void defaultReadObject() + throws IOException, ClassNotFoundException, NotActiveException + { + } + + final protected Object readObjectOverride() + throws OptionalDataException, ClassNotFoundException, IOException { + + Object readResult = null; + Object prevObject = currentObject; + Class prevDesc = currentClassDescriptor; + + boolean NotImplemented = true; + if (NotImplemented) + throw new IOException("readObjectOverride not implemented"); + + try { + currentObject = null; + + //Read in class of object to currentDescriptor + String className = dis.readUTF(); + currentClassDescriptor = Class.forName(className); + + try { + //currentObject = Allocate a new instance of the class + currentObject = + allocateNewObject(currentClassDescriptor, + currentClassDescriptor); + } catch (InstantiationException e) { + throw new InvalidClassException(currentClassDescriptor.getName(), + e.getMessage()); + } catch (IllegalAccessException e) { + throw new InvalidClassException(currentClassDescriptor.getName(), + e.getMessage()); + } + + //if currentDescriptor.isAssignable(Externalizable.class) { + // Object[] argList = {this}; + // InvokeMethod(currentObject, readExternalMethod, argList); + //} else { + // Does currentDescriptor have a readObject method + // if it does + // invokeMethod(this, readObjectMethod, {this}); + // else + // defaultReadObject(); + //} + // check for replacement on currentObject. + // if toplevel readobject + // doObjectValidations. + + } finally { + readResult = currentObject; + currentObject = prevObject; + } + return readResult; + } + + public ObjectInputStream.GetField readFields() + throws IOException, ClassNotFoundException, NotActiveException { + throw new Error("not implememted"); + } + + public synchronized void registerValidation(ObjectInputValidation obj, + int prio) + throws NotActiveException, InvalidObjectException { + } + + public int read() throws IOException { + return dis.read(); + } + + public int read(byte[] data, int offset, int length) throws IOException { + return dis.read(data, offset, length); + } + + public int available() throws IOException { + return in.available(); + } + + public boolean readBoolean() throws IOException { + throw new IOException("Not Implemented"); + } + + public byte readByte() throws IOException { + throw new IOException("Not Implemented"); + } + public int readUnsignedByte() throws IOException { + throw new IOException("Not Implemented"); + } + public short readShort() throws IOException { + throw new IOException("Not Implemented"); + } + public int readUnsignedShort() throws IOException { + throw new IOException("Not Implemented"); + } + public char readChar() throws IOException { + throw new IOException("Not Implemented"); + } + public int readInt() throws IOException { + throw new IOException("Not Implemented"); + } + public long readLong() throws IOException { + throw new IOException("Not Implemented"); + } + public float readFloat() throws IOException { + throw new IOException("Not Implemented"); + } + public double readDouble() throws IOException { + throw new IOException("Not Implemented"); + } + public void readFully(byte[] data) throws IOException { + throw new IOException("Not Implemented"); + } + public void readFully(byte[] data, int offset, int size) throws IOException { + throw new IOException("Not Implemented"); + } + public int skipBytes(int len) throws IOException { + throw new IOException("Not Implemented"); + } + public String readLine() throws IOException { + throw new IOException("Not Implemented"); + } + public String readUTF() throws IOException { + throw new IOException("Not Implemented"); + } + + public void close() throws IOException { + in.close(); + } + /**********************************************************/ + + /** + * Provide access to the persistent fields read from the input stream. + */ + + public static class InternalGetField extends ObjectInputStream.GetField { + + /** + * Get the ObjectStreamClass that describes the fields in the stream. + */ + public ObjectStreamClass getObjectStreamClass() { + throw new Error("not implemented"); + } + + /** + * Return true if the named field is defaulted and has no value + * in this stream. + */ + public boolean defaulted(String name) + throws IOException, IllegalArgumentException + { + throw new Error("not implemented"); + //ObjectStreamField field = checkField(name, null); + } + + public boolean get(String name, boolean defvalue) + throws IOException, IllegalArgumentException { + throw new Error("not implemented"); + } + + public char get(String name, char defvalue) + throws IOException, IllegalArgumentException { + throw new Error("not implemented"); + } + + public byte get(String name, byte defvalue) + throws IOException, IllegalArgumentException { + throw new Error("not implemented"); + } + + public short get(String name, short defvalue) + throws IOException, IllegalArgumentException { + throw new Error("not implemented"); + } + + public int get(String name, int defvalue) + throws IOException, IllegalArgumentException { + throw new Error("not implemented"); + } + + public long get(String name, long defvalue) + throws IOException, IllegalArgumentException { + throw new Error("not implemented"); + } + + public float get(String name, float defvalue) + throws IOException, IllegalArgumentException { + throw new Error("not implemented"); + } + + public double get(String name, double defvalue) + throws IOException, IllegalArgumentException { + throw new Error("not implemented"); + } + + public Object get(String name, Object defvalue) + throws IOException, IllegalArgumentException { + throw new Error("not implemented"); + } + + public void read(ObjectInputStream in) + throws IOException, ClassNotFoundException { + } + } + + private Object currentObject; + private Class currentClassDescriptor; + + + + /****************************************************************/ + + /* CODE LIFTED FROM ObjectStreamClass constuctor. + * ObjectStreamClass.readObjectMethod is private. + * + * Look for the readObject method + * Set the accessible flag on it here. ObjectOutputStream + * will call it as necessary. + */ + static public Method getReadObjectMethod(final Class cl) { + + Method readObjectMethod = (Method) + java.security.AccessController.doPrivileged + (new java.security.PrivilegedAction() { + public Object run() { + Method m = null; + try { + Class[] args = {ObjectInputStream.class}; + m = cl.getDeclaredMethod("readObject", args); + int mods = m.getModifiers(); + // Method must be private and non-static + if (!Modifier.isPrivate(mods) || + Modifier.isStatic(mods)) { + m = null; + } else { + m.setAccessible(true); + } + } catch (NoSuchMethodException e) { + m = null; + } + return m; + } + }); + return readObjectMethod; + } + + /*************************************************************/ + + /* taken verbatim from ObjectInputStream. */ + static private void invokeMethod(final Object obj, final Method m, + final Object[] argList) + throws IOException + { + try { + java.security.AccessController.doPrivileged + (new java.security.PrivilegedExceptionAction() { + public Object run() throws InvocationTargetException, + java.lang.IllegalAccessException { + m.invoke(obj, argList); + return null; + } + }); + } catch (java.security.PrivilegedActionException e) { + Exception ex = e.getException(); + if (ex instanceof InvocationTargetException) { + Throwable t = + ((InvocationTargetException)ex).getTargetException(); + if (t instanceof IOException) + throw (IOException)t; + else if (t instanceof RuntimeException) + throw (RuntimeException) t; + else if (t instanceof Error) + throw (Error) t; + else + throw new Error("interal error"); + } else { + // IllegalAccessException cannot happen + } + } + } + + protected boolean enableResolveObject(boolean enable) + throws SecurityException + { + throw new Error("To be implemented"); + } + + private DataInputStream dis; +}; diff --git a/test/java/io/Serializable/subclass/XObjectOutputStream.java b/test/java/io/Serializable/subclass/XObjectOutputStream.java new file mode 100644 index 0000000000..4d18af00d3 --- /dev/null +++ b/test/java/io/Serializable/subclass/XObjectOutputStream.java @@ -0,0 +1,364 @@ +/* + * Copyright 1998-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. + */ + +import java.io.*; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.InvocationTargetException; +import java.security.*; + +public class XObjectOutputStream extends AbstractObjectOutputStream { + XObjectOutputStream(OutputStream out) throws IOException { + super(out); + } + + protected boolean enableReplaceObject(boolean enable) + { + throw new Error("not implemented"); + } + + protected void annotateClass(Class<?> cl) throws IOException { + } + + public void close() throws IOException{ + out.close(); + } + + protected Object replaceObject(Object obj) throws IOException { + return obj; + } + + protected void writeStreamHeader() throws IOException { + super.writeStreamHeader(); + } + + final protected void writeObjectOverride(Object obj) throws IOException { + Object prevCurrentObject = currentObject; + currentObject = obj; + System.out.println("writeObjectOverride(" + obj.toString() + ")"); + try { + // ** Preserving reference semantics. + // if (obj already serialized) { + // look up streamId for obj and write it into 'this' stream. + // return; + // } + // + // if (obj instanceof Class) { + // //Special processing for classes. + // //Might need to call this.annotateClass(obj.getClass()) + // //someday. + // return; + // } + // + // **Replacement semantics + // Object replacement = obj; + // if (enableReplace) + // replacement = this.writeReplace(obj); + // if (replacement instanceof Replaceable) + // replacement = ((Replaceable)replacement).replaceObject(this); + // if (obj != replacement) { + // //record that all future occurances of obj should be replaced + // //with replacement + // } + // + // if obj is Externalizeable { + // Object[] argList = {this}; + // invokeMethod(obj, writeExternalMethod, argList); + // else + + Method writeObjectMethod = getWriteObjectMethod(obj.getClass()); + + if (writeObjectMethod != null) { + Object[] arglist = {this}; + invokeMethod(obj, writeObjectMethod, arglist); + } else + defaultWriteObject(); + } finally { + currentObject = prevCurrentObject; + } + } + + /* Since defaultWriteObject() does not take the object to write as a parameter, + * implementation is required to store currentObject when writeObject is called. + */ + public void defaultWriteObject() throws IOException { + Object obj = currentObject; + System.out.println("XObjectOutputStream.defaultWriteObject(" + + obj.toString() + ")"); + + //In order to access package, private and protected fields, + //one needs to use Priviledged Access and be trusted code. + //This test will avoid that problem by only serializing public fields. + Field[] fields = obj.getClass().getFields(); + for (int i= 0; i < fields.length; i++) { + //Skip non-Serializable fields. + int mods = fields[i].getModifiers(); + if (Modifier.isStatic(mods) || Modifier.isTransient(mods)) + continue; + Class FieldType = fields[i].getType(); + if (FieldType.isPrimitive()) { + System.out.println("Field " + fields[i].getName() + + " has primitive type " + FieldType.toString()); + } else { + System.out.println("**Field " + fields[i].getName() + + " is an Object of type " + FieldType.toString()); + try { + writeObject(fields[i].get(obj)); + if (FieldType.isArray()) { + Object[] array = ((Object[]) fields[i].get(obj)); + Class componentType = FieldType.getComponentType(); + if (componentType.isPrimitive()) + System.out.println("Output " + array.length + " primitive elements of" + + componentType.toString()); + else { + System.out.println("Output " + array.length + " of Object elements of" + + componentType.toString()); + for (int k = 0; k < array.length; k++) { + writeObject(array[k]); + } + } + } + } catch (IllegalAccessException e) { + throw new IOException(e.getMessage()); + } + } + } + } + + public PutField putFields() throws IOException { + currentPutField = new InternalPutField(); + return currentPutField; + } + + public void writeFields() throws IOException { + currentPutField.write(this); + } + + static final class InternalPutField extends ObjectOutputStream.PutField { + String fieldName[]; + int intValue[]; + int next; + + InternalPutField() { + fieldName = new String[10]; + intValue = new int[10]; + next = 0; + } + /** + * Put the value of the named boolean field into the persistent field. + */ + public void put(String name, boolean value) { + } + + /** + * Put the value of the named char field into the persistent fields. + */ + public void put(String name, char value) { + } + + /** + * Put the value of the named byte field into the persistent fields. + */ + public void put(String name, byte value) { + } + + /** + * Put the value of the named short field into the persistent fields. + */ + public void put(String name, short value) { + } + + /** + * Put the value of the named int field into the persistent fields. + */ + public void put(String name, int value) { + if (next < fieldName.length) { + fieldName[next] = name; + intValue[next] = value; + next++; + } + } + + /** + * Put the value of the named long field into the persistent fields. + */ + public void put(String name, long value) { + } + + /** + * Put the value of the named float field into the persistent fields. + */ + public void put(String name, float value) { + } + + /** + * Put the value of the named double field into the persistent field. + */ + public void put(String name, double value) { + } + + /** + * Put the value of the named Object field into the persistent field. + */ + public void put(String name, Object value) { + } + + /** + * Write the data and fields to the specified ObjectOutput stream. + */ + public void write(ObjectOutput out) throws IOException { + for (int i = 0; i < next; i++) + System.out.println(fieldName[i] + "=" + intValue[i]); + } + }; + + + /** + * Writes a byte. This method will block until the byte is actually + * written. + * @param b the byte + * @exception IOException If an I/O error has occurred. + * @since JDK1.1 + */ + public void write(int data) throws IOException { + } + + /** + * Writes an array of bytes. This method will block until the bytes + * are actually written. + * @param b the data to be written + * @exception IOException If an I/O error has occurred. + * @since JDK1.1 + */ + public void write(byte b[]) throws IOException { + } + + /** + * Writes a sub array of bytes. + * @param b the data to be written + * @param off the start offset in the data + * @param len the number of bytes that are written + * @exception IOException If an I/O error has occurred. + * @since JDK1.1 + */ + public void write(byte b[], int off, int len) throws IOException { + } + + public void writeBoolean(boolean data) throws IOException { + } + + public void writeByte(int data) throws IOException { + } + + public void writeShort(int data) throws IOException { + } + + public void writeChar(int data) throws IOException { + } + public void writeInt(int data) throws IOException{} + public void writeLong(long data) throws IOException{} + public void writeFloat(float data) throws IOException{} + public void writeDouble(double data) throws IOException{} + public void writeBytes(String data) throws IOException{} + public void writeChars(String data) throws IOException{} + public void writeUTF(String data) throws IOException{} + public void reset() throws IOException {} + public void available() throws IOException {} + public void drain() throws IOException {} + + private Object currentObject = null; + private InternalPutField currentPutField; + + + /********************************************************************/ + + /* CODE LIFTED FROM ObjectStreamClass constuctor. + * ObjectStreamClass.writeObjectMethod is private. + * + * Look for the writeObject method + * Set the accessible flag on it here. + * Subclass of AbstractObjectOutputStream will call it as necessary. + */ + static public Method getWriteObjectMethod(final Class cl) { + + Method writeObjectMethod = (Method) + java.security.AccessController.doPrivileged + (new java.security.PrivilegedAction() { + public Object run() { + Method m = null; + try { + Class[] args = {ObjectOutputStream.class}; + m = cl.getDeclaredMethod("writeObject", args); + int mods = m.getModifiers(); + // Method must be private and non-static + if (!Modifier.isPrivate(mods) || + Modifier.isStatic(mods)) { + m = null; + } else { + m.setAccessible(true); + } + } catch (NoSuchMethodException e) { + m = null; + } + return m; + } + }); + return writeObjectMethod; + } + + /*************************************************************/ + + /* CODE LIFTED FROM ObjectOutputStream. */ + static private void invokeMethod(final Object obj, final Method m, + final Object[] argList) + throws IOException + { + try { + java.security.AccessController.doPrivileged + (new java.security.PrivilegedExceptionAction() { + public Object run() throws InvocationTargetException, + java.lang.IllegalAccessException { + m.invoke(obj, argList); + return null; + } + }); + } catch (java.security.PrivilegedActionException e) { + Exception ex = e.getException(); + if (ex instanceof InvocationTargetException) { + Throwable t = + ((InvocationTargetException)ex).getTargetException(); + if (t instanceof IOException) + throw (IOException)t; + else if (t instanceof RuntimeException) + throw (RuntimeException) t; + else if (t instanceof Error) + throw (Error) t; + else + throw new Error("interal error"); + } else { + // IllegalAccessException cannot happen + } + } + } +}; diff --git a/test/java/io/Serializable/subclass/run.sh b/test/java/io/Serializable/subclass/run.sh new file mode 100644 index 0000000000..ae7dd650ba --- /dev/null +++ b/test/java/io/Serializable/subclass/run.sh @@ -0,0 +1,30 @@ +# +# Copyright 1998 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. +# + +# +# @bug 4100915 +mkdir classes +javac -d classes *.java +java -classpath classes -Djava.policy=Allow.policy Test +# ENABLE next line when new method for invoking a main with a SecureClassLoader is known +#java -classpath classes -Djava.policy=NotAllow.policy Test -expectSecurityException diff --git a/test/java/io/Serializable/subclassGC/SubclassGC.java b/test/java/io/Serializable/subclassGC/SubclassGC.java new file mode 100644 index 0000000000..27474e0692 --- /dev/null +++ b/test/java/io/Serializable/subclassGC/SubclassGC.java @@ -0,0 +1,84 @@ +/* + * 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 6232010 + * @summary this test checks that replacing SoftCache class with ConcurrentMap + * in ObjectInputStream/ObjectOutputStream gives an opportunity to + * classes which are inherited from OIS and OOS and loaded through + * separete ClassLoaders be available for garbage collection + * + * @author Andrey Ozerov + * @run main/othervm/policy=security.policy SubclassGC + */ + +import java.io.*; +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.lang.reflect.Constructor; +import java.net.URL; +import java.net.URLClassLoader; + +public class SubclassGC { + private static final long TIMEOUT = 1000; + + public static final void main(String[] args) throws Exception { + System.err.println("\n Regression test for bug 6232010\n"); + if (System.getSecurityManager() == null) { + System.setSecurityManager(new SecurityManager()); + } + + ClassLoader systemLoader = ClassLoader.getSystemClassLoader(); + ClassLoader loader = new URLClassLoader(((URLClassLoader) systemLoader).getURLs(), + systemLoader.getParent()); + Class<? extends ObjectOutputStream> cl = + Class.forName(SubclassOfOOS.class.getName(), false, + loader).asSubclass(ObjectOutputStream.class); + + Constructor<? extends ObjectOutputStream> cons = + cl.getConstructor(OutputStream.class); + + OutputStream os = new ByteArrayOutputStream(); + ObjectOutputStream obj = cons.newInstance(os); + + final ReferenceQueue<Class<?>> queue = new ReferenceQueue<Class<?>>(); + WeakReference<Class<?>> ref = new WeakReference<Class<?>>(cl, queue); + + cl = null; + obj = null; + loader = null; + cons = null; + systemLoader = null; + + System.err.println("\nStart Garbage Collection right now"); + System.gc(); + + Reference<? extends Class<?>> dequeued = queue.remove(TIMEOUT); + if (dequeued == ref) { + System.err.println("\nTEST PASSED"); + } else { + throw new Error(); + } + } +} diff --git a/test/java/io/Serializable/subclassGC/SubclassOfOOS.java b/test/java/io/Serializable/subclassGC/SubclassOfOOS.java new file mode 100644 index 0000000000..a289ceacaa --- /dev/null +++ b/test/java/io/Serializable/subclassGC/SubclassOfOOS.java @@ -0,0 +1,34 @@ +/* + * 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. + */ + +import java.io.*; + +public class SubclassOfOOS extends ObjectOutputStream { + public SubclassOfOOS(OutputStream os) throws IOException { + super(os); + } + + public SubclassOfOOS() throws IOException { + super(); + } +} diff --git a/test/java/io/Serializable/subclassGC/security.policy b/test/java/io/Serializable/subclassGC/security.policy new file mode 100644 index 0000000000..2997345648 --- /dev/null +++ b/test/java/io/Serializable/subclassGC/security.policy @@ -0,0 +1,9 @@ +grant codeBase "file:${{java.ext.dirs}}/*" { + permission java.security.AllPermission; +}; + +grant { + permission java.lang.RuntimePermission "createClassLoader"; + permission java.lang.RuntimePermission "getClassLoader"; +}; + diff --git a/test/java/io/Serializable/superclassDataLoss/A.java b/test/java/io/Serializable/superclassDataLoss/A.java new file mode 100644 index 0000000000..51280374b8 --- /dev/null +++ b/test/java/io/Serializable/superclassDataLoss/A.java @@ -0,0 +1,34 @@ +/* + * Copyright 2000 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. + */ + +/* + * @bug 4325590 + * @summary Verify that superclass data is not lost when incoming superclass + * descriptor is matched with local class that is not a superclass of + * the deserialized instance's class. + */ + +public class A implements java.io.Serializable { + protected final int i; + protected A(int i) { this.i = i; } +} diff --git a/test/java/io/Serializable/superclassDataLoss/B.java b/test/java/io/Serializable/superclassDataLoss/B.java new file mode 100644 index 0000000000..5e2878dfa4 --- /dev/null +++ b/test/java/io/Serializable/superclassDataLoss/B.java @@ -0,0 +1,40 @@ +/* + * Copyright 2000 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. + */ + +/* + * @bug 4325590 + * @summary Verify that superclass data is not lost when incoming superclass + * descriptor is matched with local class that is not a superclass of + * the deserialized instance's class. + */ + +public class B extends A implements Runnable { + public B() { super(0xDEADBEEF); } + + // verify superclass data still present + public void run() { + if (i != 0xDEADBEEF) { + throw new Error("superclass data erased"); + } + } +} diff --git a/test/java/io/Serializable/superclassDataLoss/Test.java b/test/java/io/Serializable/superclassDataLoss/Test.java new file mode 100644 index 0000000000..1b50093b99 --- /dev/null +++ b/test/java/io/Serializable/superclassDataLoss/Test.java @@ -0,0 +1,79 @@ +/* + * Copyright 2000 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. + */ + +/* + * @bug 4325590 + * @summary Verify that superclass data is not lost when incoming superclass + * descriptor is matched with local class that is not a superclass of + * the deserialized instance's class. + */ + +import java.io.*; +import java.net.*; + +class MixedSuperclassStream extends ObjectInputStream { + MixedSuperclassStream(InputStream in) throws IOException { super(in); } + + protected Class resolveClass(ObjectStreamClass desc) + throws IOException, ClassNotFoundException + { + // resolve A's classdesc to class != B's superclass + String name = desc.getName(); + if (name.equals("A")) { + return Class.forName(name, true, Test.ldr1); + } else if (name.equals("B")) { + return Class.forName(name, true, Test.ldr2); + } else { + return super.resolveClass(desc); + } + } +} + +public class Test { + + static URLClassLoader ldr1, ldr2; + static { + try { + ldr1 = new URLClassLoader(new URL[] { new URL("file:cb1.jar") }); + ldr2 = new URLClassLoader(new URL[] { new URL("file:cb2.jar") }); + } catch (MalformedURLException ex) { + throw new Error(); + } + } + + public static void main(String[] args) throws Exception { + Runnable a = (Runnable) Class.forName("B", true, ldr1).newInstance(); + a.run(); + + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(a); + oout.close(); + + ByteArrayInputStream bin = + new ByteArrayInputStream(bout.toByteArray()); + ObjectInputStream oin = new MixedSuperclassStream(bin); + a = (Runnable) oin.readObject(); + a.run(); + } +} diff --git a/test/java/io/Serializable/superclassDataLoss/run.sh b/test/java/io/Serializable/superclassDataLoss/run.sh new file mode 100644 index 0000000000..a2bdd1d349 --- /dev/null +++ b/test/java/io/Serializable/superclassDataLoss/run.sh @@ -0,0 +1,50 @@ +# +# Copyright 2000 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 4325590 +# @summary Verify that superclass data is not lost when incoming superclass +# descriptor is matched with local class that is not a superclass of +# the deserialized instance's class. + +if [ "${TESTJAVA}" = "" ] +then + echo "TESTJAVA not set. Test cannot execute. Failed." +exit 1 +fi + +if [ "${TESTSRC}" = "" ] +then + TESTSRC="." +fi + +set -ex + +${TESTJAVA}/bin/javac -d . ${TESTSRC}/A.java ${TESTSRC}/B.java +${TESTJAVA}/bin/jar cf cb1.jar A.class B.class +cp cb1.jar cb2.jar +rm -f A.class B.class + +${TESTJAVA}/bin/javac -d . ${TESTSRC}/Test.java +${TESTJAVA}/bin/java Test +rm -f *.class *.jar diff --git a/test/java/io/Serializable/survivePrematureClose/SurvivePrematureClose.java b/test/java/io/Serializable/survivePrematureClose/SurvivePrematureClose.java new file mode 100644 index 0000000000..d2e3a0cee3 --- /dev/null +++ b/test/java/io/Serializable/survivePrematureClose/SurvivePrematureClose.java @@ -0,0 +1,82 @@ +/* + * 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 4502808 + * @summary Verify that if the custom serialization method (i.e., readExternal, + * writeExternal, readObject or writeObject) of an object closes the + * stream it is passed, (de)serialization of that object can still + * complete. + */ + +import java.io.*; + +class A implements Externalizable { + + public A() {} + + public void writeExternal(ObjectOutput out) throws IOException { + out.writeInt(0); + out.close(); + } + + public void readExternal(ObjectInput in) + throws IOException, ClassNotFoundException + { + in.readInt(); + in.close(); + } +} + +class B implements Serializable { + + private void writeObject(ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + out.close(); + } + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + in.defaultReadObject(); + in.close(); + } +} + +public class SurvivePrematureClose { + + public static void main(String[] args) throws Exception { + writeRead(new A()); + writeRead(new B()); + } + + static void writeRead(Object obj) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(obj); + oout.close(); + ObjectInputStream oin = new ObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + oin.readObject(); + } +} diff --git a/test/java/io/Serializable/typeSafeEnum/TypeSafeEnum.java b/test/java/io/Serializable/typeSafeEnum/TypeSafeEnum.java new file mode 100644 index 0000000000..a22dd021b2 --- /dev/null +++ b/test/java/io/Serializable/typeSafeEnum/TypeSafeEnum.java @@ -0,0 +1,158 @@ +/* + * Copyright 1998 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 4140729 + * @summary Verify that writeReplace & readResolve are called by serialization. + * readResolve is used to maintain the invariant that the enums + * of TypeSafeEnum are singletons. + */ +import java.io.*; + +public class TypeSafeEnum implements Serializable, ObjectInputValidation { + private static int numWriteObject = 0; + private static int numReadObject = 0; + + + private String value; + private TypeSafeEnum(String value) { + this.value = value; + } + + final public static TypeSafeEnum FIRST = new TypeSafeEnum("First"); + final public static TypeSafeEnum SECOND = new TypeSafeEnum("Second"); + final public static TypeSafeEnum THIRD = new TypeSafeEnum("Third"); + static int numReadResolve = 0; + static int numWriteReplace = 0; + static boolean verbose = false; + + + private Object writeReplace() throws IOException { + numWriteReplace++; + if (verbose) { + System.out.println("TypeSafeEnum.writeReplace() " + + this.toString()); + } + return this; + } + + private Object readResolve() throws IOException { + numReadResolve++; + if (verbose) { + System.out.println("readResolve called on " + this.toString()); + } + if (value.equals(FIRST.value)) { + return FIRST; + } else if (value.equals(SECOND.value)) { + return SECOND; + } else if (value.equals(THIRD.value)) { + return THIRD; + } else { + //unknown type safe enum + return this; + } + } + + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + numReadObject++; + in.defaultReadObject(); + if (verbose) { + System.out.println("TypeSafeEnum.readObject() " + this.toString()); + } + if (value == null) { + in.registerValidation(this, 0); + } + } + + public void validateObject() throws InvalidObjectException { + // only top level case has null for value, validate. + if (numWriteObject != 4) { + throw new Error("Expected 4 calls to writeObject, only " + + numWriteObject + " made"); + } + if (numReadObject != 4) { + throw new Error("Expected 4 calls to readObject, only " + + numReadObject + " made"); + } + if (numWriteReplace != 4) { + throw new Error("Expected 4 calls to writeReplace, only " + + numWriteReplace + " made"); + } + if (numReadResolve != 4) { + throw new Error("Expected 4 calls to readResolve, only " + + numReadResolve + " made"); + } + } + + private void writeObject(ObjectOutputStream out) throws IOException + { + numWriteObject++; + out.defaultWriteObject(); + if (verbose) { + System.out.println("TypeSafeEnum.writeObject() " + + this.toString()); + } + } + + public String toString() { + return super.toString() + " value=" + value; + } + + public static void main(String args[]) + throws IOException, ClassNotFoundException + { + if (args.length > 0 && args[0].equals("-verbose")) + verbose = true; + + TypeSafeEnum[] writeArray = new TypeSafeEnum[7]; + writeArray[0] = FIRST; + writeArray[1] = SECOND; + writeArray[2] = THIRD; + writeArray[3] = FIRST; + writeArray[4] = SECOND; + writeArray[5] = THIRD; + writeArray[6] = new TypeSafeEnum("Third"); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream os = new ObjectOutputStream(baos); + os.writeObject(writeArray); + os.close(); + + TypeSafeEnum[] readArray; + ObjectInputStream in = + new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())); + readArray = (TypeSafeEnum[])in.readObject(); + in.close(); + + for (int i= 0; i < writeArray.length - 1 ; i++) { + if (writeArray[i] != readArray[i]) { + throw new Error("Serializa/deserialize did not preserve " + + "singleton for " + + readArray[i].toString() + + " and " + writeArray[i].toString()); + } + } + } +}; diff --git a/test/java/io/Serializable/typeStringBackRef/TypeStringBackRef.java b/test/java/io/Serializable/typeStringBackRef/TypeStringBackRef.java new file mode 100644 index 0000000000..8eb28523b0 --- /dev/null +++ b/test/java/io/Serializable/typeStringBackRef/TypeStringBackRef.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 4405949 + * @summary Verify that back references are used when writing multiple type + * strings that are equal() to one another. + */ + +import java.io.*; + +public class TypeStringBackRef implements Serializable { + + String a, b, c, d, e, f, g; + + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(ObjectStreamClass.lookup(TypeStringBackRef.class)); + oout.close(); + if (bout.size() != 116) { + throw new Error("Wrong data length: " + bout.size()); + } + } +} diff --git a/test/java/io/Serializable/underlyingOutputStreamException/UnderlyingOutputStreamException.java b/test/java/io/Serializable/underlyingOutputStreamException/UnderlyingOutputStreamException.java new file mode 100644 index 0000000000..740ce09406 --- /dev/null +++ b/test/java/io/Serializable/underlyingOutputStreamException/UnderlyingOutputStreamException.java @@ -0,0 +1,56 @@ +/* + * 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 Verify that if ObjectOutputStream's underlying OutputStream throws + * an IOException, the original IOException (not a + * StreamCorruptedException) will be thrown to the writing thread. + */ + +import java.io.*; + +class OriginalIOException extends IOException { +} + +class BrokenOutputStream extends OutputStream { + boolean broken = false; + + public void write(int b) throws IOException { + if (broken) { + throw new OriginalIOException(); + } + } +} + +public class UnderlyingOutputStreamException { + public static void main(String[] args) throws Exception { + BrokenOutputStream bout = new BrokenOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + bout.broken = true; + try { + oout.writeObject("foo"); + throw new Error(); + } catch (OriginalIOException ex) { + } + } +} diff --git a/test/java/io/Serializable/unnamedPackageSwitch/A.java b/test/java/io/Serializable/unnamedPackageSwitch/A.java new file mode 100644 index 0000000000..113236b4ab --- /dev/null +++ b/test/java/io/Serializable/unnamedPackageSwitch/A.java @@ -0,0 +1,36 @@ +/* + * Copyright 2000 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. + */ + +/* + * @bug 4348213 + * @summary Verify that deserialization allows an incoming class descriptor + * representing a class in the default package to be resolved to a + * local class with the same name in a non-default package, and + * vice-versa. + */ + +package pkg; + +public class A implements java.io.Serializable { + private static final long serialVersionUID = 0L; +} diff --git a/test/java/io/Serializable/unnamedPackageSwitch/Test.java b/test/java/io/Serializable/unnamedPackageSwitch/Test.java new file mode 100644 index 0000000000..b21ff8724b --- /dev/null +++ b/test/java/io/Serializable/unnamedPackageSwitch/Test.java @@ -0,0 +1,66 @@ +/* + * Copyright 2000 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. + */ + +/* + * @bug 4348213 + * @summary Verify that deserialization allows an incoming class descriptor + * representing a class in the unnamed package to be resolved to a + * local class with the same name in a named package, and vice-versa. + */ + +import java.io.*; + +class A implements Serializable { + private static final long serialVersionUID = 0L; +} + +class TestObjectInputStream extends ObjectInputStream { + TestObjectInputStream(InputStream in) throws IOException { super(in); } + protected Class resolveClass(ObjectStreamClass desc) + throws IOException, ClassNotFoundException + { + String name = desc.getName(); + if (name.equals("A")) { + return pkg.A.class; + } else if (name.equals("pkg.A")) { + return A.class; + } else { + return super.resolveClass(desc); + } + } +} + +public class Test { + public static void main(String[] args) throws Exception { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + oout.writeObject(new A()); + oout.writeObject(new pkg.A()); + oout.close(); + + ObjectInputStream oin = new TestObjectInputStream( + new ByteArrayInputStream(bout.toByteArray())); + oin.readObject(); + oin.readObject(); + } +} diff --git a/test/java/io/Serializable/unnamedPackageSwitch/run.sh b/test/java/io/Serializable/unnamedPackageSwitch/run.sh new file mode 100644 index 0000000000..3cf235d252 --- /dev/null +++ b/test/java/io/Serializable/unnamedPackageSwitch/run.sh @@ -0,0 +1,44 @@ +# +# Copyright 2000 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 4348213 +# @summary Verify that deserialization allows an incoming class descriptor +# representing a class in the unnamed package to be resolved to a +# local class with the same name in a named package, and vice-versa. + +if [ "${TESTJAVA}" = "" ] +then + echo "TESTJAVA not set. Test cannot execute. Failed." +exit 1 +fi + +if [ "${TESTSRC}" = "" ] +then + TESTSRC="." +fi + +set -ex + +${TESTJAVA}/bin/javac -d . ${TESTSRC}/A.java ${TESTSRC}/Test.java +${TESTJAVA}/bin/java Test diff --git a/test/java/io/Serializable/unresolvedClassDesc/Foo.java b/test/java/io/Serializable/unresolvedClassDesc/Foo.java new file mode 100644 index 0000000000..d44df1bcf3 --- /dev/null +++ b/test/java/io/Serializable/unresolvedClassDesc/Foo.java @@ -0,0 +1,32 @@ +/* + * 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. + */ + +/* + * @bug 4482471 + * @summary Verify that even if an incoming ObjectStreamClass is not resolvable + * to a local class, the ObjectStreamClass object itself is still + * deserializable (without incurring a ClassNotFoundException). + */ + +public class Foo implements java.io.Serializable { +} diff --git a/test/java/io/Serializable/unresolvedClassDesc/Read.java b/test/java/io/Serializable/unresolvedClassDesc/Read.java new file mode 100644 index 0000000000..1d07db1bab --- /dev/null +++ b/test/java/io/Serializable/unresolvedClassDesc/Read.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. + */ + +/* + * @bug 4482471 + * @summary Verify that even if an incoming ObjectStreamClass is not resolvable + * to a local class, the ObjectStreamClass object itself is still + * deserializable (without incurring a ClassNotFoundException). + */ + +import java.io.*; + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("tmp.ser")); + oin.readObject(); + oin.readObject(); + try { + oin.readObject(); + throw new Error("read of Foo instance succeeded"); + } catch (ClassNotFoundException ex) { + } + try { + oin.readObject(); + throw new Error("indirect read of Foo instance succeeded"); + } catch (ClassNotFoundException ex) { + } + } +} diff --git a/test/java/io/Serializable/unresolvedClassDesc/Write.java b/test/java/io/Serializable/unresolvedClassDesc/Write.java new file mode 100644 index 0000000000..e4f44b352e --- /dev/null +++ b/test/java/io/Serializable/unresolvedClassDesc/Write.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 4482471 + * + * @clean Write Read Foo + * @build Write Foo + * @run main Write + * @clean Write Foo + * @build Read + * @run main Read + * @clean Read + * + * @summary Verify that even if an incoming ObjectStreamClass is not resolvable + * to a local class, the ObjectStreamClass object itself is still + * deserializable (without incurring a ClassNotFoundException). + */ + +import java.io.*; + +public class Write { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("tmp.ser")); + ObjectStreamClass desc = ObjectStreamClass.lookup(Foo.class); + Foo foo = new Foo(); + oout.writeObject(desc); + oout.writeObject(new Object[]{ desc }); // test indirect references + oout.writeObject(foo); + oout.writeObject(new Object[]{ foo }); + oout.close(); + } +} diff --git a/test/java/io/Serializable/unshared/Read.java b/test/java/io/Serializable/unshared/Read.java new file mode 100644 index 0000000000..9997e15fde --- /dev/null +++ b/test/java/io/Serializable/unshared/Read.java @@ -0,0 +1,99 @@ +/* + * Copyright 2000 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. + */ + +/* + * @bug 4311991 + * @summary Test ObjectOutputStream.writeUnshared/readUnshared functionality. + */ + +import java.io.*; + +class Bar implements Serializable { + private static final long serialVersionUID = 0L; + private static final ObjectStreamField[] serialPersistentFields = + new ObjectStreamField[] { + new ObjectStreamField("obj", Object.class, true) + }; + Object obj; + + Bar(Object obj) { + this.obj = obj; + } +} + +public class Read { + public static void main(String[] args) throws Exception { + String str = "foo"; + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + + oout.writeObject(str); + oout.writeObject(str); + oout.close(); + + byte[] buf = bout.toByteArray(); + ByteArrayInputStream bin = new ByteArrayInputStream(buf); + ObjectInputStream oin = new ObjectInputStream(bin); + oin.readUnshared(); + try { + oin.readObject(); + throw new Error(); + } catch (ObjectStreamException ex) { + } + + bin = new ByteArrayInputStream(buf); + oin = new ObjectInputStream(bin); + oin.readUnshared(); + try { + oin.readUnshared(); + throw new Error(); + } catch (ObjectStreamException ex) { + } + + bin = new ByteArrayInputStream(buf); + oin = new ObjectInputStream(bin); + oin.readObject(); + try { + oin.readUnshared(); + throw new Error(); + } catch (ObjectStreamException ex) { + } + + // read in objects written by Write.main() + oin = new ObjectInputStream(new FileInputStream("tmp.ser")); + oin.readObject(); + try { + oin.readObject(); + throw new Error(); + } catch (ObjectStreamException ex) { + } + + oin = new ObjectInputStream(new FileInputStream("tmp.ser")); + oin.readObject(); + try { + oin.readUnshared(); + throw new Error(); + } catch (ObjectStreamException ex) { + } + } +} diff --git a/test/java/io/Serializable/unshared/Write.java b/test/java/io/Serializable/unshared/Write.java new file mode 100644 index 0000000000..f5832aec0a --- /dev/null +++ b/test/java/io/Serializable/unshared/Write.java @@ -0,0 +1,110 @@ +/* + * Copyright 2000 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 4311991 + * + * @clean Write Read Foo Bar + * @compile Write.java + * @run main Write + * @clean Write Read Foo Bar + * @compile Read.java + * @run main Read + * + * @summary Test ObjectOutputStream.writeUnshared/readUnshared functionality. + */ + +import java.io.*; + +class Foo implements Serializable { + private static final ObjectStreamField[] serialPersistentFields = + new ObjectStreamField[] { + new ObjectStreamField("shared1", String.class), + new ObjectStreamField("shared2", String.class, false), + new ObjectStreamField("unshared1", String.class, true), + new ObjectStreamField("unshared2", String.class, true) + }; + + String shared1, shared2, unshared1, unshared2; + + Foo() { + shared1 = shared2 = unshared1 = unshared2 = "foo"; + } +} + +class Bar implements Serializable { + private static final long serialVersionUID = 0L; + Object obj; + + Bar(Object obj) { + this.obj = obj; + } +} + +public class Write { + public static void main(String[] args) throws Exception { + String str1 = "foo"; + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + + oout.writeObject(str1); + oout.writeObject(str1); + oout.writeUnshared(str1); + oout.writeUnshared(str1); + oout.writeObject(new Foo()); + oout.close(); + + ByteArrayInputStream bin = + new ByteArrayInputStream(bout.toByteArray()); + ObjectInputStream oin = new ObjectInputStream(bin); + str1 = (String) oin.readObject(); + if (oin.readObject() != str1) { + throw new Error(); + } + String str2 = (String) oin.readObject(); + String str3 = (String) oin.readObject(); + if (str2 == str1 || str3 == str1 || str2 == str3) { + throw new Error(); + } + if (! (str1.equals(str2) && str1.equals(str3))) { + throw new Error(); + } + + Foo foo = (Foo) oin.readObject(); + if ((foo.shared1 != foo.shared2) || + (foo.shared1 == foo.unshared1) || + (foo.shared1 == foo.unshared2) || + (foo.shared2 == foo.unshared1) || + (foo.shared2 == foo.unshared2) || + (foo.unshared1 == foo.unshared2)) + { + throw new Error(); + } + + // write out object to be read by Read.main() + oout = new ObjectOutputStream(new FileOutputStream("tmp.ser")); + oout.writeObject(new Bar(str1)); + oout.writeObject(str1); + oout.close(); + } +} diff --git a/test/java/io/Serializable/userRWObjError/UserRWObjError.java b/test/java/io/Serializable/userRWObjError/UserRWObjError.java new file mode 100644 index 0000000000..7d9d25cabe --- /dev/null +++ b/test/java/io/Serializable/userRWObjError/UserRWObjError.java @@ -0,0 +1,63 @@ +/* + * Copyright 1997 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 4082734 + * @summary Ensure that Error exception is propogated from Serializable class' + * readObject & writeObject method. + */ +import java.io.*; + +/* + * Failure output: + * joef/scarry>java UserRWObjError + * Test FAILED: + * java.lang.ClassCastException: java.lang.OutOfMemoryError + * at java.io.ObjectOutputStream.invokeObjectWriter(ObjectOutputStream.java:1379) + * at java.io.ObjectOutputStream.outputObject(ObjectOutputStream.java:755) + * at java.io.ObjectOutputStream.writeObject(Objec + */ + +public class UserRWObjError implements java.io.Serializable { + + public static void main(String[] args) throws Exception { + try { + UserRWObjError obj = new UserRWObjError(); + ObjectOutputStream out = + new ObjectOutputStream(new ByteArrayOutputStream()); + out.writeObject(obj); + } catch (ClassCastException e) { + throw e; + } catch (OutOfMemoryError e) { + System.err.println("Test PASSED:"); + e.printStackTrace(); + } catch (Exception e) { + System.err.println("An Unexpected exception occurred:"); + throw e; + } + } + + private void writeObject(ObjectOutputStream out) throws IOException { + throw new OutOfMemoryError(); + } +} diff --git a/test/java/io/Serializable/validate/Validate.java b/test/java/io/Serializable/validate/Validate.java new file mode 100644 index 0000000000..da8e0aef18 --- /dev/null +++ b/test/java/io/Serializable/validate/Validate.java @@ -0,0 +1,98 @@ +/* + * Copyright 1998 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 4094892 +@summary Verify that an object is not validated more than once during deserialization. + +*/ + +import java.io.*; +import java.util.Date; + +public class Validate { + public static void main(String[] args) throws Exception { + try { + // Write class out + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutput out = new ObjectOutputStream(baos); + + Class1 c1 = new Class1(11, 22); + out.writeObject(c1); + out.writeObject(new Class1(22,33)); + out.writeObject(new Date()); + out.writeObject(new Date()); + out.writeObject(new Date()); + out.writeObject(new Date()); + out.flush(); + out.close(); + + // Read it back + ByteArrayInputStream bais = + new ByteArrayInputStream(baos.toByteArray()); + ObjectInputStream in = new ObjectInputStream(bais); + Class1 cc1 = (Class1) in.readObject(); + Class1 cc2 = (Class1) in.readObject(); + System.out.println("date: " + in.readObject()); + System.out.println("date: " + in.readObject()); + System.out.println("date: " + in.readObject()); + System.out.println("date: " + in.readObject()); + in.close(); + + System.out.println(cc1.a + " " + cc1.b); + System.out.println(cc2.a + " " + cc2.b); + } catch (IOException e) { + e.printStackTrace(); + throw e; + } catch (ClassNotFoundException e) { + e.printStackTrace(); + throw e; + } + } +} + +class Class1 implements Serializable, ObjectInputValidation { + int a, b; + transient int validates; + + public Class1(int aa, int bb) { + a = aa; + b = bb; + } + public void validateObject() throws InvalidObjectException { + if (validates > 0) + throw new Error("Implementation error: Re-validating object " + this.toString()); + validates++; + + System.out.println("Validating " + this.toString()); + if (a > b) { + throw new InvalidObjectException("Fields cannot be negative"); + } + } + private void readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException { + in.registerValidation(this, 1); + in.defaultReadObject(); + } +} diff --git a/test/java/io/Serializable/verifyDynamicObjHandleTable/VerifyDynamicObjHandleTable.java b/test/java/io/Serializable/verifyDynamicObjHandleTable/VerifyDynamicObjHandleTable.java new file mode 100644 index 0000000000..729a6c1736 --- /dev/null +++ b/test/java/io/Serializable/verifyDynamicObjHandleTable/VerifyDynamicObjHandleTable.java @@ -0,0 +1,74 @@ +/* + * Copyright 1998 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 + * @clean A + * @bug 4146453 + * @summary Test that regrow of object/handle table of ObjectOutputStream works. + */ + +import java.io.*; +import java.util.HashSet; +import java.util.Iterator; + +class A implements Serializable { + static HashSet writeObjectExtent = new HashSet(); + + private void writeObject(ObjectOutputStream out) throws IOException { + if (writeObjectExtent.contains(this)) { + throw new InvalidObjectException("writeObject: object " + + this.toString() + " has already " + + "been serialized and should " + + "have be serialized by reference."); + } else { + writeObjectExtent.add(this); + } + out.defaultWriteObject(); + } + + A() { + } +} + +public class VerifyDynamicObjHandleTable { + public static void main(String args[]) + throws IOException, ClassNotFoundException + { + ObjectOutputStream out = + new ObjectOutputStream(new ByteArrayOutputStream(3000)); + for (int i = 0; i < 1000; i++) { + out.writeObject(new A()); + } + + // Make sure that serialization subsystem does not + // allow writeObject to be called on any objects that + // have already been serialized. These objects should be + // written out by reference. + Iterator iter = A.writeObjectExtent.iterator(); + while (iter.hasNext()) { + out.writeObject(iter.next()); + } + + out.close(); + } +} diff --git a/test/java/io/Serializable/writeObjectMemory/WriteObjectMemory.java b/test/java/io/Serializable/writeObjectMemory/WriteObjectMemory.java new file mode 100644 index 0000000000..ec620d1d12 --- /dev/null +++ b/test/java/io/Serializable/writeObjectMemory/WriteObjectMemory.java @@ -0,0 +1,75 @@ +/* + * Copyright 1998-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 + * @clean A WriteObjectMemory + * @run main WriteObjectMemory + * @bug 4146453 5011410 + * @summary Test that regrow of object/handle table of ObjectOutputStream works. + */ + +import java.io.*; +import java.util.HashSet; +import java.util.Iterator; + +class A implements Serializable { + static HashSet writeObjectExtent = new HashSet(); + + private void writeObject(ObjectOutputStream out) throws IOException { + if (writeObjectExtent.contains(this)) { + throw new InvalidObjectException("writeObject: object " + + this.toString() + " has already " + + "been serialized and should " + + "have be serialized by reference."); + } else { + writeObjectExtent.add(this); + } + out.defaultWriteObject(); + } + + A() { + } +} + +public class WriteObjectMemory { + public static void main(String args[]) + throws IOException, ClassNotFoundException + { + ObjectOutputStream out = + new ObjectOutputStream(new ByteArrayOutputStream(3000)); + for (int i = 0; i < 1000; i++) { + out.writeObject(new A()); + } + + // Make sure that serialization subsystem does not + // allow writeObject to be called on any objects that + // have already been serialized. These objects should be + // written out by reference. + Iterator iter = A.writeObjectExtent.iterator(); + while (iter.hasNext()) { + out.writeObject(iter.next()); + } + + out.close(); + } +} diff --git a/test/java/io/Serializable/writeReplace/WriteReplace.java b/test/java/io/Serializable/writeReplace/WriteReplace.java new file mode 100644 index 0000000000..8322a8ef19 --- /dev/null +++ b/test/java/io/Serializable/writeReplace/WriteReplace.java @@ -0,0 +1,85 @@ +/* + * Copyright 2000 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 proper functioning of class-defined writeReplace methods. + */ + +import java.io.*; + +public class WriteReplace { + + static class ReplaceMe implements Serializable { + private Object obj; + private boolean writeReplaceCalled = false; + + public ReplaceMe(Object obj) { + this.obj = obj; + } + + private Object writeReplace() throws ObjectStreamException { + if (writeReplaceCalled) { + throw new Error("multiple calls to writeReplace"); + } + writeReplaceCalled = true; + return obj; + } + } + + public static void main(String[] args) throws Exception { + final int nobjs = 10; + final int nrounds = 10; + + Object common = "foo"; + ReplaceMe[] objs = new ReplaceMe[nobjs]; + for (int i = 0; i < nobjs; i++) { + objs[i] = new ReplaceMe(common); + } + + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ObjectOutputStream oout = new ObjectOutputStream(bout); + for (int i = 0; i < nrounds; i++) { + for (int j = 0; j < nobjs; j++) { + oout.writeObject(objs[j]); + } + } + + oout.flush(); + ByteArrayInputStream bin = + new ByteArrayInputStream(bout.toByteArray()); + ObjectInputStream oin = new ObjectInputStream(bin); + common = null; + + for (int i = 0; i < nrounds; i++) { + for (int j = 0; j < nobjs; j++) { + if (common == null) { + common = oin.readObject(); + } else { + if (oin.readObject() != common) { + throw new Error("incorrect replacement object"); + } + } + } + } + } +} diff --git a/test/java/io/Serializable/wrongReturnTypes/Read.java b/test/java/io/Serializable/wrongReturnTypes/Read.java new file mode 100644 index 0000000000..41dbe58745 --- /dev/null +++ b/test/java/io/Serializable/wrongReturnTypes/Read.java @@ -0,0 +1,76 @@ +/* + * 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. + */ + +/* + * @bug 4337857 + * @summary Verify that custom serialization methods declared with incorrect + * return types are not invoked. + */ + +import java.io.*; + +class A implements Serializable { + private static final long serialVersionUID = 0L; + + static boolean readObjectNoDataCalled; + + private Object readObjectNoData() throws ObjectStreamException { + readObjectNoDataCalled = true; + return null; + } +} + +class B extends A { + private static final long serialVersionUID = 0L; + + static boolean readObjectCalled; + static boolean readResolveCalled; + + private Integer readObject(ObjectInputStream in) + throws IOException, ClassNotFoundException + { + readObjectCalled = true; + in.defaultReadObject(); + return null; + } + + private B readResolve() throws ObjectStreamException { + readResolveCalled = true; + return this; + } +} + +public class Read { + public static void main(String[] args) throws Exception { + ObjectInputStream oin = + new ObjectInputStream(new FileInputStream("tmp.ser")); + B b = (B) oin.readObject(); + if (A.readObjectNoDataCalled) { + throw new Error("readObjectNoData with wrong return type called"); + } else if (B.readObjectCalled) { + throw new Error("readObject with wrong return type called"); + } else if (B.readResolveCalled) { + throw new Error("readResolve with wrong return type called"); + } + } +} diff --git a/test/java/io/Serializable/wrongReturnTypes/Write.java b/test/java/io/Serializable/wrongReturnTypes/Write.java new file mode 100644 index 0000000000..2dcd75245c --- /dev/null +++ b/test/java/io/Serializable/wrongReturnTypes/Write.java @@ -0,0 +1,71 @@ +/* + * 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 4337857 + * + * @clean Write Read A B + * @compile Write.java + * @run main Write + * @clean Write Read A B + * @compile Read.java + * @run main Read + * + * @summary Verify that custom serialization methods declared with incorrect + * return types are not invoked. + */ + +import java.io.*; + +class B implements Serializable { + private static final long serialVersionUID = 0L; + + static boolean writeObjectCalled; + static boolean writeReplaceCalled; + + private Object writeObject(ObjectOutputStream out) throws IOException { + writeObjectCalled = true; + out.defaultWriteObject(); + return null; + } + + private B writeReplace() throws ObjectStreamException { + writeReplaceCalled = true; + return this; + } +} + +public class Write { + public static void main(String[] args) throws Exception { + ObjectOutputStream oout = + new ObjectOutputStream(new FileOutputStream("tmp.ser")); + oout.writeObject(new B()); + oout.close(); + + if (B.writeObjectCalled) { + throw new Error("writeObject with wrong return type called"); + } else if (B.writeReplaceCalled) { + throw new Error("writeReplace with wrong return type called"); + } + } +} diff --git a/test/java/io/StreamTokenizer/Comment.java b/test/java/io/StreamTokenizer/Comment.java new file mode 100644 index 0000000000..88453c77fd --- /dev/null +++ b/test/java/io/StreamTokenizer/Comment.java @@ -0,0 +1,81 @@ +/* + * Copyright 1998 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 4106810 4027740 4078997 4097738 + @summary Make sure StreamTokenizer will correctly + parse different types of comments in input. + */ + + +import java.io.*; + +public class Comment { + + public static void main(String[] args) throws Exception { + + File f = new File(System.getProperty("test.src", "."), "input.txt"); + + int slashIsCommentStart = 1; + int slashSlashComment = 2; + int slashStarComment = 4; + + for (int i = 0; i < 8 ; i++) { + StreamTokenizer st = new StreamTokenizer(new FileReader(f)); + + /* decide the state of this run */ + boolean slashCommentFlag = ((i & slashIsCommentStart) != 0); + boolean slashSlashCommentFlag = ((i & slashSlashComment) != 0); + boolean slashStarCommentFlag = ((i & slashStarComment) != 0); + + /* set the initial state of the tokenizer */ + if (!slashCommentFlag) { + st.ordinaryChar('/'); + } + st.slashSlashComments(slashSlashCommentFlag); + st.slashStarComments(slashStarCommentFlag); + + /* now go throgh the input file */ + while(st.nextToken() != StreamTokenizer.TT_EOF) + { + String token = st.sval; + if (token == null) { + continue; + } else { + if ((token.compareTo("Error1") == 0) && slashStarCommentFlag) { + throw new Exception("Failed to pass one line C comments!"); + } + if ((token.compareTo("Error2") == 0) && slashStarCommentFlag) { + throw new Exception("Failed to pass multi line C comments!"); + } + if ((token.compareTo("Error3") == 0) && slashSlashCommentFlag) { + throw new Exception("Failed to pass C++ comments!"); + } + if ((token.compareTo("Error4") == 0) && slashCommentFlag) { + throw new Exception("Failed to pass / comments!"); + } + } + } + } + } +} diff --git a/test/java/io/StreamTokenizer/NullConstruct.java b/test/java/io/StreamTokenizer/NullConstruct.java new file mode 100644 index 0000000000..9567e9859c --- /dev/null +++ b/test/java/io/StreamTokenizer/NullConstruct.java @@ -0,0 +1,43 @@ +/* + * Copyright 1998 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 4022204 + @summary Check for null input in the constructor. + */ + + +import java.io.*; + +public class NullConstruct { + + public static void main(String[] args) throws Exception { + try { + Reader in = null; + StreamTokenizer st = new StreamTokenizer(in); + throw new Exception + ("Failed test: constructor didn't catch null input"); + } catch (NullPointerException e) { + } + } +} diff --git a/test/java/io/StreamTokenizer/QuoteTest.java b/test/java/io/StreamTokenizer/QuoteTest.java new file mode 100644 index 0000000000..cc2a77f9c6 --- /dev/null +++ b/test/java/io/StreamTokenizer/QuoteTest.java @@ -0,0 +1,61 @@ +/* + * Copyright 1999 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 4218879 + * @summary On encountering a quoted string in the stream, nextToken() must + * return '\"' and StreamTokenizer.toString() must return the actual quoted + * string. + */ + + +import java.io.*; + +public class QuoteTest { + + static String testStr = "token1 token2 \"The test string\" token4"; + public static void main(String[] args) throws Exception { + + System.err.println("Parsing String: " + testStr); + StreamTokenizer st = new StreamTokenizer(new StringReader(testStr)); + boolean foundToken = false; + String matchStr = null; + while(st.nextToken() != StreamTokenizer.TT_EOF) + { + switch (st.ttype) { + case '\"': + foundToken = true; + matchStr = st.toString(); + System.err.println("Found token " + matchStr); + break; + default: + System.err.println("Found token " + st); + break; + } + } + if (!foundToken) + throw new RuntimeException("Test failed to recognize Quote type"); + if (!matchStr.equals("Token[The test string], line 1")) + throw new RuntimeException("Test failed parse quoted string"); + } +} diff --git a/test/java/io/StreamTokenizer/ReadAhead.java b/test/java/io/StreamTokenizer/ReadAhead.java new file mode 100644 index 0000000000..cdfb4baf2c --- /dev/null +++ b/test/java/io/StreamTokenizer/ReadAhead.java @@ -0,0 +1,137 @@ +/* + * Copyright 1999 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 4150737 + @summary Ensure that StreamTokenizer does not read any further ahead + than is absolutely necessary + */ + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StreamTokenizer; +import java.io.IOException; + + +public class ReadAhead { + + + /* An InputStream subclass that cannot read past a given limit */ + static private class LimitedInputStream extends InputStream { + + private String input; + private int limit; /* Do not allow input[limit] to be read */ + private int next = 0; + + public LimitedInputStream(String input, int limit) { + this.input = input; + this.limit = limit; + } + + public int read() throws IOException { + if (next >= limit) + throw new IOException("Attempted to read too far in stream"); + return input.charAt(next++); + } + + } + + + /* A Reader subclass that cannot read past a given limit */ + static private class LimitedReader extends Reader { + + private String input; + private int limit; /* Do not allow input[limit] to be read */ + private int next = 0; + + public LimitedReader(String input, int limit) { + this.input = input; + this.limit = limit; + } + + public int read() throws IOException { + if (next >= limit) + throw new IOException("Attempted to read too far in stream"); + return input.charAt(next++); + } + + public int read(char[] b, int off, int len) throws IOException { + int top = off + len; + int i; + for (i = off; i < top; i++) { + int c = read(); + if (c < 0) break; + b[i] = (char)c; + } + return i - off; + } + + public void close() { } + + } + + + /* Interface for objects that can create new StreamTokenizers + with a given limited input */ + static private interface StreamTokenizerMaker { + public StreamTokenizer create(String input, int limit); + } + + static private void fail(String why) throws Exception { + throw new Exception(why); + } + + private static void test(StreamTokenizer st) throws Exception { + st.eolIsSignificant(true); + int tt = st.nextToken(); + if (tt != StreamTokenizer.TT_WORD) fail("expected TT_WORD"); + if (!st.sval.equals("foo")) fail("expected word token \"foo\""); + tt = st.nextToken(); + if (tt != StreamTokenizer.TT_EOL) fail("expected TT_EOL"); + } + + private static void test(StreamTokenizerMaker stm) throws Exception { + test(stm.create("foo\nx", 4)); + test(stm.create("foo\r\nx", 4)); + } + + + public static void main(String[] args) throws Exception { + + /* InputStream case */ + test(new StreamTokenizerMaker() { + public StreamTokenizer create(String input, int limit) { + return new StreamTokenizer(new LimitedInputStream(input, limit)); + }}); + + /* Reader case */ + test(new StreamTokenizerMaker() { + public StreamTokenizer create(String input, int limit) { + return new StreamTokenizer(new LimitedReader(input, limit)); + }}); + + } + +} diff --git a/test/java/io/StreamTokenizer/Reset.java b/test/java/io/StreamTokenizer/Reset.java new file mode 100644 index 0000000000..041a01df04 --- /dev/null +++ b/test/java/io/StreamTokenizer/Reset.java @@ -0,0 +1,49 @@ +/* + * Copyright 1998 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 4090992 + @summary Make sure StreamTokenizer.nextToken works correctly when + the underlying stream is reset after the end of stream has + reached. + */ + +import java.io.*; + +public class Reset { + + public static void main (String argv[]) throws Exception { + + StringBufferInputStream in = new StringBufferInputStream("[ #"); + StreamTokenizer scan = new StreamTokenizer(in); + + scan.nextToken(); + scan.nextToken(); + in.reset(); + int token = scan.nextToken(); + if (token != '[') { + throw new Exception + ("Test failed: should get token [, but get " + token); + } + } +} diff --git a/test/java/io/StreamTokenizer/input.txt b/test/java/io/StreamTokenizer/input.txt new file mode 100644 index 0000000000..9a9a2913dc --- /dev/null +++ b/test/java/io/StreamTokenizer/input.txt @@ -0,0 +1,10 @@ +/* Error1: not recognizing slashStar comment */ + +/* Error2 : not recognizing + * Error2: slashStar + * Error2: comments + */ + +// Error3: not recognizing slashSlash comments + +/ Error4: not recognizing slash comments diff --git a/test/java/io/StringReader/ClosedReady.java b/test/java/io/StringReader/ClosedReady.java new file mode 100644 index 0000000000..73b0b54039 --- /dev/null +++ b/test/java/io/StringReader/ClosedReady.java @@ -0,0 +1,51 @@ +/* + * Copyright 1998 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 4090254 + @summary Test StringReader ready method*/ + +import java.io.*; + +/** + * This class tests to see if StringReader generates + * an exception if ready is called on closed stream + */ + +public class ClosedReady { + + public static void main( String argv[] ) throws Exception { + + StringReader in = new StringReader("aaaaaaaaaaaaaaa"); + in.read(); + in.close(); + + try { + in.ready(); // IOException should be thrown here + throw new RuntimeException(" No exception during read on closed stream"); + } + catch (IOException e) { + System.err.println("Test passed: IOException is thrown"); + } + } +} diff --git a/test/java/io/StringReader/NegativeMarkLimit.java b/test/java/io/StringReader/NegativeMarkLimit.java new file mode 100644 index 0000000000..3bf85d0335 --- /dev/null +++ b/test/java/io/StringReader/NegativeMarkLimit.java @@ -0,0 +1,44 @@ +/* + * Copyright 1998 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 4153020 + @summary Negative marklimit value should throw an exception + */ + +import java.io.*; + +public class NegativeMarkLimit { + + public static void main( String argv[] ) throws Exception { + + StringReader in = new StringReader("aaaaaaaaaaaaaaa"); + try { + in.mark(-1); + } catch (IllegalArgumentException e){ + return; + } + throw new + Exception(" Negative marklimit value should throw an exception"); + } +} diff --git a/test/java/io/StringReader/Skip.java b/test/java/io/StringReader/Skip.java new file mode 100644 index 0000000000..68b6ea4e3a --- /dev/null +++ b/test/java/io/StringReader/Skip.java @@ -0,0 +1,65 @@ +/* + * 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 4175312 + * @summary Test StringReader.skip with negative param + */ + +import java.io.*; + +public class Skip { + public static void main( String argv[] ) throws Exception { + StringReader in = new StringReader("1234567"); + + // Skip forward and read + if (in.skip(3) != 3) + throw new RuntimeException("skip(3) failed"); + if (in.read() != '4') + throw new RuntimeException("post skip read failure"); + + // Skip backward and read + if (in.skip(-2) != -2) + throw new RuntimeException("skip(-2) failed"); + if (in.read() != '3') + throw new RuntimeException("read failed after negative skip"); + + // Attempt to skip backward past the beginning and read + if (in.skip(-6) != -3) + throw new RuntimeException("skip(-6) failed"); + if (in.read() != '1') + throw new RuntimeException("read after skip past beginning failed"); + + // Skip beyond the end + if (in.skip(30) != 6) + throw new RuntimeException("skip(30) failed"); + if (in.read() != -1) + throw new RuntimeException("read at EOF failed"); + + // Test after reaching end of string + if (in.skip(30) != 0) + throw new RuntimeException("skip(30) failed"); + if (in.skip(-30) != 0) + throw new RuntimeException("skip(30) failed"); + } +} diff --git a/test/java/io/StringWriter/NegativeBufferSize.java b/test/java/io/StringWriter/NegativeBufferSize.java new file mode 100644 index 0000000000..7942852b4f --- /dev/null +++ b/test/java/io/StringWriter/NegativeBufferSize.java @@ -0,0 +1,52 @@ +/* + * Copyright 1998 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 4153021 + @summary Ensure that constructor does not accept negative buffer sizes. +*/ + + + +import java.io.*; + +public class NegativeBufferSize { + + public static void main(String argv[]) throws Exception { + try { + MyStringWriter s = new MyStringWriter(-1); + } catch(IllegalArgumentException e){ + return; + } + throw new Exception("StringWriter constructor must not accept < 0 " + + " buffer sizes"); + } +} + +class MyStringWriter extends StringWriter { + + MyStringWriter(int bufsize){ + super(bufsize); + } + +} diff --git a/test/java/io/SystemInAvailable.java b/test/java/io/SystemInAvailable.java new file mode 100644 index 0000000000..3cb3c51684 --- /dev/null +++ b/test/java/io/SystemInAvailable.java @@ -0,0 +1,46 @@ +/* + * Copyright 1998-1999 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 4135795 + @summary Make sure that System.in.available() works + when System.in is the keyboard + @run ignore This test requires console (/dev/tty) input, which is not + supported by the current harness + */ + + +import java.io.*; + +public class SystemInAvailable { + + public static void main(String[] args) throws Exception { + byte[] b = new byte[1024]; + System.out.print("Press <enter>: "); + System.out.flush(); + System.in.read(b); + int a = System.in.available(); + if (a != 0) throw new Exception("System.in.available() ==> " + a); + } + +} diff --git a/test/java/io/Unicode.java b/test/java/io/Unicode.java new file mode 100644 index 0000000000..7375a0d8ab --- /dev/null +++ b/test/java/io/Unicode.java @@ -0,0 +1,151 @@ +/* + * Copyright 1999-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 4241440 4220470 + @summary Test the various two-byte Unicode encodings + + @run main Unicode UnicodeLittle little true + @run main Unicode UnicodeBig big true + @run main Unicode UnicodeLittleUnmarked little false + @run main Unicode UnicodeBigUnmarked big false + @run main Unicode iso-10646-ucs-2 big false + @run main Unicode x-utf-16be big false + @run main Unicode x-utf-16le little false + */ + +import java.io.ByteArrayOutputStream; + + +public class Unicode { + + static final int BOM_HIGH = 0xfe; + static final int BOM_LOW = 0xff; + + static final int BIG = 0; + static final int LITTLE = 1; + + + static void fail(String enc, String msg, int e0, int e1, int b0, int b1) + throws Exception + { + throw new Exception(enc + ": " + msg + + ": Expected " + + Integer.toHexString(e0) + + " " + Integer.toHexString(e1) + + ", got " + + Integer.toHexString(b0) + + " " + Integer.toHexString(b1)); + } + + + /* Chars to bytes */ + static void encode(String enc, int byteOrder, boolean markExpected) + throws Exception + { + String s = "abc"; + byte[] b = s.getBytes(enc); + int i = 0; + if (markExpected) { + int b0 = b[i++] & 0xff; + int b1 = b[i++] & 0xff; + int e0 = 0, e1 = 0; + if (byteOrder == BIG) { + e0 = BOM_HIGH; + e1 = BOM_LOW; + } else if (byteOrder == LITTLE) { + e0 = BOM_LOW; + e1 = BOM_HIGH; + } + if ((b0 != e0) || (b1 != e1)) + fail(enc, "Incorrect or missing byte-order mark", + e0, e1, b0, b1); + } + for (int j = 0; j < s.length(); j++) { + char c = s.charAt(j); + int b0 = b[i++] & 0xff; + int b1 = b[i++] & 0xff; + int e0 = 0, e1 = 0; + if (byteOrder == BIG) { + e0 = c >> 8; + e1 = c & 0xff; + } else if (byteOrder == LITTLE) { + e0 = c & 0xff; + e1 = c >> 8; + } + if ((b0 != e0) || (b1 != e1)) + fail(enc, "Incorrect content at index " + j, + e0, e1, b0, b1); + } + } + + + /* Bytes to chars */ + static void decode(String enc, int byteOrder, boolean markit) + throws Exception + { + String s = "abc"; + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + if (markit) { + if (byteOrder == BIG) { + bo.write(BOM_HIGH); + bo.write(BOM_LOW); + } else if (byteOrder == LITTLE) { + bo.write(BOM_LOW); + bo.write(BOM_HIGH); + } + } + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (byteOrder == BIG) { + bo.write(c >> 8); + bo.write(c & 0xff); + } else if (byteOrder == LITTLE) { + bo.write(c & 0xff); + bo.write(c >> 8); + } + } + byte[] b = bo.toByteArray(); + String s2 = new String(b, enc); + if (!s.equals(s2)) + throw new Exception(enc + ": Decode error"); + } + + + public static void main(String[] args) throws Exception { + String enc = args[0]; + String bos = args[1]; + boolean markExpected = Boolean.valueOf(args[2]).booleanValue(); + int byteOrder = -1; + if (bos.equals("big")) byteOrder = BIG; + if (bos.equals("little")) byteOrder = LITTLE; + + /* We run each test twice in order to check the repeatability of + String.getBytes and String(byte[], String) (4220470) */ + encode(enc, byteOrder, markExpected); + encode(enc, byteOrder, markExpected); + decode(enc, byteOrder, markExpected); + decode(enc, byteOrder, markExpected); + } + +} diff --git a/test/java/io/Writer/Append.java b/test/java/io/Writer/Append.java new file mode 100644 index 0000000000..78f0c83f47 --- /dev/null +++ b/test/java/io/Writer/Append.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 5030623 + * @summary Basic test of all append() methods in Writer and inherited classes. + */ + +import java.io.*; +import java.lang.reflect.*; + +public class Append { + // append methods throw IOException + private static Class [] io = { + Writer.class, BufferedWriter.class, FilterWriter.class, + OutputStreamWriter.class, FileWriter.class + }; + + // append methods don't throw IOException + private static Class [] nio = { + CharArrayWriter.class, StringWriter.class, PrintWriter.class, + PrintStream.class + }; + + public static void main(String [] args) { + for (int i = 0; i < io.length; i++) + test(io[i], true); + for (int i = 0; i < nio.length; i++) + test(nio[i], false); + } + + private static void test(Class c, boolean io) { + try { + Class [] cparams = { char.class }; + test(c.getMethod("append", cparams), io); + Class [] csparams = { CharSequence.class }; + test(c.getMethod("append", csparams), io); + } catch (NoSuchMethodException x) { + throw new RuntimeException("No append method found"); + } + } + + private static void test(Method m, boolean io) { + Class [] ca = m.getExceptionTypes(); + boolean found = false; + for (int i = 0; i < ca.length; i++) { + if (ca[i].equals(IOException.class)) { + found = true; + break; + } + } + + if (found && !io) + throw new RuntimeException("Unexpected IOException"); + if (!found && io) + throw new RuntimeException("Missing IOException"); + } +} diff --git a/test/java/io/Writer/WriteFromString.java b/test/java/io/Writer/WriteFromString.java new file mode 100644 index 0000000000..14bb5cc880 --- /dev/null +++ b/test/java/io/Writer/WriteFromString.java @@ -0,0 +1,119 @@ +/* + * Copyright 1998 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 4071765 + @summary Bug in the parameter of str.getChars called in write +*/ + + + +import java.io.*; + +public class WriteFromString { + + + public static void main(String argv[]) throws Exception { + LocalStringWriter lsw = new LocalStringWriter(); + boolean result = true; + + String testString = "Testing of what gets written"; + // Should write out at offset 2 for length 4 i.e."stin" + lsw.write(testString, 1, 4); + String res = lsw.toString(); + if (!res.equals("esti")) { + result = false; + System.err.println("Writer.write is incorrect:" + res); + } + + // Same bug in stringwriter as well + StringWriter sw = new StringWriter(); + sw.write(testString, 1, 4); + res = sw.toString(); + String ss = testString.substring(1,4); + System.out.println("Substring = "+ss); + if (!res.equals("esti")) { + System.err.println("StringWriter.write is incorrect:" + res); + result = false; + } + if (!result) { + throw new Exception("Writer.write method is incorrect."); + } + } + +} + +/** + * A copy of StringWriter to test the write method in Writer + */ + +class LocalStringWriter extends Writer { + + private StringBuffer buf; + + /** + * Create a new string writer, using the default initial string-buffer + * size. + */ + public LocalStringWriter() { + buf = new StringBuffer(); + lock = buf; + } + + /** + * Write a portion of an array of characters. + * + * @param cbuf Array of characters + * @param off Offset from which to start writing characters + * @param len Number of characters to write + */ + public void write(char cbuf[], int off, int len) { + if ((off < 0) || (off > cbuf.length) || (len < 0) || + ((off + len) > cbuf.length) || ((off + len) < 0)) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) { + return; + } + buf.append(cbuf, off, len); + } + + /** + * Write a string. + */ + public void write(String str) { + buf.append(str); + } + + /** + * Return the buffer's current value as a string. + */ + public String toString() { + return buf.toString(); + } + + + public void flush(){ } + + public void close(){ } + +} diff --git a/test/java/io/Writer/WriteParams.java b/test/java/io/Writer/WriteParams.java new file mode 100644 index 0000000000..b70c1a0a46 --- /dev/null +++ b/test/java/io/Writer/WriteParams.java @@ -0,0 +1,93 @@ +/* + * Copyright 1998 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 4127657 + * @summary Check for correct handling of parameters to + * XXXXWriter.write(b, off, len). + * + */ + +import java.io.*; + +public class WriteParams { + static int values[] = {Integer.MIN_VALUE, -1, 0, 1, 4, 16, 31, + 32, 33, Integer.MAX_VALUE}; + static char b[][] = {null, new char[32]}; + + static void test(Writer wtr) throws Exception { + int i = 0, j = 0, k = 0; + boolean nullPtr = false, indexOutBnd = false; + + for (i = 0; i < b.length; i++) { + for ( j = 0; j < values.length; j++) { + for ( k = 0; k < values.length; k++) { + + nullPtr = (b[i] == null); + + int bufLen = nullPtr ? 0 : b[i].length; + indexOutBnd = ((values[j] + values[k]) < 0) + || (values[j] < 0) + || (values[j] > bufLen) + || (values[k] < 0) + || ((values[j] + values[k]) > bufLen); + + try { + wtr.write(b[i], values[j], values[k]); + } catch (NullPointerException e) { + if (!nullPtr) { + throw new Exception + ("should not throw NullPointerException"); + } + continue; + } catch (IndexOutOfBoundsException e) { + if (!indexOutBnd) { + throw new Exception + ("should not throw IndexOutOfBoundsException"); + } + continue; + } + + if (nullPtr || indexOutBnd) { + throw new Exception("Should have thrown an exception"); + } + } + } + } + } + + public static void main(String args[]) throws Exception{ + StringWriter sw = new StringWriter(); + + test(sw); + + test(new BufferedWriter(sw)); + + test(new CharArrayWriter()); + + test(new OutputStreamWriter(System.err)); + + test(new PipedWriter(new PipedReader())); + } +} diff --git a/test/java/io/charStreams/ABCInputStream.java b/test/java/io/charStreams/ABCInputStream.java new file mode 100644 index 0000000000..87c1097721 --- /dev/null +++ b/test/java/io/charStreams/ABCInputStream.java @@ -0,0 +1,93 @@ +/* + * Copyright 1997 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. + */ + +/**/ + +import java.io.*; + + +public class ABCInputStream extends InputStream { + + int len; + int chunk; + int count = 0; + char next = firstChar(); + + ABCInputStream(int len) { + this(len, len); + } + + ABCInputStream(int len, int chunk) { + this.len = len; + this.chunk = chunk; + } + + static char firstChar() { + return 'a'; + } + + static char nextChar(char c) { + if (c == 'z') + return '0'; + else if (c == '9') + return 'a'; + else + return (char)(c + 1); + } + + public int read() { + if (count >= len) + return -1; + char c = next; + next = nextChar(c); + count++; + return (byte) c; + } + + public int read(byte buf[], int off, int len) { + int n = (len > chunk) ? chunk : len; + for (int i = off; i < off + n; i++) { + int c = read(); + if (c == -1) { + if (i > off) + return i - off; + else + return -1; + } + buf[i] = (byte) c; + } + return n; + } + + public int available() { + int remaining = len - count; + return (remaining > chunk) ? chunk : remaining; + } + + public void close() throws IOException { + if (len == 0) + throw new IOException("Already closed"); + len = 0; + } + +} diff --git a/test/java/io/charStreams/ABCOutputStream.java b/test/java/io/charStreams/ABCOutputStream.java new file mode 100644 index 0000000000..66bfb2920d --- /dev/null +++ b/test/java/io/charStreams/ABCOutputStream.java @@ -0,0 +1,63 @@ +/* + * Copyright 1997-2000 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. + */ + +/**/ + +import java.io.*; + + +public class ABCOutputStream extends OutputStream { + + int len; + int count = 0; + char next = ABCInputStream.firstChar(); + + ABCOutputStream(int len) { + this.len = len; + } + + public void write(int c) throws IOException { + if (count >= len) + throw new IOException("Wrote too many characters"); + if (c != next) + throw new IOException("Wrong character written: " + + "Expected '" + next + "', " + + "got '" + (char)c + "'"); + next = ABCInputStream.nextChar(next); + count++; + } + + public void write(byte buf[], int off, int len) throws IOException { + for (int i = off; i < off + len; i++) + write(buf[i]); + } + + public void close() throws IOException { + if (len == 0) + throw new IOException("Already closed"); + else if (count < len) + throw new IOException("Wrote too few characters"); + len = 0; + } + +} diff --git a/test/java/io/charStreams/ABCReader.java b/test/java/io/charStreams/ABCReader.java new file mode 100644 index 0000000000..9af08402b2 --- /dev/null +++ b/test/java/io/charStreams/ABCReader.java @@ -0,0 +1,71 @@ +/* + * Copyright 1997 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. + */ + +/**/ + +import java.io.Reader; + + +class ABCReader extends Reader { + + int len; + int count = 0; + char next = 'a'; + + ABCReader(int len) { + this.len = len; + } + + public int read() { + if (count >= len) + return -1; + char c = next; + if (next == 'z') + next = '0'; + else if (next == '9') + next = 'a'; + else + next++; + count++; + return c; + } + + public int read(char cbuf[], int off, int len) { + for (int i = off; i < off + len; i++) { + int c = read(); + if (c == -1) { + if (i > off) + return i - off; + else + return -1; + } + cbuf[i] = (char) c; + } + return len; + } + + public void close() { + len = 0; + } + +} diff --git a/test/java/io/charStreams/BCat.java b/test/java/io/charStreams/BCat.java new file mode 100644 index 0000000000..4f31409199 --- /dev/null +++ b/test/java/io/charStreams/BCat.java @@ -0,0 +1,51 @@ +/* + * Copyright 1997 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 Simple stream-copy test for BufferedReader and BufferedWriter + */ + +import java.io.*; + +public class BCat { + + public static int count = 10000; + public static int chunk = 512; + + public static void main(String[] args) throws IOException { + BufferedReader in = new BufferedReader(new InputStreamReader(new ABCInputStream(count, chunk)), + 1025); + Writer out = new BufferedWriter(new OutputStreamWriter(new ABCOutputStream(count))); + char[] buf = new char[119]; + int n; + + while ((n = in.read(buf)) != -1) { + out.write(buf, 0, n); + System.err.print(" " + n); + } + in.close(); + out.close(); + System.err.println(); + } + +} diff --git a/test/java/io/charStreams/BufferSizes.java b/test/java/io/charStreams/BufferSizes.java new file mode 100644 index 0000000000..e7f19ef122 --- /dev/null +++ b/test/java/io/charStreams/BufferSizes.java @@ -0,0 +1,76 @@ +/* + * Copyright 1997 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 interaction of buffer sizes in buffered char and byte streams + */ + +import java.io.*; + +public class BufferSizes { + + static int min = 90; + static int max = 110; + static int chunk = 100; + static int count = 1000; + + static void runBytes() throws IOException { + for (int sz = min; sz <= max; sz++) { + System.err.println(sz); + InputStream in + = new BufferedInputStream(new ABCInputStream(count, chunk), sz); + OutputStream out + = new BufferedOutputStream(new ABCOutputStream(count), sz); + int n; + byte[] buf = new byte[sz]; + while ((n = in.read(buf, 0, sz)) != -1) + out.write(buf, 0, n); + in.close(); + out.close(); + } + } + + + static void runChars() throws IOException { + for (int sz = min; sz <= max; sz++) { + System.err.println(sz); + Reader in + = new BufferedReader(new InputStreamReader(new ABCInputStream(count, chunk)), sz); + Writer out + = new BufferedWriter(new OutputStreamWriter(new ABCOutputStream(count)), sz); + int n; + char[] cbuf = new char[sz]; + + while ((n = in.read(cbuf, 0, sz)) != -1) + out.write(cbuf, 0, n); + in.close(); + out.close(); + } + } + + public static void main(String[] args) throws IOException { + runBytes(); + runChars(); + } + +} diff --git a/test/java/io/charStreams/BufferedReaderMark.java b/test/java/io/charStreams/BufferedReaderMark.java new file mode 100644 index 0000000000..a38b332a43 --- /dev/null +++ b/test/java/io/charStreams/BufferedReaderMark.java @@ -0,0 +1,135 @@ +/* + * Copyright 1997 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 General tests for BufferedReader.mark + */ + +import java.io.*; + + +public class BufferedReaderMark { + + static int bufferSize = -1; + static int inputSize = -1; + + static String d2(int n) { + String s = Integer.toString(n); + if (s.length() < 2) + return s + " "; + else + return s; + } + + static void fail(String s) { + throw new RuntimeException(s); + } + + public static void main(String[] args) throws Exception { + PrintStream log = System.err; + + if (bufferSize == -1) + bufferSize = 7; + if (inputSize == -1) + inputSize = bufferSize * 3; + + try { + Reader in = new BufferedReader(new ABCReader(inputSize), bufferSize); + char buf[] = new char[bufferSize]; + if (in.read(buf) != bufferSize) + fail("Read failed"); + in.reset(); + fail("reset() didn't throw"); + } + catch (IOException x) { + if (x.getMessage().equals("Stream not marked")) + log.println("Unmarked-stream test OK"); + else + fail(x.toString()); + } + + boolean err = false; + try { + Reader in = new BufferedReader(new ABCReader(inputSize), bufferSize); + char buf[] = new char[bufferSize]; + if (in.read() == -1) + fail("Read 1 failed"); + in.mark(bufferSize); + while (in.read() != -1); + in.reset(); + fail("reset() didn't throw"); + } + catch (IOException x) { + if (x.getMessage().equals("Mark invalid")) { + err = true; + log.println("Invalid-mark test OK"); + } + else { + log.println("Invalid-mark test failed: " + x); + fail(x.toString()); + } + } + if (! err) + fail("Invalid-mark test failed: Exception not thrown"); + + int c; + for (int off = 0; off < bufferSize * 2; off++) { + for (int ra = 0; ra <= inputSize + 2; ra++) { + Reader in = new BufferedReader(new ABCReader(inputSize), bufferSize); + + log.print(d2(off) + ", " + d2(ra) + " mark: "); + for (int i = 0; i < off; i++) { + if ((c = in.read()) == -1) { + log.print("<EOF>"); + break; + } + log.print((char) c); + } + in.mark(ra); + for (int i = 0; i < ra; i++) { + if ((c = in.read()) == -1) { + log.print("<EOF>"); + break; + } + log.print((char) c); + } + log.println(); + + log.print(d2(off) + ", " + d2(ra) + " reset: "); + in.reset(); + for (int i = 0; i < off; i++) + log.print(' '); + for (;;) { + if ((c = in.read()) == -1) { + log.print("<EOF>"); + break; + } + log.print((char) c); + } + log.println(); + + } + } + } + +} diff --git a/test/java/io/charStreams/Cat.java b/test/java/io/charStreams/Cat.java new file mode 100644 index 0000000000..8f4a4b81da --- /dev/null +++ b/test/java/io/charStreams/Cat.java @@ -0,0 +1,48 @@ +/* + * Copyright 1997 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 Simple stream-copy test for InputStreamReader & OutputStreamWriter + */ + +import java.io.*; + +public class Cat { + + public static int count = 10000; + + public static void main(String[] args) throws IOException { + Reader in = new InputStreamReader(new ABCInputStream(count)); + Writer out = new OutputStreamWriter(new ABCOutputStream(count)); + int c; + + while ((c = in.read()) != -1) { + out.write(c); + System.err.print((char)c); + } + in.close(); + out.close(); + System.err.println(); + } + +} diff --git a/test/java/io/charStreams/CharGenerator.java b/test/java/io/charStreams/CharGenerator.java new file mode 100644 index 0000000000..3b3eaae1ca --- /dev/null +++ b/test/java/io/charStreams/CharGenerator.java @@ -0,0 +1,53 @@ +/* + * Copyright 1997 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. + */ + +/**/ + +import java.io.*; + + +public class CharGenerator { + + private IntGenerator r; + int min = 0, max = 0xffff; + + public CharGenerator(IntGenerator r) { + this.r = r; + } + + public CharGenerator(IntGenerator r, int min, int max) { + this.r = r; + this.min = min; + this.max = max; + } + + public char next() { + char c; + do + c = (char) (r.next(max - min) + min); + while ((c == '\r') || (c == '\n') + || ((c >= 0xd800) && (c <= 0xdfff)) + || (c == 0xfffe)); + return c; + } +} diff --git a/test/java/io/charStreams/IntGenerator.java b/test/java/io/charStreams/IntGenerator.java new file mode 100644 index 0000000000..2c410dda60 --- /dev/null +++ b/test/java/io/charStreams/IntGenerator.java @@ -0,0 +1,46 @@ +/* + * Copyright 1997 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. + */ + +/**/ + +import java.util.Random; + + +public class IntGenerator { + + Random r; + + public IntGenerator() { + r = new Random(0); + } + + public int next(int max) { + if (max <= 0) + return 0; + int x = r.nextInt(); + if (x < 0) + x = 0 - x; + return x % (max + 1); + } + +} diff --git a/test/java/io/charStreams/LineGenerator.java b/test/java/io/charStreams/LineGenerator.java new file mode 100644 index 0000000000..0eb0cabc66 --- /dev/null +++ b/test/java/io/charStreams/LineGenerator.java @@ -0,0 +1,84 @@ +/* + * Copyright 1997 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. + */ + +/**/ + + +public class LineGenerator { + + IntGenerator ig; + StringGenerator sg; + int limit; + + public LineGenerator(IntGenerator ig, StringGenerator sg, int limit) { + this.ig = ig; + this.sg = sg; + this.limit = limit; + } + + public LineGenerator(IntGenerator ig) { + this.ig = ig; + this.sg = new StringGenerator(ig); + this.limit = -1; + } + + private char prevTerminator = 0; + private int count = 0; + public String lineTerminator; + + public String next() { + if ((count >= limit) && (limit >= 0)) + return null; + + String l = sg.next(); + + /* Avoid "\r\n" sequences + in which the '\n' terminates a blank line */ + int len = l.length(); + int t; + do + t = ig.next(2); + while ((prevTerminator == '\r') && (len == 0) && (t == 0)); + + String ts; + switch (t) { + case 0: + ts = "\n"; + prevTerminator = '\n'; + break; + case 1: + ts = "\r"; + prevTerminator = '\r'; + break; + case 2: + default: + ts = "\r\n"; + prevTerminator = '\n'; + break; + } + + count++; + lineTerminator = ts; + return l; + } +} diff --git a/test/java/io/charStreams/LineLengths.java b/test/java/io/charStreams/LineLengths.java new file mode 100644 index 0000000000..c4aaa8bf18 --- /dev/null +++ b/test/java/io/charStreams/LineLengths.java @@ -0,0 +1,62 @@ +/* + * Copyright 1997 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 Check line lengths using all recognized line-termination sequences + */ + +import java.io.*; + + +public class LineLengths { + + static String enc = "UTF8"; + static String inEnc = null; + static String outEnc = null; + + public static void main(String[] args) throws Exception { + PrintWriter log + = new PrintWriter(new OutputStreamWriter(System.err), true); + + if (inEnc == null) + inEnc = enc; + if (outEnc == null) + outEnc = enc; + + PipedOutputStream uo = new PipedOutputStream(); + PipedInputStream ui = new PipedInputStream(uo); + PipedOutputStream co = new PipedOutputStream(); + PipedInputStream ci = new PipedInputStream(co); + + BufferedWriter w = new BufferedWriter(new OutputStreamWriter(co, outEnc)); + BufferedReader r = new BufferedReader(new InputStreamReader(ci, inEnc)); + + Thread t1 = new Thread(new LineLengthsSource(uo, w, log)); + Thread t2 = new Thread(new LineSink(ui, r, log)); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + +} diff --git a/test/java/io/charStreams/LineLengthsSource.java b/test/java/io/charStreams/LineLengthsSource.java new file mode 100644 index 0000000000..e3f5b11022 --- /dev/null +++ b/test/java/io/charStreams/LineLengthsSource.java @@ -0,0 +1,98 @@ +/* + * Copyright 1997 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. + */ + +/**/ + +import java.io.*; + + +class LineLengthsSource implements Runnable { + + DataOutputStream uo; + BufferedWriter to; + PrintWriter log; + + public LineLengthsSource(OutputStream us, BufferedWriter ts, + PrintWriter log) + throws IOException + { + uo = new DataOutputStream(us); + to = ts; + this.log = log; + } + + private void flush() throws IOException { + uo.flush(); + Thread.currentThread().yield(); + to.flush(); + Thread.currentThread().yield(); + } + + private String termString(int t) { + switch (t) { + case 0: return "\n"; + case 1: return "\r"; + case 2: return "\r\n"; + default: return ""; + } + } + + private String termName(int t) { + switch (t) { + case 0: return "\\n"; + case 1: return "\\r"; + case 2: return "\\r\\n"; + default: return ""; + } + } + + private void go(int t) throws IOException { + for (int ln = 0; ln < 128; ln++) { + String ts = termString(t); + StringBuffer s = new StringBuffer(ln + ts.length()); + for (int i = 0; i < ln; i++) + s.append('x'); + log.println("[" + ln + "]" + termName(t)); + uo.writeUTF(s.toString()); + s.append(ts); + to.write(s.toString()); + flush(); + } + } + + public void run() { + try { + go(0); + go(1); + go(2); + uo.close(); + Thread.currentThread().yield(); + to.close(); + Thread.currentThread().yield(); + } + catch (IOException x) { + return; /* Probably pipe broken */ + } + } + +} diff --git a/test/java/io/charStreams/LineNumbers.java b/test/java/io/charStreams/LineNumbers.java new file mode 100644 index 0000000000..907d1ac166 --- /dev/null +++ b/test/java/io/charStreams/LineNumbers.java @@ -0,0 +1,100 @@ +/* + * Copyright 1997 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 Stochastic test of LineNumberReader + */ + +import java.io.*; + + +public class LineNumbers { + + static String enc = "UTF8"; + static String inEnc; + static String outEnc; + static int limit = 500; + + public static void main(String[] args) throws Exception { + PrintWriter log + = new PrintWriter(new OutputStreamWriter(System.err), true); + + if (inEnc == null) + inEnc = enc; + if (outEnc == null) + outEnc = enc; + + PipedOutputStream co = new PipedOutputStream(); + PipedInputStream ci = new PipedInputStream(co); + + BufferedWriter w = new BufferedWriter(new OutputStreamWriter(co, outEnc)); + LineNumberReader r = new LineNumberReader(new InputStreamReader(ci, inEnc)); + + Thread t1 = new Thread(new RandomLineSource(w, limit)); + Thread t2 = new Thread(new LineNumberSink(r, limit, log)); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + +} + + +class LineNumberSink implements Runnable { + + LineNumberReader r; + int limit; + PrintWriter log; + + LineNumberSink(LineNumberReader r, int limit, PrintWriter log) { + this.r = r; + this.limit = limit; + this.log = log; + } + + public void run() { + String s; + int n = 0; + + try { + while ((s = r.readLine()) != null) { + n++; + int ln = r.getLineNumber(); + log.println("[" + ln + "] " + s.length()); + log.println(s); + if (log.checkError()) + log.println("Conversion errors"); /* #### */ + if (n != ln) + throw new RuntimeException("Line number mismatch: Expected " + n + ", got " + ln); + } + if (n != limit) + throw new RuntimeException("Incorrect line count"); + } + catch (IOException x) { + throw new RuntimeException(x.toString()); + } + log.println(n + " lines read"); + } + +} diff --git a/test/java/io/charStreams/LineSink.java b/test/java/io/charStreams/LineSink.java new file mode 100644 index 0000000000..76721d1b30 --- /dev/null +++ b/test/java/io/charStreams/LineSink.java @@ -0,0 +1,111 @@ +/* + * Copyright 1997-2000 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. + */ + +/**/ + +import java.io.*; + + +class LineSink implements Runnable { + + DataInputStream ui; + BufferedReader ti; + int count; + PrintWriter log; + + public LineSink(InputStream us, BufferedReader ts, + int count, PrintWriter log) + throws IOException + { + this(us, ts, log); + this.count = count; + } + + public LineSink(InputStream us, BufferedReader ts, PrintWriter log) + throws IOException + { + ui = new DataInputStream(us); + ti = ts; + this.count = Integer.MAX_VALUE; + this.log = log; + } + + private String readUTFLine() throws IOException { + String s; + try { + s = ui.readUTF(); + } + catch (EOFException x) { + return null; + } + return s; + } + + public void run() { + try { + for (int ln = 0; ln < count; ln++) { + String us = readUTFLine(); + if (us == null) { + if (count < Integer.MAX_VALUE) + throw new RuntimeException("Premature EOF on UTF stream"); + log.println("EOF on UTF stream"); + break; + } + + String ts = ti.readLine(); + if (ts == null) { + if (count < Integer.MAX_VALUE) + throw new RuntimeException("Premature EOF on char stream"); + log.println("EOF on char stream"); + break; + } + + if (us.length() != ts.length()) { + log.println("Length mismatch: us = \"" + + us + "\", ts = \"" + + ts + "\""); + throw new RuntimeException("Line " + ln + + ": Length mismatch: " + + us.length() + " " + ts.length()); + } + + for (int i = 0; i < us.length(); i++) { + if (us.charAt(i) != ts.charAt(i)) + throw new RuntimeException("Line " + ln + + ": Char mismatch: [" + i + "] " + + Integer.toHexString(us.charAt(i)) + + " " + Integer.toHexString(ts.charAt(i))); + } + log.println(ln + " " + ts.length()); + } + + if (readUTFLine() != null) + throw new RuntimeException("Expected EOF on UTF stream"); + if (ti.readLine() != null) + throw new RuntimeException("Expected EOF on char stream"); + } catch (IOException x) { + throw new RuntimeException("Unexpected IOException: " + x); + } + } + +} diff --git a/test/java/io/charStreams/RandomLineSource.java b/test/java/io/charStreams/RandomLineSource.java new file mode 100644 index 0000000000..e93300decb --- /dev/null +++ b/test/java/io/charStreams/RandomLineSource.java @@ -0,0 +1,90 @@ +/* + * Copyright 1997 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. + */ + +/**/ + +import java.io.*; +import java.util.Random; + + +class RandomLineSource implements Runnable { + + DataOutputStream uo; + BufferedWriter to; + LineGenerator lg; + PrintWriter log; + + public RandomLineSource(OutputStream us, BufferedWriter ts, int limit, + PrintWriter log) + { + if (us != null) + uo = new DataOutputStream(us); + to = ts; + IntGenerator ig = new IntGenerator(); + lg = new LineGenerator(ig, new StringGenerator(ig), limit); + this.log = log; + } + + public RandomLineSource(OutputStream us, BufferedWriter ts, int limit) { + this(us, ts, limit, null); + } + + public RandomLineSource(BufferedWriter ts, int limit) { + this(null, ts, limit); + } + + private void flush() throws IOException { + if (uo != null) { + uo.flush(); + Thread.currentThread().yield(); + } + to.flush(); + for (int i = 0; i < 10; i++) + Thread.currentThread().yield(); + } + + private int count = 0; + + public void run() { + try { + String s; + + while ((s = lg.next()) != null) { + if (uo != null) + uo.writeUTF(s); + to.write(s + lg.lineTerminator); + flush(); + count++; + } + + if (uo != null) { + uo.close(); + Thread.currentThread().yield(); + } + to.close(); + Thread.currentThread().yield(); + } catch (IOException x) { + return; /* Probably pipe broken */ + } + } +} diff --git a/test/java/io/charStreams/RandomLines.java b/test/java/io/charStreams/RandomLines.java new file mode 100644 index 0000000000..8d8030307f --- /dev/null +++ b/test/java/io/charStreams/RandomLines.java @@ -0,0 +1,63 @@ +/* + * Copyright 1997 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 Stochastic tests for InputStreamReader & OutputStreamWriter + */ + +import java.io.*; + + +public class RandomLines { + + static String enc = "UTF8"; + static String inEnc; + static String outEnc; + static int count = 500; + + public static void main(String[] args) throws Exception { + PrintWriter log + = new PrintWriter(new OutputStreamWriter(System.err), true); + + if (inEnc == null) + inEnc = enc; + if (outEnc == null) + outEnc = enc; + + PipedOutputStream uo = new PipedOutputStream(); + PipedInputStream ui = new PipedInputStream(uo); + PipedOutputStream co = new PipedOutputStream(); + PipedInputStream ci = new PipedInputStream(co); + + BufferedWriter w = new BufferedWriter(new OutputStreamWriter(co, outEnc)); + BufferedReader r = new BufferedReader(new InputStreamReader(ci, inEnc)); + + Thread t1 = new Thread(new RandomLineSource(uo, w, count, log)); + Thread t2 = new Thread(new LineSink(ui, r, count, log)); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + +} diff --git a/test/java/io/charStreams/SmallReads.java b/test/java/io/charStreams/SmallReads.java new file mode 100644 index 0000000000..142a96988a --- /dev/null +++ b/test/java/io/charStreams/SmallReads.java @@ -0,0 +1,76 @@ +/* + * Copyright 1997 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 Check that BufferedReader/Writer correctly handle small reads + */ + +import java.io.*; + + +public class SmallReads { + + static class OneByteInputStream extends FilterInputStream { + + OneByteInputStream(InputStream in) { + super(in); + } + + public int read(byte[] b, int off, int len) throws IOException { + return in.read(b, off, 1); + } + + } + + static String enc = "UTF8"; + static String inEnc; + static String outEnc; + static int count = 100; + + public static void main(String[] args) throws Exception { + PrintWriter log + = new PrintWriter(new OutputStreamWriter(System.err), true); + + if (inEnc == null) + inEnc = enc; + if (outEnc == null) + outEnc = enc; + + PipedOutputStream uo = new PipedOutputStream(); + PipedInputStream ui = new PipedInputStream(uo); + PipedOutputStream co = new PipedOutputStream(); + PipedInputStream ci = new PipedInputStream(co); + InputStream ci2 = new OneByteInputStream(ci); + + BufferedWriter w = new BufferedWriter(new OutputStreamWriter(co, outEnc)); + BufferedReader r = new BufferedReader(new InputStreamReader(ci2, inEnc)); + + Thread t1 = new Thread(new RandomLineSource(uo, w, count, log)); + Thread t2 = new Thread(new LineSink(ui, r, count, log)); + t1.start(); + t2.start(); + t1.join(); + t2.join(); + } + +} diff --git a/test/java/io/charStreams/StringConvert.java b/test/java/io/charStreams/StringConvert.java new file mode 100644 index 0000000000..647537c462 --- /dev/null +++ b/test/java/io/charStreams/StringConvert.java @@ -0,0 +1,150 @@ +/* + * Copyright 1997-2000 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 General tests of String constructors and methods that convert + between character encodings. This should really be in + java/lang/String, but it shares code with the I/O charStream + tests. + */ + +import java.io.*; + + +public class StringConvert { + + static String enc = "UTF8"; + static int limit = 500; + static int max = 0xffff; + + static void fail(String s) { + throw new RuntimeException(s); + } + + public static void main(String[] args) throws Exception { + PrintStream log = System.err; + IntGenerator ig = new IntGenerator(); + CharGenerator cg; + StringGenerator sg; + String s; + int i = 0; + + /* String(byte[] bytes, String enc) + getBytes(String enc) + */ + log.println("-- String(byte[], String), getBytes(String)"); + i = 0; + cg = new CharGenerator(ig, 0, max); + sg = new StringGenerator(ig, cg, limit); + while ((s = sg.next()) != null) { + byte[] b = s.getBytes(enc); + String t = new String(b, enc); + if (!s.equals(t)) { + int n = Math.min(s.length(), t.length()); + for (int j = 0; j < n; j++) { + if (s.charAt(j) != t.charAt(j)) { + log.println("Mismatch: " + j + " " + + Integer.toHexString(s.charAt(j)) + + " != " + + Integer.toHexString(t.charAt(j))); + } + } + fail("Conversion failure"); + } + log.println("[" + i + "] " + s.length()); + i++; + } + + /* String(byte[] bytes) + getBytes() + */ + log.println("-- String(byte[]), getBytes()"); + i = 0; + cg = new CharGenerator(ig, 0x20, 0x7e); + sg = new StringGenerator(ig, cg, limit); + while ((s = sg.next()) != null) { + log.println("[" + i + "] \"" + s + "\""); + byte[] b = s.getBytes(); + String t = new String(b); + if (! s.equals(t)) + fail("Conversion failure"); + i++; + } + + /* String(byte[] bytes, int offset, int length) + getBytes() + */ + log.println("-- String(byte[], int, int), getBytes()"); + i = 0; + cg = new CharGenerator(ig, 0x20, 0x7e); + sg = new StringGenerator(ig, cg, limit); + while ((s = sg.next()) != null) { + log.println("[" + i + "] \"" + s + "\""); + byte[] b = s.getBytes(); + int o = ig.next(s.length() - 1); + int n = ig.next(s.length() - o); + String t = new String(b, o, n); + if (! s.substring(o, o + n).equals(t)) + fail("Conversion failure"); + i++; + } + + /* String(byte[] bytes, int offset, int length, String enc) + getBytes(String enc) + */ + log.println("-- String(byte[], int, int, String), getBytes(String)"); + i = 0; + cg = new CharGenerator(ig); + sg = new StringGenerator(ig, cg, limit); + while ((s = sg.next()) != null) { + log.println("[" + i + "] " + s.length()); + byte[] b = s.getBytes(enc); + int o = ig.next(100); + byte[] b2 = new byte[b.length + o]; + System.arraycopy(b, 0, b2, o, b.length); + String t = new String(b2, o, b.length, enc); + if (! s.equals(t)) + fail("Conversion failure"); + i++; + } + + /* Substrings */ + log.println("-- Substrings"); + i = 0; + cg = new CharGenerator(ig, 0x20, 0x7e); + sg = new StringGenerator(ig, cg, limit); + while ((s = sg.next()) != null) { + log.println("[" + i + "] \"" + s + "\""); + int o = ig.next(s.length() - 1); + int n = ig.next(s.length() - o); + String s2 = s.substring(o, o + n); + byte[] b = s2.getBytes(); + String t = new String(b); + if (! s2.equals(t)) + fail("Conversion failure"); + i++; + } + + } + +} diff --git a/test/java/io/charStreams/StringGenerator.java b/test/java/io/charStreams/StringGenerator.java new file mode 100644 index 0000000000..5a7bf70e77 --- /dev/null +++ b/test/java/io/charStreams/StringGenerator.java @@ -0,0 +1,73 @@ +/* + * Copyright 1997 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. + */ + +/**/ + + +public class StringGenerator { + + private IntGenerator ig; + private CharGenerator cg; + private int limit; + private int count = 0; + + public StringGenerator(IntGenerator ig, CharGenerator cg, int limit) { + this.ig = ig; + this.cg = cg; + this.limit = limit; + } + + public StringGenerator(IntGenerator ig, CharGenerator cg) { + this(ig, cg, -1); + } + + public StringGenerator(IntGenerator ig, int limit) { + this(ig, new CharGenerator(ig), limit); + } + + public StringGenerator(IntGenerator ig) { + this(ig, -1); + } + + public StringGenerator(int limit) { + this(new IntGenerator(), limit); + } + + public StringGenerator() { + this(new IntGenerator()); + } + + public String next() { + if ((count >= limit) && (limit >= 0)) + return null; + + int len = ig.next(80); + StringBuffer s = new StringBuffer(len); + + for (int i = 0; i < len; i++) + s.append(cg.next()); + + count++; + return s.toString(); + } +} diff --git a/test/java/io/charStreams/UTF16.java b/test/java/io/charStreams/UTF16.java new file mode 100644 index 0000000000..77045aa87f --- /dev/null +++ b/test/java/io/charStreams/UTF16.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 4657074 + * @summary Ensure that stream decoders work properly for UTF-16 charsets + * @run main/timeout=10 UTF16 + */ + + +import java.io.*; + +public class UTF16 { + + private static byte[] array = new byte[20000]; + + private static void go(String cs) throws Exception { + InputStream is = new ByteArrayInputStream(array); + Reader r = new InputStreamReader(is, "UTF-16LE"); + r.read(); + } + + public static void main(String[] args) throws Exception { + go("UTF-16"); + go("UTF-16LE"); + go("UTF-16BE"); + } + +} diff --git a/test/java/io/charStreams/UTF8.java b/test/java/io/charStreams/UTF8.java new file mode 100644 index 0000000000..68f3d95adf --- /dev/null +++ b/test/java/io/charStreams/UTF8.java @@ -0,0 +1,61 @@ +/* + * Copyright 1997 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 4059684 + @summary Simple heartbeat test of the UTF8 byte->char converter + */ + +import java.io.*; + +public class UTF8 { + + static String test + = "This is a simple\ntest of the UTF8\r\nbyte-to-char and char-to-byte\nconverters."; + + public static void main(String[] args) throws IOException { + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + Writer out = new OutputStreamWriter(bo, "UTF8"); + out.write(test); + out.close(); + + Reader in + = new InputStreamReader(new ByteArrayInputStream(bo.toByteArray()), + "UTF8"); + + StringBuffer sb = new StringBuffer(); + char buf[] = new char[1000]; + int n; + while ((n = in.read(buf, 0, buf.length)) >= 0) { + sb.append(buf, 0, n); + System.err.println(n); + } + if (! sb.toString().equals(test)) { + System.err.println("In: [" + test + "]"); + System.err.println("Out: [" + sb.toString() + "]"); + throw new RuntimeException("Output does not match input"); + } + + } + +} diff --git a/test/java/io/charStreams/WriteLengths.java b/test/java/io/charStreams/WriteLengths.java new file mode 100644 index 0000000000..ee85b468af --- /dev/null +++ b/test/java/io/charStreams/WriteLengths.java @@ -0,0 +1,59 @@ +/* + * 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 4429227 + * @summary Ensure that OutputStreamWriter works on whole multiples + * of its internal buffer size + */ + +import java.io.*; + + +public class WriteLengths { + + static PrintStream log = System.err; + static int failures = 0; + + static ByteArrayOutputStream bos = new ByteArrayOutputStream(1 << 15); + + static void go(int len, String enc) throws Exception { + bos.reset(); + OutputStreamWriter osw = new OutputStreamWriter(bos, enc); + char[] cs = new char[len]; + osw.write(cs); + osw.close(); + byte[] ba = bos.toByteArray(); + if (ba.length != len) { + log.println("FAIL: Wrote " + len + ", got " + ba.length + + "; enc = " + enc); + failures++; + } + } + + public static void main(String[] args) throws Exception { + for (int i = 0; i < (1 << 15); i += 1024) + go(i, "us-ascii"); + } + +} diff --git a/test/java/io/pathNames/General.java b/test/java/io/pathNames/General.java new file mode 100644 index 0000000000..780426d15c --- /dev/null +++ b/test/java/io/pathNames/General.java @@ -0,0 +1,358 @@ +/* + * Copyright 1998-2000 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. + */ + +/* + @summary Common definitions for general exhaustive pathname tests + @author Mark Reinhold + */ + +import java.io.*; +import java.util.*; + + +public class General { + + public static boolean debug = false; + + private static boolean win32 = (File.separatorChar == '\\'); + + private static int gensymCounter = 0; + + + /* Generate a filename unique to this run */ + private static String gensym() { + return "x." + ++gensymCounter; + } + + + /** + * Find a file in the given subdirectory, or descend into further + * subdirectories, if any, if no file is found here. Return null if no + * file can be found anywhere beneath the given subdirectory. + * @param dir Directory at which we started + * @param subdir Subdirectory that we're exploring + * @param dl Listing of subdirectory + */ + private static String findSomeFile(String dir, String subdir, String[] dl) { + for (int i = 0; i < dl.length; i++) { + File f = new File(subdir, dl[i]); + File df = new File(dir, f.getPath()); + if (df.exists() && df.isFile()) { + return f.getPath(); + } + } + for (int i = 0; i < dl.length; i++) { + File f = (subdir.length() == 0) ? new File(dl[i]) + : new File(subdir, dl[i]); + File df = new File(dir, f.getPath()); + if (df.exists() && df.isDirectory()) { + String[] dl2 = df.list(); + if (dl2 != null) { + String ff = findSomeFile(dir, f.getPath(), dl2); + if (ff != null) return ff; + } + } + } + return null; + } + + + /** + * Construct a string that names a file in the given directory. If create + * is true, then create a file if none is found, and throw an exception if + * that is not possible; otherwise, return null if no file can be found. + */ + private static String findSomeFile(String dir, boolean create) { + File d = new File(dir); + String[] dl = d.list(); + if (dl == null) { + throw new RuntimeException("Can't list " + dir); + } + for (int i = 0; i < dl.length; i++) { + File f = new File(dir, dl[i]); + if (f.isFile()) { + return dl[i]; + } + } + String f = findSomeFile(dir, "", dl); + if (f != null) { + return f; + } + if (create) { + File nf = new File(d, gensym()); + OutputStream os; + try { + os = new FileOutputStream(nf); + os.close(); + } catch (IOException x) { + throw new RuntimeException("Can't create a file in " + dir); + } + return nf.getName(); + } + return null; + } + + + /** + * Construct a string that names a subdirectory of the given directory. + * If create is true, then create a subdirectory if none is found, and + * throw an exception if that is not possible; otherwise, return null if + * no subdirectory can be found. + */ + private static String findSomeDir(String dir, boolean create) { + File d = new File(dir); + String[] dl = d.list(); + if (dl == null) { + throw new RuntimeException("Can't list " + dir); + } + for (int i = 0; i < dl.length; i++) { + File f = new File(d, dl[i]); + if (f.isDirectory() && f.canRead()) { + String[] dl2 = f.list(); + if (dl2.length >= 250) { + /* Heuristic to avoid scanning huge directories */ + continue; + } + return dl[i]; + } + } + if (create) { + File sd = new File(d, gensym()); + if (sd.mkdir()) return sd.getName(); + } + return null; + } + + + /** Construct a string that does not name a file in the given directory */ + private static String findNon(String dir) { + File d = new File(dir); + String[] x = new String[] { "foo", "bar", "baz" }; + for (int i = 0; i < x.length; i++) { + File f = new File(d, x[i]); + if (!f.exists()) { + return x[i]; + } + } + for (int i = 0; i < 1024; i++) { + String n = "xx" + Integer.toString(i); + File f = new File(d, n); + if (!f.exists()) { + return n; + } + } + throw new RuntimeException("Can't find a non-existent file in " + dir); + } + + + /** Ensure that the named file does not exist */ + public static void ensureNon(String fn) { + if ((new File(fn)).exists()) { + throw new RuntimeException("Test path " + fn + " exists"); + } + } + + + /** Tell whether the given character is a "slash" on this platform */ + private static boolean isSlash(char x) { + if (x == File.separatorChar) return true; + if (win32 && (x == '/')) return true; + return false; + } + + + /** + * Trim trailing slashes from the given string, but leave singleton slashes + * alone (they denote root directories) + */ + private static String trimTrailingSlashes(String s) { + int n = s.length(); + if (n == 0) return s; + n--; + while ((n > 0) && isSlash(s.charAt(n))) { + if ((n >= 1) && s.charAt(n - 1) == ':') break; + n--; + } + return s.substring(0, n + 1); + } + + + /** Concatenate two paths, trimming slashes as needed */ + private static String pathConcat(String a, String b) { + if (a.length() == 0) return b; + if (b.length() == 0) return a; + if (isSlash(a.charAt(a.length() - 1)) + || isSlash(b.charAt(0)) + || (win32 && (a.charAt(a.length() - 1) == ':'))) { + return a + b; + } else { + return a + File.separatorChar + b; + } + } + + + + /** Hash table of input pathnames, used to detect duplicates */ + private static Hashtable checked = new Hashtable(); + + /** + * Check the given pathname. Its canonical pathname should be the given + * answer. If the path names a file that exists and is readable, then + * FileInputStream and RandomAccessFile should both be able to open it. + */ + public static void check(String answer, String path) throws IOException { + String ans = trimTrailingSlashes(answer); + if (path.length() == 0) return; + if (checked.get(path) != null) { + System.err.println("DUP " + path); + return; + } + checked.put(path, path); + + String cpath; + try { + File f = new File(path); + cpath = f.getCanonicalPath(); + if (f.exists() && f.isFile() && f.canRead()) { + InputStream in = new FileInputStream(path); + in.close(); + RandomAccessFile raf = new RandomAccessFile(path, "r"); + raf.close(); + } + } catch (IOException x) { + System.err.println(ans + " <-- " + path + " ==> " + x); + if (debug) return; + else throw x; + } + if (cpath.equals(ans)) { + System.err.println(ans + " <== " + path); + } else { + System.err.println(ans + " <-- " + path + " ==> " + cpath + " MISMATCH"); + if (!debug) { + throw new RuntimeException("Mismatch: " + path + " ==> " + cpath + + ", should be " + ans); + } + } + } + + + + /* + * The following three mutually-recursive methods generate and check a tree + * of filenames of arbitrary depth. Each method has (at least) these + * arguments: + * + * int depth Remaining tree depth + * boolean create Controls whether test files and directories + * will be created as needed + * String ans Expected answer for the check method (above) + * String ask Input pathname to be passed to the check method + */ + + + /** Check a single slash case, plus its children */ + public static void checkSlash(int depth, boolean create, + String ans, String ask, String slash) + throws Exception + { + check(ans, ask + slash); + checkNames(depth, create, + ans.endsWith(File.separator) ? ans : ans + File.separator, + ask + slash); + } + + + /** Check slash cases for the given ask string */ + public static void checkSlashes(int depth, boolean create, + String ans, String ask) + throws Exception + { + check(ans, ask); + if (depth == 0) return; + + checkSlash(depth, create, ans, ask, "/"); + checkSlash(depth, create, ans, ask, "//"); + checkSlash(depth, create, ans, ask, "///"); + if (win32) { + checkSlash(depth, create, ans, ask, "\\"); + checkSlash(depth, create, ans, ask, "\\\\"); + checkSlash(depth, create, ans, ask, "\\/"); + checkSlash(depth, create, ans, ask, "/\\"); + checkSlash(depth, create, ans, ask, "\\\\\\"); + } + } + + + /** Check name cases for the given ask string */ + public static void checkNames(int depth, boolean create, + String ans, String ask) + throws Exception + { + int d = depth - 1; + File f = new File(ans); + String n; + + /* Normal name */ + if (f.exists()) { + if (f.isDirectory() && f.canRead()) { + if ((n = findSomeFile(ans, create)) != null) + checkSlashes(d, create, ans + n, ask + n); + if ((n = findSomeDir(ans, create)) != null) + checkSlashes(d, create, ans + n, ask + n); + } + n = findNon(ans); + checkSlashes(d, create, ans + n, ask + n); + } else { + n = "foo" + depth; + checkSlashes(d, create, ans + n, ask + n); + } + + /* "." */ + checkSlashes(d, create, trimTrailingSlashes(ans), ask + "."); + + /* ".." */ + if ((n = f.getParent()) != null) { + String n2; + if (win32 + && ((n2 = f.getParentFile().getParent()) != null) + && n2.equals("\\\\")) { + /* Win32 resolves \\foo\bar\.. to \\foo\bar */ + checkSlashes(d, create, ans, ask + ".."); + } else { + checkSlashes(d, create, n, ask + ".."); + } + } + else { + if (win32) + checkSlashes(d, create, ans, ask + ".."); + else { + // Fix for 4237875. We must ensure that we are sufficiently + // deep in the path hierarchy to test parents this high up + File thisPath = new File(ask); + File nextPath = new File(ask + ".."); + if (!thisPath.getCanonicalPath().equals(nextPath.getCanonicalPath())) + checkSlashes(d, create, ans + "..", ask + ".."); + } + } + } +} diff --git a/test/java/io/pathNames/GeneralWin32.java b/test/java/io/pathNames/GeneralWin32.java new file mode 100644 index 0000000000..0242402f93 --- /dev/null +++ b/test/java/io/pathNames/GeneralWin32.java @@ -0,0 +1,176 @@ +/* + * Copyright 1998-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 4032066 4039597 4046914 4054511 4065189 4109131 4875229 + @summary General exhaustive test of win32 pathname handling + @author Mark Reinhold + + @build General GeneralWin32 + @run main/timeout=600 GeneralWin32 + */ + +import java.io.*; +import java.util.*; + + +public class GeneralWin32 extends General { + + + /** + * Hardwired UNC pathnames used for testing + * + * This test attempts to use the host and share names defined in this class + * to test UNC pathnames. The test will not fail if the host or share + * don't exist, but it will print a warning saying that it was unable to + * test UNC pathnames completely. + */ + private static final String EXISTENT_UNC_HOST = "pc-cup01"; + private static final String EXISTENT_UNC_SHARE = "pcdist"; + private static final String NONEXISTENT_UNC_HOST = "non-existent-unc-host"; + private static final String NONEXISTENT_UNC_SHARE = "bogus-share"; + + + /* Pathnames relative to working directory */ + + private static void checkCaseLookup(String ud) throws IOException { + /* Use long names here to avoid 8.3 format, which Samba servers often + force to lowercase */ + File d = new File("XyZzY0123", "FOO_bar_BAZ"); + File f = new File(d, "GLORPified"); + if (!f.exists()) { + if (!d.exists()) { + if (!d.mkdirs()) { + throw new RuntimeException("Can't create directory " + d); + } + } + OutputStream o = new FileOutputStream(f); + o.close(); + } + File f2 = new File(d.getParent(), "mumble"); /* For later ud tests */ + if (!f2.exists()) { + OutputStream o = new FileOutputStream(f2); + o.close(); + } + + /* Computing the canonical path of a Win32 file should expose the true + case of filenames, rather than just using the input case */ + File y = new File(ud, f.getPath()); + String ans = y.getPath(); + check(ans, "XyZzY0123\\FOO_bar_BAZ\\GLORPified"); + check(ans, "xyzzy0123\\foo_bar_baz\\glorpified"); + check(ans, "XYZZY0123\\FOO_BAR_BAZ\\GLORPIFIED"); + } + + private static void checkWild(File f) throws Exception { + try { + f.getCanonicalPath(); + } catch (IOException x) { + return; + } + throw new Exception("Wildcard path not rejected: " + f); + } + + private static void checkWildCards(String ud) throws Exception { + File d = new File(ud).getCanonicalFile(); + checkWild(new File(d, "*.*")); + checkWild(new File(d, "*.???")); + checkWild(new File(new File(d, "*.*"), "foo")); + } + + private static void checkRelativePaths() throws Exception { + String ud = System.getProperty("user.dir").replace('/', '\\'); + checkCaseLookup(ud); + checkWildCards(ud); + checkNames(3, true, ud + "\\", ""); + } + + + /* Pathnames with drive specifiers */ + + private static char findInactiveDrive() { + for (char d = 'Z'; d >= 'E'; d--) { + File df = new File(d + ":\\"); + if (!df.exists()) { + return d; + } + } + throw new RuntimeException("Can't find an inactive drive"); + } + + private static char findActiveDrive() { + for (char d = 'C'; d <= 'Z'; d--) { + File df = new File(d + ":\\"); + if (df.exists()) return d; + } + throw new RuntimeException("Can't find an active drive"); + } + + private static void checkDrive(int depth, char drive, boolean exists) + throws Exception + { + String d = drive + ":"; + File df = new File(d); + String ans = exists ? df.getAbsolutePath() : d; + if (!ans.endsWith("\\")) + ans = ans + "\\"; + checkNames(depth, false, ans, d); + } + + private static void checkDrivePaths() throws Exception { + checkDrive(2, findActiveDrive(), true); + checkDrive(2, findInactiveDrive(), false); + } + + + /* UNC pathnames */ + + private static void checkUncPaths() throws Exception { + String s = ("\\\\" + NONEXISTENT_UNC_HOST + + "\\" + NONEXISTENT_UNC_SHARE); + ensureNon(s); + checkSlashes(2, false, s, s); + + s = "\\\\" + EXISTENT_UNC_HOST + "\\" + EXISTENT_UNC_SHARE; + if (!(new File(s)).exists()) { + System.err.println("WARNING: " + s + + " does not exist, unable to test UNC pathnames"); + return; + } + + checkSlashes(2, false, s, s); + } + + + public static void main(String[] args) throws Exception { + if (File.separatorChar != '\\') { + /* This test is only valid on win32 systems */ + return; + } + if (args.length > 0) debug = true; + checkRelativePaths(); + checkDrivePaths(); + checkUncPaths(); + } + +} diff --git a/test/java/io/pathNames/unix/TrailingSlash.java b/test/java/io/pathNames/unix/TrailingSlash.java new file mode 100644 index 0000000000..0866ff9bac --- /dev/null +++ b/test/java/io/pathNames/unix/TrailingSlash.java @@ -0,0 +1,124 @@ +/* + * 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 4427862 + * @summary Ensure that trailing slashes are ignored when opening files + */ + +import java.io.*; + + +public class TrailingSlash { + + static PrintStream log = System.err; + static int failures = 0; + + static void check(String what, String fns, + boolean expected, boolean threw) + { + if (expected == threw) { + log.println(" FAIL: new " + what + "(\"" + fns + "\") " + + (expected ? "failed" : "succeeded")); + failures++; + } + } + + static void go(String fns, boolean fis, boolean raf, boolean fos) + throws IOException + { + boolean threw; + + threw = false; + try { + new FileInputStream(fns).close(); + log.println(" FileInputStream okay"); + } catch (IOException x) { + log.println(" FileInputStream: " + x); + threw = true; + } + check("FileInputStream", fns, fis, threw); + + threw = false; + try { + new RandomAccessFile(fns, "r").close(); + log.println(" RandomAccessFile okay"); + } catch (IOException x) { + log.println(" RandomAccessFile: " + x); + threw = true; + } + check("RandomAccessFile", fns, raf, threw); + + threw = false; + try { + new FileOutputStream(fns).close(); + log.println(" FileOutputStream okay"); + } catch (IOException x) { + log.println(" FileOutputStream: " + x); + threw = true; + } + check("FileOutputStream", fns, fos, threw); + + } + + static void go(String fn, String fns) throws Exception { + + log.println("Test case: " + fns); + + File f = new File(fn); + + f.delete(); + if (f.exists()) + throw new Exception("Can't delete " + f); + + log.println(" " + fn + " does not exist"); + go(fns, false, false, true); + + f.delete(); + f.mkdir(); + log.println(" " + fn + " is a directory"); + go(fns, false, false, false); + + f.delete(); + f.createNewFile(); + log.println(" " + fn + " is a file"); + go(fns, true, true, true); + + } + + public static void main(String[] args) throws Exception { + if (File.separatorChar != '/') { + // This test is only valid on Unix systems + return; + } + + go("xyzzy", "xyzzy"); + go("xyzzy", "xyzzy/"); + go("xyzzy", "xyzzy//"); + + if (failures > 0) + throw new Exception(failures + " failures"); + + } + +} diff --git a/test/java/io/pathNames/win32/BadDriveLetter.java b/test/java/io/pathNames/win32/BadDriveLetter.java new file mode 100644 index 0000000000..6728e6db04 --- /dev/null +++ b/test/java/io/pathNames/win32/BadDriveLetter.java @@ -0,0 +1,35 @@ +/* + * Copyright 1998 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 4138774 + @summary Make sure that a bad drive letter doesn't cause an exception + */ + +public class BadDriveLetter { + + public static void main(String[] args) { + System.err.println(new java.io.File(".:").getAbsolutePath()); + } + +} diff --git a/test/java/io/pathNames/win32/DriveOnly.java b/test/java/io/pathNames/win32/DriveOnly.java new file mode 100644 index 0000000000..4156294fb8 --- /dev/null +++ b/test/java/io/pathNames/win32/DriveOnly.java @@ -0,0 +1,50 @@ +/* + * Copyright 1998 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 4096648 + @summary Make sure that isDirectory and lastModified work on "x:" + */ + +import java.io.File; + + +public class DriveOnly { + + public static void main(String[] args) throws Exception { + if (File.separatorChar != '\\') return; + File f = new File("").getCanonicalFile(); + while (f.getParent() != null) f = f.getParentFile(); + String p = f.getPath().substring(0, 2); + if (!(Character.isLetter(p.charAt(0)) && (p.charAt(1) == ':'))) { + System.err.println("No current drive, cannot run test"); + return; + } + f = new File(p); + if (!f.isDirectory()) + throw new Exception("\"" + f + "\" is not a directory"); + if (f.lastModified() == 0) + throw new Exception("\"" + f + "\" has no last-modified time"); + } + +} diff --git a/test/java/io/pathNames/win32/DriveRelativePath.java b/test/java/io/pathNames/win32/DriveRelativePath.java new file mode 100644 index 0000000000..65d7fc7043 --- /dev/null +++ b/test/java/io/pathNames/win32/DriveRelativePath.java @@ -0,0 +1,63 @@ +/* + * Copyright 1997-1998 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 4070044 4164823 + @summary Check getCanonicalPath's treatment of drive-relative paths (win32) + */ + +import java.io.*; + + +public class DriveRelativePath { + + static void fail(String s) { + throw new RuntimeException(s); + } + + public static void main(String[] args) throws IOException { + + if (File.separatorChar != '\\') { + /* This test is only valid on win32 systems */ + return; + } + + File f = new File("foo"); + String c = f.getCanonicalPath(); + System.err.println(c); + + int di = c.indexOf(':'); + if (di == -1) fail("No drive in canonical path"); + String drive = c.substring(0, di + 1); + File f2 = new File(drive + "foo"); + System.err.println(f2); + String c2 = f2.getCanonicalPath(); + System.err.println(c2); + if (!c2.equals(c)) fail("Canonical path mismatch: \"" + + f2 + "\" maps to \"" + + c2 + "\"; it should map to \"" + + c + "\""); + + } + +} diff --git a/test/java/io/pathNames/win32/DriveSlash.java b/test/java/io/pathNames/win32/DriveSlash.java new file mode 100644 index 0000000000..7a8c0c528d --- /dev/null +++ b/test/java/io/pathNames/win32/DriveSlash.java @@ -0,0 +1,53 @@ +/* + * Copyright 1998 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 4065189 + @summary Check that win32 pathnames of the form "C:\\" + can be listed by the File.list method + @author Mark Reinhold + */ + +import java.io.*; + + +public class DriveSlash { + + public static void main(String[] args) throws Exception { + + /* This test is only valid on win32 systems */ + if (File.separatorChar != '\\') return; + + File f = new File("c:\\"); + System.err.println(f.getCanonicalPath()); + String[] fs = f.list(); + if (fs == null) { + throw new Exception("File.list returned null"); + } + for (int i = 0; i < fs.length; i++) { + System.err.print(" " + fs[i]); + } + System.err.println(); + } + +} diff --git a/test/java/io/pathNames/win32/RenameDelete.java b/test/java/io/pathNames/win32/RenameDelete.java new file mode 100644 index 0000000000..336fcfb6c6 --- /dev/null +++ b/test/java/io/pathNames/win32/RenameDelete.java @@ -0,0 +1,80 @@ +/* + * Copyright 1998-1999 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 4042592 4042593 + * @summary Test operation of rename and delete on win32 + */ + +import java.io.*; + +/** + * This class tests to see if java.io.file rename() method + * operates properly with non canonical pathnames + * and then tests delete() method with non canonical pathnames + */ + +public class RenameDelete { + + public static void main(String[] args) throws Exception { + boolean success = false; + + if (File.separatorChar != '\\') { + System.err.println("Not a win32 platform -- test inapplicable"); + return; + } + + //construct a test file in this location + File f1 = new File("."); + StringBuffer location = new StringBuffer("\\"); + location.append(f1.getCanonicalPath()); + + StringBuffer fromLocation = new StringBuffer(location.toString()+"\\From"); + StringBuffer toLocation = new StringBuffer(location.toString()+"\\To"); + + f1 = new File(fromLocation.toString()); + File f2 = new File(toLocation.toString()); + + if(f1.exists() || f2.exists()) { + System.err.println("Directories exist -- test not valid"); + return; + } + + System.err.println("Create:"+f1.mkdir()); + System.err.println("Exist as directory:"+f1.exists()+" "+f1.isDirectory()); + success = f1.renameTo(f2); + System.err.println("Rename:"+success); + + if (!success) + throw new RuntimeException("File method rename did not function"); + + success = f2.delete(); + System.err.println("Delete:"+success); + + if (!success) + throw new RuntimeException("File method delete did not function"); + + } + +} diff --git a/test/java/io/pathNames/win32/SJIS.java b/test/java/io/pathNames/win32/SJIS.java new file mode 100644 index 0000000000..c91dbb9993 --- /dev/null +++ b/test/java/io/pathNames/win32/SJIS.java @@ -0,0 +1,82 @@ +/* + * Copyright 1998 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 4039597 + @summary Check that pathnames containing double-byte characters are not + corrupted by win32 path processing + @author Mark Reinhold +*/ + +import java.io.*; + + +public class SJIS { + + private static void rm(File f) { + if (!f.delete()) throw new RuntimeException("Can't delete " + f); + } + + private static void touch(File f) throws IOException { + OutputStream o = new FileOutputStream(f); + o.close(); + } + + public static void main(String[] args) throws Exception { + + /* This test is only valid on win32 systems + that use the SJIS encoding */ + if (File.separatorChar != '\\') return; + String enc = System.getProperty("file.encoding"); + if ((enc == null) || !enc.equals("SJIS")) return; + + File f = new File("\u30BD"); + if (f.exists()) rm(f); + + System.err.println(f.getCanonicalPath()); + touch(f); + System.err.println(f.getCanonicalPath()); + + rm(f); + + if (!f.mkdir()) { + throw new Exception("Can't create directory " + f); + } + File f2 = new File(f, "\u30BD"); + System.err.println(f2.getCanonicalPath()); + touch(f2); + String cfn = f2.getCanonicalPath(); + if (!(new File(cfn)).exists()) { + throw new Exception(cfn + " not found"); + } + + File d = new File("."); + String[] fs = d.list(); + if (fs == null) System.err.println("No files listed"); + for (int i = 0; i < fs.length; i++) { + System.err.println(fs[i]); + } + + } + +} diff --git a/test/java/io/pathNames/win32/bug6344646.java b/test/java/io/pathNames/win32/bug6344646.java new file mode 100644 index 0000000000..11a3aa8950 --- /dev/null +++ b/test/java/io/pathNames/win32/bug6344646.java @@ -0,0 +1,48 @@ +/* + * 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 6344646 + * @summary tests that Win32FileSystem.hashCode() uses + * locale independent case mapping. + */ + +import java.io.*; +import java.util.*; + +public class bug6344646 { + public static void main(String[] s) { + /* This test is only valid on win32 systems */ + if (File.separatorChar != '\\') { + return; + } + + Locale.setDefault(new Locale("lt")); + File f1 = new File("J\u0301"); + File f2 = new File("j\u0301"); + + if (f1.hashCode() != f2.hashCode()) { + throw new RuntimeException("File.hashCode() for \"J\u0301\" and \"j\u0301\" should be the same"); + } + } +} diff --git a/test/java/io/readBytes/ReadBytesBounds.java b/test/java/io/readBytes/ReadBytesBounds.java new file mode 100644 index 0000000000..75b0a31199 --- /dev/null +++ b/test/java/io/readBytes/ReadBytesBounds.java @@ -0,0 +1,128 @@ +/* + * Copyright 1997 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 4017728 4079849 + @summary Check for correct Array Bounds check in read of FileInputStream and + RandomAccessFile + */ + +import java.io.*; + + +/* + * The test calls the read(byte buf[] , int off , int len) of FileInputStream with + * different values of off and len to see if the ArrayOutOfBoundsException is + * thrown according to the JLS1.0 specification. The read(...) method calls + * readBytes(...) in native code(io_util.c). The read(...) method in RandomAccessFile + * also calls the same native method. So one should see similar results. + */ + + +public class ReadBytesBounds { + + public static void main(String argv[]) throws Exception{ + + int num_test_cases = 12; + int off[] = {-1 , -1 , 0 , 0 , 33 , 33 , 0 , 32 , 32 , 4 , 1 , 0}; + int len[] = {-1 , 0 , -1 , 33 , 0 , 4 , 32 , 0 , 4 , 16 , 31 , 0}; + boolean results[] = { false , false , false , false , false , false , + true , true , false , true , true , true}; + + + FileInputStream fis = null; + RandomAccessFile raf = null; + byte b[] = new byte[32]; + + int num_good = 0; + int num_bad = 0; + + String dir = System.getProperty("test.src", "."); + File testFile = new File(dir, "input.txt"); + fis = new FileInputStream(testFile); + for(int i = 0; i < num_test_cases; i++) { + + try { + int bytes_read = fis.read(b , off[i] , len[i]); + } catch(IndexOutOfBoundsException aiobe) { + if (results[i]) { + throw new RuntimeException("Unexpected result"); + } + else { + num_good++; + } + continue; + } + + if (results[i]) { + num_good++; + } + else { + throw new RuntimeException("Unexpected result"); + } + + } + System.out.println("Results for FileInputStream.read"); + System.out.println("\nTotal number of test cases = " + num_test_cases + + "\nNumber succeded = " + num_good + + "\nNumber failed = " + num_bad); + + + + num_good = 0; + num_bad = 0; + + raf = new RandomAccessFile(testFile , "r"); + for(int i = 0; i < num_test_cases; i++) { + + try { + int bytes_read = raf.read(b , off[i] , len[i]); + } catch(IndexOutOfBoundsException aiobe) { + if (results[i]) { + throw new RuntimeException("Unexpected result"); + } + else { + num_good++; + } + continue; + } + + if (results[i]) { + num_good++; + } + else { + throw new RuntimeException("Unexpected result"); + } + + } + + System.out.println("Results for RandomAccessFile.read"); + System.out.println("\nTotal number of test cases = " + num_test_cases + + "\nNumber succeded = " + num_good + + "\nNumber failed = " + num_bad); + + + } + +} diff --git a/test/java/io/readBytes/input.txt b/test/java/io/readBytes/input.txt new file mode 100644 index 0000000000..f6d8a09f13 --- /dev/null +++ b/test/java/io/readBytes/input.txt @@ -0,0 +1,14 @@ +foo +goo +moo +loo +doo +boo +coo +roo +hoo +doo +soo +woo +xoo +zoo |