Merge "CA certificate update" into klp-dev
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetTest.java
deleted file mode 100644
index 134bea6..0000000
--- a/harmony-tests/src/test/java/org/apache/harmony/nio_char/tests/java/nio/charset/CharsetTest.java
+++ /dev/null
@@ -1,245 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.nio_char.tests.java.nio.charset;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.CoderResult;
-import java.nio.charset.IllegalCharsetNameException;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Properties;
-import java.util.Set;
-
-import junit.framework.TestCase;
-
-public class CharsetTest extends TestCase {
-
- // Will contain names of charsets registered with IANA
- Set knownRegisteredCharsets = new HashSet();
-
- // Will contain names of charsets not known to be registered with IANA
- Set unknownRegisteredCharsets = new HashSet();
-
- /**
- * JUnit set-up method
- */
- public void setUp() {
- // Populate the known charset vars
- Set names = Charset.availableCharsets().keySet();
- for (Iterator nameItr = names.iterator(); nameItr.hasNext();) {
- String name = (String) nameItr.next();
- if (name.toLowerCase(Locale.ROOT).startsWith("x-"))
- unknownRegisteredCharsets.add(name);
- else
- knownRegisteredCharsets.add(name);
- }
- }
-
- /**
- * @tests java.nio.charset.Charset#isRegistered()
- */
- public void test_isRegistered() {
- // Regression for HARMONY-45
- for (Iterator nameItr = knownRegisteredCharsets.iterator(); nameItr.hasNext();) {
- String name = (String) nameItr.next();
- assertTrue("Assert 0: isRegistered() failed for " + name,
- Charset.forName(name).isRegistered());
- }
- for (Iterator nameItr = unknownRegisteredCharsets.iterator(); nameItr.hasNext();) {
- String name = (String) nameItr.next();
- assertFalse("Assert 0: isRegistered() failed for " + name,
- Charset.forName(name).isRegistered());
- }
- }
-
- /**
- * @tests java.nio.charset.Charset#isSupported(String)
- */
- public void testIsSupported_EmptyString() {
- // Regression for HARMONY-113
- try {
- Charset.isSupported("");
- fail("Assert 0: Should throw IllegalCharsetNameException");
- } catch (IllegalCharsetNameException e) {
- // Expected
- }
- }
-
- public void test_defaultCharset() {
- assertEquals("UTF-8", Charset.defaultCharset().name());
- }
-
- public void test_forNameLjava_lang_String() {
- /*
- * invoke forName two times with the same canonical name, it
- * should return the same reference.
- */
- Charset cs1 = Charset.forName("UTF-8");
- Charset cs2 = Charset.forName("UTF-8");
- assertSame(cs1, cs2);
-
- /*
- * test forName: invoke forName two times for the same Charset using
- * canonical name and alias, it should return the same reference.
- */
- Charset cs3 = Charset.forName("ASCII");
- Charset cs4 = Charset.forName("US-ASCII");
- assertSame(cs3, cs4);
- }
-
- /*
- * test cached decoder
- */
-// public void test_DecodeLjava_nio_ByteBuffer() throws Exception{
-// MockCharsetForDecoder cs1 = new MockCharsetForDecoder("CachedCharset",null);
-// MockCharsetForDecoder cs2 = new MockCharsetForDecoder("CachedCharset",null);
-// ByteBuffer in = ByteBuffer.wrap(new byte[]{0x00});
-// cs1.decode(in);
-// in.flip();
-// cs2.decode(in);
-// in.flip();
-// }
- /*
- * Mock Charset for cached decoder test
- */
- static class MockCharsetForDecoder extends Charset{
-
- public MockCharsetForDecoder(String canonicalName, String[] aliases){
- super(canonicalName, aliases);
- }
-
- public boolean contains(Charset charset) {
- return false;
- }
-
- public CharsetEncoder newEncoder() {
- return null;
- }
-
- public CharsetDecoder newDecoder() {
- return new MockCachedDecoder(this);
- }
-
-
- }
- /*
- * Mock decoder. Only one caller is permitted.
- */
- static class MockCachedDecoder extends CharsetDecoder {
- static MockCachedDecoder caller = null;
-
- public MockCachedDecoder(Charset cs) {
- super(cs, 1, 10);
- }
-
- /*
- * Only one caller is permitted.
- * If there's another caller, throw RuntimeException.
- */
- protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
- if(null == caller){
- caller = this;
- }else{
- if(caller != this){
- // Another instance
- fail("should use the same instance");
- }
- }
- return CoderResult.UNDERFLOW;
- }
- }
-
- /*
- * test cached encoder
- */
-// public void test_EncodeLjava_nio_CharBuffer() throws Exception {
-// MockCharsetForEncoder cs1 = new MockCharsetForEncoder("CachedCharset", null);
-// MockCharsetForEncoder cs2 = new MockCharsetForEncoder("CachedCharset", null);
-// CharBuffer in = CharBuffer.wrap("A");
-// cs1.encode(in);
-// in.flip();
-// cs2.encode(in);
-// }
-
- /*
- * Mock Charset for cached encoder test
- */
- static class MockCharsetForEncoder extends Charset {
-
- public MockCharsetForEncoder(String canonicalName, String[] aliases) {
- super(canonicalName, aliases);
- }
-
- public boolean contains(Charset charset) {
- return false;
- }
-
- public CharsetDecoder newDecoder() {
- return new MockDecoderForEncoder(this);
- }
-
- public CharsetEncoder newEncoder() {
- return new MockCachedEncoder(this);
- }
- }
-
- /*
- * Mock encoder. Only one caller is permitted.
- */
- static class MockCachedEncoder extends CharsetEncoder {
- static MockCachedEncoder caller = null;
-
- public MockCachedEncoder(Charset cs) {
- super(cs, 1, 10);
- }
-
- /*
- * Only one caller is permitted.
- */
- protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) {
- if (null == caller) {
- caller = this;
- } else {
- if (caller != this) {
- // Another instance
- fail("should use the same instance");
- }
- }
- return CoderResult.UNDERFLOW;
- }
- }
-
- /*
- * Mock decoder for MockCachedEncoder.
- */
- static class MockDecoderForEncoder extends CharsetDecoder {
- public MockDecoderForEncoder(Charset cs) {
- super(cs, 1, 10);
- }
-
- protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
- in.position(in.limit());
- return CoderResult.UNDERFLOW;
- }
- }
-
-}
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetProviderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetProviderTest.java
deleted file mode 100644
index b38728a..0000000
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetProviderTest.java
+++ /dev/null
@@ -1,406 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package tests.api.java.nio.charset;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.OutputStreamWriter;
-import java.nio.charset.Charset;
-import java.nio.charset.UnsupportedCharsetException;
-import java.nio.charset.spi.CharsetProvider;
-import java.util.Iterator;
-import java.util.Vector;
-
-import junit.framework.TestCase;
-import tests.api.java.nio.charset.CharsetTest.MockCharset;
-
-/**
- * Test charset providers managed by Charset.
- */
-public class CharsetProviderTest extends TestCase {
-
- static String CONFIG_FILE1 = null;
-
-
- static MockCharset charset1 = new MockCharset("mockCharset00",
- new String[] { "mockCharset01", "mockCharset02" });
-
- static MockCharset charset2 = new MockCharset("mockCharset10",
- new String[] { "mockCharset11", "mockCharset12" });
-
- /**
- * @param arg0
- */
- public CharsetProviderTest(String arg0) {
- super(arg0);
- CONFIG_FILE1 = System.getProperty("user.dir") + "/resources";
-
- String sep = System.getProperty("file.separator");
-
- if (!CONFIG_FILE1.endsWith(sep)) {
- CONFIG_FILE1 += sep;
- }
- CONFIG_FILE1 += "META-INF" + sep + "services" + sep
- + "java.nio.charset.spi.CharsetProvider";
- }
-
- /*
- * Write the string to the config file.
- */
- private void setupFile(String path, String content) throws Exception {
- String sep = System.getProperty("file.separator");
- int sepIndex = path.lastIndexOf(sep);
- File f = new File(path.substring(0, sepIndex));
- f.mkdirs();
-
- FileOutputStream fos = new FileOutputStream(path);
- OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");
- try {
- writer.write(content);
- } finally {
- writer.close();
- }
- }
-
- /*
- * Write the string to the config file.
- */
- private void cleanupFile(String path) throws Exception {
- File f = new File(path);
- f.delete();
- }
-
- /*
- * Test the method isSupported(String) with charset supported by some
- * providers (multiple).
- */
- public void testIsSupported_And_ForName_NormalProvider() throws Exception {
- try {
- assertFalse(Charset.isSupported("mockCharset10"));
- assertFalse(Charset.isSupported("mockCharset11"));
- assertFalse(Charset.isSupported("mockCharset12"));
- try {
- Charset.forName("mockCharset10");
- fail("Should throw UnsupportedCharsetException!");
- } catch (UnsupportedCharsetException e) {
- // expected
- }
- try {
- Charset.forName("mockCharset11");
- fail("Should throw UnsupportedCharsetException!");
- } catch (UnsupportedCharsetException e) {
- // expected
- }
- try {
- Charset.forName("mockCharset12");
- fail("Should throw UnsupportedCharsetException!");
- } catch (UnsupportedCharsetException e) {
- // expected
- }
-
- StringBuffer sb = new StringBuffer();
- sb.append("#comment\r");
- sb.append("\n");
- sb.append("\r\n");
- sb
- .append(" \ttests.api.java.nio.charset.CharsetTest$MockCharsetProvider \t\n\r");
- sb
- .append(" \ttests.api.java.nio.charset.CharsetTest$MockCharsetProvider \t");
- setupFile(CONFIG_FILE1, sb.toString());
-
- sb = new StringBuffer();
- sb.append(" #comment\r");
- sb.append("\n");
- sb.append("\r\n");
- sb
- .append(" \ttests.api.java.nio.charset.CharsetProviderTest$MockCharsetProvider \t\n\r");
- setupFile(CONFIG_FILE1, sb.toString());
-
- assertTrue(Charset.isSupported("mockCharset10"));
- // ignore case problem in mock, intended
- assertTrue(Charset.isSupported("MockCharset11"));
- assertTrue(Charset.isSupported("MockCharset12"));
- assertTrue(Charset.isSupported("MOCKCharset10"));
- // intended case problem in mock
- assertTrue(Charset.isSupported("MOCKCharset11"));
- assertTrue(Charset.isSupported("MOCKCharset12"));
-
- assertTrue(Charset.forName("mockCharset10") instanceof MockCharset);
- assertTrue(Charset.forName("mockCharset11") instanceof MockCharset);
- assertTrue(Charset.forName("mockCharset12") instanceof MockCharset);
-
- assertTrue(Charset.forName("mockCharset10") == charset2);
- // intended case problem in mock
- Charset.forName("mockCharset11");
- assertTrue(Charset.forName("mockCharset12") == charset2);
- } finally {
- cleanupFile(CONFIG_FILE1);
- }
- }
-
- /*
- * Test the method isSupported(String) when the configuration file contains
- * a non-existing class name.
- */
- public void testIsSupported_NonExistingClass() throws Exception {
- try {
- StringBuffer sb = new StringBuffer();
- sb.append("impossible\r");
- setupFile(CONFIG_FILE1, sb.toString());
-
- Charset.isSupported("impossible");
- fail("Should throw Error!");
- } catch (Error e) {
- // expected
- } finally {
- cleanupFile(CONFIG_FILE1);
- }
- }
-
- /*
- * Test the method isSupported(String) when the configuration file contains
- * a non-CharsetProvider class name.
- */
- public void testIsSupported_NotCharsetProviderClass() throws Exception {
- try {
- StringBuffer sb = new StringBuffer();
- sb.append("java.lang.String\r");
- setupFile(CONFIG_FILE1, sb.toString());
-
- Charset.isSupported("impossible");
- fail("Should throw ClassCastException!");
- } catch (ClassCastException e) {
- // expected
- } finally {
- cleanupFile(CONFIG_FILE1);
- }
- }
-
- /*
- * Test the method forName(String) when the charset provider supports a
- * built-in charset.
- */
- public void testForName_DuplicateWithBuiltInCharset() throws Exception {
- try {
- StringBuffer sb = new StringBuffer();
- sb
- .append("tests.api.java.nio.charset.CharsetProviderTest$MockCharsetProviderACSII\r");
- setupFile(CONFIG_FILE1, sb.toString());
-
- assertFalse(Charset.forName("us-ascii") instanceof MockCharset);
- assertFalse(Charset.availableCharsets().get("us-ascii") instanceof MockCharset);
- } finally {
- cleanupFile(CONFIG_FILE1);
- }
- }
-
- /*
- * Test the method forName(String) when the configuration file contains a
- * non-existing class name.
- */
- public void testForName_NonExistingClass() throws Exception {
- try {
- StringBuffer sb = new StringBuffer();
- sb.append("impossible\r");
- setupFile(CONFIG_FILE1, sb.toString());
-
- Charset.forName("impossible");
- fail("Should throw Error!");
- } catch (Error e) {
- // expected
- } finally {
- cleanupFile(CONFIG_FILE1);
- }
- }
-
- /*
- * Test the method forName(String) when the configuration file contains a
- * non-CharsetProvider class name.
- */
- public void testForName_NotCharsetProviderClass() throws Exception {
- try {
- StringBuffer sb = new StringBuffer();
- sb.append("java.lang.String\r");
- setupFile(CONFIG_FILE1, sb.toString());
-
- Charset.forName("impossible");
- fail("Should throw ClassCastException!");
- } catch (ClassCastException e) {
- // expected
- } finally {
- cleanupFile(CONFIG_FILE1);
- }
- }
-
- /*
- * Test the method availableCharsets() with charset supported by some
- * providers (multiple).
- */
- public void testAvailableCharsets_NormalProvider() throws Exception {
- try {
- assertFalse(Charset.availableCharsets()
- .containsKey("mockCharset10"));
- assertFalse(Charset.availableCharsets()
- .containsKey("mockCharset11"));
- assertFalse(Charset.availableCharsets()
- .containsKey("mockCharset12"));
-
- StringBuffer sb = new StringBuffer();
- sb.append("#comment\r");
- sb.append("\n");
- sb.append("\r\n");
- sb
- .append(" \ttests.api.java.nio.charset.CharsetTest$MockCharsetProvider \t\n\r");
- sb
- .append(" \ttests.api.java.nio.charset.CharsetTest$MockCharsetProvider \t");
- setupFile(CONFIG_FILE1, sb.toString());
-
- sb = new StringBuffer();
- sb.append("#comment\r");
- sb.append("\n");
- sb.append("\r\n");
- sb
- .append(" \ttests.api.java.nio.charset.CharsetProviderTest$MockCharsetProvider \t\n\r");
- setupFile(CONFIG_FILE1, sb.toString());
-
- assertTrue(Charset.availableCharsets().containsKey("mockCharset00"));
- assertTrue(Charset.availableCharsets().containsKey("MOCKCharset00"));
- assertTrue(Charset.availableCharsets().get("mockCharset00") instanceof MockCharset);
- assertTrue(Charset.availableCharsets().get("MOCKCharset00") instanceof MockCharset);
- assertFalse(Charset.availableCharsets()
- .containsKey("mockCharset01"));
- assertFalse(Charset.availableCharsets()
- .containsKey("mockCharset02"));
-
- assertTrue(Charset.availableCharsets().get("mockCharset10") == charset2);
- assertTrue(Charset.availableCharsets().get("MOCKCharset10") == charset2);
- assertFalse(Charset.availableCharsets()
- .containsKey("mockCharset11"));
- assertFalse(Charset.availableCharsets()
- .containsKey("mockCharset12"));
-
- assertTrue(Charset.availableCharsets().containsKey("mockCharset10"));
- assertTrue(Charset.availableCharsets().containsKey("MOCKCharset10"));
- assertTrue(Charset.availableCharsets().get("mockCharset10") == charset2);
- assertFalse(Charset.availableCharsets()
- .containsKey("mockCharset11"));
- assertFalse(Charset.availableCharsets()
- .containsKey("mockCharset12"));
- } finally {
- cleanupFile(CONFIG_FILE1);
- }
- }
-
- /*
- * Test the method availableCharsets(String) when the configuration file
- * contains a non-existing class name.
- */
- public void testAvailableCharsets_NonExistingClass() throws Exception {
- try {
- StringBuffer sb = new StringBuffer();
- sb.append("impossible\r");
- setupFile(CONFIG_FILE1, sb.toString());
-
- Charset.availableCharsets();
- fail("Should throw Error!");
- } catch (Error e) {
- // expected
- } finally {
- cleanupFile(CONFIG_FILE1);
- }
- }
-
- /*
- * Test the method availableCharsets(String) when the configuration file
- * contains a non-CharsetProvider class name.
- */
- public void testAvailableCharsets_NotCharsetProviderClass()
- throws Exception {
- try {
- StringBuffer sb = new StringBuffer();
- sb.append("java.lang.String\r");
- setupFile(CONFIG_FILE1, sb.toString());
-
- Charset.availableCharsets();
- fail("Should throw ClassCastException!");
- } catch (ClassCastException e) {
- // expected
- } finally {
- cleanupFile(CONFIG_FILE1);
- }
- }
-
- /*
- * Test the method availableCharsets(String) when the configuration file
- * contains an illegal string.
- */
- public void testAvailableCharsets_IllegalString() throws Exception {
- try {
- StringBuffer sb = new StringBuffer();
- sb.append("java String\r");
- setupFile(CONFIG_FILE1, sb.toString());
-
- Charset.availableCharsets();
- fail("Should throw Error!");
- } catch (Error e) {
- // expected
- } finally {
- cleanupFile(CONFIG_FILE1);
- }
- }
-
- /*
- * Mock charset provider.
- */
- public static class MockCharsetProvider extends CharsetProvider {
-
- public Charset charsetForName(String charsetName) {
- if ("MockCharset10".equalsIgnoreCase(charsetName)
- || "MockCharset11".equalsIgnoreCase(charsetName)
- || "MockCharset12".equalsIgnoreCase(charsetName)) {
- return charset2;
- }
- return null;
- }
-
- public Iterator charsets() {
- Vector v = new Vector();
- v.add(charset2);
- return v.iterator();
- }
- }
-
- /*
- * Another mock charset provider providing build-in charset "ascii".
- */
- public static class MockCharsetProviderACSII extends CharsetProvider {
-
- public Charset charsetForName(String charsetName) {
- if ("US-ASCII".equalsIgnoreCase(charsetName)
- || "ASCII".equalsIgnoreCase(charsetName)) {
- return new MockCharset("US-ASCII", new String[] { "ASCII" });
- }
- return null;
- }
-
- public Iterator charsets() {
- Vector v = new Vector();
- v.add(new MockCharset("US-ASCII", new String[] { "ASCII" }));
- return v.iterator();
- }
- }
-
-}
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetTest.java
index 99b8c44..adee76e 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetTest.java
+++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/CharsetTest.java
@@ -23,11 +23,15 @@
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.IllegalCharsetNameException;
-import java.nio.charset.UnsupportedCharsetException;
import java.nio.charset.spi.CharsetProvider;
+import java.nio.charset.UnsupportedCharsetException;
import java.security.Permission;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
+import java.util.Set;
import java.util.SortedMap;
import java.util.Vector;
@@ -38,74 +42,307 @@
*/
public class CharsetTest extends TestCase {
- static MockCharset charset1 = new MockCharset("mockCharset00",
- new String[] { "mockCharset01", "mockCharset02" });
+ public void test_allAvailableCharsets() throws Exception {
+ // Check that we can instantiate every Charset, CharsetDecoder, and CharsetEncoder.
+ for (String charsetName : Charset.availableCharsets().keySet()) {
+ if (charsetName.equals("UTF-32")) {
+ // Our UTF-32 is broken. http://b/2702411
+ // TODO: remove this hack when UTF-32 is fixed.
+ continue;
+ }
- static MockCharset charset2 = new MockCharset("mockCharset10",
- new String[] { "mockCharset11", "mockCharset12" });
+ Charset cs = Charset.forName(charsetName);
+ assertNotNull(cs.newDecoder());
+ if (cs.canEncode()) {
+ CharsetEncoder enc = cs.newEncoder();
+ assertNotNull(enc);
+ assertNotNull(enc.replacement());
+ }
+ }
+ }
- /*
- * @see TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- }
+ public void test_defaultCharset() {
+ assertEquals("UTF-8", Charset.defaultCharset().name());
+ }
- /*
- * @see TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- }
+ public void test_isRegistered() {
+ // Regression for HARMONY-45
- /*
- * Test the required 6 charsets are supported.
- */
- public void testRequiredCharsetSupported() {
- assertTrue(Charset.isSupported("US-ASCII"));
- assertTrue(Charset.isSupported("ASCII"));
- assertTrue(Charset.isSupported("ISO-8859-1"));
- assertTrue(Charset.isSupported("ISO8859_1"));
- assertTrue(Charset.isSupported("UTF-8"));
- assertTrue(Charset.isSupported("UTF8"));
- assertTrue(Charset.isSupported("UTF-16"));
- assertTrue(Charset.isSupported("UTF-16BE"));
- assertTrue(Charset.isSupported("UTF-16LE"));
+ // Will contain names of charsets registered with IANA
+ Set<String> knownRegisteredCharsets = new HashSet<String>();
- Charset c1 = Charset.forName("US-ASCII");
- assertEquals("US-ASCII", Charset.forName("US-ASCII").name());
- assertEquals("US-ASCII", Charset.forName("ASCII").name());
- assertEquals("ISO-8859-1", Charset.forName("ISO-8859-1").name());
- assertEquals("ISO-8859-1", Charset.forName("ISO8859_1").name());
- assertEquals("UTF-8", Charset.forName("UTF-8").name());
- assertEquals("UTF-8", Charset.forName("UTF8").name());
- assertEquals("UTF-16", Charset.forName("UTF-16").name());
- assertEquals("UTF-16BE", Charset.forName("UTF-16BE").name());
- assertEquals("UTF-16LE", Charset.forName("UTF-16LE").name());
+ // Will contain names of charsets not known to be registered with IANA
+ Set<String> unknownRegisteredCharsets = new HashSet<String>();
- assertNotSame(Charset.availableCharsets(), Charset.availableCharsets());
- // assertSame(Charset.forName("US-ASCII"), Charset.availableCharsets()
- // .get("US-ASCII"));
- // assertSame(Charset.forName("US-ASCII"), c1);
- assertTrue(Charset.availableCharsets().containsKey("US-ASCII"));
- assertTrue(Charset.availableCharsets().containsKey("ISO-8859-1"));
- assertTrue(Charset.availableCharsets().containsKey("UTF-8"));
- assertTrue(Charset.availableCharsets().containsKey("UTF-16"));
- assertTrue(Charset.availableCharsets().containsKey("UTF-16BE"));
- assertTrue(Charset.availableCharsets().containsKey("UTF-16LE"));
- }
+ Set<String> names = Charset.availableCharsets().keySet();
+ for (Iterator nameItr = names.iterator(); nameItr.hasNext();) {
+ String name = (String) nameItr.next();
+ if (name.toLowerCase(Locale.ROOT).startsWith("x-")) {
+ unknownRegisteredCharsets.add(name);
+ } else {
+ knownRegisteredCharsets.add(name);
+ }
+ }
- /*
- * Test the method isSupported(String) with null.
- */
- public void testIsSupported_Null() {
- try {
- Charset.isSupported(null);
- fail("Should throw IllegalArgumentException!");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
+ for (Iterator nameItr = knownRegisteredCharsets.iterator(); nameItr.hasNext();) {
+ String name = (String) nameItr.next();
+ Charset cs = Charset.forName(name);
+ if (!cs.isRegistered()) {
+ System.err.println("isRegistered was false for " + name + " " + cs.name() + " " + cs.aliases());
+ }
+ assertTrue("isRegistered was false for " + name + " " + cs.name() + " " + cs.aliases(), cs.isRegistered());
+ }
+ for (Iterator nameItr = unknownRegisteredCharsets.iterator(); nameItr.hasNext();) {
+ String name = (String) nameItr.next();
+ Charset cs = Charset.forName(name);
+ assertFalse("isRegistered was true for " + name + " " + cs.name() + " " + cs.aliases(), cs.isRegistered());
+ }
+ }
+
+ public void test_guaranteedCharsetsAvailable() throws Exception {
+ // All Java implementations must support these charsets.
+ assertNotNull(Charset.forName("ISO-8859-1"));
+ assertNotNull(Charset.forName("US-ASCII"));
+ assertNotNull(Charset.forName("UTF-16"));
+ assertNotNull(Charset.forName("UTF-16BE"));
+ assertNotNull(Charset.forName("UTF-16LE"));
+ assertNotNull(Charset.forName("UTF-8"));
+ }
+
+ // http://code.google.com/p/android/issues/detail?id=42769
+ public void test_42769() throws Exception {
+ ArrayList<Thread> threads = new ArrayList<Thread>();
+ for (int i = 0; i < 10; ++i) {
+ Thread t = new Thread(new Runnable() {
+ public void run() {
+ for (int i = 0; i < 50; ++i) {
+ Charset.availableCharsets();
+ }
+ }
+ });
+ threads.add(t);
+ }
+
+ for (Thread t : threads) {
+ t.start();
+ }
+ for (Thread t : threads) {
+ t.join();
+ }
+ }
+
+ public void test_have_canonical_EUC_JP() throws Exception {
+ assertEquals("EUC-JP", Charset.forName("EUC-JP").name());
+ }
+
+ public void test_EUC_JP_replacement_character() throws Exception {
+ assertEncodes(Charset.forName("EUC-JP"), "\ufffd", 0xf4, 0xfe);
+ }
+
+ public void test_SCSU_replacement_character() throws Exception {
+ assertDecodes(Charset.forName("SCSU"), "\ufffd", 14, 0xff);
+ assertEncodes(Charset.forName("SCSU"), "\ufffd", 14, 0xff);
+ }
+
+ public void test_Shift_JIS_replacement_character() throws Exception {
+ assertDecodes(Charset.forName("Shift_JIS"), "\ufffd", 0xfc);
+ assertEncodes(Charset.forName("Shift_JIS"), "\ufffd", 0xfc);
+ }
+
+ public void test_UTF_16() throws Exception {
+ Charset cs = Charset.forName("UTF-16");
+ // Writes big-endian, with a big-endian BOM.
+ assertEncodes(cs, "a\u0666", 0xfe, 0xff, 0, 'a', 0x06, 0x66);
+ // Reads whatever the BOM tells it to read...
+ assertDecodes(cs, "a\u0666", 0xfe, 0xff, 0, 'a', 0x06, 0x66);
+ assertDecodes(cs, "a\u0666", 0xff, 0xfe, 'a', 0, 0x66, 0x06);
+ // ...and defaults to reading big-endian if there's no BOM.
+ assertDecodes(cs, "a\u0666", 0, 'a', 0x06, 0x66);
+ }
+
+ public void test_UTF_16BE() throws Exception {
+ Charset cs = Charset.forName("UTF-16BE");
+ // Writes big-endian, with no BOM.
+ assertEncodes(cs, "a\u0666", 0, 'a', 0x06, 0x66);
+ // Treats a little-endian BOM as an error and continues to read big-endian.
+ // This test uses REPLACE mode, so we get the U+FFFD replacement character in the result.
+ assertDecodes(cs, "\ufffda\u0666", 0xff, 0xfe, 0, 'a', 0x06, 0x66);
+ // Accepts a big-endian BOM and includes U+FEFF in the decoded output.
+ assertDecodes(cs, "\ufeffa\u0666", 0xfe, 0xff, 0, 'a', 0x06, 0x66);
+ // Defaults to reading big-endian.
+ assertDecodes(cs, "a\u0666", 0, 'a', 0x06, 0x66);
+ }
+
+ public void test_UTF_16LE() throws Exception {
+ Charset cs = Charset.forName("UTF-16LE");
+ // Writes little-endian, with no BOM.
+ assertEncodes(cs, "a\u0666", 'a', 0, 0x66, 0x06);
+ // Accepts a little-endian BOM and includes U+FEFF in the decoded output.
+ assertDecodes(cs, "\ufeffa\u0666", 0xff, 0xfe, 'a', 0, 0x66, 0x06);
+ // Treats a big-endian BOM as an error and continues to read little-endian.
+ // This test uses REPLACE mode, so we get the U+FFFD replacement character in the result.
+ assertDecodes(cs, "\ufffda\u0666", 0xfe, 0xff, 'a', 0, 0x66, 0x06);
+ // Defaults to reading little-endian.
+ assertDecodes(cs, "a\u0666", 'a', 0, 0x66, 0x06);
+ }
+
+ public void test_x_UTF_16LE_BOM() throws Exception {
+ Charset cs = Charset.forName("x-UTF-16LE-BOM");
+ // Writes little-endian, with a BOM.
+ assertEncodes(cs, "a\u0666", 0xff, 0xfe, 'a', 0, 0x66, 0x06);
+ // Accepts a little-endian BOM and swallows the BOM.
+ assertDecodes(cs, "a\u0666", 0xff, 0xfe, 'a', 0, 0x66, 0x06);
+ // Swallows a big-endian BOM, but continues to read little-endian!
+ assertDecodes(cs, "\u6100\u6606", 0xfe, 0xff, 'a', 0, 0x66, 0x06);
+ // Defaults to reading little-endian.
+ assertDecodes(cs, "a\u0666", 'a', 0, 0x66, 0x06);
+ }
+
+ public void test_UTF_32() throws Exception {
+ Charset cs = Charset.forName("UTF-32");
+ // Writes big-endian, with no BOM.
+ assertEncodes(cs, "a\u0666", 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
+ // Reads whatever the BOM tells it to read...
+ assertDecodes(cs, "a\u0666", 0, 0, 0xfe, 0xff, 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
+ assertDecodes(cs, "a\u0666", 0xff, 0xfe, 0, 0, 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
+ // ...and defaults to reading big-endian if there's no BOM.
+ assertDecodes(cs, "a\u0666", 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
+ }
+
+ public void test_UTF_32BE() throws Exception {
+ Charset cs = Charset.forName("UTF-32BE");
+ // Writes big-endian, with no BOM.
+ assertEncodes(cs, "a\u0666", 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
+ // Treats a little-endian BOM as an error and continues to read big-endian.
+ // This test uses REPLACE mode, so we get the U+FFFD replacement character in the result.
+ assertDecodes(cs, "\ufffda\u0666", 0xff, 0xfe, 0, 0, 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
+ // Accepts a big-endian BOM and swallows the BOM.
+ assertDecodes(cs, "a\u0666", 0, 0, 0xfe, 0xff, 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
+ // Defaults to reading big-endian.
+ assertDecodes(cs, "a\u0666", 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
+ }
+
+ public void test_UTF_32LE() throws Exception {
+ Charset cs = Charset.forName("UTF-32LE");
+ // Writes little-endian, with no BOM.
+ assertEncodes(cs, "a\u0666", 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
+ // Accepts a little-endian BOM and swallows the BOM.
+ assertDecodes(cs, "a\u0666", 0xff, 0xfe, 0, 0, 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
+ // Treats a big-endian BOM as an error and continues to read little-endian.
+ // This test uses REPLACE mode, so we get the U+FFFD replacement character in the result.
+ assertDecodes(cs, "\ufffda\u0666", 0, 0, 0xfe, 0xff, 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
+ // Defaults to reading little-endian.
+ assertDecodes(cs, "a\u0666", 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
+ }
+
+ public void test_X_UTF_32BE_BOM() throws Exception {
+ Charset cs = Charset.forName("X-UTF-32BE-BOM");
+ // Writes big-endian, with a big-endian BOM.
+ assertEncodes(cs, "a\u0666", 0, 0, 0xfe, 0xff, 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
+ // Treats a little-endian BOM as an error and continues to read big-endian.
+ // This test uses REPLACE mode, so we get the U+FFFD replacement character in the result.
+ assertDecodes(cs, "\ufffda\u0666", 0xff, 0xfe, 0, 0, 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
+ // Swallows a big-endian BOM, and continues to read big-endian.
+ assertDecodes(cs, "a\u0666", 0, 0, 0xfe, 0xff, 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
+ // Defaults to reading big-endian.
+ assertDecodes(cs, "a\u0666", 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
+ }
+
+ public void test_X_UTF_32LE_BOM() throws Exception {
+ Charset cs = Charset.forName("X-UTF-32LE-BOM");
+ // Writes little-endian, with a little-endian BOM.
+ assertEncodes(cs, "a\u0666", 0xff, 0xfe, 0, 0, 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
+ // Accepts a little-endian BOM and swallows the BOM.
+ assertDecodes(cs, "a\u0666", 0xff, 0xfe, 0, 0, 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
+ // Treats a big-endian BOM as an error and continues to read little-endian.
+ // This test uses REPLACE mode, so we get the U+FFFD replacement character in the result.
+ assertDecodes(cs, "\ufffda\u0666", 0, 0, 0xfe, 0xff, 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
+ // Defaults to reading little-endian.
+ assertDecodes(cs, "a\u0666", 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
+ }
+
+ private byte[] toByteArray(int[] ints) {
+ byte[] result = new byte[ints.length];
+ for (int i = 0; i < ints.length; ++i) {
+ result[i] = (byte) ints[i];
+ }
+ return result;
+ }
+
+ private void assertEncodes(Charset cs, String s, int... expectedByteInts) throws Exception {
+ ByteBuffer out = cs.encode(s);
+ byte[] bytes = new byte[out.remaining()];
+ out.get(bytes);
+ assertEquals(Arrays.toString(toByteArray(expectedByteInts)), Arrays.toString(bytes));
+ }
+
+ private void assertDecodes(Charset cs, String s, int... byteInts) throws Exception {
+ ByteBuffer in = ByteBuffer.wrap(toByteArray(byteInts));
+ CharBuffer out = cs.decode(in);
+ assertEquals(s, out.toString());
+ }
+
+ public void test_forNameLjava_lang_String() {
+ // Invoke forName two times with the same canonical name.
+ // It should return the same reference.
+ Charset cs1 = Charset.forName("UTF-8");
+ Charset cs2 = Charset.forName("UTF-8");
+ assertSame(cs1, cs2);
+
+ // test forName: invoke forName two times for the same Charset using
+ // canonical name and alias, it should return the same reference.
+ Charset cs3 = Charset.forName("ASCII");
+ Charset cs4 = Charset.forName("US-ASCII");
+ assertSame(cs3, cs4);
+ }
+
+ static MockCharset charset1 = new MockCharset("mockCharset00",
+ new String[] { "mockCharset01", "mockCharset02" });
+
+ static MockCharset charset2 = new MockCharset("mockCharset10",
+ new String[] { "mockCharset11", "mockCharset12" });
+
+ // Test the required 6 charsets are supported.
+ public void testRequiredCharsetSupported() {
+ assertTrue(Charset.isSupported("US-ASCII"));
+ assertTrue(Charset.isSupported("ASCII"));
+ assertTrue(Charset.isSupported("ISO-8859-1"));
+ assertTrue(Charset.isSupported("ISO8859_1"));
+ assertTrue(Charset.isSupported("UTF-8"));
+ assertTrue(Charset.isSupported("UTF8"));
+ assertTrue(Charset.isSupported("UTF-16"));
+ assertTrue(Charset.isSupported("UTF-16BE"));
+ assertTrue(Charset.isSupported("UTF-16LE"));
+
+ Charset c1 = Charset.forName("US-ASCII");
+ assertEquals("US-ASCII", Charset.forName("US-ASCII").name());
+ assertEquals("US-ASCII", Charset.forName("ASCII").name());
+ assertEquals("ISO-8859-1", Charset.forName("ISO-8859-1").name());
+ assertEquals("ISO-8859-1", Charset.forName("ISO8859_1").name());
+ assertEquals("UTF-8", Charset.forName("UTF-8").name());
+ assertEquals("UTF-8", Charset.forName("UTF8").name());
+ assertEquals("UTF-16", Charset.forName("UTF-16").name());
+ assertEquals("UTF-16BE", Charset.forName("UTF-16BE").name());
+ assertEquals("UTF-16LE", Charset.forName("UTF-16LE").name());
+
+ assertNotSame(Charset.availableCharsets(), Charset.availableCharsets());
+ // assertSame(Charset.forName("US-ASCII"), Charset.availableCharsets().get("US-ASCII"));
+ // assertSame(Charset.forName("US-ASCII"), c1);
+ assertTrue(Charset.availableCharsets().containsKey("US-ASCII"));
+ assertTrue(Charset.availableCharsets().containsKey("ISO-8859-1"));
+ assertTrue(Charset.availableCharsets().containsKey("UTF-8"));
+ assertTrue(Charset.availableCharsets().containsKey("UTF-16"));
+ assertTrue(Charset.availableCharsets().containsKey("UTF-16BE"));
+ assertTrue(Charset.availableCharsets().containsKey("UTF-16LE"));
+ }
+
+ public void testIsSupported_Null() {
+ try {
+ Charset.isSupported(null);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
public void testIsSupported_EmptyString() {
try {
@@ -123,97 +360,67 @@
}
}
- /*
- * Test the method isSupported(String) with illegal charset name.
- */
- public void testIsSupported_IllegalName() {
- try {
- Charset.isSupported(" ///#$$");
- fail("Should throw IllegalCharsetNameException!");
- } catch (IllegalCharsetNameException e) {
- // expected
- }
- }
+ public void testIsSupported_IllegalName() {
+ try {
+ Charset.isSupported(" ///#$$");
+ fail();
+ } catch (IllegalCharsetNameException expected) {
+ }
+ }
- /*
- * Test the method isSupported(String) with not supported charset name.
- */
- public void testIsSupported_NotSupported() {
- assertFalse(Charset.isSupported("impossible"));
- }
+ public void testIsSupported_NotSupported() {
+ assertFalse(Charset.isSupported("well-formed-name-of-a-charset-that-does-not-exist"));
+ }
- /*
- * Test the method forName(String) with null.
- */
- public void testForName_Null() {
- try {
- Charset.forName(null);
- fail("Should throw IllegalArgumentException!");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
+ public void testForName_Null() {
+ try {
+ Charset.forName(null);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
- /*
- * Test the method forName(String) with empty string.
- */
- public void testForName_EmptyString() {
- try {
- Charset.forName("");
- fail("Should throw IllegalArgumentException!");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
+ public void testForName_EmptyString() {
+ try {
+ Charset.forName("");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
- /*
- * Test the method forName(String) with a string starting with ".".
- */
- public void testForName_InvalidInitialCharacter() {
- try {
- Charset.forName(".char");
- fail("Should throw IllegalArgumentException!");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
+ public void testForName_InvalidInitialCharacter() {
+ try {
+ Charset.forName(".char");
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
- /*
- * Test the method forName(String) with illegal charset name.
- */
- public void testForName_IllegalName() {
- try {
- Charset.forName(" ///#$$");
- fail("Should throw IllegalCharsetNameException!");
- } catch (IllegalCharsetNameException e) {
- // expected
- }
- }
+ public void testForName_IllegalName() {
+ try {
+ Charset.forName(" ///#$$");
+ fail();
+ } catch (IllegalCharsetNameException expected) {
+ }
+ }
- /*
- * Test the method forName(String) with not supported charset name.
- */
- public void testForName_NotSupported() {
- try {
- Charset.forName("impossible");
- fail("Should throw UnsupportedCharsetException!");
- } catch (UnsupportedCharsetException e) {
- // expected
- }
- }
+ public void testForName_NotSupported() {
+ try {
+ Charset.forName("impossible");
+ fail();
+ } catch (UnsupportedCharsetException expected) {
+ }
+ }
- /*
- * Test the constructor with normal parameter values.
- */
- public void testConstructor_Normal() {
- final String mockName = "mockChar1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:-_";
- MockCharset c = new MockCharset(mockName, new String[] { "mock" });
- assertEquals(mockName, c.name());
- assertEquals(mockName, c.displayName());
- assertEquals(mockName, c.displayName(Locale.getDefault()));
- assertEquals("mock", c.aliases().toArray()[0]);
- assertEquals(1, c.aliases().toArray().length);
- }
+ public void testConstructor_Normal() {
+ final String mockName = "mockChar1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:-_";
+ MockCharset c = new MockCharset(mockName, new String[] { "mock" });
+ assertEquals(mockName, c.name());
+ assertEquals(mockName, c.displayName());
+ assertEquals(mockName, c.displayName(Locale.getDefault()));
+ assertEquals("mock", c.aliases().toArray()[0]);
+ assertEquals(1, c.aliases().toArray().length);
+ }
public void testConstructor_EmptyCanonicalName() {
try {
@@ -231,70 +438,50 @@
}
}
- /*
- * Test the constructor with illegal canonical name, illegal character in
- * the middle.
- */
- public void testConstructor_IllegalCanonicalName_Middle() {
- try {
- new MockCharset("1%%23", new String[] { "mock" });
- fail("Should throw IllegalCharsetNameException!");
- } catch (IllegalCharsetNameException e) {
- // expected
- }
- try {
- new MockCharset("1//23", new String[] { "mock" });
- fail("Should throw IllegalCharsetNameException!");
- } catch (IllegalCharsetNameException e) {
- // expected
- }
- }
+ public void testConstructor_IllegalCanonicalName_Middle() {
+ try {
+ new MockCharset("1%%23", new String[] { "mock" });
+ fail();
+ } catch (IllegalCharsetNameException expected) {
+ }
+ try {
+ new MockCharset("1//23", new String[] { "mock" });
+ fail();
+ } catch (IllegalCharsetNameException expected) {
+ }
+ }
- /*
- * Test the constructor with null canonical name.
- */
- public void testConstructor_NullCanonicalName() {
- try {
- MockCharset c = new MockCharset(null, new String[] { "mock" });
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- // expected
- }
- }
+ public void testConstructor_NullCanonicalName() {
+ try {
+ MockCharset c = new MockCharset(null, new String[] { "mock" });
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
- /*
- * Test the constructor with null aliases.
- */
- public void testConstructor_NullAliases() {
- MockCharset c = new MockCharset("mockChar", null);
- assertEquals("mockChar", c.name());
- assertEquals("mockChar", c.displayName());
- assertEquals("mockChar", c.displayName(Locale.getDefault()));
- assertEquals(0, c.aliases().toArray().length);
- }
+ public void testConstructor_NullAliases() {
+ MockCharset c = new MockCharset("mockChar", null);
+ assertEquals("mockChar", c.name());
+ assertEquals("mockChar", c.displayName());
+ assertEquals("mockChar", c.displayName(Locale.getDefault()));
+ assertEquals(0, c.aliases().toArray().length);
+ }
- /*
- * Test the constructor with a null aliases.
- */
- public void testConstructor_NullAliase() {
- try {
- new MockCharset("mockChar", new String[] { "mock", null });
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- // expected
- }
- }
+ public void testConstructor_NullAliase() {
+ try {
+ new MockCharset("mockChar", new String[] { "mock", null });
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
- /*
- * Test the constructor with no aliases.
- */
- public void testConstructor_NoAliases() {
- MockCharset c = new MockCharset("mockChar", new String[0]);
- assertEquals("mockChar", c.name());
- assertEquals("mockChar", c.displayName());
- assertEquals("mockChar", c.displayName(Locale.getDefault()));
- assertEquals(0, c.aliases().toArray().length);
- }
+ public void testConstructor_NoAliases() {
+ MockCharset c = new MockCharset("mockChar", new String[0]);
+ assertEquals("mockChar", c.name());
+ assertEquals("mockChar", c.displayName());
+ assertEquals("mockChar", c.displayName(Locale.getDefault()));
+ assertEquals(0, c.aliases().toArray().length);
+ }
public void testConstructor_EmptyAliases() {
try {
@@ -313,499 +500,400 @@
}
}
- /*
- * Test the constructor with illegal aliase, illegal character in the
- * middle.
- */
- public void testConstructor_IllegalAliases_Middle() {
- try {
- new MockCharset("mockChar", new String[] { "mock", "22##ab" });
- fail("Should throw IllegalCharsetNameException!");
- } catch (IllegalCharsetNameException e) {
- // expected
- }
- try {
- new MockCharset("mockChar", new String[] { "mock", "22%%ab" });
- fail("Should throw IllegalCharsetNameException!");
- } catch (IllegalCharsetNameException e) {
- // expected
- }
- }
+ public void testConstructor_IllegalAliases_Middle() {
+ try {
+ new MockCharset("mockChar", new String[] { "mock", "22##ab" });
+ fail();
+ } catch (IllegalCharsetNameException expected) {
+ }
+ try {
+ new MockCharset("mockChar", new String[] { "mock", "22%%ab" });
+ fail();
+ } catch (IllegalCharsetNameException expected) {
+ }
+ }
- /*
- * Test the method aliases() with multiple aliases. Most conditions have
- * been tested in the testcases for the constructors.
- */
- public void testAliases_Multiple() {
- final String mockName = "mockChar1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:-_";
- MockCharset c = new MockCharset("mockChar", new String[] { "mock",
- mockName, "mock2" });
- assertEquals("mockChar", c.name());
- assertEquals(3, c.aliases().size());
- assertTrue(c.aliases().contains("mock"));
- assertTrue(c.aliases().contains(mockName));
- assertTrue(c.aliases().contains("mock2"));
+ public void testAliases_Multiple() {
+ final String mockName = "mockChar1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:-_";
+ MockCharset c = new MockCharset("mockChar", new String[] { "mock", mockName, "mock2" });
+ assertEquals("mockChar", c.name());
+ assertEquals(3, c.aliases().size());
+ assertTrue(c.aliases().contains("mock"));
+ assertTrue(c.aliases().contains(mockName));
+ assertTrue(c.aliases().contains("mock2"));
- try {
- c.aliases().clear();
- fail("Should throw UnsupportedOperationException!");
- } catch (UnsupportedOperationException e) {
- // expected
- }
- }
+ try {
+ c.aliases().clear();
+ fail();
+ } catch (UnsupportedOperationException expected) {
+ }
+ }
- /*
- * Test the method aliases() with duplicate aliases, one same with its
- * canonical name.
- */
- public void testAliases_Duplicate() {
- final String mockName = "mockChar1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:-_";
- MockCharset c = new MockCharset("mockChar", new String[] { "mockChar",
- "mock", mockName, "mock", "mockChar", "mock", "mock2" });
- assertEquals("mockChar", c.name());
- assertEquals(4, c.aliases().size());
- assertTrue(c.aliases().contains("mockChar"));
- assertTrue(c.aliases().contains("mock"));
- assertTrue(c.aliases().contains(mockName));
- assertTrue(c.aliases().contains("mock2"));
- }
+ public void testAliases_Duplicate() {
+ final String mockName = "mockChar1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:-_";
+ MockCharset c = new MockCharset("mockChar", new String[] { "mockChar",
+ "mock", mockName, "mock", "mockChar", "mock", "mock2" });
+ assertEquals("mockChar", c.name());
+ assertEquals(4, c.aliases().size());
+ assertTrue(c.aliases().contains("mockChar"));
+ assertTrue(c.aliases().contains("mock"));
+ assertTrue(c.aliases().contains(mockName));
+ assertTrue(c.aliases().contains("mock2"));
+ }
- /*
- * Test the method canEncode(). Test the default return value.
- */
- public void testCanEncode() {
- MockCharset c = new MockCharset("mock", null);
- assertTrue(c.canEncode());
- }
+ public void testCanEncode() {
+ MockCharset c = new MockCharset("mock", null);
+ assertTrue(c.canEncode());
+ }
- /*
- * Test the method isRegistered(). Test the default return value.
- */
- public void testIsRegistered() {
- MockCharset c = new MockCharset("mock", null);
- assertTrue(c.isRegistered());
- }
+ public void testIsRegistered() {
+ MockCharset c = new MockCharset("mock", null);
+ assertTrue(c.isRegistered());
+ }
- /*
- * The name() method has been tested by the testcases for the constructor.
- */
- public void testName() {
- // already covered by testConstructor_XXX series
- }
+ public void testDisplayName_Locale_Null() {
+ MockCharset c = new MockCharset("mock", null);
+ assertEquals("mock", c.displayName(null));
+ }
- /*
- * The displayName() method have been tested by the testcases for the
- * constructor.
- */
- public void testDisplayName() {
- // already covered by testConstructor_XXX series
- }
+ public void testCompareTo_Normal() {
+ MockCharset c1 = new MockCharset("mock", null);
+ assertEquals(0, c1.compareTo(c1));
- /*
- * Test displayName(Locale) with null.
- */
- public void testDisplayName_Locale_Null() {
- MockCharset c = new MockCharset("mock", null);
- assertEquals("mock", c.displayName(null));
- }
+ MockCharset c2 = new MockCharset("Mock", null);
+ assertEquals(0, c1.compareTo(c2));
- /*
- * Test the method compareTo(Object) with normal conditions.
- */
- public void testCompareTo_Normal() {
- MockCharset c1 = new MockCharset("mock", null);
- assertEquals(0, c1.compareTo(c1));
+ c2 = new MockCharset("mock2", null);
+ assertTrue(c1.compareTo(c2) < 0);
+ assertTrue(c2.compareTo(c1) > 0);
- MockCharset c2 = new MockCharset("Mock", null);
- assertEquals(0, c1.compareTo(c2));
+ c2 = new MockCharset("mack", null);
+ assertTrue(c1.compareTo(c2) > 0);
+ assertTrue(c2.compareTo(c1) < 0);
- c2 = new MockCharset("mock2", null);
- assertTrue(c1.compareTo(c2) < 0);
- assertTrue(c2.compareTo(c1) > 0);
+ c2 = new MockCharset("m.", null);
+ assertTrue(c1.compareTo(c2) > 0);
+ assertTrue(c2.compareTo(c1) < 0);
- c2 = new MockCharset("mack", null);
- assertTrue(c1.compareTo(c2) > 0);
- assertTrue(c2.compareTo(c1) < 0);
+ c2 = new MockCharset("m:", null);
+ assertEquals("mock".compareToIgnoreCase("m:"), c1.compareTo(c2));
+ assertEquals("m:".compareToIgnoreCase("mock"), c2.compareTo(c1));
- c2 = new MockCharset("m.", null);
- assertTrue(c1.compareTo(c2) > 0);
- assertTrue(c2.compareTo(c1) < 0);
+ c2 = new MockCharset("m-", null);
+ assertTrue(c1.compareTo(c2) > 0);
+ assertTrue(c2.compareTo(c1) < 0);
- c2 = new MockCharset("m:", null);
- assertEquals("mock".compareToIgnoreCase("m:"), c1.compareTo(c2));
- assertEquals("m:".compareToIgnoreCase("mock"), c2.compareTo(c1));
+ c2 = new MockCharset("m_", null);
+ assertTrue(c1.compareTo(c2) > 0);
+ assertTrue(c2.compareTo(c1) < 0);
+ }
- c2 = new MockCharset("m-", null);
- assertTrue(c1.compareTo(c2) > 0);
- assertTrue(c2.compareTo(c1) < 0);
+ public void testCompareTo_Null() {
+ MockCharset c1 = new MockCharset("mock", null);
+ try {
+ c1.compareTo(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
- c2 = new MockCharset("m_", null);
- assertTrue(c1.compareTo(c2) > 0);
- assertTrue(c2.compareTo(c1) < 0);
- }
+ public void testCompareTo_DiffCharsetClass() {
+ MockCharset c1 = new MockCharset("mock", null);
+ MockCharset2 c2 = new MockCharset2("Mock", new String[] { "myname" });
+ assertEquals(0, c1.compareTo(c2));
+ assertEquals(0, c2.compareTo(c1));
+ }
- /*
- * Test the method compareTo(Object) with null param.
- */
- public void testCompareTo_Null() {
- MockCharset c1 = new MockCharset("mock", null);
- try {
- c1.compareTo(null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- // expected
- }
- }
+ public void testEquals_Normal() {
+ MockCharset c1 = new MockCharset("mock", null);
+ MockCharset2 c2 = new MockCharset2("mock", null);
+ assertTrue(c1.equals(c2));
+ assertTrue(c2.equals(c1));
- /*
- * Test the method compareTo(Object) with another kind of charset object.
- */
- public void testCompareTo_DiffCharsetClass() {
- MockCharset c1 = new MockCharset("mock", null);
- MockCharset2 c2 = new MockCharset2("Mock", new String[] { "myname" });
- assertEquals(0, c1.compareTo(c2));
- assertEquals(0, c2.compareTo(c1));
- }
+ c2 = new MockCharset2("Mock", null);
+ assertFalse(c1.equals(c2));
+ assertFalse(c2.equals(c1));
+ }
- /*
- * Test the method equals(Object) with null param.
- */
- public void testEquals_Normal() {
- MockCharset c1 = new MockCharset("mock", null);
- MockCharset2 c2 = new MockCharset2("mock", null);
- assertTrue(c1.equals(c2));
- assertTrue(c2.equals(c1));
+ public void testEquals_Null() {
+ MockCharset c1 = new MockCharset("mock", null);
+ assertFalse(c1.equals(null));
+ }
- c2 = new MockCharset2("Mock", null);
- assertFalse(c1.equals(c2));
- assertFalse(c2.equals(c1));
- }
+ public void testEquals_NonCharsetObject() {
+ MockCharset c1 = new MockCharset("mock", null);
+ assertFalse(c1.equals("test"));
+ }
- /*
- * Test the method equals(Object) with normal conditions.
- */
- public void testEquals_Null() {
- MockCharset c1 = new MockCharset("mock", null);
- assertFalse(c1.equals(null));
- }
+ public void testEquals_DiffCharsetClass() {
+ MockCharset c1 = new MockCharset("mock", null);
+ MockCharset2 c2 = new MockCharset2("mock", null);
+ assertTrue(c1.equals(c2));
+ assertTrue(c2.equals(c1));
+ }
- /*
- * Test the method equals(Object) with another kind of charset object.
- */
- public void testEquals_NonCharsetObject() {
- MockCharset c1 = new MockCharset("mock", null);
- assertFalse(c1.equals("test"));
- }
+ public void testHashCode_DiffCharsetClass() {
+ MockCharset c1 = new MockCharset("mock", null);
+ assertEquals(c1.hashCode(), "mock".hashCode());
- /*
- * Test the method equals(Object) with another kind of charset object.
- */
- public void testEquals_DiffCharsetClass() {
- MockCharset c1 = new MockCharset("mock", null);
- MockCharset2 c2 = new MockCharset2("mock", null);
- assertTrue(c1.equals(c2));
- assertTrue(c2.equals(c1));
- }
+ final String mockName = "mockChar1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:-_";
+ c1 = new MockCharset(mockName, new String[] { "mockChar", "mock",
+ mockName, "mock", "mockChar", "mock", "mock2" });
+ assertEquals(mockName.hashCode(), c1.hashCode());
+ }
- /*
- * Test the method hashCode().
- */
- public void testHashCode_DiffCharsetClass() {
- MockCharset c1 = new MockCharset("mock", null);
- assertEquals(c1.hashCode(), "mock".hashCode());
+ public void testEncode_CharBuffer_Normal() throws Exception {
+ MockCharset c1 = new MockCharset("testEncode_CharBuffer_Normal_mock", null);
+ ByteBuffer bb = c1.encode(CharBuffer.wrap("abcdefg"));
+ assertEquals("abcdefg", new String(bb.array(), "iso8859-1"));
+ bb = c1.encode(CharBuffer.wrap(""));
+ assertEquals("", new String(bb.array(), "iso8859-1"));
+ }
- final String mockName = "mockChar1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:-_";
- c1 = new MockCharset(mockName, new String[] { "mockChar", "mock",
- mockName, "mock", "mockChar", "mock", "mock2" });
- assertEquals(mockName.hashCode(), c1.hashCode());
- }
+ public void testEncode_CharBuffer_Unmappable() throws Exception {
+ Charset c1 = Charset.forName("iso8859-1");
+ ByteBuffer bb = c1.encode(CharBuffer.wrap("abcd\u5D14efg"));
+ assertEquals(new String(bb.array(), "iso8859-1"),
+ "abcd" + new String(c1.newEncoder().replacement(), "iso8859-1") + "efg");
+ }
- /*
- * Test the method encode(CharBuffer) under normal condition.
- */
- public void testEncode_CharBuffer_Normal() throws Exception {
- MockCharset c1 = new MockCharset("testEncode_CharBuffer_Normal_mock", null);
- ByteBuffer bb = c1.encode(CharBuffer.wrap("abcdefg"));
- assertEquals("abcdefg", new String(bb.array(), "iso8859-1"));
- bb = c1.encode(CharBuffer.wrap(""));
- assertEquals("", new String(bb.array(), "iso8859-1"));
- }
+ public void testEncode_CharBuffer_NullCharBuffer() {
+ MockCharset c = new MockCharset("mock", null);
+ try {
+ c.encode((CharBuffer) null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
- /*
- * Test the method encode(CharBuffer) with an unmappable char.
- */
- public void testEncode_CharBuffer_Unmappable() throws Exception {
- Charset c1 = Charset.forName("iso8859-1");
- ByteBuffer bb = c1.encode(CharBuffer.wrap("abcd\u5D14efg"));
- assertEquals(new String(bb.array(), "iso8859-1"), "abcd"
- + new String(c1.newEncoder().replacement(), "iso8859-1")
- + "efg");
- }
+ public void testEncode_CharBuffer_NullEncoder() {
+ MockCharset2 c = new MockCharset2("mock2", null);
+ try {
+ c.encode(CharBuffer.wrap("hehe"));
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
- /*
- * Test the method encode(CharBuffer) with null CharBuffer.
- */
- public void testEncode_CharBuffer_NullCharBuffer() {
- MockCharset c = new MockCharset("mock", null);
- try {
- c.encode((CharBuffer) null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- // expected
- }
- }
+ public void testEncode_String_Normal() throws Exception {
+ MockCharset c1 = new MockCharset("testEncode_String_Normal_mock", null);
+ ByteBuffer bb = c1.encode("abcdefg");
+ assertEquals("abcdefg", new String(bb.array(), "iso8859-1"));
+ bb = c1.encode("");
+ assertEquals("", new String(bb.array(), "iso8859-1"));
+ }
- /*
- * Test the method encode(CharBuffer) with null encoder.
- */
- public void testEncode_CharBuffer_NullEncoder() {
- MockCharset2 c = new MockCharset2("mock2", null);
- try {
- c.encode(CharBuffer.wrap("hehe"));
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- // expected
- }
- }
+ public void testEncode_String_Unmappable() throws Exception {
+ Charset c1 = Charset.forName("iso8859-1");
+ ByteBuffer bb = c1.encode("abcd\u5D14efg");
+ assertEquals(new String(bb.array(), "iso8859-1"),
+ "abcd" + new String(c1.newEncoder().replacement(), "iso8859-1") + "efg");
+ }
- /*
- * Test the method encode(String) under normal condition.
- */
- public void testEncode_String_Normal() throws Exception {
- MockCharset c1 = new MockCharset("testEncode_String_Normal_mock", null);
- ByteBuffer bb = c1.encode("abcdefg");
- assertEquals("abcdefg", new String(bb.array(), "iso8859-1"));
- bb = c1.encode("");
- assertEquals("", new String(bb.array(), "iso8859-1"));
- }
+ public void testEncode_String_NullString() {
+ MockCharset c = new MockCharset("mock", null);
+ try {
+ c.encode((String) null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
- /*
- * Test the method encode(String) with an unmappable char.
- */
- public void testEncode_String_Unmappable() throws Exception {
- Charset c1 = Charset.forName("iso8859-1");
- ByteBuffer bb = c1.encode("abcd\u5D14efg");
- assertEquals(new String(bb.array(), "iso8859-1"), "abcd"
- + new String(c1.newEncoder().replacement(), "iso8859-1")
- + "efg");
- }
+ public void testEncode_String_NullEncoder() {
+ MockCharset2 c = new MockCharset2("mock2", null);
+ try {
+ c.encode("hehe");
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
- /*
- * Test the method encode(String) with null CharBuffer.
- */
- public void testEncode_String_NullString() {
- MockCharset c = new MockCharset("mock", null);
- try {
- c.encode((String) null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- // expected
- }
- }
+ public void testDecode_Normal() throws Exception {
+ MockCharset c1 = new MockCharset("mock", null);
+ CharBuffer cb = c1.decode(ByteBuffer.wrap("abcdefg".getBytes("iso8859-1")));
+ assertEquals("abcdefg", new String(cb.array()));
+ cb = c1.decode(ByteBuffer.wrap("".getBytes("iso8859-1")));
+ assertEquals("", new String(cb.array()));
+ }
- /*
- * Test the method encode(String) with null encoder.
- */
- public void testEncode_String_NullEncoder() {
+ public void testDecode_Malformed() throws Exception {
+ Charset c1 = Charset.forName("iso8859-1");
+ CharBuffer cb = c1.decode(ByteBuffer.wrap("abcd\u5D14efg".getBytes("iso8859-1")));
+ byte[] replacement = c1.newEncoder().replacement();
+ assertEquals(new String(cb.array()).trim(), "abcd" + new String(replacement, "iso8859-1") + "efg");
+ }
- MockCharset2 c = new MockCharset2("mock2", null);
- try {
- c.encode("hehe");
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- // expected
- }
- }
+ public void testDecode_NullByteBuffer() {
+ MockCharset c = new MockCharset("mock", null);
+ try {
+ c.decode(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
- /*
- * Test the method decode(ByteBuffer) under normal condition.
- */
- public void testDecode_Normal() throws Exception {
- MockCharset c1 = new MockCharset("mock", null);
- CharBuffer cb = c1.decode(ByteBuffer.wrap("abcdefg"
- .getBytes("iso8859-1")));
- assertEquals("abcdefg", new String(cb.array()));
- cb = c1.decode(ByteBuffer.wrap("".getBytes("iso8859-1")));
- assertEquals("", new String(cb.array()));
- }
+ public void testDecode_NullDecoder() {
+ MockCharset2 c = new MockCharset2("mock2", null);
+ try {
+ c.decode(ByteBuffer.wrap("hehe".getBytes()));
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
- /*
- * Test the method decode(ByteBuffer) with a malformed input.
- */
- public void testDecode_Malformed() throws Exception {
- Charset c1 = Charset.forName("iso8859-1");
- CharBuffer cb = c1.decode(ByteBuffer.wrap("abcd\u5D14efg"
- .getBytes("iso8859-1")));
- byte[] replacement = c1.newEncoder().replacement();
- assertEquals(new String(cb.array()).trim(), "abcd" + new String(replacement, "iso8859-1")
- + "efg");
- }
+ public void testToString() {
+ MockCharset c1 = new MockCharset("mock", null);
+ assertTrue(-1 != c1.toString().indexOf("mock"));
+ }
- /*
- * Test the method decode(ByteBuffer) with null CharBuffer.
- */
- public void testDecode_NullByteBuffer() {
- MockCharset c = new MockCharset("mock", null);
- try {
- c.decode(null);
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Test the method decode(ByteBuffer) with null encoder.
- */
- public void testDecode_NullDecoder() {
- MockCharset2 c = new MockCharset2("mock2", null);
- try {
- c.decode(ByteBuffer.wrap("hehe".getBytes()));
- fail("Should throw NullPointerException!");
- } catch (NullPointerException e) {
- // expected
- }
- }
-
- /*
- * Test the method toString().
- */
- public void testToString() {
- MockCharset c1 = new MockCharset("mock", null);
- assertTrue(-1 != c1.toString().indexOf("mock"));
- }
-
- /**
- * @tests java.nio.charset.Charset#availableCharsets()
- */
- public void test_availableCharsets() throws Exception {
- // regression test for Harmony-1051
- ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
- try {
- Thread.currentThread().setContextClassLoader(null);
- SortedMap<String, Charset> charsets = Charset.availableCharsets();
- // make sure "mockCharset00" is loaded by MockCharsetProvider
- assertTrue(charsets.containsKey("mockCharset00"));
- } finally {
- Thread.currentThread().setContextClassLoader(originalClassLoader);
- }
+ static final class MockCharset extends Charset {
+ public MockCharset(String canonicalName, String[] aliases) {
+ super(canonicalName, aliases);
}
- /**
- * @tests java.nio.charset.Charset#availableCharsets()
- */
- public void test_forNameLString() throws Exception {
- // regression test for Harmony-1051
- ClassLoader originalClassLoader = Thread.currentThread()
- .getContextClassLoader();
- try {
- Thread.currentThread().setContextClassLoader(null);
- // make sure "mockCharset00" is loaded by MockCharsetProvider
- assertNotNull(Charset.forName("mockCharset00"));
- } finally {
- Thread.currentThread().setContextClassLoader(originalClassLoader);
- }
+ public boolean contains(Charset cs) {
+ return false;
}
- /*
- * Mock charset class.
- */
- static final class MockCharset extends Charset {
+ public CharsetDecoder newDecoder() {
+ return new MockDecoder(this);
+ }
- public MockCharset(String canonicalName, String[] aliases) {
- super(canonicalName, aliases);
- }
+ public CharsetEncoder newEncoder() {
+ return new MockEncoder(this);
+ }
+ }
- public boolean contains(Charset cs) {
- return false;
- }
+ static class MockCharset2 extends Charset {
+ public MockCharset2(String canonicalName, String[] aliases) {
+ super(canonicalName, aliases);
+ }
- public CharsetDecoder newDecoder() {
- return new MockDecoder(this);
- }
+ public boolean contains(Charset cs) {
+ return false;
+ }
- public CharsetEncoder newEncoder() {
- return new MockEncoder(this);
- }
- }
+ public CharsetDecoder newDecoder() {
+ return null;
+ }
- /*
- * Another mock charset class.
- */
- static class MockCharset2 extends Charset {
+ public CharsetEncoder newEncoder() {
+ return null;
+ }
+ }
- public MockCharset2(String canonicalName, String[] aliases) {
- super(canonicalName, aliases);
- }
+ static class MockEncoder extends java.nio.charset.CharsetEncoder {
+ public MockEncoder(Charset cs) {
+ super(cs, 1, 3, new byte[] { (byte) '?' });
+ }
- public boolean contains(Charset cs) {
- return false;
- }
+ protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) {
+ while (in.remaining() > 0) {
+ out.put((byte) in.get());
+ // out.put((byte) '!');
+ }
+ return CoderResult.UNDERFLOW;
+ }
+ }
- public CharsetDecoder newDecoder() {
- return null;
- }
+ static class MockDecoder extends java.nio.charset.CharsetDecoder {
+ public MockDecoder(Charset cs) {
+ super(cs, 1, 10);
+ }
- public CharsetEncoder newEncoder() {
- return null;
- }
- }
+ protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
+ while (in.remaining() > 0) {
+ out.put((char) in.get());
+ }
+ return CoderResult.UNDERFLOW;
+ }
+ }
- /*
- * Mock encoder.
- */
- static class MockEncoder extends java.nio.charset.CharsetEncoder {
- public MockEncoder(Charset cs) {
- super(cs, 1, 3, new byte[] { (byte) '?' });
- }
+ // Test the method isSupported(String) with charset supported by multiple providers.
+ public void testIsSupported_And_ForName_NormalProvider() throws Exception {
+ assertTrue(Charset.isSupported("mockCharset10"));
+ // ignore case problem in mock, intended
+ assertTrue(Charset.isSupported("MockCharset11"));
+ assertTrue(Charset.isSupported("MockCharset12"));
+ assertTrue(Charset.isSupported("MOCKCharset10"));
+ // intended case problem in mock
+ assertTrue(Charset.isSupported("MOCKCharset11"));
+ assertTrue(Charset.isSupported("MOCKCharset12"));
- protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) {
- while (in.remaining() > 0) {
- out.put((byte) in.get());
- // out.put((byte) '!');
- }
- return CoderResult.UNDERFLOW;
- }
- }
+ assertTrue(Charset.forName("mockCharset10") instanceof MockCharset);
+ assertTrue(Charset.forName("mockCharset11") instanceof MockCharset);
+ assertTrue(Charset.forName("mockCharset12") instanceof MockCharset);
- /*
- * Mock decoder.
- */
- static class MockDecoder extends java.nio.charset.CharsetDecoder {
+ assertTrue(Charset.forName("mockCharset10") == charset2);
+ // intended case problem in mock
+ Charset.forName("mockCharset11");
+ assertTrue(Charset.forName("mockCharset12") == charset2);
+ }
- public MockDecoder(Charset cs) {
- super(cs, 1, 10);
- }
+ // Test the method availableCharsets() with charset supported by multiple providers.
+ public void testAvailableCharsets_NormalProvider() throws Exception {
+ assertTrue(Charset.availableCharsets().containsKey("mockCharset00"));
+ assertTrue(Charset.availableCharsets().containsKey("MOCKCharset00"));
+ assertTrue(Charset.availableCharsets().get("mockCharset00") instanceof MockCharset);
+ assertTrue(Charset.availableCharsets().get("MOCKCharset00") instanceof MockCharset);
+ assertFalse(Charset.availableCharsets().containsKey("mockCharset01"));
+ assertFalse(Charset.availableCharsets().containsKey("mockCharset02"));
- protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
- while (in.remaining() > 0) {
- out.put((char) in.get());
- }
- return CoderResult.UNDERFLOW;
- }
- }
+ assertTrue(Charset.availableCharsets().get("mockCharset10") == charset2);
+ assertTrue(Charset.availableCharsets().get("MOCKCharset10") == charset2);
+ assertFalse(Charset.availableCharsets().containsKey("mockCharset11"));
+ assertFalse(Charset.availableCharsets().containsKey("mockCharset12"));
- /*
- * Mock charset provider.
- */
- public static class MockCharsetProvider extends CharsetProvider {
+ assertTrue(Charset.availableCharsets().containsKey("mockCharset10"));
+ assertTrue(Charset.availableCharsets().containsKey("MOCKCharset10"));
+ assertTrue(Charset.availableCharsets().get("mockCharset10") == charset2);
+ assertFalse(Charset.availableCharsets().containsKey("mockCharset11"));
+ assertFalse(Charset.availableCharsets().containsKey("mockCharset12"));
+ }
- public Charset charsetForName(String charsetName) {
- if ("MockCharset00".equalsIgnoreCase(charsetName)
- || "MockCharset01".equalsIgnoreCase(charsetName)
- || "MockCharset02".equalsIgnoreCase(charsetName)) {
- return new MockCharset("mockCharset00", new String[] {
- "mockCharset01", "mockCharset02" });
- }
- return null;
- }
+ // Test the method forName(String) when the charset provider supports a
+ // built-in charset.
+ public void testForName_DuplicateWithBuiltInCharset() throws Exception {
+ assertFalse(Charset.forName("us-ascii") instanceof MockCharset);
+ assertFalse(Charset.availableCharsets().get("us-ascii") instanceof MockCharset);
+ }
- public Iterator charsets() {
- Vector v = new Vector();
- v.add(new MockCharset("mockCharset00", new String[] {
- "mockCharset01", "mockCharset02" }));
- return v.iterator();
- }
- }
+ public static class MockCharsetProvider extends CharsetProvider {
+ public Charset charsetForName(String charsetName) {
+ if ("MockCharset00".equalsIgnoreCase(charsetName) ||
+ "MockCharset01".equalsIgnoreCase(charsetName) ||
+ "MockCharset02".equalsIgnoreCase(charsetName)) {
+ return charset1;
+ } else if ("MockCharset10".equalsIgnoreCase(charsetName) ||
+ "MockCharset11".equalsIgnoreCase(charsetName) ||
+ "MockCharset12".equalsIgnoreCase(charsetName)) {
+ return charset2;
+ }
+ return null;
+ }
+
+ public Iterator charsets() {
+ Vector v = new Vector();
+ v.add(charset1);
+ v.add(charset2);
+ return v.iterator();
+ }
+ }
+
+ // Another mock charset provider attempting to provide the built-in charset "ascii" again.
+ public static class MockCharsetProviderASCII extends CharsetProvider {
+ public Charset charsetForName(String charsetName) {
+ if ("US-ASCII".equalsIgnoreCase(charsetName) || "ASCII".equalsIgnoreCase(charsetName)) {
+ return new MockCharset("US-ASCII", new String[] { "ASCII" });
+ }
+ return null;
+ }
+
+ public Iterator charsets() {
+ Vector v = new Vector();
+ v.add(new MockCharset("US-ASCII", new String[] { "ASCII" }));
+ return v.iterator();
+ }
+ }
}
diff --git a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetEncoderTest.java b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetEncoderTest.java
index 798a048..d483fcb 100644
--- a/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetEncoderTest.java
+++ b/harmony-tests/src/test/java/tests/api/java/nio/charset/UTFCharsetEncoderTest.java
@@ -71,10 +71,8 @@
}
public void testSpecificDefaultValue() {
- assertEquals(1.1, encoder.averageBytesPerChar(), 0.0001);
- // assertEquals(2, encoder.averageBytesPerChar(), 0.0001);
- assertEquals(4, encoder.maxBytesPerChar(), 0);
- // assertEquals(3, encoder.maxBytesPerChar(), 0);
+ assertEquals(2, encoder.averageBytesPerChar(), 0);
+ assertEquals(3, encoder.maxBytesPerChar(), 0);
}
CharBuffer getMalformedCharBuffer() {
diff --git a/luni/src/main/java/java/nio/charset/Charset.java b/luni/src/main/java/java/nio/charset/Charset.java
index 882cca7..b3e8d0b 100644
--- a/luni/src/main/java/java/nio/charset/Charset.java
+++ b/luni/src/main/java/java/nio/charset/Charset.java
@@ -217,7 +217,6 @@
* If multiple charsets have the same canonical name, it is unspecified which is returned in
* the map. This method may be slow. If you know which charset you're looking for, use
* {@link #forName}.
- * @return an immutable case-insensitive map from canonical names to {@code Charset} instances
*/
public static SortedMap<String, Charset> availableCharsets() {
// Start with a copy of the built-in charsets...
@@ -364,67 +363,56 @@
public abstract boolean contains(Charset charset);
/**
- * Gets a new instance of an encoder for this charset.
- *
- * @return a new instance of an encoder for this charset.
+ * Returns a new instance of an encoder for this charset.
*/
public abstract CharsetEncoder newEncoder();
/**
- * Gets a new instance of a decoder for this charset.
- *
- * @return a new instance of a decoder for this charset.
+ * Returns a new instance of a decoder for this charset.
*/
public abstract CharsetDecoder newDecoder();
/**
* Returns the canonical name of this charset.
+ *
+ * <p>If a charset is in the IANA registry, this will be the MIME-preferred name (a charset
+ * may have multiple IANA-registered names). Otherwise the canonical name will begin with "x-"
+ * or "X-".
*/
public final String name() {
return this.canonicalName;
}
/**
- * Gets the set of this charset's aliases.
- *
- * @return an unmodifiable set of this charset's aliases.
+ * Returns an unmodifiable set of this charset's aliases.
*/
public final Set<String> aliases() {
return Collections.unmodifiableSet(this.aliasesSet);
}
/**
- * Gets the name of this charset for the default locale.
+ * Returns the name of this charset for the default locale.
*
* <p>The default implementation returns the canonical name of this charset.
* Subclasses may return a localized display name.
- *
- * @return the name of this charset for the default locale.
*/
public String displayName() {
return this.canonicalName;
}
/**
- * Gets the name of this charset for the specified locale.
+ * Returns the name of this charset for the specified locale.
*
* <p>The default implementation returns the canonical name of this charset.
* Subclasses may return a localized display name.
- *
- * @param l
- * a certain locale
- * @return the name of this charset for the specified locale
*/
public String displayName(Locale l) {
return this.canonicalName;
}
/**
- * Indicates whether this charset is known to be registered in the IANA
+ * Returns true if this charset is known to be registered in the IANA
* Charset Registry.
- *
- * @return true if the charset is known to be registered, otherwise returns
- * false.
*/
public final boolean isRegistered() {
return !canonicalName.startsWith("x-") && !canonicalName.startsWith("X-");
@@ -432,8 +420,6 @@
/**
* Returns true if this charset supports encoding, false otherwise.
- *
- * @return true if this charset supports encoding, false otherwise.
*/
public boolean canEncode() {
return true;
diff --git a/luni/src/main/native/libcore_icu_NativeConverter.cpp b/luni/src/main/native/libcore_icu_NativeConverter.cpp
index fae56b7..fdd016a 100644
--- a/luni/src/main/native/libcore_icu_NativeConverter.cpp
+++ b/luni/src/main/native/libcore_icu_NativeConverter.cpp
@@ -57,17 +57,105 @@
UConverterFromUCallback onMalformedInput;
};
-struct UConverterDeleter {
- void operator()(UConverter* p) const {
- ucnv_close(p);
- }
-};
-typedef UniquePtr<UConverter, UConverterDeleter> UniqueUConverter;
-
static UConverter* toUConverter(jlong address) {
return reinterpret_cast<UConverter*>(static_cast<uintptr_t>(address));
}
+static jobjectArray getAliases(JNIEnv* env, const char* icuCanonicalName) {
+ // Get an upper bound on the number of aliases...
+ const char* myEncName = icuCanonicalName;
+ UErrorCode error = U_ZERO_ERROR;
+ size_t aliasCount = ucnv_countAliases(myEncName, &error);
+ if (aliasCount == 0 && myEncName[0] == 'x' && myEncName[1] == '-') {
+ myEncName = myEncName + 2;
+ aliasCount = ucnv_countAliases(myEncName, &error);
+ }
+ if (!U_SUCCESS(error)) {
+ return NULL;
+ }
+
+ // Collect the aliases we want...
+ std::vector<std::string> aliases;
+ for (size_t i = 0; i < aliasCount; ++i) {
+ const char* name = ucnv_getAlias(myEncName, i, &error);
+ if (!U_SUCCESS(error)) {
+ return NULL;
+ }
+ // TODO: why do we ignore these ones?
+ if (strchr(name, '+') == 0 && strchr(name, ',') == 0) {
+ aliases.push_back(name);
+ }
+ }
+ return toStringArray(env, aliases);
+}
+
+static const char* getICUCanonicalName(const char* name) {
+ UErrorCode error = U_ZERO_ERROR;
+ const char* canonicalName = NULL;
+ if ((canonicalName = ucnv_getCanonicalName(name, "MIME", &error)) != NULL) {
+ return canonicalName;
+ } else if ((canonicalName = ucnv_getCanonicalName(name, "IANA", &error)) != NULL) {
+ return canonicalName;
+ } else if ((canonicalName = ucnv_getCanonicalName(name, "", &error)) != NULL) {
+ return canonicalName;
+ } else if ((canonicalName = ucnv_getAlias(name, 0, &error)) != NULL) {
+ // We have some aliases in the form x-blah .. match those first.
+ return canonicalName;
+ } else if (strstr(name, "x-") == name) {
+ // Check if the converter can be opened with the name given.
+ error = U_ZERO_ERROR;
+ LocalUConverterPointer cnv(ucnv_open(name + 2, &error));
+ if (U_SUCCESS(error)) {
+ return name + 2;
+ }
+ }
+ return NULL;
+}
+
+// If a charset listed in the IANA Charset Registry is supported by an implementation
+// of the Java platform then its canonical name must be the name listed in the registry.
+// Many charsets are given more than one name in the registry, in which case the registry
+// identifies one of the names as MIME-preferred. If a charset has more than one registry
+// name then its canonical name must be the MIME-preferred name and the other names in
+// the registry must be valid aliases. If a supported charset is not listed in the IANA
+// registry then its canonical name must begin with one of the strings "X-" or "x-".
+static jstring getJavaCanonicalName(JNIEnv* env, const char* icuCanonicalName) {
+ UErrorCode status = U_ZERO_ERROR;
+
+ // Check to see if this is a well-known MIME or IANA name.
+ const char* cName = NULL;
+ if ((cName = ucnv_getStandardName(icuCanonicalName, "MIME", &status)) != NULL) {
+ return env->NewStringUTF(cName);
+ } else if ((cName = ucnv_getStandardName(icuCanonicalName, "IANA", &status)) != NULL) {
+ return env->NewStringUTF(cName);
+ }
+
+ // Check to see if an alias already exists with "x-" prefix, if yes then
+ // make that the canonical name.
+ int32_t aliasCount = ucnv_countAliases(icuCanonicalName, &status);
+ for (int i = 0; i < aliasCount; ++i) {
+ const char* name = ucnv_getAlias(icuCanonicalName, i, &status);
+ if (name != NULL && name[0] == 'x' && name[1] == '-') {
+ return env->NewStringUTF(name);
+ }
+ }
+
+ // As a last resort, prepend "x-" to any alias and make that the canonical name.
+ status = U_ZERO_ERROR;
+ const char* name = ucnv_getStandardName(icuCanonicalName, "UTR22", &status);
+ if (name == NULL && strchr(icuCanonicalName, ',') != NULL) {
+ name = ucnv_getAlias(icuCanonicalName, 1, &status);
+ }
+ // If there is no UTR22 canonical name then just return the original name.
+ if (name == NULL) {
+ name = icuCanonicalName;
+ }
+ UniquePtr<char[]> result(new char[2 + strlen(name) + 1]);
+ strcpy(&result[0], "x-");
+ strcat(&result[0], name);
+ return env->NewStringUTF(&result[0]);
+}
+
static jlong NativeConverter_openConverter(JNIEnv* env, jclass, jstring converterName) {
ScopedUtfChars converterNameChars(env, converterName);
if (converterNameChars.c_str() == NULL) {
@@ -230,52 +318,6 @@
return (cnv != NULL) ? ((ucnv_getMaxCharSize(cnv) + ucnv_getMinCharSize(cnv)) / 2.0) : -1;
}
-/*
- * If a charset listed in the IANA Charset Registry is supported by an implementation
- * of the Java platform then its canonical name must be the name listed in the registry.
- * Many charsets are given more than one name in the registry, in which case the registry
- * identifies one of the names as MIME-preferred. If a charset has more than one registry
- * name then its canonical name must be the MIME-preferred name and the other names in
- * the registry must be valid aliases. If a supported charset is not listed in the IANA
- * registry then its canonical name must begin with one of the strings "X-" or "x-".
- */
-static jstring getJavaCanonicalName(JNIEnv* env, const char* icuCanonicalName) {
- UErrorCode status = U_ZERO_ERROR;
-
- // Check to see if this is a well-known MIME or IANA name.
- const char* cName = NULL;
- if ((cName = ucnv_getStandardName(icuCanonicalName, "MIME", &status)) != NULL) {
- return env->NewStringUTF(cName);
- } else if ((cName = ucnv_getStandardName(icuCanonicalName, "IANA", &status)) != NULL) {
- return env->NewStringUTF(cName);
- }
-
- // Check to see if an alias already exists with "x-" prefix, if yes then
- // make that the canonical name.
- int32_t aliasCount = ucnv_countAliases(icuCanonicalName, &status);
- for (int i = 0; i < aliasCount; ++i) {
- const char* name = ucnv_getAlias(icuCanonicalName, i, &status);
- if (name != NULL && name[0] == 'x' && name[1] == '-') {
- return env->NewStringUTF(name);
- }
- }
-
- // As a last resort, prepend "x-" to any alias and make that the canonical name.
- status = U_ZERO_ERROR;
- const char* name = ucnv_getStandardName(icuCanonicalName, "UTR22", &status);
- if (name == NULL && strchr(icuCanonicalName, ',') != NULL) {
- name = ucnv_getAlias(icuCanonicalName, 1, &status);
- }
- // If there is no UTR22 canonical name then just return the original name.
- if (name == NULL) {
- name = icuCanonicalName;
- }
- UniquePtr<char[]> result(new char[2 + strlen(name) + 1]);
- strcpy(&result[0], "x-");
- strcat(&result[0], name);
- return env->NewStringUTF(&result[0]);
-}
-
static jobjectArray NativeConverter_getAvailableCharsetNames(JNIEnv* env, jclass) {
int32_t num = ucnv_countAvailable();
jobjectArray result = env->NewObjectArray(num, JniConstants::stringClass, NULL);
@@ -296,57 +338,6 @@
return result;
}
-static jobjectArray getAliases(JNIEnv* env, const char* icuCanonicalName) {
- // Get an upper bound on the number of aliases...
- const char* myEncName = icuCanonicalName;
- UErrorCode error = U_ZERO_ERROR;
- size_t aliasCount = ucnv_countAliases(myEncName, &error);
- if (aliasCount == 0 && myEncName[0] == 'x' && myEncName[1] == '-') {
- myEncName = myEncName + 2;
- aliasCount = ucnv_countAliases(myEncName, &error);
- }
- if (!U_SUCCESS(error)) {
- return NULL;
- }
-
- // Collect the aliases we want...
- std::vector<std::string> aliases;
- for (size_t i = 0; i < aliasCount; ++i) {
- const char* name = ucnv_getAlias(myEncName, i, &error);
- if (!U_SUCCESS(error)) {
- return NULL;
- }
- // TODO: why do we ignore these ones?
- if (strchr(name, '+') == 0 && strchr(name, ',') == 0) {
- aliases.push_back(name);
- }
- }
- return toStringArray(env, aliases);
-}
-
-static const char* getICUCanonicalName(const char* name) {
- UErrorCode error = U_ZERO_ERROR;
- const char* canonicalName = NULL;
- if ((canonicalName = ucnv_getCanonicalName(name, "MIME", &error)) != NULL) {
- return canonicalName;
- } else if((canonicalName = ucnv_getCanonicalName(name, "IANA", &error)) != NULL) {
- return canonicalName;
- } else if((canonicalName = ucnv_getCanonicalName(name, "", &error)) != NULL) {
- return canonicalName;
- } else if((canonicalName = ucnv_getAlias(name, 0, &error)) != NULL) {
- /* we have some aliases in the form x-blah .. match those first */
- return canonicalName;
- } else if (strstr(name, "x-") == name) {
- /* check if the converter can be opened with the name given */
- error = U_ZERO_ERROR;
- UniqueUConverter cnv(ucnv_open(name + 2, &error));
- if (cnv.get() != NULL) {
- return name + 2;
- }
- }
- return NULL;
-}
-
static void CHARSET_ENCODER_CALLBACK(const void* rawContext, UConverterFromUnicodeArgs* args,
const UChar* codeUnits, int32_t length, UChar32 codePoint, UConverterCallbackReason reason,
UErrorCode* status) {
@@ -544,13 +535,13 @@
}
UErrorCode errorCode = U_ZERO_ERROR;
- UniqueUConverter converter1(ucnv_open(name1Chars.c_str(), &errorCode));
+ LocalUConverterPointer converter1(ucnv_open(name1Chars.c_str(), &errorCode));
UnicodeSet set1;
- ucnv_getUnicodeSet(converter1.get(), set1.toUSet(), UCNV_ROUNDTRIP_SET, &errorCode);
+ ucnv_getUnicodeSet(&*converter1, set1.toUSet(), UCNV_ROUNDTRIP_SET, &errorCode);
- UniqueUConverter converter2(ucnv_open(name2Chars.c_str(), &errorCode));
+ LocalUConverterPointer converter2(ucnv_open(name2Chars.c_str(), &errorCode));
UnicodeSet set2;
- ucnv_getUnicodeSet(converter2.get(), set2.toUSet(), UCNV_ROUNDTRIP_SET, &errorCode);
+ ucnv_getUnicodeSet(&*converter2, set2.toUSet(), UCNV_ROUNDTRIP_SET, &errorCode);
return U_SUCCESS(errorCode) && set1.containsAll(set2);
}
@@ -560,11 +551,13 @@
if (charsetNameChars.c_str() == NULL) {
return NULL;
}
+
// Get ICU's canonical name for this charset.
const char* icuCanonicalName = getICUCanonicalName(charsetNameChars.c_str());
if (icuCanonicalName == NULL) {
return NULL;
}
+
// Get Java's canonical name for this charset.
jstring javaCanonicalName = getJavaCanonicalName(env, icuCanonicalName);
if (env->ExceptionCheck()) {
@@ -572,14 +565,14 @@
}
// Check that this charset is supported.
- // ICU doesn't offer any "isSupported", so we just open and immediately close.
- // We ignore the UErrorCode because ucnv_open returning NULL is all the information we need.
- UErrorCode dummy = U_ZERO_ERROR;
- UniqueUConverter cnv(ucnv_open(icuCanonicalName, &dummy));
- if (cnv.get() == NULL) {
- return NULL;
+ {
+ // ICU doesn't offer any "isSupported", so we just open and immediately close.
+ UErrorCode error = U_ZERO_ERROR;
+ LocalUConverterPointer cnv(ucnv_open(icuCanonicalName, &error));
+ if (!U_SUCCESS(error)) {
+ return NULL;
+ }
}
- cnv.reset();
// Get the aliases for this charset.
jobjectArray aliases = getAliases(env, icuCanonicalName);
diff --git a/luni/src/test/java/libcore/java/nio/charset/CharsetTest.java b/luni/src/test/java/libcore/java/nio/charset/CharsetTest.java
deleted file mode 100644
index 640a3dd..0000000
--- a/luni/src/test/java/libcore/java/nio/charset/CharsetTest.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package libcore.java.nio.charset;
-
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetEncoder;
-import java.util.Arrays;
-import java.util.ArrayList;
-
-public class CharsetTest extends junit.framework.TestCase {
- public void test_guaranteedCharsetsAvailable() throws Exception {
- // All Java implementations must support these charsets.
- assertNotNull(Charset.forName("ISO-8859-1"));
- assertNotNull(Charset.forName("US-ASCII"));
- assertNotNull(Charset.forName("UTF-16"));
- assertNotNull(Charset.forName("UTF-16BE"));
- assertNotNull(Charset.forName("UTF-16LE"));
- assertNotNull(Charset.forName("UTF-8"));
- }
-
- // http://code.google.com/p/android/issues/detail?id=42769
- public void test_42769() throws Exception {
- ArrayList<Thread> threads = new ArrayList<Thread>();
- for (int i = 0; i < 10; ++i) {
- Thread t = new Thread(new Runnable() {
- public void run() {
- for (int i = 0; i < 50; ++i) {
- Charset.availableCharsets();
- }
- }
- });
- threads.add(t);
- }
-
- for (Thread t : threads) {
- t.start();
- }
- for (Thread t : threads) {
- t.join();
- }
- }
-
- public void test_allAvailableCharsets() throws Exception {
- // Check that we can instantiate every Charset, CharsetDecoder, and CharsetEncoder.
- for (String charsetName : Charset.availableCharsets().keySet()) {
- if (charsetName.equals("UTF-32")) {
- // Our UTF-32 is broken. http://b/2702411
- // TODO: remove this hack when UTF-32 is fixed.
- continue;
- }
-
- Charset cs = Charset.forName(charsetName);
- assertNotNull(cs.newDecoder());
- if (cs.canEncode()) {
- CharsetEncoder enc = cs.newEncoder();
- assertNotNull(enc);
- assertNotNull(enc.replacement());
- }
- }
- }
-
- public void test_EUC_JP_replacement_character() throws Exception {
- assertEncodes(Charset.forName("EUC-JP"), "\ufffd", 0xf4, 0xfe);
- }
-
- public void test_SCSU_replacement_character() throws Exception {
- assertDecodes(Charset.forName("SCSU"), "\ufffd", 14, 0xff);
- assertEncodes(Charset.forName("SCSU"), "\ufffd", 14, 0xff);
- }
-
- public void test_Shift_JIS_replacement_character() throws Exception {
- assertDecodes(Charset.forName("Shift_JIS"), "\ufffd", 0xfc);
- assertEncodes(Charset.forName("Shift_JIS"), "\ufffd", 0xfc);
- }
-
- public void test_UTF_16() throws Exception {
- Charset cs = Charset.forName("UTF-16");
- // Writes big-endian, with a big-endian BOM.
- assertEncodes(cs, "a\u0666", 0xfe, 0xff, 0, 'a', 0x06, 0x66);
- // Reads whatever the BOM tells it to read...
- assertDecodes(cs, "a\u0666", 0xfe, 0xff, 0, 'a', 0x06, 0x66);
- assertDecodes(cs, "a\u0666", 0xff, 0xfe, 'a', 0, 0x66, 0x06);
- // ...and defaults to reading big-endian if there's no BOM.
- assertDecodes(cs, "a\u0666", 0, 'a', 0x06, 0x66);
- }
-
- public void test_UTF_16BE() throws Exception {
- Charset cs = Charset.forName("UTF-16BE");
- // Writes big-endian, with no BOM.
- assertEncodes(cs, "a\u0666", 0, 'a', 0x06, 0x66);
- // Treats a little-endian BOM as an error and continues to read big-endian.
- // This test uses REPLACE mode, so we get the U+FFFD replacement character in the result.
- assertDecodes(cs, "\ufffda\u0666", 0xff, 0xfe, 0, 'a', 0x06, 0x66);
- // Accepts a big-endian BOM and includes U+FEFF in the decoded output.
- assertDecodes(cs, "\ufeffa\u0666", 0xfe, 0xff, 0, 'a', 0x06, 0x66);
- // Defaults to reading big-endian.
- assertDecodes(cs, "a\u0666", 0, 'a', 0x06, 0x66);
- }
-
- public void test_UTF_16LE() throws Exception {
- Charset cs = Charset.forName("UTF-16LE");
- // Writes little-endian, with no BOM.
- assertEncodes(cs, "a\u0666", 'a', 0, 0x66, 0x06);
- // Accepts a little-endian BOM and includes U+FEFF in the decoded output.
- assertDecodes(cs, "\ufeffa\u0666", 0xff, 0xfe, 'a', 0, 0x66, 0x06);
- // Treats a big-endian BOM as an error and continues to read little-endian.
- // This test uses REPLACE mode, so we get the U+FFFD replacement character in the result.
- assertDecodes(cs, "\ufffda\u0666", 0xfe, 0xff, 'a', 0, 0x66, 0x06);
- // Defaults to reading little-endian.
- assertDecodes(cs, "a\u0666", 'a', 0, 0x66, 0x06);
- }
-
- public void test_x_UTF_16LE_BOM() throws Exception {
- Charset cs = Charset.forName("x-UTF-16LE-BOM");
- // Writes little-endian, with a BOM.
- assertEncodes(cs, "a\u0666", 0xff, 0xfe, 'a', 0, 0x66, 0x06);
- // Accepts a little-endian BOM and swallows the BOM.
- assertDecodes(cs, "a\u0666", 0xff, 0xfe, 'a', 0, 0x66, 0x06);
- // Swallows a big-endian BOM, but continues to read little-endian!
- assertDecodes(cs, "\u6100\u6606", 0xfe, 0xff, 'a', 0, 0x66, 0x06);
- // Defaults to reading little-endian.
- assertDecodes(cs, "a\u0666", 'a', 0, 0x66, 0x06);
- }
-
- public void test_UTF_32() throws Exception {
- Charset cs = Charset.forName("UTF-32");
- // Writes big-endian, with no BOM.
- assertEncodes(cs, "a\u0666", 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
- // Reads whatever the BOM tells it to read...
- assertDecodes(cs, "a\u0666", 0, 0, 0xfe, 0xff, 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
- assertDecodes(cs, "a\u0666", 0xff, 0xfe, 0, 0, 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
- // ...and defaults to reading big-endian if there's no BOM.
- assertDecodes(cs, "a\u0666", 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
- }
-
- public void test_UTF_32BE() throws Exception {
- Charset cs = Charset.forName("UTF-32BE");
- // Writes big-endian, with no BOM.
- assertEncodes(cs, "a\u0666", 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
- // Treats a little-endian BOM as an error and continues to read big-endian.
- // This test uses REPLACE mode, so we get the U+FFFD replacement character in the result.
- assertDecodes(cs, "\ufffda\u0666", 0xff, 0xfe, 0, 0, 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
- // Accepts a big-endian BOM and swallows the BOM.
- assertDecodes(cs, "a\u0666", 0, 0, 0xfe, 0xff, 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
- // Defaults to reading big-endian.
- assertDecodes(cs, "a\u0666", 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
- }
-
- public void test_UTF_32LE() throws Exception {
- Charset cs = Charset.forName("UTF-32LE");
- // Writes little-endian, with no BOM.
- assertEncodes(cs, "a\u0666", 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
- // Accepts a little-endian BOM and swallows the BOM.
- assertDecodes(cs, "a\u0666", 0xff, 0xfe, 0, 0, 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
- // Treats a big-endian BOM as an error and continues to read little-endian.
- // This test uses REPLACE mode, so we get the U+FFFD replacement character in the result.
- assertDecodes(cs, "\ufffda\u0666", 0, 0, 0xfe, 0xff, 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
- // Defaults to reading little-endian.
- assertDecodes(cs, "a\u0666", 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
- }
-
- public void test_X_UTF_32BE_BOM() throws Exception {
- Charset cs = Charset.forName("X-UTF-32BE-BOM");
- // Writes big-endian, with a big-endian BOM.
- assertEncodes(cs, "a\u0666", 0, 0, 0xfe, 0xff, 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
- // Treats a little-endian BOM as an error and continues to read big-endian.
- // This test uses REPLACE mode, so we get the U+FFFD replacement character in the result.
- assertDecodes(cs, "\ufffda\u0666", 0xff, 0xfe, 0, 0, 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
- // Swallows a big-endian BOM, and continues to read big-endian.
- assertDecodes(cs, "a\u0666", 0, 0, 0xfe, 0xff, 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
- // Defaults to reading big-endian.
- assertDecodes(cs, "a\u0666", 0, 0, 0, 'a', 0, 0, 0x06, 0x66);
- }
-
- public void test_X_UTF_32LE_BOM() throws Exception {
- Charset cs = Charset.forName("X-UTF-32LE-BOM");
- // Writes little-endian, with a little-endian BOM.
- assertEncodes(cs, "a\u0666", 0xff, 0xfe, 0, 0, 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
- // Accepts a little-endian BOM and swallows the BOM.
- assertDecodes(cs, "a\u0666", 0xff, 0xfe, 0, 0, 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
- // Treats a big-endian BOM as an error and continues to read little-endian.
- // This test uses REPLACE mode, so we get the U+FFFD replacement character in the result.
- assertDecodes(cs, "\ufffda\u0666", 0, 0, 0xfe, 0xff, 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
- // Defaults to reading little-endian.
- assertDecodes(cs, "a\u0666", 'a', 0, 0, 0, 0x66, 0x06, 0, 0);
- }
-
- private byte[] toByteArray(int[] ints) {
- byte[] result = new byte[ints.length];
- for (int i = 0; i < ints.length; ++i) {
- result[i] = (byte) ints[i];
- }
- return result;
- }
-
- private void assertEncodes(Charset cs, String s, int... expectedByteInts) throws Exception {
- ByteBuffer out = cs.encode(s);
- byte[] bytes = new byte[out.remaining()];
- out.get(bytes);
- assertEquals(Arrays.toString(toByteArray(expectedByteInts)), Arrays.toString(bytes));
- }
-
- private void assertDecodes(Charset cs, String s, int... byteInts) throws Exception {
- ByteBuffer in = ByteBuffer.wrap(toByteArray(byteInts));
- CharBuffer out = cs.decode(in);
- assertEquals(s, out.toString());
- }
-}
diff --git a/luni/src/test/java/libcore/java/util/OldAndroidLocaleTest.java b/luni/src/test/java/libcore/java/util/OldAndroidLocaleTest.java
index 4bd858c..fa761d3 100644
--- a/luni/src/test/java/libcore/java/util/OldAndroidLocaleTest.java
+++ b/luni/src/test/java/libcore/java/util/OldAndroidLocaleTest.java
@@ -75,7 +75,6 @@
}
// This one makes sure we have all necessary locales installed.
- // Suppress this flaky test for now.
public void testICULocales() {
String[] locales = new String[] {
// List of locales currently required for Android.
@@ -131,7 +130,6 @@
"ISO-8859-13",
"ISO-8859-14",
"ISO-8859-15",
- "ISO-8859-16",
"ISO-2022-JP",
"Windows-950",
"Windows-1250",
@@ -153,32 +151,16 @@
"GBK",
"GB2312",
"EUC-KR",
+ "GSM0338"
+ };
- // Additional encoding not included in standard ICU.
- "GSM0338" };
+ for (String encoding : encodings) {
+ assertTrue("Charset " + encoding + " must be supported", Charset.isSupported(encoding));
- for (int i = 0; i < encodings.length; i++) {
- assertTrue("Charset " + encodings[i] + " must be supported",
- Charset.isSupported(encodings[i]));
-
- Charset cs = Charset.forName(encodings[i]);
-
+ Charset cs = Charset.forName(encoding);
Set<String> aliases = cs.aliases();
- System.out.println(aliases);
+ System.out.println(cs.name() + ": " + aliases);
}
-
- // Test for valid encoding that is not included in Android. IBM-37 is
- // a perfect candidate for this, as it is being used for mainframes and
- // thus somewhat out of the scope of Android.
- assertFalse("Charset IBM-37 must not be supported",
- Charset.isSupported("IBM-37"));
-
- // Test for a bogus encoding.
- assertFalse("Charset KLINGON must not be supported",
- Charset.isSupported("KLINGON"));
-
- // Check we have the canonical EUC-JP charset.
- assertEquals("EUC-JP", Charset.forName("EUC-JP").name());
}
}
diff --git a/luni/src/test/java/libcore/java/util/ServiceLoaderTest.java b/luni/src/test/java/libcore/java/util/ServiceLoaderTest.java
index 56bb651..b69a2dd 100644
--- a/luni/src/test/java/libcore/java/util/ServiceLoaderTest.java
+++ b/luni/src/test/java/libcore/java/util/ServiceLoaderTest.java
@@ -17,23 +17,54 @@
package libcore.java.util;
import java.util.Iterator;
+import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
public class ServiceLoaderTest extends junit.framework.TestCase {
- public static interface UnimplementedInterface { }
- public void test_noImplementations() {
- assertFalse(ServiceLoader.load(UnimplementedInterface.class).iterator().hasNext());
- }
+ public static interface UnimplementedInterface { }
+ public void test_noImplementations() {
+ assertFalse(ServiceLoader.load(UnimplementedInterface.class).iterator().hasNext());
+ }
- public static class Impl1 implements ServiceLoaderTestInterface { }
- public static class Impl2 implements ServiceLoaderTestInterface { }
- public void test_implementations() {
- ServiceLoader<ServiceLoaderTestInterface> loader = ServiceLoader.load(ServiceLoaderTestInterface.class);
- Iterator<ServiceLoaderTestInterface> it = loader.iterator();
- assertTrue(it.hasNext());
- assertTrue(it.next() instanceof Impl1);
- assertTrue(it.hasNext());
- assertTrue(it.next() instanceof Impl2);
- assertFalse(it.hasNext());
+ public static class Impl1 implements ServiceLoaderTestInterface { }
+ public static class Impl2 implements ServiceLoaderTestInterface { }
+ public void test_implementations() {
+ ServiceLoader<ServiceLoaderTestInterface> loader = ServiceLoader.load(ServiceLoaderTestInterface.class);
+ Iterator<ServiceLoaderTestInterface> it = loader.iterator();
+ assertTrue(it.hasNext());
+ assertTrue(it.next() instanceof Impl1);
+ assertTrue(it.hasNext());
+ assertTrue(it.next() instanceof Impl2);
+ assertFalse(it.hasNext());
+ }
+
+ // Something like "does.not.Exist", that is a well-formed class name, but just doesn't exist.
+ public void test_missingRegisteredClass() throws Exception {
+ try {
+ ServiceLoader.load(ServiceLoaderTestInterfaceMissingClass.class).iterator().next();
+ fail();
+ } catch (ServiceConfigurationError expected) {
+ assertTrue(expected.getCause() instanceof ClassNotFoundException);
}
+ }
+
+ // Something like "java.lang.String", that is a class that exists,
+ // but doesn't implement the interface.
+ public void test_wrongTypeRegisteredClass() throws Exception {
+ try {
+ ServiceLoader.load(ServiceLoaderTestInterfaceWrongType.class).iterator().next();
+ fail();
+ } catch (ServiceConfigurationError expected) {
+ assertTrue(expected.getCause() instanceof ClassCastException);
+ }
+ }
+
+ // Something like "This is not a class name!" that's just a parse error.
+ public void test_invalidRegisteredClass() throws Exception {
+ try {
+ ServiceLoader.load(ServiceLoaderTestInterfaceParseError.class).iterator().next();
+ fail();
+ } catch (ServiceConfigurationError expected) {
+ }
+ }
}
diff --git a/luni/src/test/java/libcore/java/util/ServiceLoaderTestInterfaceMissingClass.java b/luni/src/test/java/libcore/java/util/ServiceLoaderTestInterfaceMissingClass.java
new file mode 100644
index 0000000..e2ceffd
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/ServiceLoaderTestInterfaceMissingClass.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package libcore.java.util;
+
+/**
+ * Ideally, this would have been an inner class in ServiceLoaderTest, but we need a corresponding
+ * resource file, and our build system can't cope with $ in filenames.
+ */
+public interface ServiceLoaderTestInterfaceMissingClass {
+}
diff --git a/luni/src/test/java/libcore/java/util/ServiceLoaderTestInterfaceParseError.java b/luni/src/test/java/libcore/java/util/ServiceLoaderTestInterfaceParseError.java
new file mode 100644
index 0000000..2a4dfcc
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/ServiceLoaderTestInterfaceParseError.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package libcore.java.util;
+
+/**
+ * Ideally, this would have been an inner class in ServiceLoaderTest, but we need a corresponding
+ * resource file, and our build system can't cope with $ in filenames.
+ */
+public interface ServiceLoaderTestInterfaceParseError {
+}
diff --git a/luni/src/test/java/libcore/java/util/ServiceLoaderTestInterfaceWrongType.java b/luni/src/test/java/libcore/java/util/ServiceLoaderTestInterfaceWrongType.java
new file mode 100644
index 0000000..7d3ddd4
--- /dev/null
+++ b/luni/src/test/java/libcore/java/util/ServiceLoaderTestInterfaceWrongType.java
@@ -0,0 +1,24 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package libcore.java.util;
+
+/**
+ * Ideally, this would have been an inner class in ServiceLoaderTest, but we need a corresponding
+ * resource file, and our build system can't cope with $ in filenames.
+ */
+public interface ServiceLoaderTestInterfaceWrongType {
+}
diff --git a/luni/src/test/resources/META-INF/services/java.nio.charset.spi.CharsetProvider b/luni/src/test/resources/META-INF/services/java.nio.charset.spi.CharsetProvider
new file mode 100644
index 0000000..d29245f
--- /dev/null
+++ b/luni/src/test/resources/META-INF/services/java.nio.charset.spi.CharsetProvider
@@ -0,0 +1,2 @@
+tests.api.java.nio.charset.CharsetTest$MockCharsetProvider
+tests.api.java.nio.charset.CharsetTest$MockCharsetProviderASCII
diff --git a/luni/src/test/resources/META-INF/services/libcore.java.util.ServiceLoaderTestInterface b/luni/src/test/resources/META-INF/services/libcore.java.util.ServiceLoaderTestInterface
index 8f8a9eb..2961ffb 100644
--- a/luni/src/test/resources/META-INF/services/libcore.java.util.ServiceLoaderTestInterface
+++ b/luni/src/test/resources/META-INF/services/libcore.java.util.ServiceLoaderTestInterface
@@ -5,3 +5,4 @@
libcore.java.util.ServiceLoaderTest$Impl2 # this comment is valid
libcore.java.util.ServiceLoaderTest$Impl2#as is this
libcore.java.util.ServiceLoaderTest$Impl2 # and duplicates are allowed too
+ libcore.java.util.ServiceLoaderTest$Impl2 # as is leading whitespace
diff --git a/luni/src/test/resources/META-INF/services/libcore.java.util.ServiceLoaderTestInterfaceMissingClass b/luni/src/test/resources/META-INF/services/libcore.java.util.ServiceLoaderTestInterfaceMissingClass
new file mode 100644
index 0000000..253a7b4
--- /dev/null
+++ b/luni/src/test/resources/META-INF/services/libcore.java.util.ServiceLoaderTestInterfaceMissingClass
@@ -0,0 +1 @@
+this.class.does.not.Exist
diff --git a/luni/src/test/resources/META-INF/services/libcore.java.util.ServiceLoaderTestInterfaceParseError b/luni/src/test/resources/META-INF/services/libcore.java.util.ServiceLoaderTestInterfaceParseError
new file mode 100644
index 0000000..8573996
--- /dev/null
+++ b/luni/src/test/resources/META-INF/services/libcore.java.util.ServiceLoaderTestInterfaceParseError
@@ -0,0 +1 @@
+this is not a valid class name!
diff --git a/luni/src/test/resources/META-INF/services/libcore.java.util.ServiceLoaderTestInterfaceWrongType b/luni/src/test/resources/META-INF/services/libcore.java.util.ServiceLoaderTestInterfaceWrongType
new file mode 100644
index 0000000..e8caaf3
--- /dev/null
+++ b/luni/src/test/resources/META-INF/services/libcore.java.util.ServiceLoaderTestInterfaceWrongType
@@ -0,0 +1 @@
+java.lang.String