提交 76b1f48c 编写于 作者: S sherman

6920732: opensource test/java/nio/charset

Summary: move the test cases to openjdk
Reviewed-by: martin
上级 ad17ae7f
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
* @bug 4422044
* @summary Ensure that keys in available-charset map
* are identical to canonical names
*/
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.util.*;
public class AvailableCharsetNames {
public static void main(String[] args) throws Exception {
Iterator charsetIterator = Charset.availableCharsets().keySet().iterator();
while (charsetIterator.hasNext()) {
String charsetName = (String) charsetIterator.next();
Charset charset = Charset.forName(charsetName);
if (!charset.name().equals(charsetName)) {
throw new Exception("Error: Charset name mismatch - expected "
+ charsetName + ", got " + charset.name());
}
}
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
@bug 4626545 4696726
@summary Checks the inter containment relationships between NIO charsets
*/
import java.nio.charset.*;
public class CharsetContainmentTest {
static String[] encodings =
{ "US-ASCII", "UTF-16", "UTF-16BE", "UTF-16LE", "UTF-8",
"windows-1252", "ISO-8859-1", "ISO-8859-15", "ISO-8859-2",
"ISO-8859-3", "ISO-8859-4", "ISO-8859-5", "ISO-8859-6",
"ISO-8859-7", "ISO-8859-8", "ISO-8859-9", "ISO-8859-13",
"ISO-2022-JP", "ISO-2022-KR",
// Temporarily remove ISO-2022-CN-* charsets until full encoder/decoder
// support is added (4673614)
// "x-ISO-2022-CN-CNS", "x-ISO-2022-CN-GB",
"x-ISCII91", "GBK", "GB18030", "Big5",
"x-EUC-TW", "GB2312", "EUC-KR", "x-Johab", "Big5-HKSCS",
"x-MS950-HKSCS", "windows-1251", "windows-1253", "windows-1254",
"windows-1255", "windows-1256", "windows-1257", "windows-1258",
"x-mswin-936", "x-windows-949", "x-windows-950", "windows-31j",
"Shift_JIS", "EUC-JP", "KOI8-R", "TIS-620"
};
static String[][] contains = {
{ "US-ASCII"},
encodings,
encodings,
encodings,
encodings,
{"US-ASCII", "windows-1252"},
{"US-ASCII", "ISO-8859-1"},
{"US-ASCII", "ISO-8859-15"},
{"US-ASCII", "ISO-8859-2"},
{"US-ASCII", "ISO-8859-3"},
{"US-ASCII", "ISO-8859-4"},
{"US-ASCII", "ISO-8859-5"},
{"US-ASCII", "ISO-8859-6"},
{"US-ASCII", "ISO-8859-7"},
{"US-ASCII", "ISO-8859-8"},
{"US-ASCII", "ISO-8859-9"},
{"US-ASCII", "ISO-8859-13"},
{"ISO-2022-JP"},
{"ISO-2022-KR"},
// Temporarily remove ISO-2022-CN-* charsets until full encoder/decoder
// support is added (4673614)
//{"x-ISO-2022-CN-CNS"},
//{"x-ISO-2022-CN-GB"},
{"US-ASCII", "x-ISCII91"},
{"US-ASCII", "GBK"},
encodings,
{"US-ASCII", "Big5"},
{"US-ASCII", "x-EUC-TW"},
{"US-ASCII", "GB2312"},
{"US-ASCII", "EUC-KR"},
{"US-ASCII", "x-Johab"},
{"US-ASCII", "Big5-HKSCS", "Big5"},
{"US-ASCII", "x-MS950-HKSCS", "x-windows-950"},
{"US-ASCII", "windows-1251"},
{"US-ASCII", "windows-1253"},
{"US-ASCII", "windows-1254"},
{"US-ASCII", "windows-1255"},
{"US-ASCII", "windows-1256"},
{"US-ASCII", "windows-1257"},
{"US-ASCII", "windows-1258"},
{"US-ASCII", "x-mswin-936"},
{"US-ASCII", "x-windows-949"},
{"US-ASCII", "x-windows-950"},
{"US-ASCII", "windows-31j" },
{"US-ASCII", "Shift_JIS"},
{"US-ASCII", "EUC-JP"},
{"US-ASCII", "KOI8-R"},
{"US-ASCII", "TIS-620"}};
public static void main(String[] args) throws Exception {
for (int i = 0; i < encodings.length; i++) {
Charset c = Charset.forName(encodings[i]);
for (int j = 0 ; j < contains[i].length; j++) {
if (c.contains(Charset.forName(contains[i][j])))
continue;
else {
throw new Exception ("Error: charset " + encodings[i] +
"doesn't contain " + contains[i][j]);
}
}
}
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, 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 charset containment
* @bug 6798572
*/
import java.nio.charset.*;
public class Contains {
static void ck(Charset cs1, Charset cs2, boolean cont) throws Exception {
if ((cs1.contains(cs2)) != cont)
throw new Exception("Wrong answer: "
+ cs1.name() + " contains " + cs2.name());
System.err.println(cs1.name()
+ (cont ? " contains " : " does not contain ")
+ cs2.name());
}
public static void main(String[] args) throws Exception {
Charset us_ascii = Charset.forName("US-ASCII");
Charset iso_8859_1 = Charset.forName("ISO-8859-1");
Charset iso_8859_15 = Charset.forName("ISO-8859-15");
Charset utf_8 = Charset.forName("UTF-8");
Charset utf_16be = Charset.forName("UTF-16BE");
Charset cp1252 = Charset.forName("CP1252");
ck(us_ascii, us_ascii, true);
ck(us_ascii, iso_8859_1, false);
ck(us_ascii, iso_8859_15, false);
ck(us_ascii, utf_8, false);
ck(us_ascii, utf_16be, false);
ck(us_ascii, cp1252, false);
ck(iso_8859_1, us_ascii, true);
ck(iso_8859_1, iso_8859_1, true);
ck(iso_8859_1, iso_8859_15, false);
ck(iso_8859_1, utf_8, false);
ck(iso_8859_1, utf_16be, false);
ck(iso_8859_1, cp1252, false);
ck(iso_8859_15, us_ascii, true);
ck(iso_8859_15, iso_8859_1, false);
ck(iso_8859_15, iso_8859_15, true);
ck(iso_8859_15, utf_8, false);
ck(iso_8859_15, utf_16be, false);
ck(iso_8859_15, cp1252, false);
ck(utf_8, us_ascii, true);
ck(utf_8, iso_8859_1, true);
ck(utf_8, iso_8859_15, true);
ck(utf_8, utf_8, true);
ck(utf_8, utf_16be, true);
ck(utf_8, cp1252, true);
ck(utf_16be, us_ascii, true);
ck(utf_16be, iso_8859_1, true);
ck(utf_16be, iso_8859_15, true);
ck(utf_16be, utf_8, true);
ck(utf_16be, utf_16be, true);
ck(utf_16be, cp1252, true);
ck(cp1252, us_ascii, true);
ck(cp1252, iso_8859_1, false);
ck(cp1252, iso_8859_15, false);
ck(cp1252, utf_8, false);
ck(cp1252, utf_16be, false);
ck(cp1252, cp1252, true);
checkUTF();
}
static void checkUTF() throws Exception {
for (String utfName : utfNames)
for (String csName : charsetNames)
ck(Charset.forName(utfName),
Charset.forName(csName),
true);
}
static String[] utfNames = {"utf-16",
"utf-8",
"utf-16le",
"utf-16be",
"x-utf-16le-bom"};
static String[] charsetNames = {
"US-ASCII",
"UTF-8",
"UTF-16",
"UTF-16BE",
"UTF-16LE",
"x-UTF-16LE-BOM",
"GBK",
"GB18030",
"ISO-8859-1",
"ISO-8859-15",
"ISO-8859-2",
"ISO-8859-3",
"ISO-8859-4",
"ISO-8859-5",
"ISO-8859-6",
"ISO-8859-7",
"ISO-8859-8",
"ISO-8859-9",
"ISO-8859-13",
"JIS_X0201",
"x-JIS0208",
"JIS_X0212-1990",
"GB2312",
"EUC-KR",
"x-EUC-TW",
"EUC-JP",
"x-euc-jp-linux",
"KOI8-R",
"TIS-620",
"x-ISCII91",
"windows-1251",
"windows-1252",
"windows-1253",
"windows-1254",
"windows-1255",
"windows-1256",
"windows-1257",
"windows-1258",
"windows-932",
"x-mswin-936",
"x-windows-949",
"x-windows-950",
"windows-31j",
"Big5",
"Big5-HKSCS",
"x-MS950-HKSCS",
"ISO-2022-JP",
"ISO-2022-KR",
"x-ISO-2022-CN-CNS",
"x-ISO-2022-CN-GB",
"Big5-HKSCS",
"x-Johab",
"Shift_JIS"
};
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun 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.nio.charset.*;
public class Default {
public static void main(String[] args) {
System.out.println(Charset.defaultCharset());
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
* @bug 4786884
* @summary Ensure that passing the empty string to Charset methods and
* constructors causes an IllegalArgumentException to be thrown
*
* @build EmptyCharsetName
* @run main EmptyCharsetName
* @run main/othervm -Dsun.nio.cs.bugLevel=1.4 EmptyCharsetName
*/
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
public class EmptyCharsetName {
static boolean compat;
static abstract class Test {
public abstract void go() throws Exception;
Test() throws Exception {
try {
go();
} catch (Exception x) {
if (compat) {
if (x instanceof UnsupportedCharsetException) {
System.err.println("Thrown as expected: " + x);
return;
}
throw new Exception("Exception thrown", x);
}
if (x instanceof IllegalCharsetNameException) {
System.err.println("Thrown as expected: " + x);
return;
}
throw new Exception("Incorrect exception: "
+ x.getClass().getName(),
x);
}
if (!compat)
throw new Exception("No exception thrown");
}
}
public static void main(String[] args) throws Exception {
// If sun.nio.cs.bugLevel == 1.4 then we want the 1.4 behavior
String bl = System.getProperty("sun.nio.cs.bugLevel");
compat = (bl != null && bl.equals("1.4"));
new Test() {
public void go() throws Exception {
Charset.forName("");
}};
new Test() {
public void go() throws Exception {
Charset.isSupported("");
}};
new Test() {
public void go() throws Exception {
new Charset("", new String[] { }) {
public CharsetDecoder newDecoder() {
return null;
}
public CharsetEncoder newEncoder() {
return null;
}
public boolean contains(Charset cs) {
return false;
}
};
}};
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, 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 encode/decode convenience methods
*/
import java.nio.*;
import java.nio.charset.*;
public class EncDec {
public static void main(String[] args) throws Exception {
String s = "Hello, world!";
ByteBuffer bb = ByteBuffer.allocate(100);
bb.put(Charset.forName("ISO-8859-15").encode(s)).flip();
String t = Charset.forName("UTF-8").decode(bb).toString();
System.err.println(t);
if (!t.equals(s))
throw new Exception("Mismatch: " + s + " != " + t);
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
* @bug 6330020
* @summary Ensure Charset.forName/isSupport throws the correct exception
* if the charset names passed in are illegal.
*/
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.util.*;
public class IllegalCharsetName {
public static void main(String[] args) throws Exception {
String[] illegalNames = {
".",
"_",
":",
"-",
".name",
"_name",
":name",
"-name",
"name*name",
"name?name"
};
for (int i = 0; i < illegalNames.length; i++) {
try {
Charset.forName(illegalNames[i]);
throw new Exception("Charset.forName(): No exception thrown");
} catch (IllegalCharsetNameException x) { //expected
}
try {
Charset.isSupported(illegalNames[i]);
throw new Exception("Charset.isSupported(): No exception thrown");
} catch (IllegalCharsetNameException x) { //expected
}
}
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* @test
* @bug 4777124 6920545
* @summary Verify that all Charset subclasses are available through the API
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import sun.misc.Launcher;
public class NIOCharsetAvailabilityTest {
public static void main(String[] args) throws Exception {
// build the set of all Charset subclasses in the
// two known charset implementation packages
Set charsets = new HashSet();
addCharsets(charsets, "sun.nio.cs");
addCharsets(charsets, "sun.nio.cs.ext");
// remove the charsets that the API says are available
Collection availableCharsets = Charset.availableCharsets().values();
Iterator iter = availableCharsets.iterator();
while (iter.hasNext()) {
charsets.remove(((Charset) iter.next()).getClass());
}
// remove the known pseudo-charsets that serve only to implement
// other charsets, but shouldn't be known to the public
charsets.remove(Class.forName("sun.nio.cs.Unicode"));
charsets.remove(Class.forName("sun.nio.cs.ext.HKSCS"));
charsets.remove(Class.forName("sun.nio.cs.ext.HKSCS_2001"));
charsets.remove(Class.forName("sun.nio.cs.ext.ISO2022"));
charsets.remove(Class.forName("sun.nio.cs.ext.ISO2022_CN_GB"));
charsets.remove(Class.forName("sun.nio.cs.ext.ISO2022_CN_CNS"));
// report the charsets that are implemented but not available
iter = charsets.iterator();
while (iter.hasNext()) {
System.out.println("Unused Charset subclass: " + ((Class) iter.next()).getName());
}
if (charsets.size() > 0) {
throw new RuntimeException();
}
}
private static Vector classPathSegments = new Vector();
private static void addCharsets(Set charsets, final String packageName)
throws Exception {
String classPath =
(String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("sun.boot.class.path"));
String s =
(String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("java.class.path"));
// Search combined system and application class path
if (s != null && s.length() != 0) {
classPath += File.pathSeparator + s;
}
while (classPath != null && classPath.length() != 0) {
int i = classPath.lastIndexOf(java.io.File.pathSeparatorChar);
String dir = classPath.substring(i + 1);
if (i == -1) {
classPath = null;
} else {
classPath = classPath.substring(0, i);
}
classPathSegments.insertElementAt(dir, 0);
}
// add extensions from the extension class loader
ClassLoader appLoader = Launcher.getLauncher().getClassLoader();
URLClassLoader extLoader = (URLClassLoader) appLoader.getParent();
URL[] urls = extLoader.getURLs();
for (int i = 0; i < urls.length; i++) {
try {
URI uri = new URI(urls[i].toString());
classPathSegments.insertElementAt(uri.getPath(), 0);
} catch (URISyntaxException e) {
}
}
String[] classList = (String[])
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction() {
public Object run() {
return getClassList(packageName, "");
}
});
for (int i = 0; i < classList.length; i++) {
try {
Class clazz = Class.forName(packageName + "." + classList[i]);
Class superclazz = clazz.getSuperclass();
while (superclazz != null && !superclazz.equals(Object.class)) {
if (superclazz.equals(Charset.class)) {
charsets.add(clazz);
break;
} else {
superclazz = superclazz.getSuperclass();
}
}
} catch (ClassNotFoundException e) {
}
}
}
private static final char ZIPSEPARATOR = '/';
/**
* Walk through CLASSPATH and find class list from a package.
* The class names start with prefix string
* @param package name, class name prefix
* @return class list in an array of String
*/
private static String[] getClassList(String pkgName, String prefix) {
Vector listBuffer = new Vector();
String packagePath = pkgName.replace('.', File.separatorChar)
+ File.separatorChar;
String zipPackagePath = pkgName.replace('.', ZIPSEPARATOR)
+ ZIPSEPARATOR;
for (int i = 0; i < classPathSegments.size(); i++){
String onePath = (String) classPathSegments.elementAt(i);
File f = new File(onePath);
if (!f.exists())
continue;
if (f.isFile())
scanFile(f, zipPackagePath, listBuffer, prefix);
else if (f.isDirectory()) {
String fullPath;
if (onePath.endsWith(File.separator))
fullPath = onePath + packagePath;
else
fullPath = onePath + File.separatorChar + packagePath;
File dir = new File(fullPath);
if (dir.exists() && dir.isDirectory())
scanDir(dir, listBuffer, prefix);
}
}
String[] classNames = new String[listBuffer.size()];
listBuffer.copyInto(classNames);
return classNames;
}
private static void addClass (String className, Vector listBuffer, String prefix) {
if (className != null && className.startsWith(prefix)
&& !listBuffer.contains(className))
listBuffer.addElement(className);
}
private static String midString(String str, String pre, String suf) {
String midStr;
if (str.startsWith(pre) && str.endsWith(suf))
midStr = str.substring(pre.length(), str.length() - suf.length());
else
midStr = null;
return midStr;
}
private static void scanDir(File dir, Vector listBuffer, String prefix) {
String[] fileList = dir.list();
for (int i = 0; i < fileList.length; i++) {
addClass(midString(fileList[i], "", ".class"), listBuffer, prefix);
}
}
private static void scanFile(File f, String packagePath, Vector listBuffer,
String prefix) {
try {
ZipInputStream zipFile = new ZipInputStream(new FileInputStream(f));
ZipEntry entry;
while ((entry = zipFile.getNextEntry()) != null) {
String eName = entry.getName();
if (eName.startsWith(packagePath)) {
if (eName.endsWith(".class")) {
addClass(midString(eName, packagePath, ".class"),
listBuffer, prefix);
}
}
}
} catch (FileNotFoundException e) {
System.out.println("file not found:" + e);
} catch (IOException e) {
System.out.println("file IO Exception:" + e);
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
* @bug 4448594
* @summary Ensure passing null to Charset.forName throws the correct exception
*/
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.util.*;
public class NullCharsetName {
public static void main(String[] args) throws Exception {
try {
Charset.forName(null);
} catch (Exception x) {
if (x instanceof IllegalArgumentException) {
System.err.println("Thrown as expected: " + x);
return;
}
throw new Exception("Incorrect exception: "
+ x.getClass().getName(),
x);
}
throw new Exception("No exception thrown");
}
}
此差异已折叠。
#!/bin/sh
#
# Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
# CA 95054 USA or visit www.sun.com if you need additional information or
# have any questions.
#
# @test
# @bug 4772857
# @summary Unit test for Charset.defaultCharset
#
# @build Default
# @run shell default.sh
#
# Command-line usage: sh default.sh [/path/to/build]
if [ -z "$TESTJAVA" ]; then
if [ $# -lt 1 ]; then exit 1; fi
TESTJAVA=$1; shift
TESTSRC=`pwd`
TESTCLASSES=`pwd`
fi
s="`uname -s`"
if [ "$s" != Linux -a "$s" != SunOS ]; then
echo "$s: locale command not supported on this system, skipping..."
exit 0
fi
JAVA=$TESTJAVA/bin/java
tolower() {
echo "$1" | tr '[A-Z]' '[a-z]'
}
go() {
L="$1"
shift
if [ "x`locale -a | grep \^$L\$`" != "x$L" ]; then
echo "$L: Locale not supported, skipping..."
return
fi
ecs="$1"; shift
echo -n "$L: "
cs="`LC_ALL=$L $JAVA -cp $TESTCLASSES Default`"
if [ $? != 0 ]; then
exit 1
elif [ "`tolower $cs`" != "`tolower $ecs`" ]; then
echo "$cs, expected $ecs -- ERROR"
exit 1
else
echo "$cs, as expected"
fi
}
go en_US iso-8859-1
go ja_JP.utf8 utf-8
go tr_TR iso-8859-9
go C us-ascii
if [ "$s" = Linux ]; then
go ja_JP x-euc-jp-linux
go ja_JP.eucjp x-euc-jp-linux
go ja_JP.ujis x-euc-jp-linux
go ja_JP.utf8 utf-8
fi
# Solaris
if [ "$s" = SunOS ]; then
go ja x-eucjp-open
go ja_JP.eucJP x-eucjp-open
go ja_JP.PCK x-PCK
go ja_JP.UTF-8 utf-8
fi
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
* @bug 4853350
* @summary Ensure that averages do not exceed maxima
*
* @build AverageMax
* @run main AverageMax
* @run main/othervm -Dsun.nio.cs.bugLevel=1.4 AverageMax
*/
import java.nio.*;
import java.nio.charset.*;
public class AverageMax {
static boolean compat;
static abstract class Test {
public abstract void go() throws Exception;
Test() throws Exception {
try {
go();
} catch (Exception x) {
if (compat) {
throw new Exception("Exception thrown", x);
}
if (x instanceof IllegalArgumentException) {
System.err.println("Thrown as expected: " + x);
return;
}
throw new Exception("Incorrect exception: "
+ x.getClass().getName(),
x);
}
if (!compat)
throw new Exception("No exception thrown");
}
}
public static void main(String[] args) throws Exception {
// If sun.nio.cs.bugLevel == 1.4 then we want the 1.4 behavior
String bl = System.getProperty("sun.nio.cs.bugLevel");
compat = (bl != null && bl.equals("1.4"));
final Charset ascii = Charset.forName("US-ASCII");
new Test() {
public void go() throws Exception {
new CharsetDecoder(ascii, 3.9f, 1.2f) {
protected CoderResult decodeLoop(ByteBuffer in,
CharBuffer out)
{
return null;
}
};
}};
new Test() {
public void go() throws Exception {
new CharsetEncoder(ascii, 3.9f, 1.2f) {
protected CoderResult encodeLoop(CharBuffer in,
ByteBuffer out)
{
return null;
}
};
}};
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
* @bug 4400697
* @summary Ensure that CharsetDecoder.decode throws BUE on empty input
*/
import java.nio.*;
import java.nio.charset.*;
public class EmptyInput {
public static void main(String[] args) throws Exception {
ByteBuffer bb = ByteBuffer.allocate(10);
bb.flip();
CharsetDecoder cd = Charset.forName("US-ASCII").newDecoder();
try {
cd.decode(bb, CharBuffer.allocate(10), true).throwException();
} catch (BufferUnderflowException x) {
System.err.println("BufferUnderflowException thrown as expected");
return;
}
throw new Exception("BufferUnderflowException not thrown");
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
* @bug 4821213
* @summary Unit test for CharsetEncoder.canEncode methods
*/
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
public class CanEncode {
private static int errors = 0;
private static PrintStream out = System.err;
private static void wrong(CharsetEncoder ce, boolean can, String what) {
out.println(ce.charset().name()
+ ": Wrong answer for " + what
+ ": " + !can);
errors++;
}
private static void ck(CharsetEncoder ce, char c, boolean can)
throws Exception
{
if (ce.canEncode(c) != can)
wrong(ce, can,
("'" + c + "' (0x"
+ Integer.toHexString(c & 0xffff) + ")"));
}
private static void ck(CharsetEncoder ce, String s, boolean can)
throws Exception
{
if (ce.canEncode(CharBuffer.wrap(s.toCharArray())) != can)
wrong(ce, can, "array \"" + s + "\"");
if (ce.canEncode(CharBuffer.wrap(s)) != can)
wrong(ce, can, "buffer \"" + s + "\"");
}
private static void test(String csn) throws Exception {
Charset cs = Charset.forName(csn);
CharsetEncoder ce = cs.newEncoder();
if (cs.name().equals("US-ASCII")) {
ck(ce, 'x', true);
ck(ce, '\u00B6', false);
ck(ce, "x", true);
ck(ce, "\u00B6", false);
ck(ce, "xyzzy", true);
ck(ce, "xy\u00B6", false);
}
// Unpaired surrogates should never be encodable
ck(ce, '\ud800', false);
ck(ce, '\ud801', false);
ck(ce, '\udffe', false);
ck(ce, '\udfff', false);
ck(ce, "\ud800", false);
ck(ce, "\ud801", false);
ck(ce, "\udffe", false);
ck(ce, "\udfff", false);
}
public static void main(String[] args) throws Exception {
test("US-ASCII");
test("UTF-8");
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
* @bug 6227608
* @summary Test proper handling of flush()
* @author Martin Buchholz
*/
import java.util.*;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
public class Flush {
private static byte[] contents(ByteBuffer bb) {
byte[] contents = new byte[bb.position()];
((ByteBuffer)(bb.duplicate().flip())).get(contents);
return contents;
}
private static ByteBuffer extend(ByteBuffer bb) {
ByteBuffer x = ByteBuffer.allocate(2*bb.capacity()+10);
bb.flip();
x.put(bb);
return x;
}
private static void realMain(String[] args) throws Throwable {
// A japanese character should decode as a 3-byte
// switch-to-japanese escape sequence, followed by a 2-byte
// encoding of the char itself, followed by a 3-byte return to
// ASCII escape sequence.
char[] jis0208 = {'\u3001'};
CharBuffer cb = CharBuffer.wrap(jis0208);
ByteBuffer bb = ByteBuffer.allocate(6);
CharsetEncoder enc = Charset.forName("ISO-2022-JP").newEncoder();
check(enc.encode(cb, bb, true).isUnderflow());
System.out.println(Arrays.toString(contents(bb)));
check(! cb.hasRemaining());
equal(contents(bb).length, 3 + 2);
equal(bb.get(0), (byte)0x1b);
//----------------------------------------------------------------
// We must be able to recover if flush() returns OVERFLOW
//----------------------------------------------------------------
check(enc.flush(bb).isOverflow());
check(enc.flush(bb).isOverflow());
equal(contents(bb).length, 3 + 2);
bb = extend(bb);
check(enc.flush(bb).isUnderflow());
equal(bb.get(3 + 2), (byte)0x1b);
System.out.println(Arrays.toString(contents(bb)));
equal(contents(bb).length, 3 + 2 + 3);
//----------------------------------------------------------------
// A final redundant flush() is a no-op
//----------------------------------------------------------------
check(enc.flush(bb).isUnderflow());
check(enc.flush(bb).isUnderflow());
equal(contents(bb).length, 3 + 2 + 3);
//----------------------------------------------------------------
// CharsetEncoder.encode(ByteBuffer) must call flush(ByteBuffer)
//----------------------------------------------------------------
bb = enc.encode(CharBuffer.wrap(jis0208));
byte[] expected = "\u001b$B!\"\u001b(B".getBytes("ASCII");
byte[] contents = new byte[bb.limit()]; bb.get(contents);
check(Arrays.equals(contents, expected));
}
//--------------------- Infrastructure ---------------------------
static volatile int passed = 0, failed = 0;
static void pass() { passed++; }
static void fail() { failed++; Thread.dumpStack(); }
static void fail(String msg) { System.out.println(msg); fail(); }
static void unexpected(Throwable t) { failed++; t.printStackTrace(); }
static void check(boolean cond) { if (cond) pass(); else fail(); }
static void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else {System.out.println(x + " not equal to " + y); fail(); }}
public static void main(String[] args) throws Throwable {
try { realMain(args); } catch (Throwable t) { unexpected(t); }
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new Exception("Some tests failed");
}
}
此差异已折叠。
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
@bug 6176819
@summary Check if COMPUND_TEXT charset works as expected
@run main/timeout=1200 TestCOMP
*/
import java.util.HashMap;
import java.util.Set;
import java.io.UnsupportedEncodingException;
import java.nio.charset.*;
import java.nio.*;
public class TestCOMP {
public static void main(String[] argv) throws CharacterCodingException {
String osName = System.getProperty("os.name");
if (osName.startsWith("Windows"))
return;
try {
String src =
"JIS0208\u4eb0" +
"ASCII" +
"JIS0212\u4e74\u4e79" +
"GB2312\u7279\u5b9a" +
"JIS0201\uff67\uff68" +
"Johab\uac00\uac01";
byte[] ba = src.getBytes("COMPOUND_TEXT");
/*
System.out.print("ba=");
for (int i = 0; i < ba.length; i++) {
System.out.printf("<%x> ", ba[i] & 0xff);
}
System.out.println();
*/
String dst = new String(ba, "COMPOUND_TEXT");
char[] ca = dst.toCharArray();
/*
System.out.print("ca=");
for (int i = 0; i < ca.length; i++) {
System.out.printf("<%x> ", ca[i] & 0xffff);
}
System.out.println();
*/
if (!src.equals(dst)) {
System.out.printf("src=<%s>\n", src);
System.out.printf("dst=<%s>\n", dst);
throw new CharacterCodingException();
}
} catch (Exception e){
e.printStackTrace();
}
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
@bug 6227339
@summary Check if returned CoderResult.unmappableForLength has correct
length value.
*/
import java.nio.charset.*;
import java.nio.*;
public class TestUnmappableForLength {
public static void main(String[] argv) throws CharacterCodingException {
byte[] ba = {(byte)0xa2, (byte)0xff};
//EUC_TW has its own decodeArrayLoop()
testDecode("EUC_TW", ba, 2);
//EUC_CN uses DoubleByteDecoder's decodeArrayLoop()
testDecode("EUC_CN", ba, 2);
}
static void testDecode(String csName, byte[] ba, int expected)
throws CharacterCodingException
{
try {
CoderResult cr = Charset
.forName(csName)
.newDecoder()
.decode(ByteBuffer.wrap(ba), CharBuffer.allocate(4), true);
if (cr.isUnmappable() && cr.length() != expected) {
throw new CharacterCodingException();
}
} catch (IllegalArgumentException x){
x.printStackTrace();
}
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
* @bug 4517279
* @summary Stochastic test of thread-local coder caches
*/
import java.nio.*;
import java.nio.charset.*;
import java.util.*;
public class BashCache {
private static final int THREADS = 10;
private static final int TRIALS = 1000;
private static final Charset[] charsets
= new Charset[] {
Charset.forName("US-ASCII"),
Charset.forName("UTF-8"),
Charset.forName("CP1252"),
Charset.forName("UTF-16BE") };
private static volatile boolean failed = false;
private static class Basher extends Thread {
Random rnd = new Random(System.identityHashCode(this));
public void run() {
for (int i = 0; i < TRIALS; i++) {
Charset cs = charsets[rnd.nextInt(4)];
try {
if (rnd.nextBoolean()) {
cs.encode("hi mom");
} else {
cs.decode(ByteBuffer.wrap(new byte[] {
(byte)'x', (byte)'y',
(byte)'z', (byte)'z',
(byte)'y' }));
}
} catch (Exception x) {
x.printStackTrace();
failed = true;
return;
}
if (rnd.nextBoolean())
Thread.yield();
}
}
}
public static void main(String[] args) throws Exception {
Charset cs = Charset.forName("us-ascii");
Basher[] bashers = new Basher[THREADS];
for (int i = 0; i < THREADS; i++) {
bashers[i] = new Basher();
bashers[i].start();
}
for (int i = 0; i < THREADS; i++)
bashers[i].join();
if (failed)
throw new Exception("Test failed");
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, 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 charset-based streams
*/
import java.io.*;
import java.util.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class BashStreams {
static final PrintStream log = System.err;
static class CharacterGenerator {
private final Random rand;
private final int max;
private final int limit;
private int count = 0;
CharacterGenerator(long seed, String csn, int limit) {
rand = new Random(seed);
this.max = Surrogate.UCS4_MAX + 1;
this.limit = limit;
}
private char[] saved = new char[10];
private int savedCount = 0;
void push(char c) {
saved[savedCount++] = c;
count--;
}
int count() {
return count;
}
boolean hasNext() {
return count < limit;
}
char next() {
if (count >= limit)
throw new RuntimeException("EOF");
if (savedCount > 0) {
savedCount--;
count++;
return saved[savedCount];
}
int c;
for (;;) {
c = rand.nextInt(max);
if (Surrogate.is(c) || (c == 0xfffe) || (c == 0xffff))
continue;
if (Surrogate.neededFor(c) && (count == limit - 1))
continue;
break;
}
count++;
if (Surrogate.neededFor(c)) {
count++;
push(Surrogate.low(c));
return Surrogate.high(c);
}
return (char)c;
}
}
static void mismatch(String csn, int count, char c, char d) {
throw new RuntimeException(csn + ": Mismatch at count "
+ count
+ ": " + Integer.toHexString(c)
+ " != "
+ Integer.toHexString(d));
}
static void mismatchedEOF(String csn, int count, int cgCount) {
throw new RuntimeException(csn + ": Mismatched EOFs: "
+ count
+ " != "
+ cgCount);
}
static class Sink // One abomination...
extends OutputStream
implements WritableByteChannel
{
private final String csn;
private final CharacterGenerator cg;
private int count = 0;
Sink(String csn, long seed) {
this.csn = csn;
this.cg = new CharacterGenerator(seed, csn, Integer.MAX_VALUE);
}
public void write(int b) throws IOException {
write (new byte[] { (byte)b }, 0, 1);
}
private int check(byte[] ba, int off, int len) throws IOException {
String s = new String(ba, off, len, csn);
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
char d = cg.next();
if (c != d) {
if (c == '?') {
if (Surrogate.isHigh(d))
cg.next();
continue;
}
mismatch(csn, count + i, c, d);
}
}
count += n;
return len;
}
public void write(byte[] ba, int off, int len) throws IOException {
check(ba, off, len);
}
public int write(ByteBuffer bb) throws IOException {
int n = check(bb.array(),
bb.arrayOffset() + bb.position(),
bb.remaining());
bb.position(bb.position() + n);
return n;
}
public void close() {
count = -1;
}
public boolean isOpen() {
return count >= 0;
}
}
static void testWrite(String csn, int limit, long seed, Writer w)
throws IOException
{
Random rand = new Random(seed);
CharacterGenerator cg = new CharacterGenerator(seed, csn,
Integer.MAX_VALUE);
int count = 0;
char[] ca = new char[16384];
int n = 0;
while (count < limit) {
n = rand.nextInt(ca.length);
for (int i = 0; i < n; i++)
ca[i] = cg.next();
w.write(ca, 0, n);
count += n;
}
if (Surrogate.isHigh(ca[n - 1]))
w.write(cg.next());
w.close();
}
static void testStreamWrite(String csn, int limit, long seed)
throws IOException
{
log.println(" write stream");
testWrite(csn, limit, seed,
new OutputStreamWriter(new Sink(csn, seed), csn));
}
static void testChannelWrite(String csn, int limit, long seed)
throws IOException
{
log.println(" write channel");
testWrite(csn, limit, seed,
Channels.newWriter(new Sink(csn, seed),
Charset.forName(csn)
.newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE),
8192));
}
static class Source // ... and another
extends InputStream
implements ReadableByteChannel
{
private final String csn;
private final CharsetEncoder enc;
private final CharacterGenerator cg;
private int count = 0;
Source(String csn, long seed, int limit) {
this.csn = csn.startsWith("\1") ? csn.substring(1) : csn;
this.enc = Charset.forName(this.csn).newEncoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
this.cg = new CharacterGenerator(seed, csn, limit);
}
public int read() throws IOException {
byte[] b = new byte[1];
read(b);
return b[0];
}
private CharBuffer cb = CharBuffer.allocate(8192);
private ByteBuffer bb = null;
public int read(byte[] ba, int off, int len) throws IOException {
if (!cg.hasNext())
return -1;
int end = off + len;
int i = off;
while (i < end) {
if ((bb == null) || !bb.hasRemaining()) {
cb.clear();
while (cb.hasRemaining()) {
if (!cg.hasNext())
break;
char c = cg.next();
if (Surrogate.isHigh(c) && (cb.remaining() == 1)) {
cg.push(c);
break;
}
cb.put(c);
}
cb.flip();
if (!cb.hasRemaining())
break;
bb = enc.encode(cb);
}
int d = Math.min(bb.remaining(), end - i);
bb.get(ba, i, d);
i += d;
}
return i - off;
}
public int read(ByteBuffer bb) throws IOException {
int n = read(bb.array(),
bb.arrayOffset() + bb.position(),
bb.remaining());
if (n >= 0)
bb.position(bb.position() + n);
return n;
}
public void close() {
count = -1;
}
public boolean isOpen() {
return count != -1;
}
}
static void testRead(String csn, int limit, long seed, int max,
Reader rd)
throws IOException
{
Random rand = new Random(seed);
CharacterGenerator cg = new CharacterGenerator(seed, csn, limit);
int count = 0;
char[] ca = new char[16384];
int n = 0;
while (count < limit) {
int rn = rand.nextInt(ca.length);
n = rd.read(ca, 0, rn);
if (n < 0)
break;
for (int i = 0; i < n; i++) {
char c = ca[i];
if (!cg.hasNext())
mismatchedEOF(csn, count + i, cg.count());
char d = cg.next();
if (c == '?') {
if (Surrogate.isHigh(d)) {
cg.next();
continue;
}
if (d > max)
continue;
}
if (c != d)
mismatch(csn, count + i, c, d);
}
count += n;
}
if (cg.hasNext())
mismatchedEOF(csn, count, cg.count());
rd.close();
}
static void testStreamRead(String csn, int limit, long seed, int max)
throws IOException
{
log.println(" read stream");
testRead(csn, limit, seed, max,
new InputStreamReader(new Source(csn, seed, limit), csn));
}
static void testChannelRead(String csn, int limit, long seed, int max)
throws IOException
{
log.println(" read channel");
testRead(csn, limit, seed, max,
Channels.newReader(new Source(csn, seed, limit), csn));
}
static final int LIMIT = 1 << 21;
static void test(String csn, int limit, long seed, int max)
throws Exception
{
log.println();
log.println(csn);
testStreamWrite(csn, limit, seed);
testChannelWrite(csn, limit, seed);
testStreamRead(csn, limit, seed, max);
testChannelRead(csn, limit, seed, max);
}
public static void main(String[] args) throws Exception {
if (System.getProperty("os.arch").equals("ia64")) {
// This test requires 54 minutes on an Itanium-1 processor
return;
}
int ai = 0, an = args.length;
int limit;
if (ai < an)
limit = 1 << Integer.parseInt(args[ai++]);
else
limit = LIMIT;
log.println("limit = " + limit);
long seed;
if (ai < an)
seed = Long.parseLong(args[ai++]);
else
seed = System.currentTimeMillis();
log.println("seed = " + seed);
test("UTF-8", limit, seed, Integer.MAX_VALUE);
test("US-ASCII", limit, seed, 0x7f);
test("ISO-8859-1", limit, seed, 0xff);
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
* @bug 4712786
* @summary Check charsets against reference files
*
* @build Util
* @run main Check shift_jis ref.shift_jis
* @run main/othervm -Dsun.nio.cs.map=Windows-31J/Shift_JIS Check shift_jis ref.windows-31j
*/
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
import java.util.regex.*;
public class Check {
private static PrintStream log = System.err;
private static final int UNICODE_SIZE = (1 << 16);
private final String csName;
private final String refName;
private byte[][] bytes = new byte[UNICODE_SIZE][]; // Indexed by char
private int errors = 0;
private Check(String csn, String refn) {
csName = csn;
refName = refn;
}
private Check load()
throws IOException
{
File fn = new File(System.getProperty("test.src", "."), refName);
FileChannel fc = new FileInputStream(fn).getChannel();
ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
CharBuffer cb = Charset.forName("US-ASCII").decode(bb);
Pattern p = Pattern.compile("^(\\p{XDigit}+) +(\\p{XDigit}+)$",
Pattern.MULTILINE);
Matcher m = p.matcher(cb);
while (m.find()) {
char c = (char)Integer.parseInt(m.group(1), 16);
String v = m.group(2);
int nb = v.length() >> 1;
byte[] ba = new byte[nb];
for (int i = 0; i < nb; i++) {
ba[i] = (byte)Integer.parseInt(v.substring(i << 1, (i << 1) + 2),
16);
}
bytes[c] = ba;
}
return this;
}
private void error() {
if (++errors >= 100)
throw new RuntimeException("100 errors occurred (there might be more)");
}
private void mismatch(String s, byte[] expected, byte[] got) {
log.println("Encoding mismatch on \""
+ Util.toString(s)
+ "\": Expected {"
+ Util.toString(expected)
+ "}, got {"
+ Util.toString(got)
+ "}");
error();
}
private void mismatch(int i, byte[] ba, String expected, String got) {
log.println("Decoding mismatch on \""
+ Util.toString((char)i)
+ "\", input {"
+ Util.toString(ba)
+ "}: Expected \""
+ Util.toString(expected)
+ "\", got \""
+ Util.toString(got)
+ "\"");
error();
}
private void check()
throws IOException
{
// String.getBytes(String csn)
for (int i = 0; i < UNICODE_SIZE; i++) {
if (bytes[i] == null)
continue;
String s = new String(new char[]{ (char)i });
byte[] ba = s.getBytes(csName);
if (Util.cmp(ba, bytes[i]) >= 0)
mismatch(s, bytes[i], ba);
}
log.println("String.getBytes(\"" + csName + "\") okay");
// String(byte[] ba, String csn)
for (int i = 0; i < UNICODE_SIZE; i++) {
if (bytes[i] == null)
continue;
String r = new String(new char[]{ (char)i });
String s = new String(bytes[i], csName);
if (!r.equals(s))
mismatch(i, bytes[i], r, s);
}
log.println("String(byte[] ba, \"" + csName + "\") okay");
// To be really thorough we should test OutputStreamWriter,
// InputStreamReader, and Charset{De,En}Coder here also,
// but the above will do for now.
if (errors > 0) {
throw new RuntimeException(errors + " error(s) occurred");
}
}
// Usage: Check charsetName referenceFileName
public static void main(String[] args) throws Exception {
new Check(args[0], args[1]).load().check();
}
}
#!/bin/sh
#
# Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
# CA 95054 USA or visit www.sun.com if you need additional information or
# have any questions.
#
# @test
# @summary Verify that sun.nio.cs.map property interpreted in ja multibyte locales
# @bug 4879123
# @build SJISPropTest
#
# @run shell/timeout=300 CheckSJISMappingProp.sh
# set platform-dependent variables
OS=`uname -s`
case "$OS" in
SunOS | Linux ) ;;
# Skip locale test for Windows
Windows* )
echo "Passed"; exit 0 ;;
* ) echo "Unrecognized system!" ; exit 1 ;;
esac
expectPass() {
if [ $1 -eq 0 ]
then echo "--- passed as expected"
else
echo "--- failed"
exit $1
fi
}
JAVA="${TESTJAVA}/bin/java -cp ${TESTCLASSES}"
runTest() {
echo "Testing:" ${1}
LC_ALL="$1" ; export LC_ALL
locale
# Firstly, test with property set
# (shift_jis should map to windows-31J charset)
${JAVA} -Dsun.nio.cs.map="Windows-31J/Shift_JIS" SJISPropTest MS932
expectPass $?
# Next, test without property set - "shift_jis" follows IANA conventions
# and should map to the sun.nio.cs.ext.Shift_JIS charset
${JAVA} SJISPropTest Shift_JIS
expectPass $?
}
# Run the test in the common Solaris/Linux locales
# Tests will simply run in current locale if locale isn't supported
# on the test machine/platform
for i in "ja" "ja_JP.PCK" "ja_JP.eucJP" ; do
runTest ${i}
done
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, 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 error cases are replaced correctly in String/ISR/OSW
* @bug 4457851
*
* @build Errors Util
* @run main Errors
*/
import java.io.*;
import java.nio.*;
public class Errors {
static PrintStream log = System.err;
static int failures = 0;
static final byte Q = (byte)'?';
static final byte X = (byte)'x';
static final byte Y = (byte)'y';
static final byte Z = (byte)'z';
static abstract class Test {
protected final String csn;
protected final String what;
Test(String csn, String what) {
this.csn = csn;
this.what = what;
}
abstract byte[] enc(String s) throws IOException;
Test test(String s, byte[] ref) {
log.print(" " + Util.toString(s.toCharArray()));
byte[] ba = null;
try {
ba = enc(s);
} catch (IOException x) {
log.println(" -e-> ERROR: " + x.getClass().getName());
failures++;
return this;
}
log.println(" -e-> " + Util.toString(ba));
int i = Util.cmp(ba, ref);
if (i >= 0) {
log.println(" ERROR: Mismatch at index " + i
+ ", expected: " + Util.toString(ref));
failures++;
}
return this;
}
abstract String dec(byte[] ba) throws IOException;
Test test(byte[] ba, String ref) {
log.print(" " + Util.toString(ba));
String s = null;
try {
s = dec(ba);
} catch (IOException x) {
log.println(" -d-> ERROR: " + x.getClass().getName());
failures++;
return this;
}
log.println(" -d-> " + Util.toString(s.toCharArray()));
char[] ca = s.toCharArray();
char[] refa = ref.toCharArray();
int i = Util.cmp(ca, refa);
if (i >= 0) {
log.println(" ERROR: Mismatch at index " + i
+ ", expected: " + Util.toString(refa));
failures++;
}
return this;
}
Test run() {
log.println(csn + ", " + what);
test("xyzzy", new byte[] { X, Y, Z, Z, Y });
// Malformed surrogates
test("\uD800x", new byte[] { Q, X });
test("\uDC00x", new byte[] { Q, X });
test("\uD800\uDB00x", new byte[] { Q, Q, X });
return this;
}
}
static class TestStream extends Test {
TestStream(String csn) {
super(csn, "I/O streams");
}
byte[] enc(String s) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Writer wr = new OutputStreamWriter(bos, csn);
wr.write(s);
wr.close();
return bos.toByteArray();
}
String dec(byte[] ba) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(ba);
Reader rd = new InputStreamReader(bis, csn);
char[] ca = new char[1024];
int n = rd.read(ca);
String s = new String(ca, 0, n);
rd.close();
return s;
}
}
static class TestString extends Test {
TestString(String csn) {
super(csn, "strings");
}
byte[] enc(String s) throws IOException {
return s.getBytes(csn);
}
String dec(byte[] ba) throws IOException {
return new String(ba, 0, ba.length, csn);
}
}
static void test_US_ASCII(Test t) {
t.run();
t.test("\u0080", new byte[] { Q });
t.test("\u0100", new byte[] { Q });
t.test("\uD800\uDC00", new byte[] { Q });
t.test("\uF000", new byte[] { Q });
t.test("\uFFFE", new byte[] { Q });
t.test("\uFFFF", new byte[] { Q });
t.test(new byte[] { X, (byte)0x7f, Y }, "x\u007Fy");
t.test(new byte[] { X, (byte)0x80, Y }, "x\uFFFDy");
t.test(new byte[] { (byte)0xf0, (byte)0xf0 }, "\uFFFD\uFFFD");
}
static void test_ISO_8859_1(Test t) {
t.run();
t.test("\u0080", new byte[] { (byte)0x80 });
t.test("\u0100", new byte[] { Q });
t.test("\uD800\uDC00x", new byte[] { Q, X });
t.test("\uF000", new byte[] { Q });
t.test("\uFFFE", new byte[] { Q });
t.test("\uFFFF", new byte[] { Q });
t.test(new byte[] { X, (byte)0x7f, Y }, "x\u007Fy");
t.test(new byte[] { X, (byte)0x80, Y }, "x\u0080y");
t.test(new byte[] { (byte)0xf0, (byte)0xf0 }, "\u00F0\u00F0");
}
static void test_UTF_8(Test t) {
t.run();
t.test("\u0080", new byte[] { (byte)0xC2, (byte)0x80 });
t.test("\u0100", new byte[] { (byte)0xC4, (byte)0x80 });
t.test("\uD800\uDC00",
new byte[] { (byte)0xF0, (byte)0x90, (byte)0x80, (byte)0x80 });
t.test("\uF000", new byte[] { (byte)0xEF, (byte)0x80, (byte)0x80 });
t.test("\uFFFE", new byte[] { (byte)0xEF, (byte)0xBF, (byte)0xBE });
t.test("\uFFFF", new byte[] { (byte)0xEF, (byte)0xBF, (byte)0xBF });
t.test(new byte[] { X, (byte)0x7f, Y }, "x\u007Fy");
t.test(new byte[] { X, (byte)0x80, Y }, "x\uFFFDy");
t.test(new byte[] { (byte)0xf0, (byte)0xf0 }, "\uFFFD");
}
public static void main(String[] args) throws Exception {
test_US_ASCII(new TestString("US-ASCII"));
test_US_ASCII(new TestStream("US-ASCII"));
test_ISO_8859_1(new TestString("ISO-8859-1"));
test_ISO_8859_1(new TestStream("ISO-8859-1"));
test_ISO_8859_1(new TestString("ISO-8859-15"));
test_ISO_8859_1(new TestStream("ISO-8859-15"));
test_UTF_8(new TestString("UTF-8"));
test_UTF_8(new TestStream("UTF-8"));
if (failures > 0) {
log.println();
throw new Exception("Tests failed: " + failures);
}
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, 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 InputStreamReader reads as many characters as possible
*/
// InputStreamReader is not required by its spec to read as many characters as
// possible upon each invocation of read(char[], int, int), but many programs
// (e.g., javac) depend upon this behavior.
import java.io.*;
public class FullRead {
static int MAX_LEN = 1 << 16;
static void test(File f, int len) throws Exception {
FileOutputStream fo = new FileOutputStream(f);
for (int i = 0; i < len; i++)
fo.write('x');
fo.close();
FileInputStream fi = new FileInputStream(f);
Reader rd = new InputStreamReader(fi, "US-ASCII");
char[] cb = new char[MAX_LEN + 100];
int n = rd.read(cb, 0, cb.length);
System.out.println(len + " : " + n);
if (len != n)
throw new Exception("Expected " + len + ", read " + n);
}
public static void main(String[] args) throws Exception {
File f = File.createTempFile("foo", "bar");
f.deleteOnExit();
System.out.println(f);
for (int i = 4; i <= MAX_LEN; i <<= 1)
test(f, i);
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, 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 ISR/OSW constructors that take coders
*/
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
public class IOCoders {
static Charset ascii = Charset.forName("US-ASCII");
static void isrPositive() throws Exception {
ByteArrayInputStream bis
= new ByteArrayInputStream(new byte[] { (byte)'h', (byte)'i' });
InputStreamReader isr
= new InputStreamReader(bis,
ascii.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT));
BufferedReader br = new BufferedReader(isr);
if (!br.readLine().equals("hi"))
throw new Exception();
}
static void isrNegative() throws Exception {
ByteArrayInputStream bis
= new ByteArrayInputStream(new byte[] { (byte)0xff, (byte)0xff });
InputStreamReader isr
= new InputStreamReader(bis,
ascii.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT));
BufferedReader br = new BufferedReader(isr);
try {
br.readLine();
} catch (MalformedInputException x) {
return;
}
throw new Exception();
}
static void oswPositive() throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
OutputStreamWriter osw
= new OutputStreamWriter(bos,
ascii.newEncoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT));
osw.write("hi");
osw.close();
if (!ascii.decode(ByteBuffer.wrap(bos.toByteArray()))
.toString().equals("hi"))
throw new Exception();
}
static void oswNegative() throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
OutputStreamWriter osw
= new OutputStreamWriter(bos,
ascii.newEncoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT));
try {
osw.write("\u00A0\u00A1");
} catch (UnmappableCharacterException x) {
return;
}
throw new Exception();
}
public static void main(String[] args) throws Exception {
isrPositive();
isrNegative();
oswPositive();
oswNegative();
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
* @bug 4821286
* @summary Check correctness of CharsetEncoder.isLegalReplacement(byte[])
*/
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.util.*;
public class IsLegalReplacement {
static PrintStream out = System.err;
static int errors = 0;
static String toString(byte[] ba) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < ba.length; i++) {
byte b = ba[i];
if (i > 0)
sb.append(' ');
sb.append(Integer.toHexString((b >> 4) & 0xf));
sb.append(Integer.toHexString((b >> 0) & 0xf));
}
return sb.toString();
}
static CoderResult ilr(String csn, byte[] repl) {
CharsetDecoder dec = Charset.forName(csn).newDecoder();
dec.onMalformedInput(CodingErrorAction.REPORT);
dec.onUnmappableCharacter(CodingErrorAction.REPORT);
ByteBuffer bb = ByteBuffer.wrap(repl);
CharBuffer cb = CharBuffer.allocate((int)(bb.remaining()
* dec.maxCharsPerByte()));
return dec.decode(bb, cb, true);
}
static void test(String csn, byte[] repl, boolean expected)
throws Exception
{
CharsetEncoder enc = Charset.forName(csn).newEncoder();
out.print(csn + ": " + toString(repl) + ": ");
if (enc.isLegalReplacement(repl) == expected) {
out.print("Okay");
} else {
out.print("Wrong: Expected " + expected);
errors++;
}
out.println(" (" + ilr(csn, repl) + ")");
}
public static void main(String[] args) throws Exception {
test("UTF-16", new byte [] { (byte)0xd8, 0, (byte)0xdc, 0 }, true);
test("UTF-16", new byte [] { (byte)0xdc, 0, (byte)0xd8, 0 }, false);
test("UTF-16", new byte [] { (byte)0xd8, 0 }, false);
test("UTF-16BE", new byte [] { (byte)0xd8, 0, (byte)0xdc, 0 }, true);
test("UTF-16BE", new byte [] { (byte)0xdc, 0, (byte)0xd8, 0 }, false);
test("UTF-16BE", new byte [] { (byte)0xd8, 0 }, false);
test("UTF-16LE", new byte [] { 0, (byte)0xd8, 0, (byte)0xdc }, true);
test("UTF-16LE", new byte [] { 0, (byte)0xdc, 0, (byte)0xd8 }, false);
test("UTF-16LE", new byte [] { 0, (byte)0xd8 }, false);
if (errors > 0)
throw new Exception(errors + " error(s) occurred");
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
@bug 6226510
@summary Check that ISO-2022-JP's encoder correctly resets to ASCII mode
@author Martin Buchholz
*/
import java.nio.*;
import java.nio.charset.*;
public class ResetISO2022JP {
public static void main(String[] args) throws Exception {
if (! (encode(true).equals(encode(false))))
throw new Exception("Mismatch!");
}
static String encode(boolean reuseEncoder) {
String s = "\u3042\u3043\u3044";
CharsetEncoder e = Charset.forName("ISO-2022-JP").newEncoder();
if (reuseEncoder) {
// I'm turning japanese. Yes I'm turning japanese. Yes I think so!
e.encode(CharBuffer.wrap(s), ByteBuffer.allocate(64), true);
// Should put encoder back into ASCII mode
e.reset();
}
ByteBuffer bb = ByteBuffer.allocate(64);
e.encode(CharBuffer.wrap(s), bb, true);
e.flush(bb);
bb.flip();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bb.limit(); i++)
sb.append(String.format("%02x ", bb.get(i)));
System.out.println(sb);
return sb.toString();
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
*
*
* Regression test class run by CheckSJISMappingProp.sh to verify
* that sun.nio.cs.map property is correctly interpreted in
* multibyte Japanese locales
*
*/
public class SJISPropTest {
public static void main(String[] args) throws Exception {
boolean sjisIsMS932 = false;
if (args[0].equals("MS932"))
sjisIsMS932 = true;
byte[] testBytes = { (byte)0x81, (byte)0x60 };
// JIS X based Shift_JIS and Windows-31J differ
// in a number of mappings including this one.
String expectedMS932 = new String("\uFF5E");
String expectedSJIS = new String("\u301C");
// Alias "shift_jis" will map to Windows-31J
// if the sun.nio.cs.map system property is defined as
// "Windows-31J/Shift_JIS". This should work in all
// multibyte (especially Japanese) locales.
String s = new String(testBytes, "shift_jis");
if (sjisIsMS932 && !s.equals(expectedMS932))
throw new Exception("not MS932");
else if (!sjisIsMS932 && !s.equals(expectedSJIS))
throw new Exception("not SJIS");
}
}
/*
* Copyright 2010 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/* @test
* @bug 4521942
* @summary Ensure that InputStreamReaders work properly
* when the underlying byte stream times out
*/
import java.net.*;
import java.io.*;
public class StreamTimeout {
private static PrintStream log = System.err;
private static String charset = "US-ASCII";
private static Object lock = new Object();
private static synchronized void waitABit(int millisec) {
synchronized(lock) {
try {
lock.wait(millisec);
} catch (InterruptedException e) {
//ignore
}
}
}
private static class Client extends Thread {
public void run() {
try {
Socket so = new Socket("127.0.0.1", 22222);
Writer wr = new OutputStreamWriter(so.getOutputStream(),
charset);
wr.write("ab");
wr.flush();
} catch (IOException x) {
log.print("Unexpected exception in writer: ");
x.printStackTrace();
System.exit(1);
}
}
}
private static void gobble(InputStream is, Reader rd,
int ec, boolean force)
throws Exception
{
int a = is.available();
boolean r = rd.ready();
log.print("" + a + " bytes available, "
+ "reader " + (r ? "" : "not ") + "ready");
if (!r && !force) {
log.println();
return;
}
int c;
try {
c = rd.read();
} catch (InterruptedIOException x) {
log.println();
throw x;
}
log.println(", read() ==> "
+ (c >= 0 ? ("'" + (char)c + "'" ): "EOF"));
if (c != ec)
throw new Exception("Incorrect value read: Expected "
+ ec + ", read " + (char)c);
}
public static void main(String[] args) throws Exception {
if (args.length > 0)
charset = args[0];
ServerSocket ss = new ServerSocket(22222);
Thread cl = new Client();
cl.start();
Socket s = ss.accept();
s.setSoTimeout(150);
InputStream is = s.getInputStream();
Reader rd = new InputStreamReader(is, charset);
while (is.available() <= 0)
Thread.yield();
gobble(is, rd, 'a', false);
gobble(is, rd, 'b', false);
gobble(is, rd, -1, false);
boolean caught = false;
try {
gobble(is, rd, -1, true);
} catch (InterruptedIOException e) {
log.println("Read timed out, as expected");
caught = true;
}
if (!caught) {
log.println("Read did not time out, test inapplicable");
return;
}
caught = false;
try {
gobble(is, rd, -1, true);
} catch (InterruptedIOException x) {
log.println("Second read timed out, as expected");
caught = true;
}
if (!caught)
throw new Exception("Second read completed");
}
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
//
grant {
permission java.lang.RuntimePermission "charsetProvider";
};
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册