diff options
Diffstat (limited to 'luni/src/test')
74 files changed, 2340 insertions, 12958 deletions
diff --git a/luni/src/test/java/tests/api/java/net/URLClassLoaderTest.java b/luni/src/test/java/java/net/OldURLClassLoaderTest.java index 979834f..7fa137c 100644 --- a/luni/src/test/java/tests/api/java/net/URLClassLoaderTest.java +++ b/luni/src/test/java/java/net/OldURLClassLoaderTest.java @@ -15,32 +15,16 @@ * limitations under the License. */ -package tests.api.java.net; +package java.net; -import dalvik.annotation.BrokenTest; import dalvik.annotation.SideEffect; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; - -import org.apache.harmony.security.tests.support.TestCertUtils; - -import tests.support.Support_Configuration; -import tests.support.Support_PortManager; -import tests.support.Support_TestWebData; -import tests.support.Support_TestWebServer; -import tests.support.resource.Support_Resources; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.net.URLStreamHandler; -import java.net.URLStreamHandlerFactory; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; @@ -48,8 +32,13 @@ import java.security.cert.Certificate; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; -import java.util.Vector; import java.util.jar.Manifest; +import org.apache.harmony.security.tests.support.TestCertUtils; +import tests.support.Support_Configuration; +import tests.support.Support_PortManager; +import tests.support.Support_TestWebData; +import tests.support.Support_TestWebServer; +import tests.support.resource.Support_Resources; @TestTargetClass( value = URLClassLoader.class, @@ -62,28 +51,7 @@ import java.util.jar.Manifest; ) } ) -public class URLClassLoaderTest extends junit.framework.TestCase { - - class BogusClassLoader extends ClassLoader { - public URL getResource(String res) { - try { - return new URL("http://test/BogusClassLoader"); - } catch (MalformedURLException e) { - return null; - } - } - } - - public class URLClassLoaderExt extends URLClassLoader { - - public URLClassLoaderExt(URL[] urls) { - super(urls); - } - - public Class<?> findClass(String cl) throws ClassNotFoundException { - return super.findClass(cl); - } - } +public class OldURLClassLoaderTest extends junit.framework.TestCase { URLClassLoader ucl; SecurityManager sm = new SecurityManager() { @@ -99,12 +67,6 @@ public class URLClassLoaderTest extends junit.framework.TestCase { /** * @tests java.net.URLClassLoader#URLClassLoader(java.net.URL[]) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "URLClassLoader", - args = {java.net.URL[].class} - ) public void test_Constructor$Ljava_net_URL() throws MalformedURLException { URL[] u = new URL[0]; ucl = new URLClassLoader(u); @@ -145,46 +107,8 @@ public class URLClassLoaderTest extends junit.framework.TestCase { } /** - * @tests java.net.URLClassLoader#URLClassLoader(java.net.URL[], - * java.lang.ClassLoader) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "URLClassLoader", - args = {java.net.URL[].class, java.lang.ClassLoader.class} - ) - public void test_Constructor$Ljava_net_URLLjava_lang_ClassLoader() { - ClassLoader cl = new BogusClassLoader(); - URL[] u = new URL[0]; - ucl = new URLClassLoader(u, cl); - URL res = ucl.getResource("J"); - assertNotNull(res); - assertEquals("Failed to set parent", "/BogusClassLoader", res.getFile()); - - SecurityManager oldSm = System.getSecurityManager(); - System.setSecurityManager(sm); - try { - new URLClassLoader(u, cl); - fail("SecurityException should be thrown."); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(oldSm); - } - } - - /** * @tests java.net.URLClassLoader#findResources(java.lang.String) */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "IOException checking missing. " - + "A test case that loads a resource from a webserver is missing.", - method = "findResources", - args = {java.lang.String.class} - ) - @SideEffect("Support_TestWebServer requires isolation.") public void test_findResourcesLjava_lang_String() throws Exception { Enumeration<URL> res = null; String[] resValues = { "This is a test resource file.", @@ -226,118 +150,6 @@ public class URLClassLoaderTest extends junit.framework.TestCase { assertEquals("Incorrect number of resources returned", 2, i); } - /** - * @tests java.net.URLClassLoader#getURLs() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getURLs", - args = {} - ) - public void test_getURLs() throws MalformedURLException { - URL[] urls = new URL[4]; - urls[0] = new URL("http://" + Support_Configuration.HomeAddress); - urls[1] = new URL("http://" + Support_Configuration.TestResources + "/"); - urls[2] = new URL("ftp://" + Support_Configuration.TestResources + "/"); - urls[3] = new URL("jar:file:c://" + Support_Configuration.TestResources - + "!/"); - ucl = new URLClassLoader(urls); - URL[] ucUrls = ucl.getURLs(); - for (int i = 0; i < urls.length; i++) { - assertEquals("Returned incorrect URL[]", urls[i], ucUrls[i]); - } - } - - /** - * @tests java.net.URLClassLoader#newInstance(java.net.URL[]) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "newInstance", - args = {java.net.URL[].class} - ) - @BrokenTest("web address used from support doesn't work anymore") - public void test_newInstance$Ljava_net_URL() throws MalformedURLException, - ClassNotFoundException { - // Verify that loaded class' have correct permissions - Class cl = null; - URL res = null; - URL[] urls = new URL[1]; - urls[0] = new URL(Support_Resources.getResourceURL("/UCL/UCL.jar")); - ucl = URLClassLoader.newInstance(urls); - cl = ucl.loadClass("ucl.ResClass"); - - res = cl.getClassLoader().getResource("XX.class"); - assertNotNull("Failed to load class", cl); - assertNotNull( - "Loaded class unable to access resource from same codeSource", - res); - cl = null; - - urls[0] = new URL("jar:" - + Support_Resources.getResourceURL("/UCL/UCL.jar!/")); - ucl = URLClassLoader.newInstance(urls); - cl = ucl.loadClass("ucl.ResClass"); - assertNotNull("Failed to load class from explicit jar URL", cl); - } - - /** - * @tests java.net.URLClassLoader#newInstance(java.net.URL[], - * java.lang.ClassLoader) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "newInstance", - args = {java.net.URL[].class, java.lang.ClassLoader.class} - ) - public void test_newInstance$Ljava_net_URLLjava_lang_ClassLoader() { - ClassLoader cl = new BogusClassLoader(); - URL[] u = new URL[0]; - ucl = URLClassLoader.newInstance(u, cl); - URL res = ucl.getResource("J"); - assertNotNull(res); - assertEquals("Failed to set parent", "/BogusClassLoader", res.getFile()); - } - - /** - * @tests java.net.URLClassLoader#URLClassLoader(java.net.URL[], - * java.lang.ClassLoader, java.net.URLStreamHandlerFactory) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "URLClassLoader", - args = {java.net.URL[].class, java.lang.ClassLoader.class, - java.net.URLStreamHandlerFactory.class} - ) - public void test_Constructor$Ljava_net_URLLjava_lang_ClassLoaderLjava_net_URLStreamHandlerFactory() { - class TestFactory implements URLStreamHandlerFactory { - public URLStreamHandler createURLStreamHandler(String protocol) { - return null; - } - } - ClassLoader cl = new BogusClassLoader(); - URL[] u = new URL[0]; - ucl = new URLClassLoader(u, cl, new TestFactory()); - URL res = ucl.getResource("J"); - assertNotNull(res); - assertEquals("Failed to set parent", "/BogusClassLoader", res.getFile()); - - SecurityManager oldSm = System.getSecurityManager(); - System.setSecurityManager(sm); - try { - new URLClassLoader(u, cl, new TestFactory()); - fail("SecurityException should be thrown."); - } catch (SecurityException e) { - // expected - } finally { - System.setSecurityManager(oldSm); - } - } - @TestTargetNew( level = TestLevel.COMPLETE, notes = "", @@ -366,12 +178,6 @@ public class URLClassLoaderTest extends junit.framework.TestCase { } } - @TestTargetNew( - level = TestLevel.SUFFICIENT, - notes = "", - method = "getPermissions", - args = { CodeSource.class } - ) public void test_getPermissions() throws MalformedURLException { URL url = new URL("http://" + Support_Configuration.SpecialInetTestAddress); Certificate[] chain = TestCertUtils.getCertChain(); @@ -387,13 +193,6 @@ public class URLClassLoaderTest extends junit.framework.TestCase { assertNotNull(permCol1); } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "definePackage", - args = { java.lang.String.class, java.util.jar.Manifest.class, - java.net.URL.class } - ) public void test_definePackage() throws MalformedURLException { Manifest manifest = new Manifest(); URL[] u = new URL[0]; @@ -484,78 +283,6 @@ public class URLClassLoaderTest extends junit.framework.TestCase { } } - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Checks getResource, indirectly checks findResource", - clazz = ClassLoader.class, - method = "getResource", - args = {java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Checks getResource, indirectly checks findResource", - method = "findResource", - args = {java.lang.String.class} - ) - }) - public void testFindResource_H3461() throws Exception { - File tmpDir = new File(System.getProperty("java.io.tmpdir")); - File dir = new File(tmpDir, "encode#me"); - File f, f2; - URLClassLoader loader; - URL dirUrl; - - if (!dir.exists()) { - dir.mkdir(); - } - dir.deleteOnExit(); - dirUrl = dir.toURI().toURL(); - loader = new URLClassLoader( new URL[] { dirUrl }); - - f = File.createTempFile("temp", ".dat", dir); - f.deleteOnExit(); - f2 = File.createTempFile("bad#name#", ".dat", dir); - f2.deleteOnExit(); - - assertNotNull("Unable to load resource from path with problematic name", - loader.getResource(f.getName())); - assertEquals("URL was not correctly encoded", - f2.toURI().toURL(), - loader.getResource(f2.getName())); - } - - /** - * @tests java.net.URLClassLoader#getResource(java.lang.String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getResource", - args = {java.lang.String.class} - ) - public void test_getResourceLjava_lang_String() - throws MalformedURLException { - URL url1 = new URL("file:///"); - URLClassLoader loader = new URLClassLoader(new URL[] { url1 }); - long start = System.currentTimeMillis(); - // try without the leading / - URL result = loader.getResource("dir1/file1"); - long end = System.currentTimeMillis(); - long time = end - start; - if (time < 100) { - time = 100; - } - - start = System.currentTimeMillis(); - // try with the leading forward slash - result = loader.getResource("/dir1/file1"); - end = System.currentTimeMillis(); - long uncTime = end - start; - assertTrue("too long. UNC path formed? UNC time: " + uncTime - + " regular time: " + time, uncTime <= (time * 4)); - } - /** * Regression for Harmony-2237 */ diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLTest.java b/luni/src/test/java/java/net/OldURLTest.java index 9edeac5..8863429 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/URLTest.java +++ b/luni/src/test/java/java/net/OldURLTest.java @@ -14,21 +14,12 @@ * limitations under the License. */ -package org.apache.harmony.luni.tests.java.net; +package java.net; import dalvik.annotation.BrokenTest; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; import dalvik.annotation.TestLevel; +import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; - -import junit.framework.TestCase; - -import tests.support.Support_Configuration; -import tests.support.Support_PortManager; -import tests.support.resource.Support_Resources; -import tests.util.TestEnvironment; - import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; @@ -38,27 +29,17 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.Field; -import java.net.HttpURLConnection; -import java.net.InetSocketAddress; -import java.net.MalformedURLException; -import java.net.Proxy; -import java.net.ProxySelector; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; -import java.net.URLStreamHandler; -import java.net.URLStreamHandlerFactory; import java.security.Permission; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import junit.framework.TestCase; +import tests.support.Support_Configuration; +import tests.support.resource.Support_Resources; +import tests.util.TestEnvironment; @TestTargetClass(URL.class) -public class URLTest extends TestCase { +public class OldURLTest extends TestCase { private static final String helloWorldString = "Hello World"; @@ -73,22 +54,6 @@ public class URLTest extends TestCase { } /** - * @tests java.net.URL#getHost() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Regression test.", - method = "getHost", - args = {} - ) - public void test_getHost() throws MalformedURLException { - // Regression for HARMONY-60 - String ipv6Host = "FEDC:BA98:7654:3210:FEDC:BA98:7654:3210"; - URL url = new URL("http", ipv6Host, -1, "myfile"); - assertEquals(("[" + ipv6Host + "]"), url.getHost()); - } - - /** * @tests java.net.URL#URL(java.lang.String, java.lang.String, int, java.lang.String) */ @TestTargetNew( @@ -315,19 +280,6 @@ public class URLTest extends TestCase { } /** - * Test method for {@link java.net.URL#set(java.lang.String, java.lang.String, int, java.lang.String, java.lang.String)}. - */ - @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, - notes = "final class protected method", - method = "set", - args = {java.lang.String.class, java.lang.String.class, int.class, java.lang.String.class, java.lang.String.class} - ) - public void testSetStringStringIntStringString() { - - } - - /** * Test method for {@link java.net.URL#equals(java.lang.Object)}. */ @TestTargetNew( @@ -585,88 +537,6 @@ public class URLTest extends TestCase { } /** - * Test method for {@link java.net.URL#openConnection(java.net.Proxy)}. - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "See ExcludedProxyTest.", - method = "openConnection", - args = {java.net.Proxy.class} - ) - @BrokenTest("the host address isn't working anymore") - public void testOpenConnectionProxy() throws IOException { - - // create Proxy - - System.setProperty("http.proxyHost", - Support_Configuration.ProxyServerTestHost); - System.setProperty("http.proxyPort", "80"); - - URL u2 = new URL("http://" - + Support_Configuration.ProxyServerTestHost - + "/cgi-bin/test.pl"); - - SocketAddress addr1 = new InetSocketAddress(Support_Configuration.ProxyServerTestHost, 80); - Proxy proxy1 = new Proxy(Proxy.Type.HTTP, addr1); - - // create test input - String posted = "just a test"; - - // perform test - java.net.HttpURLConnection conn = (java.net.HttpURLConnection) u2 - .openConnection(proxy1); - conn.setDoOutput(true); - conn.setRequestMethod("POST"); - conn.setConnectTimeout(3000); - - OutputStream out = conn.getOutputStream(); - out.write(posted.getBytes()); - out.close(); - - - /* - InputStream in = conn.getErrorStream(); - if (in != null ){ - BufferedReader r = new BufferedReader(new InputStreamReader(in), 200); - String line; - while((line = r.readLine())!= null) { - System.err.println(line); - } - } - */ - - conn.getResponseCode(); - InputStream is = conn.getInputStream(); - String response = ""; - byte[] b = new byte[1024]; - int count = 0; - while ((count = is.read(b)) > 0) { - response += new String(b, 0, count); - } - assertTrue("Response to POST method invalid", response - .equals(posted)); - - // Exception test - URL httpUrl = new URL("http://abc.com"); - URL jarUrl = new URL("jar:" - + Support_Resources.getResourceURL("/JUC/lf.jar!/plus.bmp")); - URL ftpUrl = new URL("ftp://" + Support_Configuration.FTPTestAddress - + "/nettest.txt"); - URL fileUrl = new URL("file://abc"); - URL[] urlList = { httpUrl, jarUrl, ftpUrl, fileUrl }; - for (int i = 0; i < urlList.length; ++i) { - try { - urlList[i].openConnection(null); - } catch (IllegalArgumentException iae) { - // expected - } - } - // should not throw exception too - fileUrl.openConnection(Proxy.NO_PROXY); - - } - - /** * Test method for {@link java.net.URL#toString()}. */ @TestTargetNew( @@ -877,19 +747,6 @@ public class URLTest extends TestCase { } /** - * Test method for {@link java.net.URL#set(java.lang.String, java.lang.String, int, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)}. - */ - @TestTargetNew( - level = TestLevel.NOT_FEASIBLE, - notes = "final class protected method", - method = "set", - args = {java.lang.String.class, java.lang.String.class, int.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class} - ) - public void testSetStringStringIntStringStringStringStringString() { - - } - - /** * Test method for {@link java.net.URL#getDefaultPort()}. */ @TestTargetNew( @@ -1065,29 +922,10 @@ public class URLTest extends TestCase { assertTrue("SSISH2 returns a wrong anchor: " + u.getRef(), u.getRef() .equals("foo")); - byte[] ba; - InputStream is; - String s; - - // Cannot make this test fail if no exception is thrown: Debatable - /* - try { - u = new URL("http", "www.yahoo.com", 8080, "test.html#foo", - null); - fail("No error occurred"); - } catch (MalformedURLException e) { - // ok - } catch (NullPointerException e) { - // ok - } - */ - TestURLStreamHandler lh = new TestURLStreamHandler(); - u = new URL("http", "www.yahoo.com", 8080, "test.html#foo", lh); - try { new URL(null, "1", 0, "file", lh); fail("Exception expected, but nothing was thrown!"); @@ -1242,49 +1080,4 @@ public class URLTest extends TestCase { url = new URL(strURL); assertEquals(strURL, url.toExternalForm()); } - - - ServerSocket ss; - - Socket s; - - Thread t; - - - - protected void startServer(String name, int port) { - try { - ss = new ServerSocket(port, 5); - } catch (IOException e) { - fail(name + ": " + e); - } - } - - class SServer extends Thread implements Runnable { - Socket s1 = null; - - public void run() { - try { - ss.setSoTimeout(5000); - s1 = ss.accept(); - ss.close(); - Thread.sleep(4000); - } catch (java.io.InterruptedIOException x) { - System.out.println(Thread.currentThread() - + ", accept() timeout fired: " + x); - } catch (InterruptedException x) { - } catch (Exception e) { - System.out.println("Unable to accept: " + e.toString()); - } finally { - try { - if (s1 != null) - s1.close(); - } catch (java.io.IOException e) { - } - } - } - } - - - } diff --git a/luni/src/test/java/java/nio/channels/OldServerSocketChannelTest.java b/luni/src/test/java/java/nio/channels/OldServerSocketChannelTest.java new file mode 100644 index 0000000..e24a604 --- /dev/null +++ b/luni/src/test/java/java/nio/channels/OldServerSocketChannelTest.java @@ -0,0 +1,140 @@ +/* + * 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 java.nio.channels; + +import dalvik.annotation.TestLevel; +import dalvik.annotation.TestTargetClass; +import dalvik.annotation.TestTargetNew; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.nio.channels.spi.SelectorProvider; +import junit.framework.TestCase; +import tests.support.Support_PortManager; + +/* + * test for ServerSocketChannel + */ +@TestTargetClass(ServerSocketChannel.class) +public class OldServerSocketChannelTest extends TestCase { + + private static final int TIME_UNIT = 200; + + private InetSocketAddress localAddr1; + + private ServerSocketChannel serverChannel; + + private SocketChannel clientChannel; + + protected void setUp() throws Exception { + super.setUp(); + this.localAddr1 = new InetSocketAddress( + "127.0.0.1", Support_PortManager + .getNextPort()); + this.serverChannel = ServerSocketChannel.open(); + this.clientChannel = SocketChannel.open(); + } + + protected void tearDown() throws Exception { + if (null != this.serverChannel) { + try { + this.serverChannel.close(); + } catch (Exception e) { + //ignore + } + + } + if (null != this.clientChannel) { + try { + this.clientChannel.close(); + } catch (Exception e) { + //ignore + } + } + super.tearDown(); + } + + // ------------------------------------------------------------------- + // Test for methods in abstract class. + // ------------------------------------------------------------------- + /* + * Test method for 'java.nio.channels.ServerSocketChannel()' + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "ServerSocketChannel", + args = {java.nio.channels.spi.SelectorProvider.class} + ) + public void testConstructor() throws IOException { + ServerSocketChannel channel = + SelectorProvider.provider().openServerSocketChannel(); + assertNotNull(channel); + assertSame(SelectorProvider.provider(),channel.provider()); + } + + @TestTargetNew( + level = TestLevel.PARTIAL_COMPLETE, + notes = "", + method = "isOpen", + args = {} + ) + public void testIsOpen() throws Exception { + assertTrue(this.serverChannel.isOpen()); + this.serverChannel.close(); + assertFalse(this.serverChannel.isOpen()); + } + + @TestTargetNew( + level = TestLevel.PARTIAL_COMPLETE, + notes = "Verifies ClosedByInterruptException.", + method = "accept", + args = {} + ) + public void test_accept_Block_NoConnect_interrupt() throws IOException { + assertTrue(this.serverChannel.isBlocking()); + ServerSocket gotSocket = this.serverChannel.socket(); + gotSocket.bind(localAddr1); + + class MyThread extends Thread { + public String errMsg = null; + public void run() { + try { + serverChannel.accept(); + errMsg = "should throw ClosedByInterruptException"; + } catch (ClosedByInterruptException e) { + // expected + } catch (Exception e) { + errMsg = "caught wrong Exception: " + e.getClass() + ": " + + e.getMessage(); + } + } + } + MyThread thread = new MyThread(); + thread.start(); + try { + Thread.currentThread().sleep(TIME_UNIT); + thread.interrupt(); + } catch (InterruptedException e) { + fail("Should not throw a InterruptedException"); + } + if (thread.errMsg != null) { + fail(thread.errMsg); + } + } +} diff --git a/luni/src/test/java/java/nio/channels/OldSocketChannelTest.java b/luni/src/test/java/java/nio/channels/OldSocketChannelTest.java new file mode 100644 index 0000000..d692062 --- /dev/null +++ b/luni/src/test/java/java/nio/channels/OldSocketChannelTest.java @@ -0,0 +1,449 @@ +/* + * 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 java.nio.channels; + +import dalvik.annotation.BrokenTest; +import dalvik.annotation.TestLevel; +import dalvik.annotation.TestTargetClass; +import dalvik.annotation.TestTargetNew; +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.SocketException; +import java.nio.ByteBuffer; +import java.nio.channels.spi.SelectorProvider; +import junit.framework.TestCase; +import tests.support.Support_PortManager; + +@TestTargetClass(SocketChannel.class) +/** + * Tests for SocketChannel and its default implementation. + */ +public class OldSocketChannelTest extends TestCase { + + private static final int CAPACITY_NORMAL = 200; + + private static final int CAPACITY_HUGE = 512 * 1024; + + private InetSocketAddress localAddr1; + + private SocketChannel channel1; + + private SocketChannel channel2; + + private ServerSocket server1; + + private final static int TIMEOUT = 60000; + + protected void setUp() throws Exception { + super.setUp(); + this.localAddr1 = new InetSocketAddress("127.0.0.1", + Support_PortManager.getNextPort()); + this.channel1 = SocketChannel.open(); + this.channel2 = SocketChannel.open(); + this.server1 = new ServerSocket(localAddr1.getPort()); + } + + protected void tearDown() throws Exception { + super.tearDown(); + if (null != this.channel1) { + try { + this.channel1.close(); + } catch (Exception e) { + // ignore + } + } + if (null != this.channel2) { + try { + this.channel2.close(); + } catch (Exception e) { + // ignore + } + } + if (null != this.server1) { + try { + this.server1.close(); + } catch (Exception e) { + // ignore + } + } + } + + // ------------------------------------------------------------------- + // Test for methods in abstract class. + // ------------------------------------------------------------------- + public void testConstructor() throws IOException { + SocketChannel channel = + SelectorProvider.provider().openSocketChannel(); + assertNotNull(channel); + assertSame(SelectorProvider.provider(), channel.provider()); + channel = SocketChannel.open(); + assertNotNull(channel); + assertSame(SelectorProvider.provider(), channel.provider()); + MockSocketChannel chan = new MockSocketChannel( + SelectorProvider.provider()); + assertTrue(chan.isConstructorCalled); + } + + public void testValidOps() { + MockSocketChannel testMSChannel = new MockSocketChannel(null); + assertEquals(13, this.channel1.validOps()); + assertEquals(13, testMSChannel.validOps()); + } + + public void testOpen() throws IOException { + java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1]; + buf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL); + MockSocketChannel testMSChannel = new MockSocketChannel(null); + MockSocketChannel testMSChannelnotnull = new MockSocketChannel( + SelectorProvider.provider()); + SocketChannel testSChannel = MockSocketChannel.open(); + assertTrue(testSChannel.isOpen()); + assertNull(testMSChannel.provider()); + assertNotNull(testSChannel.provider()); + assertEquals(SelectorProvider.provider(), testSChannel.provider()); + assertNotNull(testMSChannelnotnull.provider()); + assertEquals(this.channel1.provider(), testMSChannelnotnull.provider()); + try { + this.channel1.write(buf); + fail("Should throw NotYetConnectedException"); + } catch (NotYetConnectedException e) { + // correct + } + } + + public void testIsOpen() throws Exception { + assertTrue(this.channel1.isOpen()); + this.channel1.close(); + assertFalse(this.channel1.isOpen()); + } + + public void testIsConnected() throws Exception { + assertFalse(this.channel1.isConnected());// not connected + this.channel1.configureBlocking(false); + assertFalse(this.channel1.connect(localAddr1)); + assertFalse(this.channel1.isConnected()); + assertTrue(this.channel1.isConnectionPending()); + assertTrue(tryFinish()); + assertTrue(this.channel1.isConnected()); + this.channel1.close(); + assertFalse(this.channel1.isConnected()); + } + + public void testIsConnectionPending() throws Exception { + // ensure + ensureServerClosed(); + this.channel1.configureBlocking(false); + assertFalse(this.channel1.isConnectionPending()); + // finish + try { + this.channel1.finishConnect(); + fail("Should throw NoConnectionPendingException"); + } catch (NoConnectionPendingException e) { + // OK. + } + assertFalse(this.channel1.isConnectionPending()); + // connect + assertFalse(this.channel1.connect(localAddr1)); + assertTrue(this.channel1.isConnectionPending()); + this.channel1.close(); + + assertFalse(this.channel1.isConnectionPending()); + } + + public void testChannelBasicStatus() { + Socket gotSocket = this.channel1.socket(); + assertFalse(gotSocket.isClosed()); + assertTrue(this.channel1.isBlocking()); + assertFalse(this.channel1.isRegistered()); + assertEquals((SelectionKey.OP_CONNECT | SelectionKey.OP_READ | + SelectionKey.OP_WRITE), this.channel1.validOps()); + assertEquals(SelectorProvider.provider(), this.channel1.provider()); + } + + public void testOpenSocketAddress() throws IOException { + this.channel1 = SocketChannel.open(localAddr1); + assertTrue(this.channel1.isConnected()); + + SocketAddress newTypeAddress = new SubSocketAddress(); + try { + this.channel1 = SocketChannel.open(newTypeAddress); + fail("Should throw UnexpectedAddressTypeException"); + } catch (UnsupportedAddressTypeException e) { + // expected + } + + SocketAddress unresolvedAddress = + InetSocketAddress.createUnresolved("127.0.0.1", 8080); + try { + this.channel1 = SocketChannel.open(unresolvedAddress); + fail("Should throw UnresolvedAddressException"); + } catch (UnresolvedAddressException e) { + // expected + } + + SocketChannel channel1IP = null; + try { + channel1IP = SocketChannel.open(null); + fail("Should throw an IllegalArgumentException"); + } catch (IllegalArgumentException e) { + // correct + } + assertNull(channel1IP); + } + + private void ensureServerClosed() throws IOException { + if (null != this.server1) { + this.server1.close(); + assertTrue(this.server1.isClosed()); + } + } + + private void statusConnected_NotPending() { + assertTrue(this.channel1.isConnected()); + assertFalse(this.channel1.isConnectionPending()); + assertTrue(this.channel1.isOpen()); + } + + private boolean tryFinish() throws IOException { + /* + * the result of finish will be asserted in multi-thread tests. + */ + boolean connected = false; + assertTrue(this.channel1.isOpen()); + try { + connected = this.channel1.finishConnect(); + } catch (SocketException e) { + // Finish connection failed, probably due to reset by peer error. + } + if (connected) { + statusConnected_NotPending(); + } + return connected; + } + + /** + * @tests java.nio.channels.SocketChannel#read(ByteBuffer) + */ + @TestTargetNew( + level = TestLevel.PARTIAL_COMPLETE, + notes = "", + method = "write", + args = {java.nio.ByteBuffer.class} + ) + @BrokenTest("Occasionally fail in CTS, but works in CoreTestRunner") + public void test_writeLjava_nio_ByteBuffer_Nonblocking_HugeData() throws IOException { + // initialize write content + ByteBuffer writeContent = ByteBuffer.allocate(CAPACITY_HUGE); + for (int i = 0; i < CAPACITY_HUGE; i++) { + writeContent.put((byte) i); + } + writeContent.flip(); + + // establish connection + channel1.connect(localAddr1); + Socket acceptedSocket = server1.accept(); + + channel1.configureBlocking(false); + int writtenTotalCount = 0; + int writtenCount = 1; + long startTime = System.currentTimeMillis(); + // use SocketChannel.write(ByteBuffer) to try to write CAPACITY_HUGE bytes + while (writtenTotalCount < CAPACITY_HUGE && writtenCount > 0) { + writtenCount = channel1.write(writeContent); + if (writtenCount == 0 && writtenTotalCount < CAPACITY_HUGE) { + assertEquals(0, channel1.write(writeContent)); + break; + } + writtenTotalCount += writtenCount; + // if the channel could not finish writing in TIMEOUT ms, the + // test fails. It is used to guarantee the test never hangs even + // if there are bugs of SocketChannel implementation. + assertTimeout(startTime, TIMEOUT); + } + } + + /* + * Fails if the difference between current time and start time is greater + * than timeout. + */ + private void assertTimeout(long startTime, long timeout) { + long currentTime = System.currentTimeMillis(); + if ((currentTime - startTime) > timeout) { + fail("Timeout"); + } + } + + /** + * @throws IOException + * @tests java.nio.channels.SocketChannel#read(ByteBuffer) + */ + @TestTargetNew( + level = TestLevel.PARTIAL_COMPLETE, + notes = "", + method = "read", + args = {java.nio.ByteBuffer[].class} + ) + public void test_socketChannel_read_DirectByteBuffer() throws InterruptedException, IOException { + + ServerThread server = new ServerThread(); + server.start(); + Thread.currentThread().sleep(1000); + + InetSocketAddress address = new InetSocketAddress(InetAddress + .getByName("localhost"), port); + + // First test with array based byte buffer + SocketChannel sc = SocketChannel.open(); + sc.connect(address); + + ByteBuffer buf = ByteBuffer.allocate(data.length); + buf.limit(data.length / 2); + sc.read(buf); + + buf.limit(buf.capacity()); + sc.read(buf); + sc.close(); + + // Make sure the buffer is filled correctly + buf.rewind(); + assertSameContent(data, buf); + + // Now test with direct byte buffer + sc = SocketChannel.open(); + sc.connect(address); + + buf = ByteBuffer.allocateDirect(data.length); + buf.limit(data.length / 2); + sc.read(buf); + + buf.limit(buf.capacity()); + sc.read(buf); + sc.close(); + + // Make sure the buffer is filled correctly + buf.rewind(); + assertSameContent(data, buf); + } + + private void assertSameContent(byte[] data, ByteBuffer buf) { + for (byte b : data) { + if (b != buf.get()) { + int pos = buf.position() - 1; + fail("Content not equal. Buffer position: " + + (pos) + " expected: " + b + " was: " + buf.get(pos)); + } + } + } + + public static boolean done = false; + public static int port = Support_PortManager.getNextPort(); + public static byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + + static class ServerThread extends Thread { + @Override + public void run() { + try { + ServerSocketChannel ssc = ServerSocketChannel.open(); + InetSocketAddress addr = new InetSocketAddress(InetAddress + .getByAddress(new byte[] {0, 0, 0, 0}), port); + ssc.socket().bind(addr, 0); + + ByteBuffer buf = ByteBuffer.allocate(10); + buf.put(data); + + while (!done) { + SocketChannel sc = ssc.accept(); + buf.rewind(); + sc.write(buf); + } + } catch (Exception e) { + // ignore + } + } + } + + class MockSocketChannel extends SocketChannel { + + private boolean isConstructorCalled = false; + + public MockSocketChannel(SelectorProvider provider) { + super(provider); + isConstructorCalled = true; + } + + public Socket socket() { + return null; + } + + public boolean isConnected() { + return false; + } + + public boolean isConnectionPending() { + return false; + } + + public boolean connect(SocketAddress address) throws IOException { + return false; + } + + public boolean finishConnect() throws IOException { + return false; + } + + public int read(ByteBuffer target) throws IOException { + return 0; + } + + public long read(ByteBuffer[] targets, int offset, int length) + throws IOException { + return 0; + } + + public int write(ByteBuffer source) throws IOException { + return 0; + } + + public long write(ByteBuffer[] sources, int offset, int length) + throws IOException { + return 0; + } + + protected void implCloseSelectableChannel() throws IOException { + // empty + } + + protected void implConfigureBlocking(boolean blockingMode) + throws IOException { + // empty + } + } + + class SubSocketAddress extends SocketAddress { + private static final long serialVersionUID = 1L; + + // empty + public SubSocketAddress() { + super(); + } + } +} diff --git a/luni/src/test/java/java/security/OldAlgorithmParameterGeneratorTest.java b/luni/src/test/java/java/security/OldAlgorithmParameterGeneratorTest.java new file mode 100644 index 0000000..81111a7 --- /dev/null +++ b/luni/src/test/java/java/security/OldAlgorithmParameterGeneratorTest.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package java.security; + +import dalvik.annotation.TestTargetClass; + +@TestTargetClass(AlgorithmParameterGenerator.class) +public class OldAlgorithmParameterGeneratorTest extends junit.framework.TestCase { + + public void test_initI() throws Exception { + // Test for method void + // java.security.AlgorithmParameterGenerator.init(int) + // checks that no exception is thrown + int[] valid = {512, 576, 640, 960, 1024}; + AlgorithmParameterGenerator gen = AlgorithmParameterGenerator + .getInstance("DSA"); + + for (int i = 0; i < valid.length; i++) { + try { + gen.init(valid[i]); + } catch (Exception e) { + fail("Exception should not be thrown for valid parameter" + valid[i]); + } + } + } + + public void test_initILjava_security_SecureRandom() throws Exception { + // Test for method void + // java.security.AlgorithmParameterGenerator.init(int, + // java.security.SecureRandom) + // checks that no exception is thrown + int[] valid = {512, 576, 640, 960, 1024}; + AlgorithmParameterGenerator gen = AlgorithmParameterGenerator + .getInstance("DSA"); + + for (int i = 0; i < valid.length; i++) { + try { + gen.init(valid[i], new SecureRandom()); + gen.init(valid[i], null); + } catch (Exception e) { + fail("Exception should not be thrown for valid parameter" + valid[i]); + } + } + } +} diff --git a/luni/src/test/java/tests/targets/security/DHTest.java b/luni/src/test/java/java/security/OldDHTest.java index 9a30a76..c257d09 100644 --- a/luni/src/test/java/tests/targets/security/DHTest.java +++ b/luni/src/test/java/java/security/OldDHTest.java @@ -13,25 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; +package java.security; import dalvik.annotation.BrokenTest; import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; - -import junit.framework.TestCase; - -import java.security.AlgorithmParameterGenerator; -import java.security.AlgorithmParameters; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; - import javax.crypto.spec.DHParameterSpec; +import junit.framework.TestCase; -public class DHTest extends TestCase { +public class OldDHTest extends TestCase { @TestTargetNew( level = TestLevel.ADDITIONAL, diff --git a/luni/src/test/java/java/security/OldKeyPairGeneratorTestDH.java b/luni/src/test/java/java/security/OldKeyPairGeneratorTestDH.java new file mode 100644 index 0000000..7c8a5e5 --- /dev/null +++ b/luni/src/test/java/java/security/OldKeyPairGeneratorTestDH.java @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2009 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 java.security; + +import dalvik.annotation.BrokenTest; +import junit.framework.TestCase; +import tests.security.KeyAgreementHelper; + +public class OldKeyPairGeneratorTestDH extends TestCase { + + @BrokenTest("Takes ages due to DH computations. Disabling for now.") + public void testKeyPairGenerator() throws NoSuchAlgorithmException { + KeyPairGenerator generator = KeyPairGenerator.getInstance("DH"); + + generator.initialize(1024); + + KeyPair keyPair = generator.generateKeyPair(); + + assertNotNull("no keypair generated", keyPair); + assertNotNull("no public key generated", keyPair.getPublic()); + assertNotNull("no private key generated", keyPair.getPrivate()); + + new KeyAgreementHelper("DH").test(keyPair); + } +} diff --git a/luni/src/test/java/java/security/cert/OldPKIXParametersTest.java b/luni/src/test/java/java/security/cert/OldPKIXParametersTest.java new file mode 100644 index 0000000..d1cdd3b --- /dev/null +++ b/luni/src/test/java/java/security/cert/OldPKIXParametersTest.java @@ -0,0 +1,246 @@ +/* + * 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. + */ + +/** + * @author Vladimir N. Molotkov + * @version $Revision$ + */ + +package java.security.cert; + +import dalvik.annotation.BrokenTest; +import dalvik.annotation.TestLevel; +import dalvik.annotation.TestTargetClass; +import dalvik.annotation.TestTargetNew; +import java.io.ByteArrayInputStream; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.util.Calendar; +import java.util.Collections; +import java.util.Set; +import junit.framework.TestCase; +import org.apache.harmony.security.tests.support.cert.TestUtils; +import tests.targets.security.KeyStoreTestPKCS12; + +/** + * Tests for <code>PKIXParameters</code> fields and methods + */ +@TestTargetClass(PKIXParameters.class) +public class OldPKIXParametersTest extends TestCase { + + /** + * Test for <code>clone()</code> method<br> + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "clone", + args = {} + ) + public final void testClone() throws InvalidAlgorithmParameterException { + Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); + if (taSet == null) { + fail(getName() + + ": not performed (could not create test TrustAnchor set)"); + } + + PKIXParameters cpp = new PKIXParameters(taSet); + PKIXParameters cppc = (PKIXParameters) cpp.clone(); + + assertEquals(cpp.getPolicyQualifiersRejected(), cppc + .getPolicyQualifiersRejected()); + assertEquals(cpp.getCertPathCheckers(), cppc.getCertPathCheckers()); + assertEquals(cpp.getCertStores(), cppc.getCertStores()); + assertEquals(cpp.getDate(), cppc.getDate()); + assertEquals(cpp.getInitialPolicies(), cppc.getInitialPolicies()); + assertEquals(cpp.getSigProvider(), cppc.getSigProvider()); + assertEquals(cpp.getTargetCertConstraints(), cppc + .getTargetCertConstraints()); + assertEquals(cpp.getTrustAnchors(), cppc.getTrustAnchors()); + + assertEquals(cpp.isAnyPolicyInhibited(), cppc.isAnyPolicyInhibited()); + assertEquals(cpp.isExplicitPolicyRequired(), cppc + .isExplicitPolicyRequired()); + assertEquals(cpp.isPolicyMappingInhibited(), cppc + .isPolicyMappingInhibited()); + assertEquals(cpp.isRevocationEnabled(), cppc.isRevocationEnabled()); + + cpp.setDate(Calendar.getInstance().getTime()); + cpp.setPolicyQualifiersRejected(!cppc.getPolicyQualifiersRejected()); + assertFalse(cpp.getDate().equals(cppc.getDate())); + assertFalse(cpp.getPolicyQualifiersRejected() == cppc + .getPolicyQualifiersRejected()); + + cppc.setExplicitPolicyRequired(!cpp.isExplicitPolicyRequired()); + cppc.setRevocationEnabled(!cpp.isRevocationEnabled()); + + assertFalse(cpp.isExplicitPolicyRequired() == cppc + .isExplicitPolicyRequired()); + assertFalse(cpp.isRevocationEnabled() == cppc.isRevocationEnabled()); + + PKIXParameters cpp1 = null; + try { + cpp1.clone(); + } catch (NullPointerException e) { + // expected + } + } + + /** + * Test for <code>isPolicyMappingInhibited()</code> method<br> + * Assertion: returns true if policy mapping is inhibited, false otherwise + * Assertion: by default, policy mapping is not inhibited (the flag is + * false) + * + * @throws InvalidAlgorithmParameterException + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "isPolicyMappingInhibited", + args = {} + ) + public final void testIsPolicyMappingInhibited() throws Exception { + Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); + if (taSet == null) { + fail(getName() + ": not performed (could not create test TrustAnchor set)"); + } + + PKIXParameters p = new PKIXParameters(taSet); + assertFalse(p.isPolicyMappingInhibited()); + + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + TestUtils.initCertPathSSCertChain(); + Set<TrustAnchor> taSet2 = Collections.singleton(new TrustAnchor( + TestUtils.rootCertificateSS, null)); + p = new PKIXParameters(taSet2); + + assertFalse(p.isPolicyMappingInhibited()); + p.setPolicyMappingInhibited(true); + assertTrue(p.isRevocationEnabled()); + } + + /** + * Test for <code>isPolicyMappingInhibited()</code> method<br> + * Assertion: returns the current value of the RevocationEnabled flag + * Assertion: when a <code>PKIXParameters</code> object is created, this + * flag is set to true + * + * @throws InvalidAlgorithmParameterException + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "isRevocationEnabled", + args = {} + ) + public final void testIsRevocationEnabled() throws Exception { + Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); + if (taSet == null) { + fail(getName() + + ": not performed (could not create test TrustAnchor set)"); + } + + PKIXParameters p = new PKIXParameters(taSet); + assertTrue(p.isRevocationEnabled()); + + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + TestUtils.initCertPathSSCertChain(); + Set<TrustAnchor> taSet2 = Collections.singleton(new TrustAnchor( + TestUtils.rootCertificateSS, null)); + p = new PKIXParameters(taSet2); + + assertTrue(p.isRevocationEnabled()); + p.setRevocationEnabled(false); + assertFalse(p.isRevocationEnabled()); + } + + /** + * Test for <code>toString</code> method<br> + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "toString", + args = {} + ) + public final void testToString() throws Exception { + Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); + if (taSet == null) { + fail(getName() + + ": not performed (could not create test TrustAnchor set)"); + } + + PKIXParameters p = new PKIXParameters(taSet); + assertNotNull(p.toString()); + + PKIXParameters p1 = null; + try { + p1.toString(); + fail("NullPointerException expected"); + } catch (NullPointerException e) { + // expected + } + } + + /** + * Test #4 for <code>PKIXParameters(KeyStore)</code> constructor<br> + * + * @throws InvalidAlgorithmParameterException + * @throws KeyStoreException + */ + @TestTargetNew( + level = TestLevel.PARTIAL_COMPLETE, + notes = "Verifies everything except null argument", + method = "PKIXParameters", + args = {java.security.KeyStore.class} + ) + @BrokenTest("Fails in CTS environment, but passes in CoreTestRunner") + public final void testPKIXParametersKeyStore04() throws Exception { + + + KeyStore store = KeyStore.getInstance("PKCS12"); + KeyStoreTestPKCS12 k = new KeyStoreTestPKCS12(); + ByteArrayInputStream stream = new ByteArrayInputStream(k.keyStoreData); + + try { + PKIXParameters p = new PKIXParameters(store); + } catch (KeyStoreException e) { + // ok + } + + store = KeyStore.getInstance("PKCS12"); + store.load(stream, new String(KeyStoreTestPKCS12.keyStorePassword) + .toCharArray()); + stream.close(); + + try { + PKIXParameters p = new PKIXParameters(store); + } catch (InvalidAlgorithmParameterException e) { + // ok + } + + + KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); + keystore.load(null,null); + keystore.setCertificateEntry("test", TestUtils.rootCertificateSS); + + + PKIXParameters p = new PKIXParameters(keystore); + } +} diff --git a/luni/src/test/java/java/text/OldDecimalFormatTest.java b/luni/src/test/java/java/text/OldDecimalFormatTest.java new file mode 100644 index 0000000..9823ed1 --- /dev/null +++ b/luni/src/test/java/java/text/OldDecimalFormatTest.java @@ -0,0 +1,1267 @@ +/* + * 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 java.text; + +import dalvik.annotation.AndroidOnly; +import dalvik.annotation.TestLevel; +import dalvik.annotation.TestTargetClass; +import dalvik.annotation.TestTargetNew; +import dalvik.annotation.TestTargets; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.BitSet; +import java.util.Locale; +import junit.framework.TestCase; +import tests.support.Support_DecimalFormat; + + +@TestTargetClass(DecimalFormat.class) +public class OldDecimalFormatTest extends TestCase { + + @TestTargetNew( + level = TestLevel.PARTIAL_COMPLETE, + notes = "", + method = "formatToCharacterIterator", + args = {java.lang.Object.class} + ) + public void test_formatToCharacterIterator() throws Exception { + AttributedCharacterIterator iterator; + int[] runStarts; + int[] runLimits; + String result; + char current; + + // For BigDecimal with multiplier test. + DecimalFormat df = new DecimalFormat(); + df.setMultiplier(10); + iterator = df.formatToCharacterIterator(new BigDecimal("12345678901234567890")); + result = "123,456,789,012,345,678,900"; + current = iterator.current(); + for (int i = 0; i < result.length(); i++) { + assertEquals("wrong char @" + i, result.charAt(i), current); + current = iterator.next(); + } + + // For BigDecimal with multiplier test. + df = new DecimalFormat(); + df.setMultiplier(-1); + df.setMaximumFractionDigits(20); + iterator = df.formatToCharacterIterator(new BigDecimal("1.23456789012345678901")); + result = "-1.23456789012345678901"; + current = iterator.current(); + for (int i = 0; i < result.length(); i++) { + assertEquals("wrong char @" + i, result.charAt(i), current); + current = iterator.next(); + } + + iterator = new DecimalFormat() + .formatToCharacterIterator(new BigDecimal("1.23456789E1234")); + runStarts = new int[] {0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14}; + runLimits = new int[] {2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15}; + result = "12,345,678,900,"; // 000,000,000,000.... + current = iterator.current(); + for (int i = 0; i < runStarts.length; i++) { + assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart()); + assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit()); + assertEquals("wrong char @" + i, result.charAt(i), current); + current = iterator.next(); + } + assertEquals(0, iterator.getBeginIndex()); + assertEquals(1646, iterator.getEndIndex()); + + iterator = new DecimalFormat() + .formatToCharacterIterator(new BigDecimal("1.23456789E301")); + runStarts = new int[] {0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14}; + runLimits = new int[] {2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15}; + result = "12,345,678,900,"; // 000,000,000,000.... + current = iterator.current(); + for (int i = 0; i < runStarts.length; i++) { + assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart()); + assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit()); + assertEquals("wrong char @" + i, result.charAt(i), current); + current = iterator.next(); + } + assertEquals(0, iterator.getBeginIndex()); + assertEquals(402, iterator.getEndIndex()); + + iterator = new DecimalFormat() + .formatToCharacterIterator(new BigDecimal("1.2345678E4")); + runStarts = new int[] {0, 0, 2, 3, 3, 3, 6, 7, 7, 7}; + runLimits = new int[] {2, 2, 3, 6, 6, 6, 7, 10, 10, 10}; + result = "12,345.678"; + current = iterator.current(); + for (int i = 0; i < runStarts.length; i++) { + assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart()); + assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit()); + assertEquals("wrong char @" + i, result.charAt(i), current); + current = iterator.next(); + } + assertEquals(0, iterator.getBeginIndex()); + assertEquals(10, iterator.getEndIndex()); + + iterator = new DecimalFormat() + .formatToCharacterIterator(new BigInteger("123456789")); + runStarts = new int[] {0, 0, 0, 3, 4, 4, 4, 7, 8, 8, 8}; + runLimits = new int[] {3, 3, 3, 4, 7, 7, 7, 8, 11, 11, 11}; + result = "123,456,789"; + current = iterator.current(); + for (int i = 0; i < runStarts.length; i++) { + assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart()); + assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit()); + assertEquals("wrong char @" + i, result.charAt(i), current); + current = iterator.next(); + } + assertEquals(0, iterator.getBeginIndex()); + assertEquals(11, iterator.getEndIndex()); + } + + /* + * Test the getter and setter of parseBigDecimal and parseIntegerOnly and + * test the default value of them. + */ + @TestTargets({ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "isParseBigDecimal", + args = {} + ), + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "setParseBigDecimal", + args = {boolean.class} + ) + }) + public void test_isParseBigDecimalLjava_lang_Boolean_isParseIntegerOnlyLjava_lang_Boolean() { + + // parseBigDecimal default to false + DecimalFormat form = (DecimalFormat) DecimalFormat + .getInstance(Locale.US); + assertFalse(form.isParseBigDecimal()); + form.setParseBigDecimal(true); + assertTrue(form.isParseBigDecimal()); + + try { + Number result = form.parse("123.123"); + assertEquals(new BigDecimal("123.123"), result); + } catch (ParseException e) { + fail("ParseException was thrown."); + } + + form.setParseBigDecimal(false); + assertFalse(form.isParseBigDecimal()); + + try { + Number result = form.parse("123.123"); + assertFalse(result instanceof BigDecimal); + } catch (ParseException e) { + fail("ParseException was thrown."); + } + + // parseIntegerOnly default to false + assertFalse(form.isParseIntegerOnly()); + } + + @TestTargets({ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "isParseIntegerOnly", + args = {} + ), + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "setParseIntegerOnly", + args = {boolean.class} + ) + }) + public void test_isParseIntegerOnly() { + + DecimalFormat format = new DecimalFormat(); + assertFalse("Default value of isParseIntegerOnly is true", + format.isParseIntegerOnly()); + + format.setParseIntegerOnly(true); + assertTrue(format.isParseIntegerOnly()); + try { + Number result = format.parse("123.123"); + assertEquals(new Long("123"), result); + } catch (ParseException e) { + fail("ParseException was thrown."); + } + + format.setParseIntegerOnly(false); + assertFalse(format.isParseIntegerOnly()); + try { + Number result = format.parse("123.123"); + assertEquals(new Double("123.123"), result); + } catch (ParseException e) { + fail("ParseException was thrown."); + } + } + + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "isGroupingUsed", + args = {} + ) + public void test_isGroupingUsed() { + String [] patterns = {"####.##", "######.######", "000000.000000", + "######.000000", "000000.######", " ###.###", "$#####.######", + "$$####.######"}; + + for(String pattern:patterns) { + DecimalFormat format = new DecimalFormat(pattern); + assertFalse(format.isGroupingUsed()); + } + + DecimalFormat format = new DecimalFormat("###,####"); + assertTrue(format.isGroupingUsed()); + } + + // Test the type of the returned object + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "parse", + args = {java.lang.String.class, java.text.ParsePosition.class} + ) + public void test_parseLjava_lang_String_Ljava_text_ParsePosition() { + DecimalFormat form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); + form.setParseIntegerOnly(true); + form.setParseBigDecimal(true); + + final String doubleMax2 = "359,538,626,972,463,141,629,054,847,463,408," + + "713,596,141,135,051,689,993,197,834,953,606,314,521,560,057,077," + + "521,179,117,265,533,756,343,080,917,907,028,764,928,468,642,653," + + "778,928,365,536,935,093,407,075,033,972,099,821,153,102,564,152," + + "490,980,180,778,657,888,151,737,016,910,267,884,609,166,473,806," + + "445,896,331,617,118,664,246,696,549,595,652,408,289,446,337,476," + + "354,361,838,599,762,500,808,052,368,249,716,736"; + Number number = form.parse(doubleMax2, new ParsePosition(0)); + assertTrue(number instanceof BigDecimal); + BigDecimal result = (BigDecimal)number; + assertEquals(new BigDecimal(Double.MAX_VALUE).add(new BigDecimal( + Double.MAX_VALUE)), result); + } + + @TestTargetNew( + level = TestLevel.PARTIAL_COMPLETE, + method = "getMinimumIntegerDigits", + args = {} + ) + @AndroidOnly("Difference to RI") + public void test_getMaximumIntegerDigits_AndroidOnly() { + final int maxIntDigit = 309; + + // When use default locale, in this case zh_CN + // the returned instance of NumberFormat is a DecimalFormat + DecimalFormat form = new DecimalFormat("00.###E0"); + NumberFormat nform = DecimalFormat.getInstance(Locale.US); + nform = DecimalFormat.getInstance(Locale.US); + form = null; + if (nform instanceof DecimalFormat) { + form = (DecimalFormat) nform; + } + // getMaximumIntegerDigits from NumberFormat default to 309 + // getMaximumIntegerDigits from DecimalFormat default to 309 + // the following 2 assertions will fail on RI implementation, since the + // implementation of ICU and RI are not identical. RI does not give + // DecimalFormat an initial bound about its maximumIntegerDigits + // (default to Integer.MAX_VALUE: 2147483647 ) + assertEquals(maxIntDigit, nform.getMaximumIntegerDigits()); + assertEquals(maxIntDigit, form.getMaximumIntegerDigits()); + } + + @TestTargetNew( + level = TestLevel.PARTIAL_COMPLETE, + method = "getMinimumIntegerDigits", + args = {} + ) + @AndroidOnly("second 0 needs to be quoted in icu." + + "(quoting special characters in prefix and suffix necessary)") + public void test_getMaximumIntegerDigits2() { + // regression test for HARMONY-878 + assertTrue(new DecimalFormat("0\t'0'").getMaximumIntegerDigits() > 0); + } + + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "setPositivePrefix", + args = {java.lang.String.class} + ) + public void test_setPositivePrefixLjava_lang_String() { + DecimalFormat format = new DecimalFormat(); + assertEquals("", format.getPositivePrefix()); + + format.setPositivePrefix("PosPrf"); + assertEquals("PosPrf", format.getPositivePrefix()); + try { + assertTrue(format.parse("PosPrf123.45").doubleValue() == 123.45); + } catch(java.text.ParseException pe) { + fail("ParseException was thrown."); + } + + format.setPositivePrefix(""); + assertEquals("", format.getPositivePrefix()); + + format.setPositivePrefix(null); + assertNull(format.getPositivePrefix()); + } + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "setPositiveSuffix", + args = {java.lang.String.class} + ) + public void test_setPositiveSuffixLjava_lang_String() { + DecimalFormat format = new DecimalFormat(); + assertEquals("", format.getPositiveSuffix()); + + format.setPositiveSuffix("PosSfx"); + assertEquals("PosSfx", format.getPositiveSuffix()); + try { + assertTrue(format.parse("123.45PosSfx").doubleValue() == 123.45); + } catch(java.text.ParseException pe) { + fail("ParseException was thrown."); + } + + format.setPositiveSuffix(""); + assertEquals("", format.getPositiveSuffix()); + + format.setPositiveSuffix(null); + assertNull(format.getPositiveSuffix()); + } + @TestTargets({ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "setNegativePrefix", + args = {java.lang.String.class} + ), + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "getNegativePrefix", + args = {} + ) + }) + public void test_setNegativePrefixLjava_lang_String() { + DecimalFormat format = new DecimalFormat(); + assertEquals("-", format.getNegativePrefix()); + + format.setNegativePrefix("NegPrf"); + assertEquals("NegPrf", format.getNegativePrefix()); + try { + assertTrue(format.parse("NegPrf123.45").doubleValue() == -123.45); + } catch(java.text.ParseException pe) { + fail("ParseException was thrown."); + } + format.setNegativePrefix(""); + assertEquals("", format.getNegativePrefix()); + + format.setNegativePrefix(null); + assertNull(format.getNegativePrefix()); + } + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "setNegativeSuffix", + args = {java.lang.String.class} + ) + public void test_setNegativeSuffixLjava_lang_String() { + DecimalFormat format = new DecimalFormat(); + assertEquals("", format.getNegativeSuffix()); + + format.setNegativeSuffix("NegSfx"); + assertEquals("NegSfx", format.getNegativeSuffix()); + try { + assertTrue(format.parse("123.45NegPfx").doubleValue() == 123.45); + } catch(java.text.ParseException pe) { + fail("ParseException was thrown."); + } + + format.setNegativeSuffix(""); + assertEquals("", format.getNegativeSuffix()); + + format.setNegativeSuffix(null); + assertNull(format.getNegativeSuffix()); + } + + /** + * @tests java.text.DecimalFormat#toLocalizedPattern() Test of method + * java.text.DecimalFormat#toLocalizedPattern(). + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "toLocalizedPattern", + args = {} + ) + public void test_toLocalizedPattern() { + DecimalFormat format = new DecimalFormat(); + format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); + try { + format.applyLocalizedPattern("#.#"); + assertEquals("Wrong pattern 1", "#0.#", format.toLocalizedPattern()); + format.applyLocalizedPattern("#."); + assertEquals("Wrong pattern 2", "#0.", format.toLocalizedPattern()); + format.applyLocalizedPattern("#"); + assertEquals("Wrong pattern 3", "#", format.toLocalizedPattern()); + format.applyLocalizedPattern(".#"); + assertEquals("Wrong pattern 4", "#.0", format.toLocalizedPattern()); + } catch (Exception e) { + fail("Unexpected exception " + e.toString()); + } + } + + /** + * @tests java.text.DecimalFormat#toPattern() Test of method + * java.text.DecimalFormat#toPattern(). + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "toPattern", + args = {} + ) + public void test_toPattern() { + DecimalFormat format = new DecimalFormat(); + try { + format.applyPattern("#.#"); + assertEquals("Wrong pattern 1", "#0.#", format.toPattern()); + format.applyPattern("#."); + assertEquals("Wrong pattern 2", "#0.", format.toPattern()); + format.applyPattern("#"); + assertEquals("Wrong pattern 3", "#", format.toPattern()); + format.applyPattern(".#"); + assertEquals("Wrong pattern 4", "#.0", format.toPattern()); + } catch (Exception e) { + fail("Unexpected exception " + e.toString()); + } + } + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "setGroupingUsed", + args = {boolean.class} + ) + public void test_setGroupingUse() { + DecimalFormat format = new DecimalFormat(); + + StringBuffer buf = new StringBuffer(); + format.setGroupingUsed(false); + format.format(new Long(1970), buf, new FieldPosition(0)); + assertEquals("1970", buf.toString()); + assertFalse(format.isGroupingUsed()); + format.format(new Long(1970), buf, new FieldPosition(0)); + assertEquals("19701970", buf.toString()); + assertFalse(format.isGroupingUsed()); + + format.setGroupingUsed(true); + format.format(new Long(1970), buf, new FieldPosition(0)); + assertEquals("197019701,970", buf.toString()); + assertTrue(format.isGroupingUsed()); + } + + /** + * @tests java.text.DecimalFormat#DecimalFormat() Test of method + * java.text.DecimalFormat#DecimalFormat(). + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "DecimalFormat", + args = {} + ) + public void test_Constructor() { + // Test for method java.text.DecimalFormat() + // the constructor form that specifies a pattern is equal to the form + // constructed with no pattern and applying that pattern using the + // applyPattern call + try { + DecimalFormat format1 = new DecimalFormat(); + format1.applyPattern("'$'1000.0000"); + DecimalFormat format2 = new DecimalFormat(); + format2.applyPattern("'$'1000.0000"); + assertTrue( + "Constructed format did not match applied format object", + format2.equals(format1)); + DecimalFormat format3 = new DecimalFormat("'$'1000.0000"); + assertTrue( + "Constructed format did not match applied format object", + format3.equals(format1)); + DecimalFormat format4 = new DecimalFormat("'$'8000.0000"); + assertTrue( + "Constructed format did not match applied format object", + !format4.equals(format1)); + } catch (Exception e) { + fail("Unexpected exception " + e.toString()); + } + } + + /** + * @tests java.text.DecimalFormat#DecimalFormat(java.lang.String) + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "DecimalFormat", + args = {java.lang.String.class} + ) + public void test_ConstructorLjava_lang_String() { + // Test for method java.text.DecimalFormat(java.lang.String) + // the constructor form that specifies a pattern is equal to the form + // constructed with no pattern and applying that pattern using the + // applyPattern call + DecimalFormat format = new DecimalFormat("'$'0000.0000"); + DecimalFormat format1 = new DecimalFormat(); + format1.applyPattern("'$'0000.0000"); + assertTrue("Constructed format did not match applied format object", + format.equals(format1)); + + String [] patterns = {"####.##", "######.######", "000000.000000", + "######.000000", "000000.######", " ###.###", "$#####.######", + "$$####.######", "%#,##,###,####", "#,##0.00;(#,##0.00)"}; + + for(String str:patterns) { + new DecimalFormat(str); + } + + try { + new DecimalFormat(null); + fail("NullPointerException wasn't thrown."); + } catch(NullPointerException npe){ + //expected + } + + String [] incPatterns = {"%#,##,###,####'", "#.##0.00"}; + for(String str:incPatterns) { + try { + new DecimalFormat(str); + fail("IllegalArgumentException wasn't thrown for pattern: " + str); + } catch(IllegalArgumentException iae){ + //expected + } + } + } + + /** + * @tests java.text.DecimalFormat#DecimalFormat(java.lang.String, + * java.text.DecimalFormatSymbols) Test of method + * java.text.DecimalFormat#DecimalFormat(java.lang.String, + * java.text.DecimalFormatSymbols). Case 1: Try to construct object + * using correct pattern and fromat symbols. Case 2: Try to construct + * object using null arguments. Case 3: Try to construct object using + * incorrect pattern. + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "DecimalFormat", + args = {java.lang.String.class, java.text.DecimalFormatSymbols.class} + ) + public void test_ConstructorLjava_lang_StringLjava_text_DecimalFormatSymbols() { + try { + // case 1: Try to construct object using correct pattern and fromat + // symbols. + DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.CANADA); + DecimalFormat format1 = new DecimalFormat("'$'1000.0000", dfs); + DecimalFormat format2 = new DecimalFormat(); + format2.applyPattern("'$'1000.0000"); + format2.setDecimalFormatSymbols(dfs); + assertTrue( + "Constructed format did not match applied format object", + format2.equals(format1)); + assertTrue( + "Constructed format did not match applied format object", + !format1.equals(new DecimalFormat("'$'1000.0000", + new DecimalFormatSymbols(Locale.CHINA)))); + + // case 2: Try to construct object using null arguments. + try { + new DecimalFormat("'$'1000.0000", (DecimalFormatSymbols) null); + fail("Expected NullPointerException was not thrown"); + } catch (NullPointerException e) { + // expected + } + try { + new DecimalFormat(null, new DecimalFormatSymbols()); + fail("Expected NullPointerException was not thrown"); + } catch (NullPointerException e) { + // expected + } + try { + new DecimalFormat(null, (DecimalFormatSymbols) null); + fail("Expected NullPointerException was not thrown"); + } catch (NullPointerException e) { + // expected + } + + // case 3: Try to construct object using incorrect pattern. + try { + new DecimalFormat("$'", new DecimalFormatSymbols()); + fail("Expected IllegalArgumentException was not thrown"); + } catch (IllegalArgumentException e) { + // expected + } + } catch (Exception e) { + fail("Unexpected exception " + e.toString()); + } + } + + /** + * @tests java.text.DecimalFormat#applyLocalizedPattern(java.lang.String) + * Test of method + * java.text.DecimalFormat#applyLocalizedPattern(java.lang.String). + * Case 1: Try to apply correct variants of pattern. Case 2: Try to + * apply malformed patten. Case 3: Try to apply null patern. + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "applyLocalizedPattern", + args = {java.lang.String.class} + ) + public void test_applyLocalizedPatternLjava_lang_String() { + DecimalFormat format = new DecimalFormat(); + try { + // case 1: Try to apply correct variants of pattern. + format.applyLocalizedPattern("#.#"); + assertEquals("Wrong pattern 1", "#0.#", format.toLocalizedPattern()); + format.applyLocalizedPattern("#."); + assertEquals("Wrong pattern 2", "#0.", format.toLocalizedPattern()); + format.applyLocalizedPattern("#"); + assertEquals("Wrong pattern 3", "#", format.toLocalizedPattern()); + format.applyLocalizedPattern(".#"); + assertEquals("Wrong pattern 4", "#.0", format.toLocalizedPattern()); + + // case 2: Try to apply malformed patten. + try { + format.applyLocalizedPattern("'#,#:#0.0#;(#)"); + fail("Expected IllegalArgumentException was not thrown"); + } catch (IllegalArgumentException e) { + // expected + } + + // case 3: Try to apply null patern. + try { + format.applyLocalizedPattern((String) null); + fail("Expected NullPointerException was not thrown"); + } catch (NullPointerException e) { + // expected + } + } catch (Exception e) { + fail("Unexpected exception " + e.toString()); + } + } + + /** + * @tests java.text.DecimalFormat#applyPattern(java.lang.String) + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + method = "applyPattern", + args = {java.lang.String.class} + ) + public void test_applyPatternLjava_lang_String() { + DecimalFormat format = new DecimalFormat("#.#"); + assertEquals("Wrong pattern 1", "#0.#", format.toPattern()); + format = new DecimalFormat("#."); + assertEquals("Wrong pattern 2", "#0.", format.toPattern()); + format = new DecimalFormat("#"); + assertEquals("Wrong pattern 3", "#", format.toPattern()); + format = new DecimalFormat(".#"); + assertEquals("Wrong pattern 4", "#.0", format.toPattern()); + + DecimalFormat decFormat = new DecimalFormat("#.#"); + + try { + decFormat.applyPattern(null); + fail("NullPointerException was not thrown."); + } catch(NullPointerException npe) { + //expected + } + + String [] incPatterns = {"%#,##,###,####'", "#.##0.00"}; + for(String str:incPatterns) { + try { + decFormat.applyPattern(str); + fail("IllegalArgumentException was not thrown for pattern: " + + str); + } catch(IllegalArgumentException iae) { + //expected + } + } + } + + @TestTargetNew( + level = TestLevel.COMPLETE, + method = "applyPattern", + args = {java.lang.String.class} + ) + @AndroidOnly("icu supports 2 grouping sizes.") + public void test_applyPatternLjava_lang_String2() { + DecimalFormat decFormat = new DecimalFormat("#.#"); + String [] patterns = {"####.##", "######.######", "000000.000000", + "######.000000", "000000.######", " ###.###", "$#####.######", + "$$####.######", "%#,##,###,####", "#,##0.00;(#,##0.00)", + "##.##-E"}; + + String [] expResult = {"#0.##", "#0.######", "#000000.000000", + "#.000000", "#000000.######", " #0.###", "$#0.######", + "$$#0.######", + "%#,###,####", // icu only. icu supports two grouping sizes + "#,##0.00;(#,##0.00)", + "#0.##-'E'"}; // icu only. E in the suffix does not need to be + // quoted. This is done automatically. + + for (int i = 0; i < patterns.length; i++) { + decFormat.applyPattern(patterns[i]); + String result = decFormat.toPattern(); + assertEquals("Failed to apply following pattern: " + patterns[i] + + " expected: " + expResult[i] + " returned: " + result, + expResult[i], result); + } + } + + /** + * @tests java.text.DecimalFormat#clone() + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "clone", + args = {} + ) + public void test_clone() { + DecimalFormat format = (DecimalFormat) DecimalFormat + .getInstance(Locale.US); + DecimalFormat cloned = (DecimalFormat) format.clone(); + assertEquals(cloned.getDecimalFormatSymbols(), format + .getDecimalFormatSymbols()); + + format = new DecimalFormat("'$'0000.0000"); + DecimalFormat format1 = (DecimalFormat) (format.clone()); + // make sure the objects are equal + assertTrue("Object's clone isn't equal!", format.equals(format1)); + // change the content of the clone and make sure it's not equal anymore + // verifies that it's data is now distinct from the original + format1.applyPattern("'$'0000.####"); + assertTrue("Object's changed clone should not be equal!", !format + .equals(format1)); + } + + private void compare(String testName, String format, String expected) { + assertTrue(testName + " got: " + format + " expected: " + expected, + format.equals(expected)); + } + + private boolean compare(int count, String format, String expected) { + boolean result = format.equals(expected); + if (!result) + System.out.println("Failure test: " + count + " got: " + format + + " expected: " + expected); + return result; + } + + /** + * @tests java.text.DecimalFormat#format(double, java.lang.StringBuffer, + * java.text.FieldPosition) + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + method = "format", + args = {double.class, java.lang.StringBuffer.class, java.text.FieldPosition.class} + ) + public void test_formatDLjava_lang_StringBufferLjava_text_FieldPosition() { + new Support_DecimalFormat( + "test_formatDLjava_lang_StringBufferLjava_text_FieldPosition") + .t_format_with_FieldPosition(); + + int failCount = 0; + BitSet failures = new BitSet(); + + final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US); + + DecimalFormat df = new DecimalFormat("00.0#E0", dfs); + compare("00.0#E0: 0.0", df.format(0.0), "00.0E0"); + compare("00.0#E0: 1.0", df.format(1.0), "10.0E-1"); + compare("00.0#E0: 12.0", df.format(12.0), "12.0E0"); + compare("00.0#E0: 123.0", df.format(123.0), "12.3E1"); + compare("00.0#E0: 1234.0", df.format(1234.0), "12.34E2"); + compare("00.0#E0: 12346.0", df.format(12346.0), "12.35E3"); + compare("00.0#E0: 99999.0", df.format(99999.0), "10.0E4"); + compare("00.0#E0: 1.2", df.format(1.2), "12.0E-1"); + compare("00.0#E0: 12.3", df.format(12.3), "12.3E0"); + compare("00.0#E0: 123.4", df.format(123.4), "12.34E1"); + compare("00.0#E0: 1234.6", df.format(1234.6), "12.35E2"); + compare("00.0#E0: 9999.9", df.format(9999.9), "10.0E3"); + compare("00.0#E0: 0.1", df.format(0.1), "10.0E-2"); + compare("00.0#E0: 0.12", df.format(0.12), "12.0E-2"); + compare("00.0#E0: 0.123", df.format(0.123), "12.3E-2"); + compare("00.0#E0: 0.1234", df.format(0.1234), "12.34E-2"); + compare("00.0#E0: 0.12346", df.format(0.12346), "12.35E-2"); + compare("00.0#E0: 0.99999", df.format(0.99999), "10.0E-1"); + compare("00.0#E0: -0.0", df.format(-0.0), "-00.0E0"); + compare("00.0#E0: -1.0", df.format(-1.0), "-10.0E-1"); + compare("00.0#E0: -12.0", df.format(-12.0), "-12.0E0"); + compare("00.0#E0: -123.0", df.format(-123.0), "-12.3E1"); + compare("00.0#E0: -1234.0", df.format(-1234.0), "-12.34E2"); + compare("00.0#E0: -12346.0", df.format(-12346.0), "-12.35E3"); + compare("00.0#E0: -99999.0", df.format(-99999.0), "-10.0E4"); + + df = new DecimalFormat("##0.0E0", dfs); + compare("##0.0E0: -0.0", df.format(-0.0), "-0.0E0"); + compare("##0.0E0: 0.0", df.format(0.0), "0.0E0"); + compare("##0.0E0: 1.0", df.format(1.0), "1.0E0"); + compare("##0.0E0: 12.0", df.format(12.0), "12E0"); + compare("##0.0E0: 123.0", df.format(123.0), "123E0"); // Android fails, here! + compare("##0.0E0: 1234.0", df.format(1234.0), "1.234E3"); + compare("##0.0E0: 12346.0", df.format(12346.0), "12.35E3"); + // Fails in JDK 1.2.2 + if (!compare(failCount, df.format(99999.0), "100E3")) + failures.set(failCount); + failCount++; + compare("##0.0E0: 999999.0", df.format(999999.0), "1.0E6"); + + df = new DecimalFormat("#00.0##E0", dfs); + compare("#00.0##E0: 0.1", df.format(0.1), "100E-3"); + compare("#00.0##E0: 0.12", df.format(0.12), "120E-3"); + compare("#00.0##E0: 0.123", df.format(0.123), "123E-3"); + compare("#00.0##E0: 0.1234", df.format(0.1234), "123.4E-3"); + compare("#00.0##E0: 0.1234567", df.format(0.1234567), "123.457E-3"); + compare("#00.0##E0: 0.01", df.format(0.01), "10.0E-3"); + compare("#00.0##E0: 0.012", df.format(0.012), "12.0E-3"); + compare("#00.0##E0: 0.0123", df.format(0.0123), "12.3E-3"); + compare("#00.0##E0: 0.01234", df.format(0.01234), "12.34E-3"); + compare("#00.0##E0: 0.01234567", df.format(0.01234567), "12.3457E-3"); + compare("#00.0##E0: 0.001", df.format(0.001), "1.00E-3"); + compare("#00.0##E0: 0.0012", df.format(0.0012), "1.20E-3"); + compare("#00.0##E0: 0.00123", df.format(0.00123), "1.23E-3"); + compare("#00.0##E0: 0.001234", df.format(0.001234), "1.234E-3"); + compare("#00.0##E0: 0.001234567", df.format(0.001234567), "1.23457E-3"); + compare("#00.0##E0: 0.0001", df.format(0.0001), "100E-6"); + compare("#00.0##E0: 0.00012", df.format(0.00012), "120E-6"); + compare("#00.0##E0: 0.000123", df.format(0.000123), "123E-6"); + compare("#00.0##E0: 0.0001234", df.format(0.0001234), "123.4E-6"); + compare("#00.0##E0: 0.0001234567", df.format(0.0001234567), + "123.457E-6"); + + // Fails in JDK 1.2.2 + if (!compare(failCount, df.format(0.0), "0.00E0")) + failures.set(failCount); + failCount++; + compare("#00.0##E0: 1.0", df.format(1.0), "1.00E0"); + compare("#00.0##E0: 12.0", df.format(12.0), "12.0E0"); + compare("#00.0##E0: 123.0", df.format(123.0), "123E0"); + compare("#00.0##E0: 1234.0", df.format(1234.0), "1.234E3"); + compare("#00.0##E0: 12345.0", df.format(12345.0), "12.345E3"); + compare("#00.0##E0: 123456.0", df.format(123456.0), "123.456E3"); + compare("#00.0##E0: 1234567.0", df.format(1234567.0), "1.23457E6"); + compare("#00.0##E0: 12345678.0", df.format(12345678.0), "12.3457E6"); + compare("#00.0##E0: 99999999.0", df.format(99999999.0), "100E6"); + + df = new DecimalFormat("#.0E0", dfs); + compare("#.0E0: -0.0", df.format(-0.0), "-.0E0"); + compare("#.0E0: 0.0", df.format(0.0), ".0E0"); + compare("#.0E0: 1.0", df.format(1.0), ".1E1"); + compare("#.0E0: 12.0", df.format(12.0), ".12E2"); + compare("#.0E0: 123.0", df.format(123.0), ".12E3"); + compare("#.0E0: 1234.0", df.format(1234.0), ".12E4"); + compare("#.0E0: 9999.0", df.format(9999.0), ".1E5"); + + df = new DecimalFormat("0.#E0", dfs); + compare("0.#E0: -0.0", df.format(-0.0), "-0E0"); + compare("0.#E0: 0.0", df.format(0.0), "0E0"); + compare("0.#E0: 1.0", df.format(1.0), "1E0"); + compare("0.#E0: 12.0", df.format(12.0), "1.2E1"); + compare("0.#E0: 123.0", df.format(123.0), "1.2E2"); + compare("0.#E0: 1234.0", df.format(1234.0), "1.2E3"); + compare("0.#E0: 9999.0", df.format(9999.0), "1E4"); + + df = new DecimalFormat(".0E0", dfs); + compare(".0E0: -0.0", df.format(-0.0), "-.0E0"); + compare(".0E0: 0.0", df.format(0.0), ".0E0"); + compare(".0E0: 1.0", df.format(1.0), ".1E1"); + compare(".0E0: 12.0", df.format(12.0), ".1E2"); + compare(".0E0: 123.0", df.format(123.0), ".1E3"); + compare(".0E0: 1234.0", df.format(1234.0), ".1E4"); + compare(".0E0: 9999.0", df.format(9999.0), ".1E5"); + + df = new DecimalFormat("0.E0", dfs); + // Fails in JDK 1.2.2 + if (!compare(failCount, df.format(0.0), "0.E0")) + failures.set(failCount); + failCount++; + if (!compare(failCount, df.format(1.0), "1.E0")) + failures.set(failCount); + failCount++; + if (!compare(failCount, df.format(12.0), "1.E1")) + failures.set(failCount); + failCount++; + if (!compare(failCount, df.format(123.0), "1.E2")) + failures.set(failCount); + failCount++; + if (!compare(failCount, df.format(1234.0), "1.E3")) + failures.set(failCount); + failCount++; + if (!compare(failCount, df.format(9999.0), "1.E4")) + failures.set(failCount); + failCount++; + + df = new DecimalFormat("##0.00#E0", dfs); + compare("##0.00#E0: 0.1", df.format(0.1), "100E-3"); + compare("##0.00#E0: 0.1234567", df.format(0.1234567), "123.457E-3"); + compare("##0.00#E0: 0.9999999", df.format(0.9999999), "1.00E0"); + compare("##0.00#E0: 0.01", df.format(0.01), "10.0E-3"); + compare("##0.00#E0: 0.01234567", df.format(0.01234567), "12.3457E-3"); + compare("##0.00#E0: 0.09999999", df.format(0.09999999), "100E-3"); + compare("##0.00#E0: 0.001", df.format(0.001), "1.00E-3"); + compare("##0.00#E0: 0.001234567", df.format(0.001234567), "1.23457E-3"); + compare("##0.00#E0: 0.009999999", df.format(0.009999999), "10.0E-3"); + compare("##0.00#E0: 0.0001", df.format(0.0001), "100E-6"); + compare("##0.00#E0: 0.0001234567", df.format(0.0001234567), + "123.457E-6"); + compare("##0.00#E0: 0.0009999999", df.format(0.0009999999), "1.00E-3"); + + df = new DecimalFormat("###0.00#E0", dfs); + compare("###0.00#E0: 0.1", df.format(0.1), "1000E-4"); + compare("###0.00#E0: 0.12345678", df.format(0.12345678), "1234.568E-4"); + compare("###0.00#E0: 0.99999999", df.format(0.99999999), "1.00E0"); + compare("###0.00#E0: 0.01", df.format(0.01), "100E-4"); + compare("###0.00#E0: 0.012345678", df.format(0.012345678), + "123.4568E-4"); + compare("###0.00#E0: 0.099999999", df.format(0.099999999), "1000E-4"); + compare("###0.00#E0: 0.001", df.format(0.001), "10.0E-4"); + compare("###0.00#E0: 0.0012345678", df.format(0.0012345678), + "12.34568E-4"); + compare("###0.00#E0: 0.0099999999", df.format(0.0099999999), "100E-4"); + compare("###0.00#E0: 0.0001", df.format(0.0001), "1.00E-4"); + compare("###0.00#E0: 0.00012345678", df.format(0.00012345678), + "1.234568E-4"); + compare("###0.00#E0: 0.00099999999", df.format(0.00099999999), + "10.0E-4"); + // Fails in JDK 1.2.2 + if (!compare(failCount, df.format(0.00001), "1000E-8")) + failures.set(failCount); + failCount++; + compare("###0.00#E0: 0.000012345678", df.format(0.000012345678), + "1234.568E-8"); + compare("###0.00#E0: 0.000099999999", df.format(0.000099999999), + "1.00E-4"); + + df = new DecimalFormat("###0.0#E0", dfs); + compare("###0.0#E0: 0.1", df.format(0.1), "1000E-4"); + compare("###0.0#E0: 0.1234567", df.format(0.1234567), "1234.57E-4"); + compare("###0.0#E0: 0.9999999", df.format(0.9999999), "1.0E0"); + // Fails in JDK 1.2.2 + if (!compare(failCount, df.format(0.01), "100E-4")) + failures.set(failCount); + failCount++; + compare("###0.0#E0: 0.01234567", df.format(0.01234567), "123.457E-4"); + compare("###0.0#E0: 0.09999999", df.format(0.09999999), "1000E-4"); + compare("###0.0#E0: 0.001", df.format(0.001), "10E-4"); + compare("###0.0#E0: 0.001234567", df.format(0.001234567), "12.3457E-4"); + // Fails in JDK 1.2.2 + if (!compare(failCount, df.format(0.009999999), "100E-4")) + failures.set(failCount); + failCount++; + compare("###0.0#E0: 0.0001", df.format(0.0001), "1.0E-4"); + compare("###0.0#E0: 0.0001234567", df.format(0.0001234567), + "1.23457E-4"); + compare("###0.0#E0: 0.0009999999", df.format(0.0009999999), "10E-4"); + // Fails in JDK 1.2.2 + if (!compare(failCount, df.format(0.00001), "1000E-8")) + failures.set(failCount); + failCount++; + compare("###0.0#E0: 0.00001234567", df.format(0.00001234567), + "1234.57E-8"); + compare("###0.0#E0: 0.00009999999", df.format(0.00009999999), "1.0E-4"); + + assertTrue("Failed " + failures + " of " + failCount, + failures.length() == 0); + + String formatString = "##0.#"; + df = new DecimalFormat(formatString, dfs); + df.setMinimumFractionDigits(30); + compare(formatString + ": 0.000000000000000000000000000000", df + .format(0.0), "0.000000000000000000000000000000"); + compare(formatString + ": -0.000000000000000000000000000000", df + .format(-0.0), "-0.000000000000000000000000000000"); + compare(formatString + ": 1.000000000000000000000000000000", df + .format(1.0), "1.000000000000000000000000000000"); + compare(formatString + ": -1.000000000000000000000000000000", df + .format(-1.0), "-1.000000000000000000000000000000"); + + df = new DecimalFormat(formatString); + df.setMaximumFractionDigits(30); + compare(formatString + ": 0", df.format(0.0), "0"); + compare(formatString + ": -0", df.format(-0.0), "-0"); + compare(formatString + ": 1", df.format(1.0), "1"); + compare(formatString + ": -1", df.format(-1.0), "-1"); + } + + /** + * @tests java.text.DecimalFormat#format(double) + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + method = "format", + args = {double.class} + ) + public void test_formatD() { + DecimalFormat format = (DecimalFormat) NumberFormat + .getInstance(Locale.ENGLISH); + format.setGroupingUsed(false); + format.setMaximumFractionDigits(400); + assertEquals("123456789012345", format.format(123456789012345.)); + assertEquals("1", "12345678901234.5", format.format(12345678901234.5)); + assertEquals("2", "1234567890123.25", format.format(1234567890123.25)); + assertEquals("3", "999999999999.375", format.format(999999999999.375)); + assertEquals("4", "99999999999.0625", format.format(99999999999.0625)); + assertEquals("5", "9999999999.03125", format.format(9999999999.03125)); + assertEquals("6", "999999999.015625", format.format(999999999.015625)); + assertEquals("7", "99999999.0078125", format.format(99999999.0078125)); + assertEquals("8", "9999999.00390625", format.format(9999999.00390625)); + assertEquals("9", "999999.001953125", format.format(999999.001953125)); + assertEquals("10", "9999.00048828125", format.format(9999.00048828125)); + assertEquals("11", "999.000244140625", format.format(999.000244140625)); + assertEquals("12", "99.0001220703125", format.format(99.0001220703125)); + assertEquals("13", "9.00006103515625", format.format(9.00006103515625)); + assertEquals("14", "0.000030517578125", format.format(0.000030517578125)); + } + + + /** + * @tests java.text.DecimalFormat#getNegativePrefix() Test of method + * java.text.DecimalFormat#getNegativePrefix(). + */ + @TestTargets({ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "getNegativePrefix", + args = {} + ), + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "setNegativePrefix", + args = {java.lang.String.class} + ) + }) + public void test_getNegativePrefix() { + DecimalFormat df = new DecimalFormat(); + try { + df.setNegativePrefix("--"); + assertTrue("Incorrect negative prefix", df.getNegativePrefix() + .equals("--")); + } catch (Exception e) { + fail("Unexpected exception " + e.toString()); + } + } + + /** + * @tests java.text.DecimalFormat#getNegativeSuffix() Test of method + * java.text.DecimalFormat#getNegativeSuffix(). + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "getNegativeSuffix", + args = {} + ) + public void test_getNegativeSuffix() { + DecimalFormat df = new DecimalFormat(); + try { + df.setNegativeSuffix("&"); + assertTrue("Incorrect negative suffix", df.getNegativeSuffix() + .equals("&")); + } catch (Exception e) { + fail("Unexpected exception " + e.toString()); + } + } + + /** + * @tests java.text.DecimalFormat#getPositivePrefix() Test of method + * java.text.DecimalFormat#getPositivePrefix(). + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "getPositivePrefix", + args = {} + ) + public void test_getPositivePrefix() { + DecimalFormat df = new DecimalFormat(); + try { + df.setPositivePrefix("++"); + assertTrue("Incorrect positive prefix", df.getPositivePrefix() + .equals("++")); + } catch (Exception e) { + fail("Unexpected exception " + e.toString()); + } + } + + /** + * @tests java.text.DecimalFormat#getPositiveSuffix() Test of method + * java.text.DecimalFormat#getPositiveSuffix(). + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "getPositiveSuffix", + args = {} + ) + public void test_getPositiveSuffix() { + DecimalFormat df = new DecimalFormat(); + try { + df.setPositiveSuffix("%"); + assertTrue("Incorrect positive prefix", df.getPositiveSuffix() + .equals("%")); + } catch (Exception e) { + fail("Unexpected exception " + e.toString()); + } + } + + /** + * @tests java.text.DecimalFormat#hashCode() Test of method + * java.text.DecimalFormat#hashCode(). + */ + @TestTargetNew( + level = TestLevel.COMPLETE, + notes = "", + method = "hashCode", + args = {} + ) + public void test_hashCode() { + try { + DecimalFormat df1 = new DecimalFormat(); + DecimalFormat df2 = (DecimalFormat) df1.clone(); + assertTrue("Hash codes of equals object are not equal", df2 + .hashCode() == df1.hashCode()); + } catch (Exception e) { + fail("Unexpected exception " + e.toString()); + } + } + + /** + * @tests java.text.DecimalFormat#parse(java.lang.String, + * java.text.ParsePosition) + */ + @TestTargetNew( + level = TestLevel.PARTIAL, + notes = "Vrifies boundary values.", + method = "parse", + args = {java.lang.String.class, java.text.ParsePosition.class} + ) + public void test_parseLjava_lang_StringLjava_text_ParsePosition() { + DecimalFormat format = (DecimalFormat) NumberFormat + .getNumberInstance(Locale.ENGLISH); + ParsePosition pos = new ParsePosition(0); + Number result = format.parse("9223372036854775807", pos); + assertTrue("Wrong result type for Long.MAX_VALUE", + result.getClass() == Long.class); + assertEquals("Wrong result Long.MAX_VALUE", + Long.MAX_VALUE, result.longValue()); + pos = new ParsePosition(0); + result = format.parse("-9223372036854775808", pos); + assertTrue("Wrong result type for Long.MIN_VALUE", + result.getClass() == Long.class); + assertTrue("Wrong result Long.MIN_VALUE: " + result.longValue(), result + .longValue() == Long.MIN_VALUE); + pos = new ParsePosition(0); + result = format.parse("9223372036854775808", pos); + assertTrue("Wrong result type for Long.MAX_VALUE+1", + result.getClass() == Double.class); + assertEquals("Wrong result Long.MAX_VALUE + 1", + (double) Long.MAX_VALUE + 1, result.doubleValue()); + pos = new ParsePosition(0); + result = format.parse("-9223372036854775809", pos); + assertTrue("Wrong result type for Long.MIN_VALUE - 1", + result.getClass() == Double.class); + assertEquals("Wrong result Long.MIN_VALUE - 1", + (double) Long.MIN_VALUE - 1, result.doubleValue()); + + pos = new ParsePosition(0); + result = format.parse("18446744073709551629", pos); + assertTrue("Wrong result type for overflow", + result.getClass() == Double.class); + assertEquals("Wrong result for overflow", + 18446744073709551629d, result.doubleValue()); + + pos = new ParsePosition(0); + result = format.parse("42325917317067571199", pos); + assertTrue("Wrong result type for overflow a: " + result, result + .getClass() == Double.class); + assertTrue("Wrong result for overflow a: " + result, result + .doubleValue() == 42325917317067571199d); + pos = new ParsePosition(0); + result = format.parse("4232591731706757119E1", pos); + assertTrue("Wrong result type for overflow b: " + result, result + .getClass() == Double.class); + assertEquals("Wrong result for overflow b: " + result, + 42325917317067571190d, result.doubleValue()); + pos = new ParsePosition(0); + result = format.parse(".42325917317067571199E20", pos); + assertTrue("Wrong result type for overflow c: " + result, result + .getClass() == Double.class); + assertTrue("Wrong result for overflow c: " + result, result + .doubleValue() == 42325917317067571199d); + pos = new ParsePosition(0); + result = format.parse("922337203685477580.9E1", pos); + assertTrue("Wrong result type for overflow d: " + result, result + .getClass() == Double.class); + assertTrue("Wrong result for overflow d: " + result, result + .doubleValue() == 9223372036854775809d); + pos = new ParsePosition(0); + result = format.parse("9.223372036854775809E18", pos); + assertTrue("Wrong result type for overflow e: " + result, result + .getClass() == Double.class); + assertTrue("Wrong result for overflow e: " + result, result + .doubleValue() == 9223372036854775809d); + + // test parse with multipliers + format.setMultiplier(100); + result = format.parse("9223372036854775807", new ParsePosition(0)); + assertTrue("Wrong result type multiplier 100: " + result, result + .getClass() == Long.class); + // RI on windows and linux both answer with a slightly rounded result + assertTrue("Wrong result for multiplier 100: " + result, result + .longValue() == 92233720368547760L); + format.setMultiplier(1000); + result = format.parse("9223372036854775807", new ParsePosition(0)); + assertTrue("Wrong result type multiplier 1000: " + result, result + .getClass() == Long.class); + assertTrue("Wrong result for multiplier 1000: " + result, result + .longValue() == 9223372036854776L); + + format.setMultiplier(10000); + result = format.parse("9223372036854775807", new ParsePosition(0)); + assertTrue("Wrong result type multiplier 10000: " + result, result + .getClass() == Double.class); + assertTrue("Wrong result for multiplier 10000: " + result, result + .doubleValue() == 922337203685477.5807d); + + } +} diff --git a/luni/src/test/java/org/apache/harmony/text/tests/java/text/NumberFormatTest.java b/luni/src/test/java/java/text/OldNumberFormatTest.java index 4da671b..8609fe1 100644 --- a/luni/src/test/java/org/apache/harmony/text/tests/java/text/NumberFormatTest.java +++ b/luni/src/test/java/java/text/OldNumberFormatTest.java @@ -14,125 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.apache.harmony.text.tests.java.text; +package java.text; -import dalvik.annotation.TestTargets; +import dalvik.annotation.BrokenTest; import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargetClass; -import dalvik.annotation.BrokenTest; -import tests.support.Support_Locale; - -import junit.framework.TestCase; - -import java.text.ChoiceFormat; -import java.text.DecimalFormat; -import java.text.FieldPosition; -import java.text.NumberFormat; -import java.text.ParseException; -import java.text.ParsePosition; +import dalvik.annotation.TestTargetNew; import java.util.Currency; import java.util.Locale; +import junit.framework.TestCase; +import tests.support.Support_Locale; @TestTargetClass(NumberFormat.class) -public class NumberFormatTest extends TestCase { - - /** - * @tests java.text.NumberFormat#format(java.lang.Object, - * java.lang.StringBuffer, java.text.FieldPosition) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "format", - args = {java.lang.Object.class, java.lang.StringBuffer.class, java.text.FieldPosition.class} - ) - public void test_formatLjava_lang_ObjectLjava_lang_StringBufferLjava_text_FieldPosition() { - FieldPosition pos; - StringBuffer out; - DecimalFormat format = (DecimalFormat) NumberFormat - .getInstance(Locale.US); - - pos = new FieldPosition(0); - out = format.format(new Long(Long.MAX_VALUE), new StringBuffer(), pos); - assertEquals("Wrong result L1: " + out, "9,223,372,036,854,775,807", - out.toString()); - - pos = new FieldPosition(0); - out = format.format(new Long(Long.MIN_VALUE), new StringBuffer(), pos); - assertEquals("Wrong result L2: " + out, "-9,223,372,036,854,775,808", - out.toString()); - - pos = new FieldPosition(0); - out = format.format(new java.math.BigInteger(String - .valueOf(Long.MAX_VALUE)), new StringBuffer(), pos); - assertEquals("Wrong result BI1: " + out, "9,223,372,036,854,775,807", - out.toString()); - - pos = new FieldPosition(0); - out = format.format(new java.math.BigInteger(String - .valueOf(Long.MIN_VALUE)), new StringBuffer(), pos); - assertEquals("Wrong result BI2: " + out, "-9,223,372,036,854,775,808", - out.toString()); - - java.math.BigInteger big; - pos = new FieldPosition(0); - big = new java.math.BigInteger(String.valueOf(Long.MAX_VALUE)) - .add(new java.math.BigInteger("1")); - out = format.format(big, new StringBuffer(), pos); - assertEquals("Wrong result BI3: " + out, "9,223,372,036,854,775,808", - out.toString()); - - pos = new FieldPosition(0); - big = new java.math.BigInteger(String.valueOf(Long.MIN_VALUE)) - .add(new java.math.BigInteger("-1")); - out = format.format(big, new StringBuffer(), pos); - assertEquals("Wrong result BI4: " + out, "-9,223,372,036,854,775,809", - out.toString()); - - pos = new FieldPosition(0); - out = format.format(new java.math.BigDecimal("51.348"), - new StringBuffer(), pos); - assertEquals("Wrong result BD1: " + out, "51.348", out.toString()); - - pos = new FieldPosition(0); - out = format.format(new java.math.BigDecimal("51"), new StringBuffer(), - pos); - assertEquals("Wrong result BD2: " + out, "51", out.toString()); - - } - - /** - * @tests java.text.NumberFormat#getIntegerInstance() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getIntegerInstance", - args = {} - ) - public void test_getIntegerInstance() throws ParseException { - // Test for method java.text.NumberFormat getIntegerInstance() - Locale origLocale = Locale.getDefault(); - Locale.setDefault(Locale.US); - - DecimalFormat format = (DecimalFormat) NumberFormat - .getIntegerInstance(); - - assertEquals( - "Test1: NumberFormat.getIntegerInstance().toPattern() returned wrong pattern", - "#,##0", format.toPattern()); - assertEquals( - "Test2: NumberFormat.getIntegerInstance().format(35.76) returned wrong value", - "36", format.format(35.76)); - assertEquals( - "Test3: NumberFormat.getIntegerInstance().parse(\"35.76\") returned wrong number", - new Long(35), format.parse("35.76")); - assertEquals( - "Test4: NumberFormat.getIntegerInstance().parseObject(\"35.76\") returned wrong number", - new Long(35), format.parseObject("35.76")); - Locale.setDefault(origLocale); - } +public class OldNumberFormatTest extends TestCase { /** * @tests java.text.NumberFormat#getIntegerInstance(java.util.Locale) @@ -226,33 +120,6 @@ public class NumberFormatTest extends TestCase { } /** - * @tests java.text.NumberFormat#getCurrency() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getCurrency", - args = {} - ) - public void test_getCurrency() { - // Test for method java.util.Currency getCurrency() - - // a subclass that supports currency formatting - Currency currH = Currency.getInstance("HUF"); - NumberFormat format = NumberFormat.getInstance(new Locale("hu", "HU")); - assertSame("Returned incorrect currency", currH, format.getCurrency()); - - // a subclass that doesn't support currency formatting - ChoiceFormat cformat = new ChoiceFormat( - "0#Less than one|1#one|1<Between one and two|2<Greater than two"); - try { - ((NumberFormat) cformat).getCurrency(); - fail("Expected UnsupportedOperationException"); - } catch (UnsupportedOperationException e) { - } - } - - /** * @tests java.text.NumberFormat#setMaximumIntegerDigits() */ @TestTargetNew( diff --git a/luni/src/test/java/tests/targets/security/AlgorithmParameterGeneratorTestAES.java b/luni/src/test/java/javax/crypto/spec/AlgorithmParameterGeneratorTestAES.java index fc7ecb2..1c1132e 100644 --- a/luni/src/test/java/tests/targets/security/AlgorithmParameterGeneratorTestAES.java +++ b/luni/src/test/java/javax/crypto/spec/AlgorithmParameterGeneratorTestAES.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; +package javax.crypto.spec; -import dalvik.annotation.TestTargetClass; +import tests.security.AlgorithmParameterGeneratorTest; +import tests.security.AlgorithmParameterSymmetricHelper; public class AlgorithmParameterGeneratorTestAES extends AlgorithmParameterGeneratorTest { diff --git a/luni/src/test/java/tests/targets/security/AlgorithmParameterGeneratorTestDH.java b/luni/src/test/java/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java index cba7cc6..6073186 100644 --- a/luni/src/test/java/tests/targets/security/AlgorithmParameterGeneratorTestDH.java +++ b/luni/src/test/java/javax/crypto/spec/AlgorithmParameterGeneratorTestDH.java @@ -13,13 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; +package javax.crypto.spec; import dalvik.annotation.BrokenTest; import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargets; +import tests.security.AlgorithmParameterGeneratorTest; +import tests.security.AlgorithmParameterKeyAgreementHelper; public class AlgorithmParameterGeneratorTestDH extends AlgorithmParameterGeneratorTest { diff --git a/luni/src/test/java/tests/targets/security/AlgorithmParameterGeneratorTestDSA.java b/luni/src/test/java/javax/crypto/spec/AlgorithmParameterGeneratorTestDSA.java index a8afb9e..78770c4 100644 --- a/luni/src/test/java/tests/targets/security/AlgorithmParameterGeneratorTestDSA.java +++ b/luni/src/test/java/javax/crypto/spec/AlgorithmParameterGeneratorTestDSA.java @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; - -import dalvik.annotation.TestTargetClass; +package javax.crypto.spec; import java.security.spec.DSAParameterSpec; +import tests.security.AlgorithmParameterGeneratorTest; +import tests.security.AlgorithmParameterSignatureHelper; public class AlgorithmParameterGeneratorTestDSA extends AlgorithmParameterGeneratorTest { @@ -25,6 +25,4 @@ public class AlgorithmParameterGeneratorTestDSA extends public AlgorithmParameterGeneratorTestDSA() { super("DSA", new AlgorithmParameterSignatureHelper<DSAParameterSpec>("DSA", DSAParameterSpec.class)); } - - } diff --git a/luni/src/test/java/tests/targets/security/AlgorithmParametersTestAES.java b/luni/src/test/java/javax/crypto/spec/AlgorithmParametersTestAES.java index 95dfaa8..253df10 100644 --- a/luni/src/test/java/tests/targets/security/AlgorithmParametersTestAES.java +++ b/luni/src/test/java/javax/crypto/spec/AlgorithmParametersTestAES.java @@ -13,11 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; +package javax.crypto.spec; -import dalvik.annotation.TestTargetClass; - -import javax.crypto.spec.IvParameterSpec; +import tests.security.AlgorithmParameterSymmetricHelper; +import tests.security.AlgorithmParametersTest; public class AlgorithmParametersTestAES extends AlgorithmParametersTest { diff --git a/luni/src/test/java/tests/targets/security/AlgorithmParametersTestDES.java b/luni/src/test/java/javax/crypto/spec/AlgorithmParametersTestDES.java index d6d22ca..c218a3e 100644 --- a/luni/src/test/java/tests/targets/security/AlgorithmParametersTestDES.java +++ b/luni/src/test/java/javax/crypto/spec/AlgorithmParametersTestDES.java @@ -13,11 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; +package javax.crypto.spec; -import dalvik.annotation.TestTargetClass; - -import javax.crypto.spec.IvParameterSpec; +import tests.security.AlgorithmParameterSymmetricHelper; +import tests.security.AlgorithmParametersTest; public class AlgorithmParametersTestDES extends AlgorithmParametersTest { diff --git a/luni/src/test/java/tests/targets/security/AlgorithmParametersTestDESede.java b/luni/src/test/java/javax/crypto/spec/AlgorithmParametersTestDESede.java index e4b1f77..6d5ee23 100644 --- a/luni/src/test/java/tests/targets/security/AlgorithmParametersTestDESede.java +++ b/luni/src/test/java/javax/crypto/spec/AlgorithmParametersTestDESede.java @@ -13,11 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; +package javax.crypto.spec; -import javax.crypto.spec.IvParameterSpec; - -import dalvik.annotation.TestTargetClass; +import tests.security.AlgorithmParameterSymmetricHelper; +import tests.security.AlgorithmParametersTest; public class AlgorithmParametersTestDESede extends AlgorithmParametersTest { diff --git a/luni/src/test/java/tests/targets/security/AlgorithmParametersTestDH.java b/luni/src/test/java/javax/crypto/spec/AlgorithmParametersTestDH.java index 3bda78d..59746e6 100644 --- a/luni/src/test/java/tests/targets/security/AlgorithmParametersTestDH.java +++ b/luni/src/test/java/javax/crypto/spec/AlgorithmParametersTestDH.java @@ -13,17 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; +package javax.crypto.spec; import dalvik.annotation.BrokenTest; import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargets; - import java.math.BigInteger; - -import javax.crypto.spec.DHParameterSpec; +import tests.security.AlgorithmParameterKeyAgreementHelper; +import tests.security.AlgorithmParametersTest; public class AlgorithmParametersTestDH extends AlgorithmParametersTest { diff --git a/luni/src/test/java/tests/targets/security/AlgorithmParametersTestDSA.java b/luni/src/test/java/javax/crypto/spec/AlgorithmParametersTestDSA.java index ea89b52..2e46821 100644 --- a/luni/src/test/java/tests/targets/security/AlgorithmParametersTestDSA.java +++ b/luni/src/test/java/javax/crypto/spec/AlgorithmParametersTestDSA.java @@ -13,12 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; +package javax.crypto.spec; import java.math.BigInteger; import java.security.spec.DSAParameterSpec; - -import dalvik.annotation.TestTargetClass; +import tests.security.AlgorithmParameterSignatureHelper; +import tests.security.AlgorithmParametersTest; public class AlgorithmParametersTestDSA extends AlgorithmParametersTest { diff --git a/luni/src/test/java/tests/targets/security/AlgorithmParametersTestOAEP.java b/luni/src/test/java/javax/crypto/spec/AlgorithmParametersTestOAEP.java index b366eab..de87958 100644 --- a/luni/src/test/java/tests/targets/security/AlgorithmParametersTestOAEP.java +++ b/luni/src/test/java/javax/crypto/spec/AlgorithmParametersTestOAEP.java @@ -13,14 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; - -import dalvik.annotation.TestTargetClass; +package javax.crypto.spec; import java.security.spec.MGF1ParameterSpec; - -import javax.crypto.spec.OAEPParameterSpec; -import javax.crypto.spec.PSource; +import tests.security.AlgorithmParameterAsymmetricHelper; +import tests.security.AlgorithmParametersTest; public class AlgorithmParametersTestOAEP extends AlgorithmParametersTest { diff --git a/luni/src/test/java/tests/targets/security/KeyFactoryTestDH.java b/luni/src/test/java/javax/crypto/spec/KeyFactoryTestDH.java index 721ae1b..8378883 100644 --- a/luni/src/test/java/tests/targets/security/KeyFactoryTestDH.java +++ b/luni/src/test/java/javax/crypto/spec/KeyFactoryTestDH.java @@ -13,17 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; +package javax.crypto.spec; -import dalvik.annotation.TestTargetClass; - -import javax.crypto.spec.DHPrivateKeySpec; -import javax.crypto.spec.DHPublicKeySpec; +import java.security.KeyPair; +import tests.security.KeyAgreementHelper; +import tests.security.KeyFactoryTest; public class KeyFactoryTestDH extends KeyFactoryTest<DHPublicKeySpec, DHPrivateKeySpec> { public KeyFactoryTestDH() { - super("DH", new KeyAgreementHelper("DH"), DHPublicKeySpec.class, DHPrivateKeySpec.class); + super("DH", DHPublicKeySpec.class, DHPrivateKeySpec.class); } + @Override protected void check(KeyPair keyPair) { + new KeyAgreementHelper("DH").test(keyPair); + } } diff --git a/luni/src/test/java/tests/targets/security/KeyFactoryTestDSA.java b/luni/src/test/java/javax/crypto/spec/KeyFactoryTestDSA.java index 3a52fce..881c5d2 100644 --- a/luni/src/test/java/tests/targets/security/KeyFactoryTestDSA.java +++ b/luni/src/test/java/javax/crypto/spec/KeyFactoryTestDSA.java @@ -13,18 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; - -import dalvik.annotation.TestTargetClass; +package javax.crypto.spec; +import java.security.KeyPair; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; +import tests.security.KeyFactoryTest; +import tests.security.SignatureHelper; public class KeyFactoryTestDSA extends KeyFactoryTest<DSAPublicKeySpec, DSAPrivateKeySpec> { public KeyFactoryTestDSA() { - super("DSA", new SignatureHelper("DSA"), DSAPublicKeySpec.class, DSAPrivateKeySpec.class); + super("DSA", DSAPublicKeySpec.class, DSAPrivateKeySpec.class); } + @Override protected void check(KeyPair keyPair) { + new SignatureHelper("DSA").test(keyPair); + } } diff --git a/luni/src/test/java/tests/targets/security/KeyFactoryTestRSA.java b/luni/src/test/java/javax/crypto/spec/KeyFactoryTestRSA.java index ec96459..a754c1f 100644 --- a/luni/src/test/java/tests/targets/security/KeyFactoryTestRSA.java +++ b/luni/src/test/java/javax/crypto/spec/KeyFactoryTestRSA.java @@ -13,19 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; - -import dalvik.annotation.TestTargetClass; +package javax.crypto.spec; +import java.security.KeyPair; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; +import tests.security.CipherAsymmetricCryptHelper; +import tests.security.KeyFactoryTest; public class KeyFactoryTestRSA extends KeyFactoryTest<RSAPublicKeySpec, RSAPrivateKeySpec> { @SuppressWarnings("unchecked") public KeyFactoryTestRSA() { - super("RSA", new CipherAsymmetricCryptHelper("RSA"), RSAPublicKeySpec.class, RSAPrivateKeySpec.class); + super("RSA", RSAPublicKeySpec.class, RSAPrivateKeySpec.class); } + @Override protected void check(KeyPair keyPair) { + new CipherAsymmetricCryptHelper("RSA").test(keyPair); + } } diff --git a/luni/src/test/java/tests/targets/security/KeyPairGeneratorTestDH.java b/luni/src/test/java/javax/crypto/spec/KeyPairGeneratorTestDH.java index 99546e2..7383d37 100644 --- a/luni/src/test/java/tests/targets/security/KeyPairGeneratorTestDH.java +++ b/luni/src/test/java/javax/crypto/spec/KeyPairGeneratorTestDH.java @@ -13,13 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; +package javax.crypto.spec; import dalvik.annotation.BrokenTest; import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargets; +import java.security.NoSuchAlgorithmException; +import tests.security.KeyAgreementHelper; +import tests.security.KeyPairGeneratorTest; public class KeyPairGeneratorTestDH extends KeyPairGeneratorTest { @@ -45,7 +47,7 @@ public class KeyPairGeneratorTestDH extends KeyPairGeneratorTest { ) }) @BrokenTest("Takes ages due to DH computations. Disabling for now.") - public void testKeyPairGenerator() { + public void testKeyPairGenerator() throws NoSuchAlgorithmException { super.testKeyPairGenerator(); } } diff --git a/luni/src/test/java/tests/targets/security/KeyPairGeneratorTestDSA.java b/luni/src/test/java/javax/crypto/spec/KeyPairGeneratorTestDSA.java index 0137106..04afb5a 100644 --- a/luni/src/test/java/tests/targets/security/KeyPairGeneratorTestDSA.java +++ b/luni/src/test/java/javax/crypto/spec/KeyPairGeneratorTestDSA.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; +package javax.crypto.spec; -import dalvik.annotation.TestTargetClass; +import tests.security.KeyPairGeneratorTest; +import tests.security.SignatureHelper; public class KeyPairGeneratorTestDSA extends KeyPairGeneratorTest { diff --git a/luni/src/test/java/tests/targets/security/KeyPairGeneratorTestRSA.java b/luni/src/test/java/javax/crypto/spec/KeyPairGeneratorTestRSA.java index c29f3e9..a16bf09 100644 --- a/luni/src/test/java/tests/targets/security/KeyPairGeneratorTestRSA.java +++ b/luni/src/test/java/javax/crypto/spec/KeyPairGeneratorTestRSA.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; +package javax.crypto.spec; -import dalvik.annotation.TestTargetClass; +import tests.security.CipherAsymmetricCryptHelper; +import tests.security.KeyPairGeneratorTest; public class KeyPairGeneratorTestRSA extends KeyPairGeneratorTest { diff --git a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/AllTests.java b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/AllTests.java index 0a71ca6..ba4f63a 100644 --- a/luni/src/test/java/org/apache/harmony/luni/tests/java/net/AllTests.java +++ b/luni/src/test/java/org/apache/harmony/luni/tests/java/net/AllTests.java @@ -29,7 +29,7 @@ public class AllTests { TestRunner.main(new String[] { AllTests.class.getName() }); } - public static final Test suite() { + public static Test suite() { TestSuite suite = new TestSuite("Tests for java.net"); // add net testsuites here @@ -44,7 +44,6 @@ public class AllTests { suite.addTestSuite(URITest.class); suite.addTestSuite(URLConnectionTest.class); suite.addTestSuite(URLEncoderTest.class); - suite.addTestSuite(URLTest.class); return suite; } diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java index cbf7cd6..0f6c837 100644 --- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java +++ b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AllTests.java @@ -47,9 +47,7 @@ public class AllTests { suite.addTestSuite(SelectableChannelTest.class); suite.addTestSuite(SelectionKeyTest.class); suite.addTestSuite(SelectorTest.class); - suite.addTestSuite(ServerSocketChannelTest.class); suite.addTestSuite(SinkChannelTest.class); - suite.addTestSuite(SocketChannelTest.class); suite.addTestSuite(SourceChannelTest.class); suite.addTestSuite(UnresolvedAddressExceptionTest.class); suite.addTestSuite(UnsupportedAddressTypeExceptionTest.class); diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ServerSocketChannelTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ServerSocketChannelTest.java deleted file mode 100644 index 88d0d4d..0000000 --- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ServerSocketChannelTest.java +++ /dev/null @@ -1,888 +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.tests.java.nio.channels; - -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.BrokenTest; -import dalvik.annotation.KnownFailure; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.nio.ByteBuffer; -import java.nio.channels.AsynchronousCloseException; -import java.nio.channels.ClosedByInterruptException; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.IllegalBlockingModeException; -import java.nio.channels.NotYetBoundException; -import java.nio.channels.SelectionKey; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.nio.channels.spi.SelectorProvider; - -import junit.framework.TestCase; - -import tests.support.Support_PortManager; - -/* - * test for ServerSocketChannel - */ -@TestTargetClass(ServerSocketChannel.class) -public class ServerSocketChannelTest extends TestCase { - - private static final int CAPACITY_NORMAL = 200; - - private static final int CAPACITY_64KB = 65536; - - private static final int TIME_UNIT = 200; - - private InetSocketAddress localAddr1; - - private ServerSocketChannel serverChannel; - - private SocketChannel clientChannel; - - protected void setUp() throws Exception { - super.setUp(); - this.localAddr1 = new InetSocketAddress( - "127.0.0.1", Support_PortManager - .getNextPort()); - this.serverChannel = ServerSocketChannel.open(); - this.clientChannel = SocketChannel.open(); - } - - protected void tearDown() throws Exception { - if (null != this.serverChannel) { - try { - this.serverChannel.close(); - } catch (Exception e) { - //ignore - } - - } - if (null != this.clientChannel) { - try { - this.clientChannel.close(); - } catch (Exception e) { - //ignore - } - } - super.tearDown(); - } - - // ------------------------------------------------------------------- - // Test for methods in abstract class. - // ------------------------------------------------------------------- - /* - * Test method for 'java.nio.channels.ServerSocketChannel()' - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "ServerSocketChannel", - args = {java.nio.channels.spi.SelectorProvider.class} - ) - public void testConstructor() throws IOException { - ServerSocketChannel channel = - SelectorProvider.provider().openServerSocketChannel(); - assertNotNull(channel); - assertSame(SelectorProvider.provider(),channel.provider()); - } - - /* - * Test method for 'java.nio.channels.ServerSocketChannel.validOps()' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "validOps", - args = {} - ) - public void test_validOps() { - MockServerSocketChannel testMSChnlnull = new MockServerSocketChannel( - null); - MockServerSocketChannel testMSChnl = new MockServerSocketChannel( - SelectorProvider.provider()); - assertEquals(SelectionKey.OP_ACCEPT, this.serverChannel.validOps()); - assertEquals(SelectionKey.OP_ACCEPT, testMSChnl.validOps()); - assertEquals(SelectionKey.OP_ACCEPT, testMSChnlnull.validOps()); - - } - - /* - * Test method for 'java.nio.channels.ServerSocketChannel.open()' - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies in setUp method.", - method = "open", - args = {} - ) - public void test_open() { - MockServerSocketChannel testMSChnl = new MockServerSocketChannel(null); - MockServerSocketChannel testMSChnlnotnull = new MockServerSocketChannel( - SelectorProvider.provider()); - assertEquals(SelectionKey.OP_ACCEPT, testMSChnlnotnull.validOps()); - assertNull(testMSChnl.provider()); - assertNotNull(testMSChnlnotnull.provider()); - assertEquals(testMSChnlnotnull.provider(), this.serverChannel - .provider()); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "isOpen", - args = {} - ) - public void testIsOpen() throws Exception { - assertTrue(this.serverChannel.isOpen()); - this.serverChannel.close(); - assertFalse(this.serverChannel.isOpen()); - } - - // ------------------------------------------------------------------- - // Test for socket() - // ------------------------------------------------------------------- - - /* - * Test method for 'com.ibm.io.nio.ServerSocketChannelImpl.socket()' - * Test method for 'com.ibm.io.nio.ServerSocketChannelImpl.isOpen()' - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "socket", - args = {} - ),@TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "isOpen", - args = {} - ) - }) - public void test_socket_Block_BeforeClose() throws Exception { - assertTrue(this.serverChannel.isOpen()); - assertTrue(this.serverChannel.isBlocking()); - ServerSocket s1 = this.serverChannel.socket(); - assertFalse(s1.isClosed()); - assertSocketNotAccepted(s1); - ServerSocket s2 = this.serverChannel.socket(); - // same - assertSame(s1, s2); - - // socket close makes the channel close - s1.close(); - assertFalse(this.serverChannel.isOpen()); - - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "socket", - args = {} - ) - public void test_socket_NonBlock_BeforeClose() throws Exception { - assertTrue(this.serverChannel.isOpen()); - this.serverChannel.configureBlocking(false); - ServerSocket s1 = this.serverChannel.socket(); - assertFalse(s1.isClosed()); - assertSocketNotAccepted(s1); - ServerSocket s2 = this.serverChannel.socket(); - // same - assertSame(s1, s2); - - // socket close makes the channel close - s1.close(); - assertFalse(this.serverChannel.isOpen()); - - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "socket", - args = {} - ) - public void test_socket_Block_Closed() throws Exception { - this.serverChannel.close(); - assertFalse(this.serverChannel.isOpen()); - assertTrue(this.serverChannel.isBlocking()); - ServerSocket s1 = this.serverChannel.socket(); - assertTrue(s1.isClosed()); - assertSocketNotAccepted(s1); - ServerSocket s2 = this.serverChannel.socket(); - // same - assertSame(s1, s2); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "socket", - args = {} - ) - public void test_socket_NonBlock_Closed() throws Exception { - this.serverChannel.configureBlocking(false); - this.serverChannel.close(); - assertFalse(this.serverChannel.isBlocking()); - assertFalse(this.serverChannel.isOpen()); - ServerSocket s1 = this.serverChannel.socket(); - assertTrue(s1.isClosed()); - assertSocketNotAccepted(s1); - ServerSocket s2 = this.serverChannel.socket(); - // same - assertSame(s1, s2); - } - - private void assertSocketNotAccepted(ServerSocket s) throws IOException { - assertFalse(s.isBound()); - assertNull(s.getInetAddress()); - assertEquals(-1, s.getLocalPort()); - assertNull(s.getLocalSocketAddress()); - assertEquals(0, s.getSoTimeout()); - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies default status of ServerSocketChannel.", - method = "validOps", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies default status of ServerSocketChannel.", - method = "provider", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies default status of ServerSocketChannel.", - method = "isRegistered", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies default status of ServerSocketChannel.", - method = "isBlocking", - args = {} - ) - }) - public void testChannelBasicStatus() { - ServerSocket gotSocket = this.serverChannel.socket(); - assertFalse(gotSocket.isClosed()); - assertTrue(this.serverChannel.isBlocking()); - assertFalse(this.serverChannel.isRegistered()); - assertEquals(SelectionKey.OP_ACCEPT, this.serverChannel.validOps()); - assertEquals(SelectorProvider.provider(), this.serverChannel.provider()); - } - - // ------------------------------------------------------------------- - // Test for accept() - // ------------------------------------------------------------------- - - /* - * Test method for 'com.ibm.io.nio.ServerSocketChannelImpl.accept()' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NotYetBoundException.", - method = "accept", - args = {} - ) - public void test_accept_Block_NotYetBound() throws IOException { - assertTrue(this.serverChannel.isOpen()); - assertTrue(this.serverChannel.isBlocking()); - try { - this.serverChannel.accept(); - fail("Should throw NotYetBoundException"); - } catch (NotYetBoundException e) { - // correct - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NotYetBoundException.", - method = "accept", - args = {} - ) - public void test_accept_NonBlock_NotYetBound() throws IOException { - assertTrue(this.serverChannel.isOpen()); - this.serverChannel.configureBlocking(false); - try { - this.serverChannel.accept(); - fail("Should throw NotYetBoundException"); - } catch (NotYetBoundException e) { - // correct - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies ClosedChannelException.", - method = "accept", - args = {} - ) - public void test_accept_ClosedChannel() throws Exception { - this.serverChannel.close(); - assertFalse(this.serverChannel.isOpen()); - try { - this.serverChannel.accept(); - fail("Should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // OK. - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies AsynchronousCloseException.", - method = "accept", - args = {} - ) - public void test_accept_Block_NoConnect_close() throws IOException { - assertTrue(this.serverChannel.isBlocking()); - ServerSocket gotSocket = this.serverChannel.socket(); - gotSocket.bind(localAddr1); - // blocking mode , will block and wait for ever... - // so must close the server channel with another thread. - new Thread() { - public void run() { - try { - Thread.sleep(TIME_UNIT); - ServerSocketChannelTest.this.serverChannel.close(); - } catch (Exception e) { - fail("Fail to close the server channel because of" - + e.getClass().getName()); - } - } - }.start(); - try { - this.serverChannel.accept(); - fail("Should throw a AsynchronousCloseException"); - } catch (AsynchronousCloseException e) { - // OK. - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies ClosedByInterruptException.", - method = "accept", - args = {} - ) - public void test_accept_Block_NoConnect_interrupt() throws IOException { - assertTrue(this.serverChannel.isBlocking()); - ServerSocket gotSocket = this.serverChannel.socket(); - gotSocket.bind(localAddr1); - - class MyThread extends Thread { - public String errMsg = null; - public void run() { - try { - serverChannel.accept(); - errMsg = "should throw ClosedByInterruptException"; - } catch (ClosedByInterruptException e) { - // expected - } catch (Exception e) { - errMsg = "caught wrong Exception: " + e.getClass() + ": " + - e.getMessage(); - } - } - } - MyThread thread = new MyThread(); - thread.start(); - try { - Thread.currentThread().sleep(TIME_UNIT); - thread.interrupt(); - } catch (InterruptedException e) { - fail("Should not throw a InterruptedException"); - } - if (thread.errMsg != null) { - fail(thread.errMsg); - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that accept() returns null if the channel is in non-blocking mode and no connection is available to be accepted.", - method = "accept", - args = {} - ) - public void test_accept_NonBlock_NoConnect() throws IOException { - ServerSocket gotSocket = this.serverChannel.socket(); - gotSocket.bind(localAddr1); - this.serverChannel.configureBlocking(false); - // non-blocking mode , will immediately return - assertNull(this.serverChannel.accept()); - } - - /** - * @tests ServerSocketChannel#accept().socket() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "accept", - args = {} - ) - public void test_accept_socket_read_Block() throws IOException { - serverChannel.socket().bind(localAddr1); - ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL); - - for (int i = 0; i < CAPACITY_NORMAL; i++) { - buf.put((byte) i); - } - clientChannel.connect(localAddr1); - Socket serverSocket = serverChannel.accept().socket(); - InputStream in = serverSocket.getInputStream(); - buf.flip(); - clientChannel.write(buf); - clientChannel.close(); - assertReadResult(in,CAPACITY_NORMAL); - } - - /** - * Asserts read content. The read content should contain <code>size</code> - * bytes, and the value should be a sequence from 0 to size-1 - * ([0,1,...size-1]). Otherwise, the method throws Exception. - * - */ - private void assertReadResult(InputStream in, int size) throws IOException{ - byte[] readContent = new byte[size + 1]; - int count = 0; - int total = 0; - while ((count = in.read(readContent, total, size + 1 - total)) != -1) { - total = total + count; - } - assertEquals(size, total); - for (int i = 0; i < size; i++) { - assertEquals((byte) i, readContent[i]); - } - } - - /** - * @tests ServerSocketChannel#accept().socket() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "accept", - args = {} - ) - public void test_accept_socket_read_NonBlock() throws Exception { - serverChannel.configureBlocking(false); - serverChannel.socket().bind(localAddr1); - ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL); - for (int i = 0; i < CAPACITY_NORMAL; i++) { - buf.put((byte) i); - } - buf.flip(); - clientChannel.connect(localAddr1); - Socket serverSocket = serverChannel.accept().socket(); - InputStream in = serverSocket.getInputStream(); - clientChannel.write(buf); - clientChannel.close(); - assertReadResult(in,CAPACITY_NORMAL); - } - - /** - * @tests ServerSocketChannel#accept().socket() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "accept", - args = {} - ) - public void test_accept_socket_write_Block() throws IOException { - assertTrue(serverChannel.isBlocking()); - ServerSocket serverSocket = serverChannel.socket(); - serverSocket.bind(localAddr1); - - byte[] writeContent = new byte[CAPACITY_NORMAL]; - for (int i = 0; i < writeContent.length; i++) { - writeContent[i] = (byte) i; - } - clientChannel.connect(localAddr1); - Socket socket = serverChannel.accept().socket(); - OutputStream out = socket.getOutputStream(); - out.write(writeContent); - out.flush(); - socket.close(); - assertWriteResult(CAPACITY_NORMAL); - } - - - /** - * @tests ServerSocketChannel#accept().socket() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "accept", - args = {} - ) - public void test_accept_socket_write_NonBlock() throws Exception { - serverChannel.configureBlocking(false); - ServerSocket serverSocket = serverChannel.socket(); - serverSocket.bind(localAddr1); - - byte[] writeContent = new byte[CAPACITY_NORMAL]; - for (int i = 0; i < CAPACITY_NORMAL; i++) { - writeContent[i] = (byte) i; - } - clientChannel.connect(localAddr1); - Socket clientSocket = serverChannel.accept().socket(); - OutputStream out = clientSocket.getOutputStream(); - out.write(writeContent); - clientSocket.close(); - assertWriteResult(CAPACITY_NORMAL); - } - - /** - * @tests ServerSocketChannel#accept().socket() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "accept", - args = {} - ) - @BrokenTest("Sporadic timeouts in CTS, but not in CoreTestRunner") - public void test_accept_socket_read_Block_RWLargeData() throws IOException { - serverChannel.socket().bind(localAddr1); - ByteBuffer buf = ByteBuffer.allocate(CAPACITY_64KB); - for (int i = 0; i < CAPACITY_64KB; i++) { - buf.put((byte) i); - } - buf.flip(); - clientChannel.connect(localAddr1); - clientChannel.write(buf); - clientChannel.close(); - Socket socket = serverChannel.accept().socket(); - InputStream in = socket.getInputStream(); - assertReadResult(in,CAPACITY_64KB); - } - - /** - * @tests ServerSocketChannel#accept().socket() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "accept", - args = {} - ) - @BrokenTest("Sporadic timeouts in CTS, but not in CoreTestRunner") - public void test_accept_socket_read_NonBlock_RWLargeData() - throws Exception { - serverChannel.configureBlocking(false); - serverChannel.socket().bind(localAddr1); - ByteBuffer buf = ByteBuffer.allocate(CAPACITY_64KB); - for (int i = 0; i < CAPACITY_64KB; i++) { - buf.put((byte) i); - } - buf.flip(); - clientChannel.connect(localAddr1); - clientChannel.write(buf); - clientChannel.close(); - Socket socket = serverChannel.accept().socket(); - InputStream in = socket.getInputStream(); - assertReadResult(in,CAPACITY_64KB); - } - - /** - * @tests ServerSocketChannel#accept().socket() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "accept", - args = {} - ) - @BrokenTest("Sporadic timeouts in CTS, but not in CoreTestRunner") - public void test_accept_socket_write_NonBlock_RWLargeData() - throws Exception { - serverChannel.configureBlocking(false); - serverChannel.socket().bind(localAddr1); - byte[] writeContent = new byte[CAPACITY_64KB]; - for (int i = 0; i < writeContent.length; i++) { - writeContent[i] = (byte) i; - } - clientChannel.connect(localAddr1); - Socket socket = serverChannel.accept().socket(); - OutputStream out = socket.getOutputStream(); - out.write(writeContent); - socket.close(); - assertWriteResult(CAPACITY_64KB); - } - - /** - * @tests ServerSocketChannel#accept().socket() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "accept", - args = {} - ) - @BrokenTest("Sporadic timeouts in CTS, but not in CoreTestRunner") - public void test_accept_socket_write_Block_RWLargeData() throws Exception { - serverChannel.socket().bind(localAddr1); - byte[] writeContent = new byte[CAPACITY_64KB]; - for (int i = 0; i < writeContent.length; i++) { - writeContent[i] = (byte) i; - } - clientChannel.connect(localAddr1); - Socket socket = serverChannel.accept().socket(); - OutputStream out = socket.getOutputStream(); - out.write(writeContent); - socket.close(); - assertWriteResult(CAPACITY_64KB); - } - - /** - * Uses SocketChannel.read(ByteBuffer) to verify write result. - */ - private void assertWriteResult(int size) throws IOException{ - ByteBuffer buf = ByteBuffer.allocate(size + 1); - int count = 0; - int total = 0; - long beginTime = System.currentTimeMillis(); - while ((count = clientChannel.read(buf)) != -1) { - total = total + count; - // 10s timeout to avoid dead loop - if (System.currentTimeMillis() - beginTime > 10000){ - break; - } - } - assertEquals(total, size); - buf.flip(); - for (int i = 0; i < count; i++) { - assertEquals((byte) i, buf.get(i)); - } - } - - /** - * @tests ServerSocketChannel#socket().getSoTimeout() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that accept method returns null since there are no pending connections. Doesn't verify exceptions.", - method = "accept", - args = {} - ) - public void test_accept_SOTIMEOUT() throws IOException { - // regression test for Harmony-707 - final int SO_TIMEOUT = 10; - ServerSocketChannel ssc = ServerSocketChannel.open(); - try { - ServerSocket ss = ssc.socket(); - ss.bind(localAddr1); - ssc.configureBlocking(false); - ss.setSoTimeout(SO_TIMEOUT); - SocketChannel client = ssc.accept(); - // non blocking mode, returns null since there are no pending connections. - assertNull(client); - int soTimeout = ss.getSoTimeout(); - // Harmony failed here. - assertEquals(SO_TIMEOUT, soTimeout); - } finally { - ssc.close(); - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "accept", - args = {} - ) - @KnownFailure("http://b/1952042 - issues with sockets forgetting their local and remote addresses") - public void test_accept_Security() throws IOException { - this.clientChannel.configureBlocking(true); - this.serverChannel.configureBlocking(true); - SecurityManager sm = System.getSecurityManager(); - MockSecurityManager mockManager = new MockSecurityManager("127.0.0.1"); - System.setSecurityManager(mockManager); - - Thread t = new Thread() { - public void run() { - try { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - } - clientChannel.connect(localAddr1); - } catch (IOException e) { - } - } - }; - t.start(); - - try { - ServerSocket ss = this.serverChannel.socket(); - ss.bind(localAddr1); - this.serverChannel.accept(); - } finally { - System.setSecurityManager(sm); - } - - assertTrue(mockManager.checkAcceptCalled); - } - - /** - * @tests ServerSocket#socket().accept() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Regression test. Verifies IllegalBlockingModeException.", - method = "socket", - args = {} - ) - public void test_socket_accept_Blocking_NotBound() throws IOException { - // regression test for Harmony-748 - ServerSocket gotSocket = serverChannel.socket(); - serverChannel.configureBlocking(true); - try { - gotSocket.accept(); - fail("Should throw an IllegalBlockingModeException"); - } catch (IllegalBlockingModeException e) { - // expected - } - serverChannel.close(); - try { - gotSocket.accept(); - fail("Should throw an IllegalBlockingModeException"); - } catch (IllegalBlockingModeException e) { - // expected - } - } - - /** - * @tests ServerSocket#socket().accept() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Regression test. Verifies IllegalBlockingModeException.", - method = "socket", - args = {} - ) - public void test_socket_accept_Nonblocking_NotBound() throws IOException { - // regression test for Harmony-748 - ServerSocket gotSocket = serverChannel.socket(); - serverChannel.configureBlocking(false); - try { - gotSocket.accept(); - fail("Should throw an IllegalBlockingModeException"); - } catch (IllegalBlockingModeException e) { - // expected - } - serverChannel.close(); - try { - gotSocket.accept(); - fail("Should throw an IllegalBlockingModeException"); - } catch (IllegalBlockingModeException e) { - // expected - } - } - - /** - * @tests ServerSocket#socket().accept() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Regression test. Verifies IllegalBlockingModeException, ClosedChannelException.", - method = "socket", - args = {} - ) - public void test_socket_accept_Nonblocking_Bound() throws IOException { - // regression test for Harmony-748 - serverChannel.configureBlocking(false); - ServerSocket gotSocket = serverChannel.socket(); - gotSocket.bind(localAddr1); - try { - gotSocket.accept(); - fail("Should throw an IllegalBlockingModeException"); - } catch (IllegalBlockingModeException e) { - // expected - } - serverChannel.close(); - try { - gotSocket.accept(); - fail("Should throw a ClosedChannelException"); - } catch (ClosedChannelException e) { - // expected - } - } - - /** - * @tests ServerSocket#socket().accept() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Regression test. Verifies ClosedChannelException.", - method = "socket", - args = {} - ) - public void test_socket_accept_Blocking_Bound() throws IOException { - // regression test for Harmony-748 - serverChannel.configureBlocking(true); - ServerSocket gotSocket = serverChannel.socket(); - gotSocket.bind(localAddr1); - serverChannel.close(); - try { - gotSocket.accept(); - fail("Should throw a ClosedChannelException"); - } catch (ClosedChannelException e) { - // expected - } - } - - /** - * Regression test for HARMONY-4961 - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Regression test. Verifies that returned socket returns correct local port.", - method = "socket", - args = {} - ) - public void test_socket_getLocalPort() throws IOException { - // regression test for Harmony-4961 - serverChannel.socket().bind(localAddr1); - clientChannel.connect(localAddr1); - SocketChannel myChannel = serverChannel.accept(); - int port = myChannel.socket().getLocalPort(); - assertEquals(localAddr1.getPort(), port); - myChannel.close(); - clientChannel.close(); - serverChannel.close(); - } -} diff --git a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SocketChannelTest.java b/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SocketChannelTest.java deleted file mode 100644 index 37f63fe..0000000 --- a/luni/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SocketChannelTest.java +++ /dev/null @@ -1,4385 +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.tests.java.nio.channels; - -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestLevel; -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.BrokenTest; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.BindException; -import java.net.ConnectException; -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.SocketException; -import java.nio.ByteBuffer; -import java.nio.channels.AlreadyConnectedException; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.ConnectionPendingException; -import java.nio.channels.IllegalBlockingModeException; -import java.nio.channels.NoConnectionPendingException; -import java.nio.channels.NotYetConnectedException; -import java.nio.channels.SelectableChannel; -import java.nio.channels.SelectionKey; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.nio.channels.UnresolvedAddressException; -import java.nio.channels.UnsupportedAddressTypeException; -import java.nio.channels.spi.SelectorProvider; - -import junit.framework.TestCase; -import tests.support.Support_PortManager; - -@TestTargetClass(SocketChannel.class) -/** - * Tests for SocketChannel and its default implementation. - */ -public class SocketChannelTest extends TestCase { - - private static final int CAPACITY_NORMAL = 200; - - private static final int CAPACITY_HUGE = 512 * 1024; - - private InetSocketAddress localAddr1; - - private InetSocketAddress localAddr2; - - private SocketChannel channel1; - - private SocketChannel channel2; - - private ServerSocket server1; - - private ServerSocket server2; - - private final static int TIMEOUT = 60000; - - private final static int EOF = -1; - - protected void setUp() throws Exception { - super.setUp(); - this.localAddr1 = new InetSocketAddress("127.0.0.1", - Support_PortManager.getNextPort()); - this.localAddr2 = new InetSocketAddress("127.0.0.1", - Support_PortManager.getNextPort()); - this.channel1 = SocketChannel.open(); - this.channel2 = SocketChannel.open(); - this.server1 = new ServerSocket(localAddr1.getPort()); - } - - protected void tearDown() throws Exception { - super.tearDown(); - if (null != this.channel1) { - try { - this.channel1.close(); - } catch (Exception e) { - // ignore - } - } - if (null != this.channel2) { - try { - this.channel2.close(); - } catch (Exception e) { - // ignore - } - } - if (null != this.server1) { - try { - this.server1.close(); - } catch (Exception e) { - // ignore - } - } - if (null != this.server2) { - try { - this.server2.close(); - } catch (Exception e) { - // ignore - } - } - } - - // ------------------------------------------------------------------- - // Test for methods in abstract class. - // ------------------------------------------------------------------- - /* - * Test method for 'java.nio.channels.SocketChannel()' - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "SocketChannel", - args = {SelectorProvider.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "provider", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "open", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - clazz = SelectorProvider.class, - method = "openSocketChannel", - args = {} - ) - }) - public void testConstructor() throws IOException { - SocketChannel channel = - SelectorProvider.provider().openSocketChannel(); - assertNotNull(channel); - assertSame(SelectorProvider.provider(), channel.provider()); - channel = SocketChannel.open(); - assertNotNull(channel); - assertSame(SelectorProvider.provider(), channel.provider()); - MockSocketChannel chan = new MockSocketChannel( - SelectorProvider.provider()); - assertTrue(chan.isConstructorCalled); - } - - /* - * Test method for 'java.nio.channels.SocketChannel.validOps()' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "validOps", - args = {} - ) - public void testValidOps() { - MockSocketChannel testMSChannel = new MockSocketChannel(null); - assertEquals(13, this.channel1.validOps()); - assertEquals(13, testMSChannel.validOps()); - } - - /* - * Test method for 'java.nio.channels.SocketChannel.open()' - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "open", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "SocketChannel", - args = {SelectorProvider.class} - ) - }) - public void testOpen() throws IOException { - java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1]; - buf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL); - MockSocketChannel testMSChannel = new MockSocketChannel(null); - MockSocketChannel testMSChannelnotnull = new MockSocketChannel( - SelectorProvider.provider()); - SocketChannel testSChannel = MockSocketChannel.open(); - assertTrue(testSChannel.isOpen()); - assertNull(testMSChannel.provider()); - assertNotNull(testSChannel.provider()); - assertEquals(SelectorProvider.provider(), testSChannel.provider()); - assertNotNull(testMSChannelnotnull.provider()); - assertEquals(this.channel1.provider(), testMSChannelnotnull.provider()); - try { - this.channel1.write(buf); - fail("Should throw NotYetConnectedException"); - } catch (NotYetConnectedException e) { - // correct - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "isOpen", - args = {} - ) - public void testIsOpen() throws Exception { - assertTrue(this.channel1.isOpen()); - this.channel1.close(); - assertFalse(this.channel1.isOpen()); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isConnected", - args = {} - ) - public void testIsConnected() throws Exception { - assertFalse(this.channel1.isConnected());// not connected - this.channel1.configureBlocking(false); - assertFalse(this.channel1.connect(localAddr1)); - assertFalse(this.channel1.isConnected()); - assertTrue(this.channel1.isConnectionPending()); - assertTrue(tryFinish()); - assertTrue(this.channel1.isConnected()); - this.channel1.close(); - assertFalse(this.channel1.isConnected()); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isConnectionPending", - args = {} - ) - public void testIsConnectionPending() throws Exception { - // ensure - ensureServerClosed(); - this.channel1.configureBlocking(false); - assertFalse(this.channel1.isConnectionPending()); - // finish - try { - this.channel1.finishConnect(); - fail("Should throw NoConnectionPendingException"); - } catch (NoConnectionPendingException e) { - // OK. - } - assertFalse(this.channel1.isConnectionPending()); - // connect - assertFalse(this.channel1.connect(localAddr1)); - assertTrue(this.channel1.isConnectionPending()); - this.channel1.close(); - - assertFalse(this.channel1.isConnectionPending()); - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies default status of SocketChannel.", - method = "validOps", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies default status of SocketChannel.", - method = "provider", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies default status of SocketChannel.", - method = "isRegistered", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies default status of SocketChannel.", - method = "isBlocking", - args = {} - ) - }) - public void testChannelBasicStatus() { - Socket gotSocket = this.channel1.socket(); - assertFalse(gotSocket.isClosed()); - assertTrue(this.channel1.isBlocking()); - assertFalse(this.channel1.isRegistered()); - assertEquals((SelectionKey.OP_CONNECT | SelectionKey.OP_READ | - SelectionKey.OP_WRITE), this.channel1.validOps()); - assertEquals(SelectorProvider.provider(), this.channel1.provider()); - } - - /* - * Test method for 'java.nio.channels.SocketChannel.open(SocketAddress)' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "open", - args = {java.net.SocketAddress.class} - ) - public void testOpenSocketAddress() throws IOException { - this.channel1 = SocketChannel.open(localAddr1); - assertTrue(this.channel1.isConnected()); - - SecurityManager smngr = System.getSecurityManager(); - System.setSecurityManager(new MockSecurityManager("blargh")); - try { - this.channel1 = SocketChannel.open(localAddr2); - fail("Should throw SecurityException"); - } catch (SecurityException e) { - // expected - } - System.setSecurityManager(smngr); - - SocketAddress newTypeAddress = new SubSocketAddress(); - try { - this.channel1 = SocketChannel.open(newTypeAddress); - fail("Should throw UnexpectedAddressTypeException"); - } catch (UnsupportedAddressTypeException e) { - // expected - } - - SocketAddress unresolvedAddress = - InetSocketAddress.createUnresolved("127.0.0.1", 8080); - try { - this.channel1 = SocketChannel.open(unresolvedAddress); - fail("Should throw UnresolvedAddressException"); - } catch (UnresolvedAddressException e) { - // expected - } - - SocketChannel channel1IP = null; - try { - channel1IP = SocketChannel.open(null); - fail("Should throw an IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // correct - } - assertNull(channel1IP); - } - - /* - * Test method for 'java.nio.channels.SocketChannel.read(ByteBuffer[])' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class} - ) - public void testReadByteBufferArray() throws IOException { - java.nio.ByteBuffer[] byteBuf = null; - MockSocketChannel testMSChannelnull = new MockSocketChannel(null); - MockSocketChannel testMSChannel = new MockSocketChannel( - SelectorProvider.provider()); - ServerSocket testServer = new ServerSocket(Support_PortManager - .getNextPort()); - try { - try { - this.channel1.read(byteBuf); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - byteBuf = new java.nio.ByteBuffer[CAPACITY_NORMAL]; - try { - this.channel1.read(byteBuf); - fail("Should throw NotYetConnectedException"); - } catch (NotYetConnectedException e) { - // correct - } - long readNum = CAPACITY_NORMAL; - readNum = testMSChannel.read(byteBuf); - assertEquals(0, readNum); - readNum = CAPACITY_NORMAL; - readNum = testMSChannelnull.read(byteBuf); - assertEquals(0, readNum); - } finally { - testServer.close(); - } - } - - /* - * Test method for 'java.nio.channels.SocketChannel.read(ByteBuffer[])' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class} - ) - public void testReadByteBufferArray_BufNull() throws IOException { - java.nio.ByteBuffer[] byteBuf = null; - MockSocketChannel testMSChannelnull = new MockSocketChannel(null); - MockSocketChannel testMSChannel = new MockSocketChannel( - SelectorProvider.provider()); - try { - this.channel1.read(byteBuf); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - try { - testMSChannel.read(byteBuf); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - try { - testMSChannelnull.read(byteBuf); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - } - - /* - * Test method for 'java.nio.channels.SocketChannel.write(ByteBuffer[])' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify AsynchronousCloseException," + - "ClosedByInterruptException.", - method = "write", - args = {java.nio.ByteBuffer[].class} - ) - public void testWriteByteBufferArray() throws IOException { - java.nio.ByteBuffer[] byteBuf = null; - MockSocketChannel testMSChannelnull = new MockSocketChannel(null); - MockSocketChannel testMSChannel = new MockSocketChannel( - SelectorProvider.provider()); - try { - this.channel1.write(byteBuf); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - byteBuf = new java.nio.ByteBuffer[1]; - byteBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); - try { - this.channel1.write(byteBuf); - fail("Should throw NotYetConnectedException"); - } catch (NotYetConnectedException e) { - // correct - } - testMSChannel.write(byteBuf); - testMSChannelnull.write(byteBuf); - - this.channel1.close(); - try { - this.channel1.write(byteBuf); - fail("Should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // correct - } - } - - /* - * Test method for 'java.nio.channels.SocketChannel.write(ByteBuffer[])' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer[].class} - ) - public void testWriteByteBufferArray_BufNull() throws IOException { - java.nio.ByteBuffer[] byteBuf = null; - MockSocketChannel testMSChannelnull = new MockSocketChannel(null); - MockSocketChannel testMSChannel = new MockSocketChannel( - SelectorProvider.provider()); - this.channel1.connect(localAddr1); - try { - this.channel1.write(byteBuf); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - byteBuf = new java.nio.ByteBuffer[1]; - try { - this.channel1.write(byteBuf); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "socket", - args = {} - ) - @AndroidOnly("Fails on RI. See comment below") - public void testSocket_BasicStatusBeforeConnect() throws IOException { - assertFalse(this.channel1.isConnected());// not connected - Socket s1 = this.channel1.socket(); - // RI fails here. RI returns 0 while spec says getLocalPort() - // shall return -1 for unbound socket - assertSocketBeforeConnect(s1); - Socket s2 = this.channel1.socket(); - // same - assertSame(s1, s2); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "socket", - args = {} - ) - public void testSocket_Block_BasicStatusAfterConnect() throws IOException { - assertFalse(this.channel1.isConnected());// not connected - assertTrue(this.channel1.connect(localAddr1)); - - assertTrue(this.channel1.isConnected()); - Socket s1 = this.channel1.socket(); - - assertSocketAfterConnect(s1, localAddr1); - Socket s2 = this.channel1.socket(); - // same - assertSame(s1, s2); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "socket", - args = {} - ) - @AndroidOnly("Fails on RI. See comment below") - public void testSocket_NonBlock_BasicStatusAfterConnect() throws Exception { - assertFalse(this.channel1.isConnected());// not connected - this.channel1.configureBlocking(false); - assertFalse(this.channel1.connect(localAddr1)); - assertFalse(this.channel1.isConnected()); - assertTrue(this.channel1.isConnectionPending()); - Socket s1 = this.channel1.socket(); - // status of not connected - // RI fails here. RI returns 0 while spec says getLocalPort() - // shall return -1 for unbound socket - assertSocketBeforeConnect(s1); - Socket s2 = this.channel1.socket(); - // same - assertSame(s1, s2); - - assertTrue(tryFinish()); - assertTrue(this.channel1.isConnected()); - s1 = this.channel1.socket(); - assertSocketAfterConnect(s1, localAddr1); - s2 = this.channel1.socket(); - // same - assertSame(s1, s2); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "socket", - args = {} - ) - public void testSocket_Block_ActionsBeforeConnect() throws IOException { - assertFalse(this.channel1.isConnected());// not connected - Socket s = this.channel1.socket(); - assertSocketAction_Block_BeforeConnect(s); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "socket", - args = {} - ) - public void testSocket_Block_ActionsAfterConnect() throws IOException { - assertFalse(this.channel1.isConnected());// not connected - assertTrue(this.channel1.connect(localAddr1)); - assertTrue(this.channel1.isConnected()); - Socket s = this.channel1.socket(); - assertSocketAction_Block_AfterConnect(s); - - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "socket", - args = {} - ) - public void testSocket_NonBlock_ActionsAfterConnectBeforeFinish() - throws IOException { - assertFalse(this.channel1.isConnected());// not connected - this.channel1.configureBlocking(false); - assertFalse(this.channel1.connect(localAddr1)); - assertFalse(this.channel1.isConnected()); - assertTrue(this.channel1.isConnectionPending()); - Socket s1 = this.channel1.socket(); - // Action of not connected - assertSocketAction_NonBlock_BeforeConnect(s1); - Socket s2 = this.channel1.socket(); - // same - assertSame(s1, s2); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "socket", - args = {} - ) - public void testSocket_NonBlock_ActionsAfterConnectAfterFinish() - throws Exception { - assertFalse(this.channel1.isConnected());// not connected - this.channel1.configureBlocking(false); - assertFalse(this.channel1.connect(localAddr1)); - assertTrue(tryFinish()); - Socket s1 = this.channel1.socket(); - assertSocketAction_NonBlock_AfterConnect(s1); - Socket s2 = this.channel1.socket(); - // same - assertSame(s1, s2); - } - - private void assertSocketBeforeConnect(Socket s) throws IOException { - assertFalse(s.isBound()); - assertFalse(s.isClosed()); - assertFalse(s.isConnected()); - assertFalse(s.getKeepAlive()); - try { - s.getInputStream(); - fail("Should throw SocketException."); - } catch (SocketException e) { - // OK. - } - assertFalse(s.getOOBInline()); - try { - s.getOutputStream(); - fail("Should throw SocketException."); - } catch (SocketException e) { - // OK. - } - assertEquals(-1, s.getSoLinger()); - assertFalse(s.getTcpNoDelay()); - - assertFalse(s.isInputShutdown()); - assertFalse(s.isOutputShutdown()); - - assertNull(s.getInetAddress()); - assertEquals(s.getLocalAddress().getHostAddress(), "0.0.0.0"); - assertFalse(s.getReuseAddress()); - assertNull(s.getLocalSocketAddress()); - - // not connected - assertEquals(0, s.getPort()); - assertTrue(s.getReceiveBufferSize() >= 8192); - assertNull(s.getRemoteSocketAddress()); - assertTrue(s.getSendBufferSize() >= 8192); - assertEquals(0, s.getSoTimeout()); - assertEquals(0, s.getTrafficClass()); - - // RI fails here. RI returns 0 while spec says unbound socket should - // return -1. - assertEquals(-1, s.getLocalPort()); - } - - private void assertSocketAfterConnect(Socket s, InetSocketAddress address) - throws IOException { - assertTrue(s.isBound()); - assertFalse(s.isClosed()); - assertTrue(s.isConnected()); - assertFalse(s.getKeepAlive()); - - assertNotNull(s.getInputStream()); - assertNotNull(s.getOutputStream()); - - assertFalse(s.getOOBInline()); - assertEquals(-1, s.getSoLinger()); - assertFalse(s.getTcpNoDelay()); - - assertFalse(s.isInputShutdown()); - assertFalse(s.isOutputShutdown()); - - assertSame(s.getInetAddress(), address.getAddress()); - - assertEquals(this.localAddr1.getAddress(), s.getLocalAddress()); - assertEquals(address.getPort(), s.getPort()); - assertNotNull(s.getLocalSocketAddress()); - assertTrue(s.getReceiveBufferSize() >= 8192); - // equal , not same - assertNotSame(address, s.getRemoteSocketAddress()); - assertEquals(address, s.getRemoteSocketAddress()); - // assertFalse(s.getReuseAddress()); - assertTrue(s.getSendBufferSize() >= 8192); - assertEquals(0, s.getSoTimeout()); - assertEquals(0, s.getTrafficClass()); - } - - private void assertSocketAction_Block_BeforeConnect(Socket s) - throws IOException { - assertFalse(this.channel1.isConnected()); - this.server2 = new ServerSocket(localAddr2.getPort()); - s.connect(localAddr2); - assertTrue(this.channel1.isConnected()); - assertTrue(s.isConnected()); - - assertSocketAfterConnect(s, localAddr2); - - try { - s.bind(localAddr2); - fail("Should throw AlreadyConnectedException"); - } catch (AlreadyConnectedException e) { - // OK. - } - - s.close(); - assertTrue(s.isClosed()); - assertFalse(this.channel1.isOpen()); - } - - private void assertSocketAction_NonBlock_BeforeConnect(Socket s) - throws IOException { - assertFalse(this.channel1.isConnected()); - this.server2 = new ServerSocket(localAddr2.getPort()); - try { - s.connect(localAddr2); - fail("Should throw IllegalBlockingModeException"); - } catch (IllegalBlockingModeException e1) { - // OK. - } - - if (this.channel1.isConnectionPending()) { - try { - s.bind(localAddr2); - fail("Should throw ConnectionPendingException"); - } catch (ConnectionPendingException e1) { - // OK. - } - } else { - try { - s.bind(localAddr2); - fail("Should throw BindException"); - } catch (BindException e1) { - // OK. - } - } - - assertFalse(this.channel1.isConnected()); - assertFalse(s.isConnected()); - - s.close(); - assertTrue(s.isClosed()); - assertFalse(this.channel1.isOpen()); - } - - private void assertSocketAction_Block_AfterConnect(Socket s) - throws IOException { - assertEquals(localAddr1.getPort(), s.getPort()); - assertTrue(this.channel1.isConnected()); - assertTrue(s.isConnected()); - try { - s.connect(localAddr2); - fail("Should throw AlreadyConnectedException"); - } catch (AlreadyConnectedException e) { - // OK. - } - - try { - s.bind(localAddr2); - fail("Should throw AlreadyConnectedException"); - } catch (AlreadyConnectedException e) { - // OK. - } - - s.close(); - assertTrue(s.isClosed()); - assertFalse(this.channel1.isOpen()); - } - - private void assertSocketAction_NonBlock_AfterConnect(Socket s) - throws IOException { - assertEquals(localAddr1.getPort(), s.getPort()); - assertTrue(this.channel1.isConnected()); - assertTrue(s.isConnected()); - - if (this.channel1.isConnectionPending()) { - try { - s.connect(localAddr2); - fail("Should throw AlreadyConnectedException"); - } catch (AlreadyConnectedException e) { - // OK. - } - } else { - try { - s.connect(localAddr2); - fail("Should throw IllegalBlockingModeException"); - } catch (IllegalBlockingModeException e) { - // OK. - } - } - - try { - s.bind(localAddr2); - fail("Should throw AlreadyConnectedException"); - } catch (AlreadyConnectedException e) { - // OK. - } - - s.close(); - assertTrue(s.isClosed()); - assertFalse(this.channel1.isOpen()); - } - - // ------------------------------------------------------------------- - // Tests for connect(), finishConnect(),isConnected(),isConnectionPending() - // These methods are very close, so we test them together, call them "CFII". - // ------------------------------------------------------------------- - /** - * connect-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_Norml_NoServer_Block() throws Exception { - // ensure - ensureServerClosed(); - assertTrue(this.channel1.isBlocking()); - statusNotConnected_NotPending(); - // connect - try { - this.channel1.connect(localAddr1); - fail("Should throw a ConnectException here."); - } catch (ConnectException e) { - // OK. - } - statusChannelClosed(); - try { - this.channel1.finishConnect(); - fail("Should throw a ClosedChannelException here."); - } catch (ClosedChannelException e) { - // OK. - } - } - - /** - * connect-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_Norml_NoServer_NonBlock() throws Exception { - connectNoServerNonBlock(); - - this.channel1.close(); - statusChannelClosed(); - } - - /** - * connect-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_Norml_Server_Block() throws Exception { - connectServerBlock(); - - this.channel1.close(); - statusChannelClosed(); - - } - - /** - * connect-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_Norml_Server_NonBlock() throws Exception { - connectServerNonBlock(); - - this.channel1.close(); - statusChannelClosed(); - } - - /** - * connect-->server closed-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_ServerClosed_Block() throws Exception { - // ensure - ensureServerOpen(); - assertTrue(this.channel1.isBlocking()); - statusNotConnected_NotPending(); - // connect - assertTrue(this.channel1.connect(localAddr1)); - statusConnected_NotPending(); - - ensureServerClosed(); - - tryFinish(); - - this.channel1.close(); - statusChannelClosed(); - - } - - /** - * connect-->server closed-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_ServerClosed_NonBlock() throws Exception { - // ensure - ensureServerOpen(); - this.channel1.configureBlocking(false); - statusNotConnected_NotPending(); - // connect - assertFalse(this.channel1.connect(localAddr1)); - statusNotConnected_Pending(); - - ensureServerClosed(); - - tryFinish(); - - this.channel1.close(); - statusChannelClosed(); - } - - /** - * connect-->finish-->server closed-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_ServerClosedAfterFinish_Block() throws Exception { - connectServerBlock(); - - ensureServerClosed(); - assertTrue(this.channel1.isOpen()); - this.channel1.close(); - statusChannelClosed(); - - } - - /** - * connect-->finish-->server closed-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_ServerClosedAfterFinish_NonBlock() throws Exception { - connectServerNonBlock(); - - ensureServerClosed(); - assertTrue(this.channel1.isOpen()); - this.channel1.close(); - statusChannelClosed(); - } - - /** - * no server-->connect-->server open-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_ServerStartLater_Block() throws Exception { - // ensure - ensureServerClosed(); - assertTrue(this.channel1.isBlocking()); - statusNotConnected_NotPending(); - // connect - try { - this.channel1.connect(localAddr1); - fail("Should throw a ConnectException here."); - } catch (ConnectException e) { - // OK. - } - statusChannelClosed(); - ensureServerOpen(); - try { - this.channel1.finishConnect(); - fail("Should throw a ClosedChannelException here."); - } catch (ClosedChannelException e) { - // OK. - } - } - - /** - * no server-->connect-->server open-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_ServerStartLater_NonBlock() throws Exception { - // ensure - ensureServerClosed(); - this.channel1.configureBlocking(false); - statusNotConnected_NotPending(); - // connect - assertFalse(this.channel1.connect(localAddr1)); - statusNotConnected_Pending(); - - ensureServerOpen(); - - try { - assertFalse(this.channel1.finishConnect()); - statusNotConnected_Pending(); - this.channel1.close(); - } catch (ConnectException e) { - // OK - } - } - - /** - * connect-->finish-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_FinishTwice_NoServer_NonBlock() throws Exception { - // ensure - ensureServerClosed(); - this.channel1.configureBlocking(false); - statusNotConnected_NotPending(); - // connect - assertFalse(this.channel1.connect(localAddr1)); - statusNotConnected_Pending(); - try { - assertFalse(this.channel1.finishConnect()); - } catch (ConnectException e) { - // OK - } - statusChannelClosed(); - try { - assertFalse(this.channel1.finishConnect()); - } catch (ClosedChannelException e) { - // OK - } - statusChannelClosed(); - - this.channel1.close(); - statusChannelClosed(); - } - - /** - * connect-->finish-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_FinishTwice_Server_Block() throws Exception { - connectServerBlock(); - tryFinish(); - this.channel1.close(); - statusChannelClosed(); - - } - - /** - * connect-->finish-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_FinishTwice_Server_NonBlock() throws Exception { - connectServerNonBlock(); - tryFinish(); - this.channel1.close(); - statusChannelClosed(); - } - - /** - * connect-->finish-->connect-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies case: connect-->finish-->connect-->close. Verifies ClosedChannelException, ConnectException.", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies case: connect-->finish-->connect-->close. Verifies ClosedChannelException, ConnectException.", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_ConnectAfterFinish_NoServer_Block() throws Exception { - // ensure - ensureServerClosed(); - assertTrue(this.channel1.isBlocking()); - statusNotConnected_NotPending(); - // connect - try { - this.channel1.connect(localAddr1); - fail("Should throw a ConnectException here."); - } catch (ConnectException e) { - // OK. - } - statusChannelClosed(); - try { - this.channel1.finishConnect(); - fail("Should throw a ClosedChannelException here."); - } catch (ClosedChannelException e) { - // OK. - } - statusChannelClosed(); - try { - this.channel1.connect(localAddr1); - fail("Should throw a ClosedChannelException here."); - } catch (ClosedChannelException e) { - // OK. - } - statusChannelClosed(); - } - - /** - * connect-->finish-->connect-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies case: connect-->finish-->connect-->close. Verifies ConnectionPendingException, ConnectException.", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies case: connect-->finish-->connect-->close. Verifies ConnectionPendingException, ConnectException.", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_ConnectAfterFinish_NoServer_NonBlock() - throws Exception { - // ensure - ensureServerClosed(); - this.channel1.configureBlocking(false); - statusNotConnected_NotPending(); - // connect - assertFalse(this.channel1.connect(localAddr1)); - statusNotConnected_Pending(); - - try { - this.channel1.connect(localAddr1); - fail("Should throw a ConnectionPendingException here."); - } catch (ConnectionPendingException e) { - // OK. - } - statusNotConnected_Pending(); - - // connect another addr - try { - this.channel1.connect(localAddr2); - fail("Should throw a ConnectionPendingException here."); - } catch (ConnectionPendingException e) { - // OK. - } - statusNotConnected_Pending(); - - // connect if server closed - ensureServerClosed(); - - try { - this.channel1.connect(localAddr1); - fail("Should throw a ConnectionPendingException here."); - } catch (ConnectionPendingException e) { - // OK. - } - statusNotConnected_Pending(); - - this.channel1.close(); - - statusChannelClosed(); - } - - /** - * connect-->finish-->connect-->close - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies AlreadyConnectedException.", - method = "connect", - args = {java.net.SocketAddress.class} - ) - public void testCFII_ConnectAfterFinish_Server_Block() throws Exception { - connectServerBlock(); - - if (!this.channel1.isConnected()) { - fail("Connection failed," + - "testCFII_ConnectAfterFinish_Server_Block not finished."); - } - - try { - this.channel1.connect(localAddr1); - fail("Should throw an AlreadyConnectedException here."); - } catch (AlreadyConnectedException e) { - // OK. - } - statusConnected_NotPending(); - - // connect another addr - try { - this.channel1.connect(localAddr2); - fail("Should throw an AlreadyConnectedException here."); - } catch (AlreadyConnectedException e) { - // OK. - } - statusConnected_NotPending(); - - // connect if server closed - ensureServerClosed(); - - try { - this.channel1.connect(localAddr1); - fail("Should throw an AlreadyConnectedException here."); - } catch (AlreadyConnectedException e) { - // OK. - } - statusConnected_NotPending(); - - this.channel1.close(); - statusChannelClosed(); - - } - - /** - * connect-->finish-->connect-->close - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies AlreadyConnectedException.", - method = "connect", - args = {java.net.SocketAddress.class} - ) - public void testCFII_ConnectAfterFinish_Server_NonBlock() throws Exception { - connectServerNonBlock(); - - if (!this.channel1.isConnected()) { - fail("Connection failed," + - "testCFII_ConnectAfterFinish_Server_Block not finished."); - } - try { - this.channel1.connect(localAddr1); - fail("Should throw an AlreadyConnectedException or a ConnectionPendingException here."); - } catch (AlreadyConnectedException e) { - // OK. - } - - statusConnected_NotPending(); - - // connect another addr - try { - this.channel1.connect(localAddr2); - fail("Should throw an AlreadyConnectedException here."); - } catch (AlreadyConnectedException e) { - // OK. - } - statusConnected_NotPending(); - - // connect if server closed - ensureServerClosed(); - - try { - this.channel1.connect(localAddr1); - fail("Should throw an AlreadyConnectedException here."); - } catch (AlreadyConnectedException e) { - // OK. - } - statusConnected_NotPending(); - - this.channel1.close(); - statusChannelClosed(); - } - - /** - * connect-->connect-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies case: connect-->connect-->finish-->close. Verifies ConnectionPendingException, ConnectException.", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies case: connect-->connect-->finish-->close. Verifies ConnectionPendingException, ConnectException.", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_ConnectTwice_NoServer_NonBlock() throws Exception { - // ensure - ensureServerClosed(); - this.channel1.configureBlocking(false); - statusNotConnected_NotPending(); - // connect - assertFalse(this.channel1.connect(localAddr1)); - statusNotConnected_Pending(); - - try { - this.channel1.connect(localAddr1); - fail("Should throw a ConnectionPendingException here."); - } catch (ConnectionPendingException e) { - // OK. - } - statusNotConnected_Pending(); - - // connect another addr - try { - this.channel1.connect(localAddr2); - fail("Should throw a ConnectionPendingException here."); - } catch (ConnectionPendingException e) { - // OK. - } - statusNotConnected_Pending(); - - // connect if server closed - ensureServerClosed(); - - try { - this.channel1.connect(localAddr1); - fail("Should throw a ConnectionPendingException here."); - } catch (ConnectionPendingException e) { - // OK. - } - statusNotConnected_Pending(); - this.channel1.close(); - - statusChannelClosed(); - } - - /** - * connect-->connect-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies case connect-->connect-->finish-->close. Verifies AlreadyConnectedException.", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies case connect-->connect-->finish-->close. Verifies AlreadyConnectedException.", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_ConnectTwice_Server_Block() throws Exception { - // ensure - ensureServerOpen(); - assertTrue(this.channel1.isBlocking()); - statusNotConnected_NotPending(); - // connect - assertTrue(this.channel1.connect(localAddr1)); - statusConnected_NotPending(); - - try { - this.channel1.connect(localAddr1); - fail("Should throw an AlreadyConnectedException here."); - } catch (AlreadyConnectedException e) { - // OK. - } - statusConnected_NotPending(); - - // connect another addr - try { - this.channel1.connect(localAddr2); - fail("Should throw an AlreadyConnectedException here."); - } catch (AlreadyConnectedException e) { - // OK. - } - statusConnected_NotPending(); - - // connect if server closed - ensureServerClosed(); - - try { - this.channel1.connect(localAddr1); - fail("Should throw an AlreadyConnectedException here."); - } catch (AlreadyConnectedException e) { - // OK. - } - statusConnected_NotPending(); - - tryFinish(); - - this.channel1.close(); - statusChannelClosed(); - - } - - /** - * connect-->connect-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies case connect-->connect-->finish-->close. Verifies ConnectionPendingException.", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies case connect-->connect-->finish-->close. Verifies ConnectionPendingException.", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_ConnectTwice_Server_NonBlock() throws Exception { - // ensure - ensureServerOpen(); - this.channel1.configureBlocking(false); - statusNotConnected_NotPending(); - // connect - assertFalse(this.channel1.connect(localAddr1)); - statusNotConnected_Pending(); - - try { - this.channel1.connect(localAddr1); - fail("Should throw a ConnectionPendingException here."); - } catch (ConnectionPendingException e) { - // OK. - } - statusNotConnected_Pending(); - - // connect another addr - try { - this.channel1.connect(localAddr2); - fail("Should throw a ConnectionPendingException here."); - } catch (ConnectionPendingException e) { - // OK. - } - statusNotConnected_Pending(); - - // connect if server closed - ensureServerClosed(); - - try { - this.channel1.connect(localAddr1); - fail("Should throw a ConnectionPendingException here."); - } catch (ConnectionPendingException e) { - // OK. - } - statusNotConnected_Pending(); - - tryFinish(); - - this.channel1.close(); - statusChannelClosed(); - } - - /** - * finish-->connect-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_FinishFirst_NoServer_Block() throws Exception { - // ensure - ensureServerClosed(); - assertTrue(this.channel1.isBlocking()); - statusNotConnected_NotPending(); - // finish - try { - this.channel1.finishConnect(); - fail("Should throw NoConnectionPendingException"); - } catch (NoConnectionPendingException e) { - // OK. - } - statusNotConnected_NotPending(); - // connect - try { - this.channel1.connect(localAddr1); - fail("Should throw a ConnectException here."); - } catch (ConnectException e) { - // OK. - } - statusChannelClosed(); - try { - this.channel1.finishConnect(); - fail("Should throw a ClosedChannelException here."); - } catch (ClosedChannelException e) { - // OK. - } - statusChannelClosed(); - } - - /** - * finish-->connect-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_FinishFirst_NoServer_NonBlock() throws Exception { - // ensure - ensureServerClosed(); - this.channel1.configureBlocking(false); - statusNotConnected_NotPending(); - // finish - try { - this.channel1.finishConnect(); - fail("Should throw NoConnectionPendingException"); - } catch (NoConnectionPendingException e) { - // OK. - } - statusNotConnected_NotPending(); - // connect - assertFalse(this.channel1.connect(localAddr1)); - statusNotConnected_Pending(); - this.channel1.close(); - - statusChannelClosed(); - } - - /** - * finish-->connect-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_FinishFirst_Server_Block() throws Exception { - // ensure - ensureServerOpen(); - assertTrue(this.channel1.isBlocking()); - statusNotConnected_NotPending(); - // finish - try { - this.channel1.finishConnect(); - fail("Should throw NoConnectionPendingException"); - } catch (NoConnectionPendingException e) { - // OK. - } - statusNotConnected_NotPending(); - // connect - assertTrue(this.channel1.connect(localAddr1)); - statusConnected_NotPending(); - - tryFinish(); - - this.channel1.close(); - statusChannelClosed(); - - } - - /** - * finish-->connect-->finish-->close - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_FinishFirst_Server_NonBlock() throws Exception { - // ensure - ensureServerOpen(); - this.channel1.configureBlocking(false); - statusNotConnected_NotPending(); - // finish - try { - this.channel1.finishConnect(); - fail("Should throw NoConnectionPendingException"); - } catch (NoConnectionPendingException e) { - // OK. - } - statusNotConnected_NotPending(); - // connect - assertFalse(this.channel1.connect(localAddr1)); - statusNotConnected_Pending(); - - tryFinish(); - - this.channel1.close(); - statusChannelClosed(); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ) - public void testCFII_Null() throws Exception { - statusNotConnected_NotPending(); - try { - this.channel1.connect(null); - fail("Should throw an IllegalArgumentException here."); - } catch (IllegalArgumentException e) { - // OK. - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ) - public void testCFII_UnsupportedType() throws Exception { - statusNotConnected_NotPending(); - SocketAddress newTypeAddress = new SubSocketAddress(); - try { - this.channel1.connect(newTypeAddress); - fail("Should throw an UnsupportedAddressTypeException here."); - } catch (UnsupportedAddressTypeException e) { - // OK. - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ) - public void testCFII_Unresolved() throws IOException { - statusNotConnected_NotPending(); - InetSocketAddress unresolved = new InetSocketAddress( - "unresolved address", 1080); - try { - this.channel1.connect(unresolved); - fail("Should throw an UnresolvedAddressException here."); - } catch (UnresolvedAddressException e) { - // OK. - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ) - public void testCFII_EmptyHost() throws Exception { - statusNotConnected_NotPending(); - ServerSocket server = new ServerSocket(0); - int port = server.getLocalPort(); - server.close(); - try { - this.channel1.connect(new InetSocketAddress("", port)); - fail("Should throw ConnectException"); - } catch (ConnectException e) { - // correct - } - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies ClosedChannelException.", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies ClosedChannelException.", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_CloseFirst() throws Exception { - this.channel1.close(); - statusChannelClosed(); - ensureServerOpen(); - try { - this.channel1.connect(localAddr1); - fail("Should throw ClosedChannelException."); - } catch (ClosedChannelException e) { - // OK. - } - statusChannelClosed(); - try { - this.channel1.finishConnect(); - fail("Should throw ClosedChannelException."); - } catch (ClosedChannelException e) { - // OK. - } - statusChannelClosed(); - try { - this.channel1.configureBlocking(false); - fail("Should throw ClosedChannelException."); - } catch (ClosedChannelException e) { - // OK. - } - statusChannelClosed(); - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_StatusAfterFinish() throws Exception { - // 1. close server, finish must return false, check the status - ensureServerClosed(); - - // 1.1 block mode - assertTrue(this.channel1.isBlocking()); - try { - channel1.connect(localAddr1); - fail("Should throw ConnectException"); - } catch (ConnectException e) { - // OK. - } - - assertFalse(this.channel1.isOpen()); - assertTrue(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnectionPending()); - - // 1.2 non block mode - this.channel1 = SocketChannel.open(); - this.channel1.configureBlocking(false); - assertFalse(this.channel1.connect(localAddr1)); - try { - assertFalse(this.channel1.finishConnect()); - fail("Should throw IOException: Connection refused"); - } catch (ConnectException e) { - // OK - } - statusChannelClosed(); - - // 2. start server, finish usually return true, check the status - ensureServerOpen(); - - // 2.1 block mode - this.channel1 = SocketChannel.open(); - assertTrue(this.channel1.isBlocking()); - assertTrue(this.channel1.connect(localAddr1)); - assertTrue(this.channel1.finishConnect()); - statusConnected_NotPending(); - this.channel1.close(); - - // 2.2 non block mode - this.channel1 = SocketChannel.open(); - this.channel1.configureBlocking(false); - assertFalse(this.channel1.connect(localAddr1)); - tryFinish(); - this.channel1.close(); - } - - private void ensureServerClosed() throws IOException { - if (null != this.server1) { - this.server1.close(); - assertTrue(this.server1.isClosed()); - } - if (null != this.server2) { - this.server2.close(); - assertTrue(this.server2.isClosed()); - } - } - - private void ensureServerOpen() throws IOException { - ensureServerClosed(); - this.server1 = new ServerSocket(localAddr1.getPort()); - this.server2 = new ServerSocket(localAddr2.getPort()); - assertTrue(this.server1.isBound()); - assertTrue(this.server2.isBound()); - } - - private void connectNoServerNonBlock() throws Exception { - // ensure - ensureServerClosed(); - this.channel1.configureBlocking(false); - statusNotConnected_NotPending(); - // connect - assertFalse(this.channel1.connect(localAddr1)); - statusNotConnected_Pending(); - try { - assertFalse(this.channel1.finishConnect()); - } catch (ConnectException e) { - // OK - } - ensureServerClosed(); - } - - private void connectServerNonBlock() throws Exception { - // ensure - ensureServerOpen(); - this.channel1.configureBlocking(false); - statusNotConnected_NotPending(); - // connect - assertFalse(this.channel1.connect(localAddr1)); - statusNotConnected_Pending(); - - tryFinish(); - } - - private void connectServerBlock() throws Exception { - // ensure - ensureServerOpen(); - assertTrue(this.channel1.isBlocking()); - statusNotConnected_NotPending(); - // connect - assertTrue(this.channel1.connect(localAddr1)); - statusConnected_NotPending(); - - tryFinish(); - } - - private void statusChannelClosed() { - assertFalse(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertFalse(this.channel1.isOpen()); - } - - private void statusNotConnected_NotPending() { - assertFalse(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - } - - private void statusNotConnected_Pending() { - assertFalse(this.channel1.isConnected()); - assertTrue(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - } - - private void statusConnected_NotPending() { - assertTrue(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - } - - private boolean tryFinish() throws IOException { - /* - * the result of finish will be asserted in multi-thread tests. - */ - boolean connected = false; - assertTrue(this.channel1.isOpen()); - try { - connected = this.channel1.finishConnect(); - } catch (SocketException e) { - // Finish connection failed, probably due to reset by peer error. - } - if (connected) { - statusConnected_NotPending(); - } - return connected; - } - - // ------------------------------------------------------------------- - // Original tests. Test method for CFII with real data. - // ------------------------------------------------------------------- - - /** - * - * 'SocketChannelImpl.connect(SocketAddress)' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ) - public void testCFII_Data_ConnectWithServer() throws Exception { - ensureServerOpen(); - java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer - .allocate(CAPACITY_NORMAL); - java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1]; - writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); - assertFalse(this.channel1.isRegistered()); - assertTrue(this.channel1.isBlocking()); - - this.channel1.connect(localAddr1); - - assertTrue(this.channel1.isBlocking()); - assertTrue(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf)); - assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBufArr, 0, 1)); - - this.channel1.configureBlocking(false); - try { - this.channel1.connect(localAddr1); - fail("Should throw AlreadyConnectedException"); - } catch (AlreadyConnectedException e) { - // correct - } - - assertFalse(this.channel1.isRegistered()); - tryFinish(); - } - - /* - * Test method for 'SocketChannelImpl.connect(SocketAddress)' - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - }) - public void testCFII_Data_ConnectWithServer_nonBlocking() throws Exception { - ensureServerOpen(); - java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer - .allocate(CAPACITY_NORMAL); - java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1]; - writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); - assertFalse(this.channel1.isRegistered()); - assertTrue(this.channel1.isBlocking()); - this.channel1.configureBlocking(false); - this.channel1.connect(localAddr1); - - assertFalse(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnected()); - assertTrue(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - assertTrue(tryFinish()); - assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf)); - assertEquals(CAPACITY_NORMAL, this.channel1 - .write(writeBufArr, 0, 1)); - - this.channel1.configureBlocking(false); - try { - this.channel1.connect(localAddr1); - fail("Should throw AlreadyConnectedException"); - } catch (AlreadyConnectedException e) { - // correct - } - - assertFalse(this.channel1.isRegistered()); - tryFinish(); - } - - /* - * Test method for 'SocketChannelImpl.finishConnect()' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - public void testCFII_Data_FinishConnect_nonBlocking() throws IOException { - ensureServerOpen(); - - java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer - .allocate(CAPACITY_NORMAL); - java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1]; - writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); - - this.channel1.configureBlocking(false); - try { - this.channel1.finishConnect(); - fail("Should throw NoConnectionPendingException"); - } catch (NoConnectionPendingException e) { - // correct - } - this.channel1.connect(localAddr1); - assertFalse(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnected()); - assertTrue(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - this.server1.accept(); - assertTrue(tryFinish()); - assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf)); - assertEquals(CAPACITY_NORMAL, this.channel1 - .write(writeBufArr, 0, 1)); - try { - this.channel1.connect(localAddr1); - fail("Should throw AlreadyConnectedException"); - } catch (AlreadyConnectedException e) { - // correct - } - - assertFalse(this.channel1.isRegistered()); - tryFinish(); - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "connect", - args = {java.net.SocketAddress.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies IOException", - method = "open", - args = {SocketAddress.class} - ) - }) - public void testCFII_Data_FinishConnect_AddrSetServerStartLater() - throws IOException { - ensureServerClosed(); - java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1]; - writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); - this.channel1.configureBlocking(false); - try { - SocketChannel.open(localAddr1); - fail("Should throw ConnectException"); - } catch (ConnectException e) { - // correct - } - assertTrue(this.channel1.isOpen()); - assertFalse(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnectionPending()); - this.channel1.configureBlocking(true); - try { - this.channel1.finishConnect(); - fail("Should throw NoConnectionPendingException"); - } catch (NoConnectionPendingException e) { - // correct - } - try { - this.channel1.connect(localAddr2); - fail("Should throw ConnectException"); - } catch (ConnectException e) { - // correct - } - - assertTrue(this.channel1.isBlocking()); - try { - this.channel1.finishConnect(); - fail("Should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // correct - } - assertFalse(this.channel1.isConnected()); - // finish after finish OK - assertFalse(this.channel1.isConnectionPending()); - this.channel1 = SocketChannel.open(); - this.channel1.configureBlocking(false); - this.channel1.connect(localAddr1); - assertFalse(this.channel1.isConnected()); - ensureServerOpen(); - // cannot connect? - assertFalse(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnected()); - assertTrue(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - try { - this.channel1.connect(localAddr1); - fail("Should throw ConnectionPendingException"); - } catch (ConnectionPendingException e) { - // correct - } - this.channel1.configureBlocking(true); - try { - this.channel1.connect(localAddr1); - fail("Should throw ConnectionPendingException"); - } catch (ConnectionPendingException e) { - // correct - } - tryFinish(); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - public void testCFII_Data_FinishConnect_ServerStartLater() - throws IOException { - ensureServerClosed(); - java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1]; - writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); - this.channel1.configureBlocking(true); - try { - this.channel1.finishConnect(); - fail("Should throw NoConnectionPendingException"); - } catch (NoConnectionPendingException e) { - // correct - } - try { - this.channel1.connect(localAddr1); - fail("Should throw ConnectException"); - } catch (ConnectException e) { - // correct - } - - try { - this.channel1.finishConnect(); - fail("Should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // correct - } - assertFalse(this.channel1.isConnected()); - // finish after finish OK - assertFalse(this.channel1.isConnectionPending()); - this.channel1 = SocketChannel.open(); - this.channel1.configureBlocking(false); - this.channel1.connect(localAddr1); - assertFalse(this.channel1.isConnected()); - ensureServerOpen(); - // cannot connect? - assertFalse(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnected()); - assertTrue(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - try { - this.channel1.connect(localAddr1); - fail("Should throw ConnectionPendingException"); - } catch (ConnectionPendingException e) { - // correct - } - this.channel1.configureBlocking(true); - try { - this.channel1.connect(localAddr1); - fail("Should throw ConnectionPendingException"); - } catch (ConnectionPendingException e) { - // correct - } - tryFinish(); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "finishConnect", - args = {} - ) - public void testCFII_Data_FinishConnect_Blocking() throws IOException { - ensureServerOpen(); - java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer - .allocate(CAPACITY_NORMAL); - java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1]; - writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); - this.channel1.configureBlocking(true); - try { - this.channel1.finishConnect(); - fail("Should throw NoConnectionPendingException"); - } catch (NoConnectionPendingException e) { - // correct - } - - this.channel1.connect(localAddr1); - - assertTrue(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - assertTrue(tryFinish()); - assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf)); - assertEquals(CAPACITY_NORMAL, this.channel1 - .write(writeBufArr, 0, 1)); - - try { - this.channel1.connect(localAddr1); - fail("Should throw AlreadyConnectedException"); - } catch (AlreadyConnectedException e) { - // correct - } - - assertFalse(this.channel1.isRegistered()); - tryFinish(); - } - - /** - * Regression test for Harmony-1947. - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify exceptions.", - method = "finishConnect", - args = {} - ) - public void test_finishConnect() throws Exception { - SocketAddress address = new InetSocketAddress("localhost", 2046); - - ServerSocketChannel theServerChannel = ServerSocketChannel.open(); - ServerSocket serversocket = theServerChannel.socket(); - serversocket.setReuseAddress(true); - // Bind the socket - serversocket.bind(address); - - boolean doneNonBlockingConnect = false; - // Loop so that we make sure we're definitely testing finishConnect() - while (!doneNonBlockingConnect) { - channel1 = SocketChannel.open(); - - // Set the SocketChannel to non-blocking so that connect(..) does - // not block - channel1.configureBlocking(false); - boolean connected = channel1.connect(address); - if (!connected) { - // Now set the SocketChannel back to blocking so that - // finishConnect() blocks. - channel1.configureBlocking(true); - doneNonBlockingConnect = channel1.finishConnect(); - } else { - fail("Non blocking connect was connected too fast." + - "Could not test finishConnect()."); - } - if (doneNonBlockingConnect) { - tryFinish(); - } else { - fail("finishConnect() did not finish the connection."); - } - channel1.close(); - } - if (!serversocket.isClosed()) { - serversocket.close(); - } - } - - // ------------------------------------------------------------------- - // End of original tests. Test method for CFII with real data. - // ------------------------------------------------------------------- - - /** - * @tests java.nio.channels.SocketChannel#read(ByteBuffer) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class} - ) - public void test_readLByteBuffer_Blocking() throws IOException { - // initialize write content - byte[] writeContent = new byte[CAPACITY_NORMAL]; - for (int i = 0; i < writeContent.length; i++) { - writeContent[i] = (byte) i; - } - // establish connection - channel1.connect(localAddr1); - Socket acceptedSocket = server1.accept(); - - // use OutputStream.write to send CAPACITY_NORMAL bytes data - OutputStream out = acceptedSocket.getOutputStream(); - out.write(writeContent); - // use close to guarantee all data is sent - acceptedSocket.close(); - - ByteBuffer readContent = ByteBuffer.allocate(CAPACITY_NORMAL + 1); - int totalCount = 0; - int count = 0; - long startTime = System.currentTimeMillis(); - // use SocketChannel.read to read data - while (totalCount <= CAPACITY_NORMAL) { - count = channel1.read(readContent); - if (EOF == count) { - break; - } - totalCount += count; - // if the channel could not finish reading in TIMEOUT ms, the - // test fails. It is used to guarantee the test never hangs even - // if there are bugs of SocketChannel implementation. For - // blocking read, it possibly returns 0 in some cases. - assertTimeout(startTime, TIMEOUT); - } - - // assert read content - assertEquals(CAPACITY_NORMAL, totalCount); - assertEquals(CAPACITY_NORMAL, readContent.position()); - readContent.flip(); - for (int i = 0; i < CAPACITY_NORMAL; i++) { - assertEquals(writeContent[i], readContent.get()); - } - } - - /** - * @tests java.nio.channels.SocketChannel#read(ByteBuffer) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class} - ) - public void test_readLByteBuffer_Nonblocking() throws IOException { - // initialize write content - byte[] writeContent = new byte[CAPACITY_NORMAL]; - for (int i = 0; i < writeContent.length; i++) { - writeContent[i] = (byte) i; - } - - // establish connection - channel1.connect(localAddr1); - Socket acceptedSocket = server1.accept(); - // use OutputStream.write to write CAPACITY_NORMAL bytes data. - OutputStream out = acceptedSocket.getOutputStream(); - out.write(writeContent); - // use close to guarantee all data is sent - acceptedSocket.close(); - - channel1.configureBlocking(false); - ByteBuffer readContent = ByteBuffer.allocate(CAPACITY_NORMAL + 1); - int totalCount = 0; - int count = 0; - long startTime = System.currentTimeMillis(); - // use SocketChannel.read to read data - while (totalCount <= CAPACITY_NORMAL) { - count = channel1.read(readContent); - if (EOF == count) { - break; - } - totalCount += count; - // if the channel could not finish reading in TIMEOUT ms, the - // test fails. It is used to guarantee the test never hangs even - // if there are bugs of SocketChannel implementation. - assertTimeout(startTime, TIMEOUT); - } - - // assert read content - assertEquals(CAPACITY_NORMAL, totalCount); - assertEquals(CAPACITY_NORMAL, readContent.position()); - readContent.flip(); - for (int i = 0; i < CAPACITY_NORMAL; i++) { - assertEquals(writeContent[i], readContent.get()); - } - } - - /** - * @tests java.nio.channels.SocketChannel#write(ByteBuffer) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer.class} - ) - public void test_writeLjava_nio_ByteBuffer_Blocking() throws IOException { - // initialize write content - ByteBuffer writeContent = ByteBuffer.allocate(CAPACITY_NORMAL); - for (int i = 0; i < CAPACITY_NORMAL; i++) { - writeContent.put((byte) i); - } - writeContent.flip(); - // establish connection - channel1.connect(localAddr1); - Socket acceptedSocket = server1.accept(); - - // use SocketChannel.write(ByteBuffer) to write CAPACITY_NORMAL bytes - // data - int writtenCount = channel1.write(writeContent); - // assert written count and ByteBuffer position - assertEquals(CAPACITY_NORMAL, writtenCount); - assertEquals(CAPACITY_NORMAL, writeContent.position()); - // use close to guarantee all data is sent - channel1.close(); - - InputStream in = acceptedSocket.getInputStream(); - int totalCount = 0; - int count = 0; - byte[] readContent = new byte[CAPACITY_NORMAL + 1]; - // if the channel could not finish reading in TIMEOUT ms, the test - // fails. It is used to guarantee the test never hangs even if there - // are bugs of SocketChannel implementation. - acceptedSocket.setSoTimeout(TIMEOUT); - - // use InputStream.read to read data. - while (totalCount <= CAPACITY_NORMAL) { - count = in.read(readContent, totalCount, readContent.length - - totalCount); - if (EOF == count) { - break; - } - totalCount += count; - } - - // assert read content - assertEquals(CAPACITY_NORMAL, totalCount); - writeContent.flip(); - for (int i = 0; i < CAPACITY_NORMAL; i++) { - assertEquals(writeContent.get(), readContent[i]); - } - } - - /** - * @tests java.nio.channels.SocketChannel#write(ByteBuffer) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer.class} - ) - public void test_writeLjava_nio_ByteBuffer_NonBlocking() throws Exception { - // initialize write content - ByteBuffer writeContent = ByteBuffer.allocate(CAPACITY_NORMAL); - for (int i = 0; i < CAPACITY_NORMAL; i++) { - writeContent.put((byte) i); - } - writeContent.flip(); - - // establish connection - channel1.connect(localAddr1); - Socket acceptedSocket = server1.accept(); - - channel1.configureBlocking(false); - int writtenTotalCount = 0; - int writtenCount = 0; - long startTime = System.currentTimeMillis(); - // use SocketChannel.write(ByteBuffer) to write CAPACITY_NORMAL bytes - while (writtenTotalCount < CAPACITY_NORMAL) { - writtenCount = channel1.write(writeContent); - writtenTotalCount += writtenCount; - // if the channel could not finish writing in TIMEOUT ms, the - // test fails. It is used to guarantee the test never hangs even - // if there are bugs of SocketChannel implementation. - assertTimeout(startTime, TIMEOUT); - } - // assert written count and ByteBuffer position - assertEquals(CAPACITY_NORMAL, writtenTotalCount); - assertEquals(CAPACITY_NORMAL, writeContent.position()); - // use close to guarantee all data is sent - channel1.close(); - - InputStream in = acceptedSocket.getInputStream(); - byte[] readContent = new byte[CAPACITY_NORMAL + 1]; - int totalCount = 0; - int count = 0; - // if the channel could not finish reading in TIMEOUT ms, the test - // fails. It is used to guarantee the test never hangs even if there - // are bugs of SocketChannel implementation. - acceptedSocket.setSoTimeout(TIMEOUT); - // use InputStream.read to read data. - while (totalCount <= CAPACITY_NORMAL) { - count = in.read(readContent, totalCount, readContent.length - - totalCount); - if (EOF == count) { - break; - } - totalCount += count; - } - // assert read content - assertEquals(CAPACITY_NORMAL, totalCount); - writeContent.flip(); - for (int i = 0; i < CAPACITY_NORMAL; i++) { - assertEquals(writeContent.get(), readContent[i]); - } - } - - /** - * @tests java.nio.channels.SocketChannel#read(ByteBuffer) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer.class} - ) - @BrokenTest("Occasionally fail in CTS, but works in CoreTestRunner") - public void test_writeLjava_nio_ByteBuffer_Nonblocking_HugeData() throws IOException { - // initialize write content - ByteBuffer writeContent = ByteBuffer.allocate(CAPACITY_HUGE); - for (int i = 0; i < CAPACITY_HUGE; i++) { - writeContent.put((byte) i); - } - writeContent.flip(); - - // establish connection - channel1.connect(localAddr1); - Socket acceptedSocket = server1.accept(); - - channel1.configureBlocking(false); - int writtenTotalCount = 0; - int writtenCount = 1; - long startTime = System.currentTimeMillis(); - // use SocketChannel.write(ByteBuffer) to try to write CAPACITY_HUGE bytes - while (writtenTotalCount < CAPACITY_HUGE && writtenCount > 0) { - writtenCount = channel1.write(writeContent); - if (writtenCount == 0 && writtenTotalCount < CAPACITY_HUGE) { - assertEquals(0, channel1.write(writeContent)); - break; - } - writtenTotalCount += writtenCount; - // if the channel could not finish writing in TIMEOUT ms, the - // test fails. It is used to guarantee the test never hangs even - // if there are bugs of SocketChannel implementation. - assertTimeout(startTime, TIMEOUT); - } - } - - /* - * Fails if the difference between current time and start time is greater - * than timeout. - */ - private void assertTimeout(long startTime, long timeout) { - long currentTime = System.currentTimeMillis(); - if ((currentTime - startTime) > timeout) { - fail("Timeout"); - } - } - - // ------------------------------------------------- - // Test for read/write but no real data expressed - // ------------------------------------------------- - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies ClosedChannelException", - method = "read", - args = {java.nio.ByteBuffer.class} - ) - public void testReadByteBuffer() throws Exception { - assertTrue(this.server1.isBound()); - java.nio.ByteBuffer readBuf = java.nio.ByteBuffer - .allocate(CAPACITY_NORMAL); - assertFalse(this.channel1.isRegistered()); - assertTrue(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - // note: blocking-mode will make the read process endless! - this.channel1.configureBlocking(false); - try { - channel1.read(readBuf); - fail("Should throw NotYetConnectedException"); - } catch (NotYetConnectedException e) { - // correct - } - this.channel1.connect(localAddr1); - assertFalse(this.channel1.isBlocking()); - assertTrue(this.channel1.isConnectionPending()); - assertFalse(this.channel1.isConnected()); - assertTrue(tryFinish()); - assertEquals(0, this.channel1.read(readBuf)); - - this.channel1.close(); - try { - channel1.read(readBuf); - fail("Should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // correct - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies ClosedChannelException", - method = "read", - args = {java.nio.ByteBuffer.class} - ) - public void testReadByteBuffer_Direct() throws Exception { - assertTrue(this.server1.isBound()); - java.nio.ByteBuffer readBuf = java.nio.ByteBuffer - .allocateDirect(CAPACITY_NORMAL); - assertFalse(this.channel1.isRegistered()); - assertTrue(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - // note: blocking-mode will make the read process endless! - this.channel1.configureBlocking(false); - try { - channel1.read(readBuf); - fail("Should throw NotYetConnectedException"); - } catch (NotYetConnectedException e) { - // correct - } - this.channel1.connect(localAddr1); - assertFalse(this.channel1.isBlocking()); - assertTrue(this.channel1.isConnectionPending()); - assertFalse(this.channel1.isConnected()); - assertTrue(tryFinish()); - assertEquals(0, this.channel1.read(readBuf)); - - this.channel1.close(); - try { - channel1.read(readBuf); - fail("Should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // correct - } - } - - public void testReadByteBuffer_Direct2() throws IOException { - byte[] request = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - ByteBuffer buffer = ByteBuffer.allocateDirect(128); - - ServerSocketChannel server = ServerSocketChannel.open(); - server.socket().bind( - new InetSocketAddress(InetAddress.getLocalHost(), 0), 5); - Socket client = new Socket(InetAddress.getLocalHost(), server.socket() - .getLocalPort()); - client.setTcpNoDelay(false); - Socket worker = server.socket().accept(); - SocketChannel workerChannel = worker.getChannel(); - - OutputStream out = client.getOutputStream(); - out.write(request); - out.close(); - - buffer.limit(5); - int bytesRead = workerChannel.read(buffer); - assertEquals(5, bytesRead); - assertEquals(5, buffer.position()); - - buffer.limit(request.length); - bytesRead = workerChannel.read(buffer); - assertEquals(6, bytesRead); - - buffer.flip(); - assertEquals(request.length, buffer.limit()); - - assertEquals(ByteBuffer.wrap(request), buffer); - - client.close(); - worker.close(); - server.close(); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer.class} - ) - public void testReadByteBuffer_BufNull() throws Exception { - assertTrue(this.server1.isBound()); - java.nio.ByteBuffer readBuf = java.nio.ByteBuffer.allocate(0); - // note: blocking-mode will make the read process endless! - this.channel1.configureBlocking(false); - try { - channel1.read((java.nio.ByteBuffer) null); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - this.channel1.connect(localAddr1); - assertTrue(tryFinish()); - try { - this.channel1.read((java.nio.ByteBuffer) null); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - assertEquals(0, this.channel1.read(readBuf)); - } - - /* - * SocketChannelImpl.read(ByteBuffer[], int, int)' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void testReadByteBufferArrayIntInt() throws Exception { - assertTrue(this.server1.isBound()); - java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[2]; - readBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); - readBuf[1] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); - assertFalse(this.channel1.isRegistered()); - assertTrue(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - // note: blocking-mode will make the read process endless! - this.channel1.configureBlocking(false); - try { - channel1.read(readBuf, 0, 1); - fail("Should throw NotYetConnectedException"); - } catch (NotYetConnectedException e) { - // correct - } - this.channel1.connect(localAddr1); - assertFalse(this.channel1.isBlocking()); - assertTrue(this.channel1.isConnectionPending()); - assertFalse(this.channel1.isConnected()); - assertTrue(tryFinish()); - assertEquals(0, this.channel1.read(readBuf, 0, 1)); - assertEquals(0, this.channel1.read(readBuf, 0, 2)); - - this.channel1.close(); - try { - channel1.read(readBuf, 0, 1); - fail("Should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // correct - } - } - - /* - * SocketChannelImpl.read(ByteBuffer[], int, int)' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void testReadByteBufferArrayIntInt_Direct() throws Exception { - assertTrue(this.server1.isBound()); - java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[2]; - readBuf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL); - readBuf[1] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL); - assertFalse(this.channel1.isRegistered()); - assertTrue(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - // note: blocking-mode will make the read process endless! - this.channel1.configureBlocking(false); - try { - channel1.read(readBuf, 0, 1); - fail("Should throw NotYetConnectedException"); - } catch (NotYetConnectedException e) { - // correct - } - this.channel1.connect(localAddr1); - assertFalse(this.channel1.isBlocking()); - assertTrue(this.channel1.isConnectionPending()); - assertFalse(this.channel1.isConnected()); - assertTrue(tryFinish()); - assertEquals(0, this.channel1.read(readBuf, 0, 1)); - assertEquals(0, this.channel1.read(readBuf, 0, 2)); - - this.channel1.close(); - try { - channel1.read(readBuf, 0, 1); - fail("Should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // correct - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void testReadByteBufferArrayIntInt_BufNull() throws Exception { - assertTrue(this.server1.isBound()); - java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[2]; - readBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); - assertFalse(this.channel1.isRegistered()); - assertTrue(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - // note: blocking-mode will make the read process endless! - this.channel1.configureBlocking(false); - try { - channel1.read(null, 0, 0); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - this.channel1.connect(localAddr1); - assertTrue(tryFinish()); - - try { - channel1.read(null, 0, 0); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - try { - channel1.read(readBuf, 0, 2); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - - assertEquals(0, this.channel1.read(readBuf, 0, 1)); - - this.channel1.close(); - try { - channel1.read(null, 0, 1); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer.class} - ) - public void testWriteByteBuffer() throws IOException { - assertTrue(this.server1.isBound()); - java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer - .allocate(CAPACITY_NORMAL); - assertFalse(this.channel1.isRegistered()); - assertTrue(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - try { - channel1.write(writeBuf); - fail("Should throw NotYetConnectedException"); - } catch (NotYetConnectedException e) { - // correct - } - this.channel1.connect(localAddr1); - assertTrue(this.channel1.isBlocking()); - assertTrue(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf)); - - this.channel1.close(); - try { - channel1.write(writeBuf); - fail("Should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // correct - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify AsynchronousCloseException, ClosedByInterruptException.", - method = "write", - args = {java.nio.ByteBuffer.class} - ) - public void testWriteByteBuffer_Direct() throws IOException { - assertTrue(this.server1.isBound()); - java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer - .allocateDirect(CAPACITY_NORMAL); - assertFalse(this.channel1.isRegistered()); - assertTrue(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - try { - channel1.write(writeBuf); - fail("Should throw NotYetConnectedException"); - } catch (NotYetConnectedException e) { - // correct - } - this.channel1.connect(localAddr1); - assertTrue(this.channel1.isBlocking()); - assertTrue(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf)); - - this.channel1.close(); - try { - channel1.write(writeBuf); - fail("Should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // correct - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer.class} - ) - public void testWriteByteBuffer_BufNull() throws IOException { - assertTrue(this.server1.isBound()); - java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer.allocate(0); - this.channel1.connect(localAddr1); - assertEquals(this.channel1.write(writeBuf), 0); - try { - this.channel1.write((java.nio.ByteBuffer) null); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - } - - /* - * SocketChannelImpl.write(ByteBuffer[], int, int)' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify AsynchronousCloseException," + - "ClosedByInterruptException.", - method = "write", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void testWriteByteBufferArrayIntInt() throws IOException { - java.nio.ByteBuffer[] writeBuf = new java.nio.ByteBuffer[2]; - writeBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); - writeBuf[1] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); - assertFalse(this.channel1.isRegistered()); - assertTrue(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - try { - channel1.write(writeBuf, 0, 1); - fail("Should throw NotYetConnectedException"); - } catch (NotYetConnectedException e) { - // correct - } - this.channel1.connect(localAddr1); - assertTrue(this.channel1.isBlocking()); - assertTrue(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 1)); - // still writes the same size as above - assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 2)); - writeBuf[0].flip(); - writeBuf[1].flip(); - assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2)); - this.channel1.close(); - try { - channel1.write(writeBuf, 0, 1); - fail("Should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // correct - } - } - - /* - * SocketChannelImpl.write(ByteBuffer[], int, int)' - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void testWriteByteBufferArrayIntInt_Direct() throws IOException { - java.nio.ByteBuffer[] writeBuf = new java.nio.ByteBuffer[2]; - writeBuf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL); - writeBuf[1] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL); - assertFalse(this.channel1.isRegistered()); - assertTrue(this.channel1.isBlocking()); - assertFalse(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - try { - channel1.write(writeBuf, 0, 1); - fail("Should throw NotYetConnectedException"); - } catch (NotYetConnectedException e) { - // correct - } - this.channel1.connect(localAddr1); - assertTrue(this.channel1.isBlocking()); - assertTrue(this.channel1.isConnected()); - assertFalse(this.channel1.isConnectionPending()); - assertTrue(this.channel1.isOpen()); - assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 1)); - // still writes the same size as above - assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 2)); - writeBuf[0].flip(); - writeBuf[1].flip(); - assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2)); - this.channel1.close(); - try { - channel1.write(writeBuf, 0 ,1); - fail("Should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // correct - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void testWriteByteBufferArrayIntInt_BufNull() throws IOException { - java.nio.ByteBuffer[] writeBuf = new java.nio.ByteBuffer[0]; - - this.channel1.connect(localAddr1); - try { - this.channel1.write(null, 0, 1); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - assertEquals(0, this.channel1.write(writeBuf, 0, 0)); - try { - this.channel1.write(writeBuf, 0, 1); - fail("Should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // correct - } - writeBuf = new java.nio.ByteBuffer[1]; - try { - this.channel1.write(writeBuf, 0, 1); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - writeBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL); - try { - this.channel1.write(writeBuf, 0, 2); - fail("Should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // correct - } - this.server1.close(); - try { - channel1.read(null, 0, 1); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // correct - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies IndexOutOfBoundsException.", - method = "write", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void testWriteByteBufferArrayIntInt_SizeError() throws IOException { - java.nio.ByteBuffer[] writeBuf = - {java.nio.ByteBuffer.allocate(CAPACITY_NORMAL)}; - - this.channel1.connect(localAddr1); - try { - this.channel1.write(writeBuf, -1, 1); - fail("Should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // correct - } - assertEquals(0, this.channel1.write(writeBuf, 0, 0)); - try { - this.channel1.write(writeBuf, 0, -1); - fail("Should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // correct - } - try { - this.channel1.write(writeBuf, 1, 1); - fail("Should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // correct - } - try { - this.channel1.write(writeBuf, 0, 2); - fail("Should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // correct - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void testReadByteBufferArrayIntInt_SizeError() throws IOException { - java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[0]; - - this.channel1.connect(localAddr1); - try { - this.channel1.read(null, -1, 1); - fail("Should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // correct - } - assertEquals(0, this.channel1.read(readBuf, 0, 0)); - try { - this.channel1.read(readBuf, 0, -1); - fail("Should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // correct - } - readBuf = new java.nio.ByteBuffer[1]; - try { - this.channel1.read(readBuf, 2, 1); - fail("Should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // correct - } - try { - this.channel1.read(readBuf, 2, -1); - fail("Should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // correct - } - this.server1.close(); - try { - assertEquals(CAPACITY_NORMAL, this.channel1.read(null, -1, -1)); - fail("Should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // correct - } - } - - /* - * ========================================================================== - * Tests for read/write real data - * ========================================================================== - */ - - - /** - * @tests java.nio.channels.SocketChannel#read(ByteBuffer[]) - */ - public void test_read$LByteBuffer() throws IOException { - MockSocketChannel sc = new MockSocketChannel(null); - ByteBuffer [] byteBufferArray = { ByteBuffer.allocate(1), ByteBuffer.allocate(1)}; - // Verify that calling read(ByteBuffer[]) leads to the method - // read(ByteBuffer[], int, int) being called with a 0 for the - // second parameter and targets.length as the third parameter. - sc.read(byteBufferArray); - assertTrue(sc.isReadCalled); - } - - /** - * @tests java.nio.channels.SocketChannel#read(ByteBuffer[],int,int) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class} - ) - public void test_read$LByteBuffer_blocking() throws Exception { - assert_read$LByteBuffer(true); - } - - /** - * @tests java.nio.channels.SocketChannel#read(ByteBuffer[],int,int) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class} - ) - public void test_read$LByteBuffer_nonblocking() throws Exception { - assert_read$LByteBuffer(false); - } - - private void assert_read$LByteBuffer(boolean isBlocking) throws IOException { - // initialize write content - byte[] writeContent = new byte[CAPACITY_NORMAL * 2]; - for (int i = 0; i < CAPACITY_NORMAL * 2; i++) { - writeContent[i] = (byte) i; - } - ByteBuffer[] readContents = new ByteBuffer[2]; - readContents[0] = ByteBuffer.allocate(CAPACITY_NORMAL); - readContents[1] = ByteBuffer.allocate(CAPACITY_NORMAL + 1); - // establish connection - channel1.connect(localAddr1); - Socket acceptedSocket = server1.accept(); - // use OutputStream.write to send CAPACITY_NORMAL * 2 bytes data - OutputStream out = acceptedSocket.getOutputStream(); - out.write(writeContent); - // use close to guarantee all data is sent - acceptedSocket.close(); - // configure block/nonblock mode - channel1.configureBlocking(isBlocking); - long startTime = System.currentTimeMillis(); - long totalRead = 0; - long countRead = 0; - - while (totalRead <= CAPACITY_NORMAL * 2) { - countRead = channel1.read(readContents); - if (0 == countRead && !readContents[1].hasRemaining()) { - // read returns 0 because readContents is full - break; - } - if (EOF == countRead) { - break; - } - totalRead += countRead; - // if the channel could not finish reading in TIMEOUT ms, the - // test fails. It is used to guarantee the test never hangs even - // if there are bugs of SocketChannel implementation. For - // blocking read, it possibly returns 0 in some cases. - assertTimeout(startTime, TIMEOUT); - } - - // assert total bytes read and the position of ByteBuffers - assertEquals(CAPACITY_NORMAL * 2, totalRead); - assertEquals(CAPACITY_NORMAL, readContents[0].position()); - assertEquals(CAPACITY_NORMAL, readContents[1].position()); - // assert read content - readContents[0].flip(); - readContents[1].flip(); - for (int i = 0; i < CAPACITY_NORMAL; i++) { - assertEquals(writeContent[i], readContents[0].get()); - } - for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) { - assertEquals(writeContent[i], readContents[1].get()); - } - } - - /** - * @tests java.nio.channels.SocketChannel#read(ByteBuffer[],int,int) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void test_read$LByteBufferII_blocking() throws Exception { - assert_read$LByteBufferII(true); - } - - /** - * @tests java.nio.channels.SocketChannel#read(ByteBuffer[],int,int) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void test_read$LByteBufferII_nonblocking() throws Exception { - assert_read$LByteBufferII(false); - } - - private void assert_read$LByteBufferII(boolean isBlocking) throws IOException { - // initialize write content - byte[] writeContent = new byte[CAPACITY_NORMAL * 2]; - for (int i = 0; i < CAPACITY_NORMAL * 2; i++) { - writeContent[i] = (byte) i; - } - ByteBuffer[] readContents = new ByteBuffer[2]; - readContents[0] = ByteBuffer.allocate(CAPACITY_NORMAL); - readContents[1] = ByteBuffer.allocate(CAPACITY_NORMAL + 1); - // establish connection - channel1.connect(localAddr1); - Socket acceptedSocket = server1.accept(); - // use OutputStream.write to send CAPACITY_NORMAL * 2 bytes data - OutputStream out = acceptedSocket.getOutputStream(); - out.write(writeContent); - // use close to guarantee all data is sent - acceptedSocket.close(); - // configure block/nonblock mode - channel1.configureBlocking(isBlocking); - long startTime = System.currentTimeMillis(); - long totalRead = 0; - long countRead = 0; - - while (totalRead <= CAPACITY_NORMAL * 2) { - countRead = channel1.read(readContents, 0, 2); - if (0 == countRead && !readContents[1].hasRemaining()) { - // read returns 0 because readContents is full - break; - } - if (EOF == countRead) { - break; - } - totalRead += countRead; - // if the channel could not finish reading in TIMEOUT ms, the - // test fails. It is used to guarantee the test never hangs even - // if there are bugs of SocketChannel implementation. For - // blocking read, it possibly returns 0 in some cases. - assertTimeout(startTime, TIMEOUT); - } - - // assert total bytes read and the position of ByteBuffers - assertEquals(CAPACITY_NORMAL * 2, totalRead); - assertEquals(CAPACITY_NORMAL, readContents[0].position()); - assertEquals(CAPACITY_NORMAL, readContents[1].position()); - // assert read content - readContents[0].flip(); - readContents[1].flip(); - for (int i = 0; i < CAPACITY_NORMAL; i++) { - assertEquals(writeContent[i], readContents[0].get()); - } - for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) { - assertEquals(writeContent[i], readContents[1].get()); - } - } - - /** - * @tests java.nio.channels.SocketChannel#write(ByteBuffer[],int,int) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer[].class} - ) - public void test_write$LByteBuffer_blocking() throws Exception { - assert_write$LByteBuffer(true); - } - - /** - * @tests java.nio.channels.SocketChannel#write(ByteBuffer[],int,int) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer[].class} - ) - public void test_write$LByteBuffer_nonblocking() throws Exception { - assert_write$LByteBuffer(false); - } - - private void assert_write$LByteBuffer(boolean isBlocking) - throws IOException { - // initialize write contents - ByteBuffer writeContents[] = new ByteBuffer[2]; - writeContents[0] = ByteBuffer.allocate(CAPACITY_NORMAL); - writeContents[1] = ByteBuffer.allocate(CAPACITY_NORMAL); - for (int i = 0; i < CAPACITY_NORMAL; i++) { - writeContents[0].put((byte) i); - } - for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) { - writeContents[1].put((byte) i); - } - writeContents[0].flip(); - writeContents[1].flip(); - // establish connection - channel1.connect(localAddr1); - Socket acceptedSocket = server1.accept(); - // set blocking/nonblocking mode - channel1.configureBlocking(isBlocking); - - assertEquals(2 * CAPACITY_NORMAL, channel1.write(writeContents)); - - // assert written count and ByteBuffer position - assertEquals(CAPACITY_NORMAL, writeContents[0].position()); - assertEquals(CAPACITY_NORMAL, writeContents[1].position()); - // use close to guarantee all data is sent - channel1.close(); - InputStream in = acceptedSocket.getInputStream(); - byte[] readContent = new byte[CAPACITY_NORMAL * 2 + 1]; - int totalCount = 0; - int count = 0; - // if the channel could not finish reading in TIMEOUT ms, the test - // fails. It is used to guarantee the test never hangs even if there - // are bugs of SocketChannel implementation. - acceptedSocket.setSoTimeout(TIMEOUT); - // use InputStream.read to read data. - while (totalCount <= CAPACITY_NORMAL) { - count = in.read(readContent, totalCount, readContent.length - - totalCount); - if (EOF == count) { - break; - } - totalCount += count; - } - // assert read content - assertEquals(CAPACITY_NORMAL * 2, totalCount); - writeContents[0].flip(); - writeContents[1].flip(); - for (int i = 0; i < CAPACITY_NORMAL; i++) { - assertEquals(writeContents[0].get(), readContent[i]); - } - for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) { - assertEquals(writeContents[1].get(), readContent[i]); - } - } - - /** - * @tests java.nio.channels.SocketChannel#write(ByteBuffer[]) - */ - public void test_write$LByteBuffer() throws IOException { - MockSocketChannel sc = new MockSocketChannel(null); - ByteBuffer [] byteBufferArray = { ByteBuffer.allocate(1), ByteBuffer.allocate(1)}; - // Verify that calling write(ByteBuffer[]) leads to the method - // write(ByteBuffer[], int, int) being called with a 0 for the - // second parameter and sources.length as the third parameter. - sc.write(byteBufferArray); - assertTrue(sc.isWriteCalled); - } - - /** - * @tests java.nio.channels.SocketChannel#write(ByteBuffer[],int,int) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void test_write$LByteBufferII_blocking() throws Exception { - assert_write$LByteBufferII(true); - } - - /** - * @tests java.nio.channels.SocketChannel#write(ByteBuffer[],int,int) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void test_write$LByteBufferII_nonblocking() throws Exception { - assert_write$LByteBufferII(false); - } - - private void assert_write$LByteBufferII(boolean isBlocking) - throws IOException { - // initialize write contents - ByteBuffer writeContents[] = new ByteBuffer[2]; - writeContents[0] = ByteBuffer.allocate(CAPACITY_NORMAL); - writeContents[1] = ByteBuffer.allocate(CAPACITY_NORMAL); - for (int i = 0; i < CAPACITY_NORMAL; i++) { - writeContents[0].put((byte) i); - } - for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) { - writeContents[1].put((byte) i); - } - writeContents[0].flip(); - writeContents[1].flip(); - // establish connection - channel1.connect(localAddr1); - Socket acceptedSocket = server1.accept(); - // set blocking/nonblocking mode - channel1.configureBlocking(isBlocking); - - assertEquals(CAPACITY_NORMAL, channel1.write(writeContents, 0, 1)); - assertEquals(CAPACITY_NORMAL, channel1.write(writeContents, 1, 1)); - - // assert written count and ByteBuffer position - assertEquals(CAPACITY_NORMAL, writeContents[0].position()); - assertEquals(CAPACITY_NORMAL, writeContents[1].position()); - // use close to guarantee all data is sent - channel1.close(); - InputStream in = acceptedSocket.getInputStream(); - byte[] readContent = new byte[CAPACITY_NORMAL * 2 + 1]; - int totalCount = 0; - int count = 0; - // if the channel could not finish reading in TIMEOUT ms, the test - // fails. It is used to guarantee the test never hangs even if there - // are bugs of SocketChannel implementation. - acceptedSocket.setSoTimeout(TIMEOUT); - // use InputStream.read to read data. - while (totalCount <= CAPACITY_NORMAL) { - count = in.read(readContent, totalCount, readContent.length - - totalCount); - if (EOF == count) { - break; - } - totalCount += count; - } - // assert read content - assertEquals(CAPACITY_NORMAL * 2, totalCount); - writeContents[0].flip(); - writeContents[1].flip(); - for (int i = 0; i < CAPACITY_NORMAL; i++) { - assertEquals(writeContents[0].get(), readContent[i]); - } - for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) { - assertEquals(writeContents[1].get(), readContent[i]); - } - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "socket", - args = {} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - clazz = SelectableChannel.class, - method = "configureBlocking", - args = {boolean.class} - ) - }) - public void testSocket_configureblocking() throws IOException { - byte[] serverWBuf = new byte[CAPACITY_NORMAL]; - for (int i = 0; i < serverWBuf.length; i++) { - serverWBuf[i] = (byte) i; - } - java.nio.ByteBuffer buf = java.nio.ByteBuffer - .allocate(CAPACITY_NORMAL + 1); - channel1.connect(localAddr1); - server1.accept(); - Socket sock = this.channel1.socket(); - channel1.configureBlocking(false); - assertFalse(channel1.isBlocking()); - OutputStream channelSocketOut = sock.getOutputStream(); - try { - // write operation is not allowed in non-blocking mode - channelSocketOut.write(buf.array()); - fail("Non-Blocking mode should cause IllegalBlockingModeException"); - } catch (IllegalBlockingModeException e) { - // correct - } - channel1.configureBlocking(true); - assertTrue(channel1.isBlocking()); - // write operation is allowed in blocking mode - channelSocketOut.write(buf.array()); - } - - /** - * @tests SocketChannel#read(ByteBuffer[], int, int) when remote server - * closed - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void test_socketChannel_read_ByteBufferII_remoteClosed() - throws Exception { - // regression 1 for HARMONY-549 - ServerSocketChannel ssc = ServerSocketChannel.open(); - ssc.socket().bind(localAddr2); - SocketChannel sc = SocketChannel.open(); - sc.connect(localAddr2); - ssc.accept().close(); - ByteBuffer[] buf = {ByteBuffer.allocate(10)}; - assertEquals(-1, sc.read(buf, 0, 1)); - ssc.close(); - sc.close(); - } - - /** - * @tests SocketChannel#write(ByteBuffer[], int, int) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void test_socketChannel_write_ByteBufferII() throws Exception { - // regression 2 for HARMONY-549 - ServerSocketChannel ssc = ServerSocketChannel.open(); - ssc.socket().bind(localAddr2); - SocketChannel sc = SocketChannel.open(); - sc.connect(localAddr2); - SocketChannel sock = ssc.accept(); - ByteBuffer[] buf = {ByteBuffer.allocate(10), null}; - try { - sc.write(buf, 0, 2); - fail("should throw NPE"); - } catch (NullPointerException e) { - // expected - } - ssc.close(); - sc.close(); - ByteBuffer target = ByteBuffer.allocate(10); - assertEquals(-1, sock.read(target)); - } - - /** - * @tests SocketChannel#read(ByteBuffer[], int, int) with a null ByteBuffer - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class, int.class, int.class} - ) - public void test_socketChannel_read_ByteBufferII_bufNULL() throws Exception { - // regression 3 for HARMONY-549 - ServerSocketChannel ssc = ServerSocketChannel.open(); - ssc.socket().bind(localAddr2); - SocketChannel sc = SocketChannel.open(); - sc.connect(localAddr2); - ssc.accept(); - ByteBuffer[] buf = new ByteBuffer[2]; - buf[0] = ByteBuffer.allocate(1); - // let buf[1] be null - try { - sc.read(buf, 0, 2); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - ssc.close(); - sc.close(); - } - - /** - * @tests SocketChannel#write(ByteBuffer) after close - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer.class} - ) - public void test_socketChannel_write_close() throws Exception { - // regression 4 for HARMONY-549 - ServerSocketChannel ssc = ServerSocketChannel.open(); - ssc.socket().bind(localAddr2); - SocketChannel sc = SocketChannel.open(); - sc.connect(localAddr2); - SocketChannel sock = ssc.accept(); - ByteBuffer buf = null; - ssc.close(); - sc.close(); - try { - sc.write(buf); - fail("should throw NPE"); - } catch (NullPointerException e) { - // expected - } - sock.close(); - } - - /** - * @tests SocketChannel#write(ByteBuffer) if position is not zero - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "write", - args = {java.nio.ByteBuffer.class} - ) - public void test_socketChannel_write_ByteBuffer_posNotZero() - throws Exception { - // regression 5 for HARMONY-549 - final String testStr = "Hello World"; - ByteBuffer readBuf = ByteBuffer.allocate(11); - ByteBuffer buf = ByteBuffer.wrap(testStr.getBytes()); - ServerSocketChannel ssc = ServerSocketChannel.open(); - ssc.socket().bind(localAddr2); - SocketChannel sc = SocketChannel.open(); - sc.connect(localAddr2); - buf.position(2); - ssc.accept().write(buf); - assertEquals(9, sc.read(readBuf)); - buf.flip(); - readBuf.flip(); - byte[] read = new byte[9]; - byte[] write = new byte[11]; - buf.get(write); - readBuf.get(read); - for (int i = 0; i < 9; i++) { - assertEquals(read[i], write[i + 2]); - } - } - - /** - * @tests SocketChannelImpl#read(ByteBuffer[]) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify exceptions.", - method = "read", - args = {java.nio.ByteBuffer[].class} - ) - public void test_read$LByteBuffer_Blocking() throws IOException { - // regression test for Harmony-728 - byte[] data = new byte[CAPACITY_NORMAL]; - for (int i = 0; i < CAPACITY_NORMAL; i++) { - data[i] = (byte) i; - } - ByteBuffer[] buf = new ByteBuffer[2]; - buf[0] = ByteBuffer.allocate(CAPACITY_NORMAL); - buf[1] = ByteBuffer.allocate(CAPACITY_NORMAL); - channel1.connect(localAddr1); - Socket socket = null; - try { - socket = server1.accept(); - OutputStream out = socket.getOutputStream(); - out.write(data); - // should not block here - channel1.read(buf); - } finally { - if (null != socket) { - socket.close(); - } else { - fail(); - } - } - } - - /** - * @tests SocketChannelImpl#socket().getOutputStream().read - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies IllegalBlockingModeException, NullPointerException.", - method = "socket", - args = {} - ) - public void test_socket_getOutputStream_nonBlocking_read_Exception() - throws IOException { - channel1.connect(this.localAddr1); - InputStream is = channel1.socket().getInputStream(); - channel1.configureBlocking(false); - try { - is.read(); - fail("should throw IllegalBlockingModeException"); - } catch (IllegalBlockingModeException e) { - // expected - } - try { - is.read(null, 1, 1); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - is.read(null, -1, 1); - fail("should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // expected - } - // closed - is.close(); - try { - is.read(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - is.read(); - fail("should throw IllegalBlockingModeException"); - } catch (IllegalBlockingModeException e) { - // expected - } - try { - is.read(null, 1, 1); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - is.read(null, -1, 1); - fail("should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // expected - } - } - - /** - * @tests SocketChannelImpl#socket().getOutputStream().read - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NullPointerException, ClosedChannelException, IndexOutOfBoundsException.", - method = "socket", - args = {} - ) - public void test_socket_getOutputStream_blocking_read_Exception() - throws IOException { - channel1.connect(this.localAddr1); - InputStream is = channel1.socket().getInputStream(); - try { - is.read(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - is.read(null, 1, 1); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - is.read(null, -1, 1); - fail("should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // expected - } - // closed - is.close(); - try { - is.read(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - is.read(); - fail("should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // expected - } - try { - is.read(null, 1, 1); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - is.read(null, -1, 1); - fail("should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // expected - } - } - - /** - * @tests SocketChannelImpl#socket().getOutputStream().write - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NullPointerException, IllegalBlockingModeException.", - method = "socket", - args = {} - ) - public void test_socket_getOutputStream_nonBlocking_write_Exception() - throws IOException { - channel1.connect(this.localAddr1); - OutputStream os = channel1.socket().getOutputStream(); - channel1.configureBlocking(false); - try { - os.write(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - os.write(1); - fail("should throw IllegalBlockingModeException"); - } catch (IllegalBlockingModeException e) { - // expected - } - try { - os.write(1); - fail("should throw IllegalBlockingModeException"); - } catch (IllegalBlockingModeException e) { - // expected - } - try { - os.write(null, 1, 1); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - os.write(null, -1, 1); - fail("should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // expected - } - // closed - os.close(); - try { - os.write(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - os.write(1); - fail("should throw IllegalBlockingModeException"); - } catch (IllegalBlockingModeException e) { - // expected - } - try { - os.write(null, 1, 1); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - os.write(null, -1, 1); - fail("should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // expected - } - } - - /** - * @tests SocketChannelImpl#socket().getOutputStream().write - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NullPointerException, IndexOutOfBoundsException, ClosedChannelException.", - method = "socket", - args = {} - ) - public void test_socket_getOutputStream_blocking_write_Exception() - throws IOException { - channel1.connect(this.localAddr1); - OutputStream os = channel1.socket().getOutputStream(); - try { - os.write(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - os.write(null, 1, 1); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - os.write(null, -1, 1); - fail("should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // expected - } - // closed - os.close(); - try { - os.write(null); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - os.write(1); - fail("should throw ClosedChannelException"); - } catch (ClosedChannelException e) { - // expected - } - try { - os.write(null, 1, 1); - fail("should throw NullPointerException"); - } catch (NullPointerException e) { - // expected - } - try { - os.write(null, -1, 1); - fail("should throw IndexOutOfBoundsException"); - } catch (IndexOutOfBoundsException e) { - // expected - } - } - - /** - * @tests SocketChannelImpl#socket().getOutputStream().write(int) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "socket", - args = {} - ) - public void test_socket_getOutputStream_write_oneByte() - throws IOException { - - // Regression test for Harmony-3475 - - int MAGIC = 123; - - channel1.connect(this.localAddr1); - - OutputStream os = channel1.socket().getOutputStream(); - - Socket acceptedSocket = server1.accept(); - - InputStream in = acceptedSocket.getInputStream(); - - os.write(MAGIC); - channel1.close(); - - int lastByte = in.read(); - if (lastByte == -1) { - fail("Server received nothing. Expected 1 byte."); - } else if (lastByte != MAGIC) { - fail("Server received wrong single byte: " + lastByte - + ", expected: " + MAGIC); - } - - lastByte = in.read(); - if (lastByte != -1) { - fail("Server received too long sequence. Expected 1 byte."); - } - } - - public void testSocket_setOptions() throws IOException { - channel1.connect(localAddr1); - Socket socket = channel1.socket(); - - ByteBuffer buffer = ByteBuffer.wrap(new byte[] {1, 2, 3}); - socket.setKeepAlive(true); - channel1.write(buffer); - - socket.setOOBInline(true); - channel1.write(buffer); - - socket.setReceiveBufferSize(100); - channel1.write(buffer); - - socket.setReuseAddress(true); - channel1.write(buffer); - - socket.setSendBufferSize(100); - channel1.write(buffer); - - socket.setSoLinger(true, 100); - channel1.write(buffer); - - socket.setSoTimeout(1000); - channel1.write(buffer); - - socket.setTcpNoDelay(true); - channel1.write(buffer); - - socket.setTrafficClass(10); - channel1.write(buffer); - } - - /** - * @throws IOException - * @tests java.nio.channels.SocketChannel#read(ByteBuffer) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "read", - args = {java.nio.ByteBuffer[].class} - ) - public void test_socketChannel_read_DirectByteBuffer() throws InterruptedException, IOException { - - ServerThread server = new ServerThread(); - server.start(); - Thread.currentThread().sleep(1000); - - InetSocketAddress address = new InetSocketAddress(InetAddress - .getByName("localhost"), port); - - // First test with array based byte buffer - SocketChannel sc = SocketChannel.open(); - sc.connect(address); - - ByteBuffer buf = ByteBuffer.allocate(data.length); - buf.limit(data.length / 2); - sc.read(buf); - - buf.limit(buf.capacity()); - sc.read(buf); - sc.close(); - - // Make sure the buffer is filled correctly - buf.rewind(); - assertSameContent(data, buf); - - // Now test with direct byte buffer - sc = SocketChannel.open(); - sc.connect(address); - - buf = ByteBuffer.allocateDirect(data.length); - buf.limit(data.length / 2); - sc.read(buf); - - buf.limit(buf.capacity()); - sc.read(buf); - sc.close(); - - // Make sure the buffer is filled correctly - buf.rewind(); - assertSameContent(data, buf); - } - - private void assertSameContent(byte[] data, ByteBuffer buf) { - for (byte b : data) { - if (b != buf.get()) { - int pos = buf.position() - 1; - fail("Content not equal. Buffer position: " + - (pos) + " expected: " + b + " was: " + buf.get(pos)); - } - } - } - - public static boolean done = false; - public static int port = Support_PortManager.getNextPort(); - public static byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; - - static class ServerThread extends Thread { - @Override - public void run() { - try { - ServerSocketChannel ssc = ServerSocketChannel.open(); - InetSocketAddress addr = new InetSocketAddress(InetAddress - .getByAddress(new byte[] {0, 0, 0, 0}), port); - ssc.socket().bind(addr, 0); - - ByteBuffer buf = ByteBuffer.allocate(10); - buf.put(data); - - while (!done) { - SocketChannel sc = ssc.accept(); - buf.rewind(); - sc.write(buf); - } - } catch (Exception e) { - // ignore - } - } - } - - class MockSocketChannel extends SocketChannel { - - private boolean isWriteCalled = false; - - private boolean isReadCalled = false; - - private boolean isConstructorCalled = false; - - public MockSocketChannel(SelectorProvider provider) { - super(provider); - isConstructorCalled = true; - } - - public Socket socket() { - return null; - } - - public boolean isConnected() { - return false; - } - - public boolean isConnectionPending() { - return false; - } - - public boolean connect(SocketAddress address) throws IOException { - return false; - } - - public boolean finishConnect() throws IOException { - return false; - } - - public int read(ByteBuffer target) throws IOException { - return 0; - } - - public long read(ByteBuffer[] targets, int offset, int length) - throws IOException { - // Verify that calling read(ByteBuffer[]) leads to the method - // read(ByteBuffer[], int, int) being called with a 0 for the - // second parameter and targets.length as the third parameter. - if (0 == offset && length == targets.length) { - isReadCalled = true; - } - return 0; - } - - public int write(ByteBuffer source) throws IOException { - return 0; - } - - public long write(ByteBuffer[] sources, int offset, int length) - throws IOException { - // Verify that calling write(ByteBuffer[]) leads to the method - // write(ByteBuffer[], int, int) being called with a 0 for the - // second parameter and sources.length as the third parameter. - if (0 == offset && length == sources.length) { - isWriteCalled = true; - } - return 0; - } - - protected void implCloseSelectableChannel() throws IOException { - // empty - } - - protected void implConfigureBlocking(boolean blockingMode) - throws IOException { - // empty - } - } - - class SubSocketAddress extends SocketAddress { - private static final long serialVersionUID = 1L; - - // empty - public SubSocketAddress() { - super(); - } - } -} diff --git a/luni/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParameterGenerator3Test.java b/luni/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParameterGenerator3Test.java deleted file mode 100644 index f6320b5..0000000 --- a/luni/src/test/java/org/apache/harmony/security/tests/java/security/AlgorithmParameterGenerator3Test.java +++ /dev/null @@ -1,269 +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.security.tests.java.security; - -import java.math.BigInteger; -import java.security.AlgorithmParameterGenerator; -import java.security.AlgorithmParameters; -import java.security.InvalidAlgorithmParameterException; -import java.security.NoSuchProviderException; -import java.security.Provider; -import java.security.SecureRandom; -import java.security.Security; -import java.security.spec.DSAParameterSpec; - -import dalvik.annotation.BrokenTest; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; - -@TestTargetClass(AlgorithmParameterGenerator.class) -public class AlgorithmParameterGenerator3Test extends junit.framework.TestCase { - - /** - * @tests java.security.AlgorithmParameterGenerator#generateParameters() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "generateParameters", - args = {} - ) - @BrokenTest("Takes too long due to math implementation, disabling for now") - public void test_generateParameters() throws Exception { - // Test for method java.security.AlgorithmParameters - // java.security.AlgorithmParameterGenerator.generateParameters() - AlgorithmParameterGenerator gen = AlgorithmParameterGenerator - .getInstance("DSA"); - gen.init(1024); - - // WARNING - The next line can take MINUTES to run - AlgorithmParameters params = gen.generateParameters(); - assertNotNull("params is null", params); - } - - /** - * @tests java.security.AlgorithmParameterGenerator#getAlgorithm() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getAlgorithm", - args = {} - ) - public void test_getAlgorithm() throws Exception { - // Test for method java.lang.String - // java.security.AlgorithmParameterGenerator.getAlgorithm() - String alg = AlgorithmParameterGenerator.getInstance("DSA") - .getAlgorithm(); - assertEquals("getAlgorithm ok", "DSA", alg); - } - - /** - * @tests java.security.AlgorithmParameterGenerator#getInstance(java.lang.String) - */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies getInstance with parameter", - method = "getInstance", - args = {java.lang.String.class} - ) - public void test_getInstanceLjava_lang_String() throws Exception { - // Test for method java.security.AlgorithmParameterGenerator - // java.security.AlgorithmParameterGenerator.getInstance(java.lang.String) - AlgorithmParameterGenerator.getInstance("DSA"); - } - - /** - * @tests java.security.AlgorithmParameterGenerator#getInstance(java.lang.String, - * java.lang.String) - */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Test NoSuchAlgorithmException is missed", - method = "getInstance", - args = {java.lang.String.class, java.lang.String.class} - ) - public void test_getInstanceLjava_lang_StringLjava_lang_String() throws Exception { - // Test for method java.security.AlgorithmParameterGenerator - // java.security.AlgorithmParameterGenerator.getInstance(java.lang.String, - // java.lang.String) - - // Opting for DSA here as it is pretty widely supported - Provider[] provs = Security - .getProviders("AlgorithmParameterGenerator.DSA"); - - for (int i = 0; i < provs.length; i++) { - AlgorithmParameterGenerator.getInstance("DSA", provs[i].getName()); - }// end for - - - // exception case - should throw IllegalArgumentException for null - // provider - try { - AlgorithmParameterGenerator.getInstance("DSA", (String) null); - fail("Should have thrown IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // Expected - } - - // exception case - should throw IllegalArgumentException for empty - // provider - try { - AlgorithmParameterGenerator.getInstance("DSA", ""); - fail("Should have thrown IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // Expected - } - - // exception case - should throw NoSuchProviderException - try { - AlgorithmParameterGenerator.getInstance("DSA", "IDontExist"); - fail("Should have thrown NoSuchProviderException"); - } catch (NoSuchProviderException e) { - // Expected - } - } - - /** - * @tests java.security.AlgorithmParameterGenerator#getProvider() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies provider with null parameter", - method = "getProvider", - args = {} - ) - public void test_getProvider() throws Exception { - // Test for method java.security.Provider - // java.security.AlgorithmParameterGenerator.getProvider() - // checks that no exception is thrown - Provider p = AlgorithmParameterGenerator.getInstance("DSA") - .getProvider(); - assertNotNull("provider is null", p); - } - - /** - * @tests java.security.AlgorithmParameterGenerator#init(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "init", - args = {int.class} - ) - public void test_initI() throws Exception { - // Test for method void - // java.security.AlgorithmParameterGenerator.init(int) - // checks that no exception is thrown - int[] valid = {512, 576, 640, 960, 1024}; - AlgorithmParameterGenerator gen = AlgorithmParameterGenerator - .getInstance("DSA"); - - for (int i = 0; i < valid.length; i++) { - try { - gen.init(valid[i]); - } catch (Exception e) { - fail("Exception should not be thrown for valid parameter" + valid[i]); - - } - } - } - - /** - * @tests java.security.AlgorithmParameterGenerator#init(int, - * java.security.SecureRandom) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "init", - args = {int.class, java.security.SecureRandom.class} - ) - public void test_initILjava_security_SecureRandom() throws Exception { - // Test for method void - // java.security.AlgorithmParameterGenerator.init(int, - // java.security.SecureRandom) - // checks that no exception is thrown - int[] valid = {512, 576, 640, 960, 1024}; - AlgorithmParameterGenerator gen = AlgorithmParameterGenerator - .getInstance("DSA"); - - for (int i = 0; i < valid.length; i++) { - try { - gen.init(valid[i], new SecureRandom()); - gen.init(valid[i], null); - } catch (Exception e) { - fail("Exception should not be thrown for valid parameter" + valid[i]); - - } - } - } - - /** - * @tests java.security.AlgorithmParameterGenerator#init(java.security.spec.AlgorithmParameterSpec) - */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies InvalidAlgorithmParameterException exception only", - method = "init", - args = {java.security.spec.AlgorithmParameterSpec.class} - ) - public void test_initLjava_security_spec_AlgorithmParameterSpec() throws Exception { - // Test for method void - // java.security.AlgorithmParameterGenerator.init(java.security.spec.AlgorithmParameterSpec) - // checks that InvalidAlgorithmParameterException is thrown - DSAParameterSpec spec = new DSAParameterSpec(BigInteger.ONE, - BigInteger.ONE, BigInteger.ONE); - AlgorithmParameterGenerator gen = AlgorithmParameterGenerator - .getInstance("DSA"); - try { - gen.init(spec); - fail("No expected InvalidAlgorithmParameterException"); - } catch (InvalidAlgorithmParameterException e) { - //expected - } - } - - /** - * @tests java.security.AlgorithmParameterGenerator#init(java.security.spec.AlgorithmParameterSpec, - * java.security.SecureRandom) - */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies InvalidAlgorithmParameterException exception only", - method = "init", - args = {java.security.spec.AlgorithmParameterSpec.class, java.security.SecureRandom.class} - ) - public void test_initLjava_security_spec_AlgorithmParameterSpecLjava_security_SecureRandom() throws Exception { - // Test for method void - // java.security.AlgorithmParameterGenerator.init(java.security.spec.AlgorithmParameterSpec, - // java.security.SecureRandom) - // checks that InvalidAlgorithmParameterException is thrown - DSAParameterSpec spec = new DSAParameterSpec(BigInteger.ONE, - BigInteger.ONE, BigInteger.ONE); - AlgorithmParameterGenerator gen = AlgorithmParameterGenerator - .getInstance("DSA"); - try { - gen.init(spec, new SecureRandom()); - fail("No expected InvalidAlgorithmParameterException"); - } catch (InvalidAlgorithmParameterException e) { - //expected - } - } -} diff --git a/luni/src/test/java/org/apache/harmony/security/tests/java/security/AllTests.java b/luni/src/test/java/org/apache/harmony/security/tests/java/security/AllTests.java index c0d5640..97f58d0 100644 --- a/luni/src/test/java/org/apache/harmony/security/tests/java/security/AllTests.java +++ b/luni/src/test/java/org/apache/harmony/security/tests/java/security/AllTests.java @@ -33,7 +33,6 @@ public class AllTests { suite.addTestSuite(AccessController2Test.class); suite.addTestSuite(AlgorithmParameterGenerator1Test.class); suite.addTestSuite(AlgorithmParameterGenerator2Test.class); - suite.addTestSuite(AlgorithmParameterGenerator3Test.class); suite.addTestSuite(AlgorithmParametersSpiTest.class); suite.addTestSuite(AlgorithmParametersTest.class); suite.addTestSuite(AllPermission2Test.class); diff --git a/luni/src/test/java/org/apache/harmony/text/tests/java/text/AllTests.java b/luni/src/test/java/org/apache/harmony/text/tests/java/text/AllTests.java index 58c2c93..5f05690 100644 --- a/luni/src/test/java/org/apache/harmony/text/tests/java/text/AllTests.java +++ b/luni/src/test/java/org/apache/harmony/text/tests/java/text/AllTests.java @@ -17,6 +17,7 @@ package org.apache.harmony.text.tests.java.text; +import java.text.OldNumberFormatTest; import junit.framework.Test; import junit.framework.TestSuite; @@ -38,7 +39,6 @@ public class AllTests { suite.addTestSuite(DateFormatSymbolsTest.class); suite.addTestSuite(DateFormatTest.class); suite.addTestSuite(DecimalFormatSymbolsTest.class); - suite.addTestSuite(DecimalFormatTest.class); suite.addTestSuite(DecimalFormatTestICU.class); suite.addTestSuite(FieldPositionTest.class); suite.addTestSuite(FormatFieldTest.class); @@ -47,7 +47,7 @@ public class AllTests { suite.addTestSuite(MessageFormatTest.class); suite.addTestSuite(NormalizerTest.class); suite.addTestSuite(NumberFormatFieldTest.class); - suite.addTestSuite(NumberFormatTest.class); + suite.addTestSuite(OldNumberFormatTest.class); suite.addTestSuite(ParseExceptionTest.class); suite.addTestSuite(ParsePositionTest.class); suite.addTestSuite(RuleBasedCollatorTest.class); diff --git a/luni/src/test/java/org/apache/harmony/text/tests/java/text/DecimalFormatTest.java b/luni/src/test/java/org/apache/harmony/text/tests/java/text/DecimalFormatTest.java deleted file mode 100644 index 7156dc2..0000000 --- a/luni/src/test/java/org/apache/harmony/text/tests/java/text/DecimalFormatTest.java +++ /dev/null @@ -1,2885 +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.text.tests.java.text; - -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.BrokenTest; -import dalvik.annotation.KnownFailure; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; - -import junit.framework.TestCase; - -import tests.support.Support_BitSet; -import tests.support.Support_DecimalFormat; -import tests.support.Support_Locale; - -import java.io.ObjectInputStream; -import java.io.IOException; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.math.RoundingMode; -import java.text.AttributedCharacterIterator; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.FieldPosition; -import java.text.NumberFormat; -import java.text.ParseException; -import java.text.ParsePosition; -import java.util.BitSet; -import java.util.Currency; -import java.util.Locale; - - -@TestTargetClass(DecimalFormat.class) -public class DecimalFormatTest extends TestCase { - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Regression test for AttributedCharacterIterator.", - method = "formatToCharacterIterator", - args = {java.lang.Object.class} - ) - public void testAttributedCharacterIterator() throws Exception { - // Regression for http://issues.apache.org/jira/browse/HARMONY-333 - AttributedCharacterIterator iterator = new DecimalFormat() - .formatToCharacterIterator(new Integer(1)); - assertNotNull(iterator); - assertFalse("attributes should exist", iterator.getAttributes() - .isEmpty()); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "formatToCharacterIterator", - args = {java.lang.Object.class} - ) - public void test_formatToCharacterIterator() throws Exception { - AttributedCharacterIterator iterator; - int[] runStarts; - int[] runLimits; - String result; - char current; - - // For BigDecimal with multiplier test. - DecimalFormat df = new DecimalFormat(); - df.setMultiplier(10); - iterator = df.formatToCharacterIterator(new BigDecimal("12345678901234567890")); - result = "123,456,789,012,345,678,900"; - current = iterator.current(); - for (int i = 0; i < result.length(); i++) { - assertEquals("wrong char @" + i, result.charAt(i), current); - current = iterator.next(); - } - - // For BigDecimal with multiplier test. - df = new DecimalFormat(); - df.setMultiplier(-1); - df.setMaximumFractionDigits(20); - iterator = df.formatToCharacterIterator(new BigDecimal("1.23456789012345678901")); - result = "-1.23456789012345678901"; - current = iterator.current(); - for (int i = 0; i < result.length(); i++) { - assertEquals("wrong char @" + i, result.charAt(i), current); - current = iterator.next(); - } - - iterator = new DecimalFormat() - .formatToCharacterIterator(new BigDecimal("1.23456789E1234")); - runStarts = new int[] {0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14}; - runLimits = new int[] {2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15}; - result = "12,345,678,900,"; // 000,000,000,000.... - current = iterator.current(); - for (int i = 0; i < runStarts.length; i++) { - assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart()); - assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit()); - assertEquals("wrong char @" + i, result.charAt(i), current); - current = iterator.next(); - } - assertEquals(0, iterator.getBeginIndex()); - assertEquals(1646, iterator.getEndIndex()); - - iterator = new DecimalFormat() - .formatToCharacterIterator(new BigDecimal("1.23456789E301")); - runStarts = new int[] {0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11, 11, 11, 14}; - runLimits = new int[] {2, 2, 3, 6, 6, 6, 7, 10, 10, 10, 11, 14, 14, 14, 15}; - result = "12,345,678,900,"; // 000,000,000,000.... - current = iterator.current(); - for (int i = 0; i < runStarts.length; i++) { - assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart()); - assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit()); - assertEquals("wrong char @" + i, result.charAt(i), current); - current = iterator.next(); - } - assertEquals(0, iterator.getBeginIndex()); - assertEquals(402, iterator.getEndIndex()); - - iterator = new DecimalFormat() - .formatToCharacterIterator(new BigDecimal("1.2345678E4")); - runStarts = new int[] {0, 0, 2, 3, 3, 3, 6, 7, 7, 7}; - runLimits = new int[] {2, 2, 3, 6, 6, 6, 7, 10, 10, 10}; - result = "12,345.678"; - current = iterator.current(); - for (int i = 0; i < runStarts.length; i++) { - assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart()); - assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit()); - assertEquals("wrong char @" + i, result.charAt(i), current); - current = iterator.next(); - } - assertEquals(0, iterator.getBeginIndex()); - assertEquals(10, iterator.getEndIndex()); - - iterator = new DecimalFormat() - .formatToCharacterIterator(new BigInteger("123456789")); - runStarts = new int[] {0, 0, 0, 3, 4, 4, 4, 7, 8, 8, 8}; - runLimits = new int[] {3, 3, 3, 4, 7, 7, 7, 8, 11, 11, 11}; - result = "123,456,789"; - current = iterator.current(); - for (int i = 0; i < runStarts.length; i++) { - assertEquals("wrong start @" + i, runStarts[i], iterator.getRunStart()); - assertEquals("wrong limit @" + i, runLimits[i], iterator.getRunLimit()); - assertEquals("wrong char @" + i, result.charAt(i), current); - current = iterator.next(); - } - assertEquals(0, iterator.getBeginIndex()); - assertEquals(11, iterator.getEndIndex()); - } - - /* - * Test the getter and setter of parseBigDecimal and parseIntegerOnly and - * test the default value of them. - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isParseBigDecimal", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setParseBigDecimal", - args = {boolean.class} - ) - }) - public void test_isParseBigDecimalLjava_lang_Boolean_isParseIntegerOnlyLjava_lang_Boolean() { - - // parseBigDecimal default to false - DecimalFormat form = (DecimalFormat) DecimalFormat - .getInstance(Locale.US); - assertFalse(form.isParseBigDecimal()); - form.setParseBigDecimal(true); - assertTrue(form.isParseBigDecimal()); - - try { - Number result = form.parse("123.123"); - assertEquals(new BigDecimal("123.123"), result); - } catch (ParseException e) { - fail("ParseException was thrown."); - } - - form.setParseBigDecimal(false); - assertFalse(form.isParseBigDecimal()); - - try { - Number result = form.parse("123.123"); - assertFalse(result instanceof BigDecimal); - } catch (ParseException e) { - fail("ParseException was thrown."); - } - - // parseIntegerOnly default to false - assertFalse(form.isParseIntegerOnly()); - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isParseIntegerOnly", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setParseIntegerOnly", - args = {boolean.class} - ) - }) - public void test_isParseIntegerOnly() { - - DecimalFormat format = new DecimalFormat(); - assertFalse("Default value of isParseIntegerOnly is true", - format.isParseIntegerOnly()); - - format.setParseIntegerOnly(true); - assertTrue(format.isParseIntegerOnly()); - try { - Number result = format.parse("123.123"); - assertEquals(new Long("123"), result); - } catch (ParseException e) { - fail("ParseException was thrown."); - } - - format.setParseIntegerOnly(false); - assertFalse(format.isParseIntegerOnly()); - try { - Number result = format.parse("123.123"); - assertEquals(new Double("123.123"), result); - } catch (ParseException e) { - fail("ParseException was thrown."); - } - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isGroupingUsed", - args = {} - ) - public void test_isGroupingUsed() { - String [] patterns = {"####.##", "######.######", "000000.000000", - "######.000000", "000000.######", " ###.###", "$#####.######", - "$$####.######"}; - - for(String pattern:patterns) { - DecimalFormat format = new DecimalFormat(pattern); - assertFalse(format.isGroupingUsed()); - } - - DecimalFormat format = new DecimalFormat("###,####"); - assertTrue(format.isGroupingUsed()); - } - - // Test the type of the returned object - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "parse", - args = {java.lang.String.class, java.text.ParsePosition.class} - ) - public void test_parseLjava_lang_String_Ljava_text_ParsePosition() { - DecimalFormat form = (DecimalFormat) DecimalFormat - .getInstance(Locale.US); - Number number = form.parse("23.1", new ParsePosition(0)); - assertTrue(number instanceof Double); - - // Test parsed object of type double when - // parseBigDecimal is set to true - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - number = form.parse("23.1", new ParsePosition(0)); - assertTrue(number instanceof Double); - - form.setParseBigDecimal(true); - number = form.parse("23.1", new ParsePosition(0)); - - assertTrue(number instanceof BigDecimal); - assertEquals(new BigDecimal("23.1"), number); - - // When parseIntegerOnly set to true, all float numbers will be parsed - // into Long. - // With the exception that, the value is out of the bound of Long or - // some special values such as NaN or Infinity. - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - form.setParseIntegerOnly(true); - number = form.parse("23.1f", new ParsePosition(0)); - - assertTrue(number instanceof Long); - - number = form.parse("23.0", new ParsePosition(0)); - assertTrue(number instanceof Long); - - number = form.parse("-0.0", new ParsePosition(0)); - assertTrue(number instanceof Long); - assertTrue(new Long(0).equals(number)); - - number = form.parse("-9,223,372,036,854,775,8080.00", - new ParsePosition(0)); - assertTrue(number instanceof Double); - - // Even if parseIntegerOnly is set to true, NaN will be parsed to Double - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - form.setParseIntegerOnly(true); - DecimalFormatSymbols symbols = new DecimalFormatSymbols(); - number = form.parse(symbols.getNaN(), new ParsePosition(0)); - assertTrue(number instanceof Double); - - // Even if parseIntegerOnly is set to true, Infinity will still be - // parsed to Double - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - form.setParseIntegerOnly(true); - symbols = new DecimalFormatSymbols(); - number = form.parse(symbols.getInfinity(), new ParsePosition(0)); - assertTrue(number instanceof Double); - - // ParseBigDecimal take precedence of parseBigInteger - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - form.setParseIntegerOnly(true); - form.setParseBigDecimal(true); - - number = form.parse("23.1f", new ParsePosition(0)); - - assertTrue(number instanceof BigDecimal); - - number = form.parse("23.0", new ParsePosition(0)); - assertTrue(number instanceof BigDecimal); - - number = form.parse("-9,223,372,036,854,775,8080.00", - new ParsePosition(0)); - assertFalse(number instanceof BigInteger); - assertTrue(number instanceof BigDecimal); - - final String doubleMax2 = "359,538,626,972,463,141,629,054,847,463,408," - + "713,596,141,135,051,689,993,197,834,953,606,314,521,560,057,077," - + "521,179,117,265,533,756,343,080,917,907,028,764,928,468,642,653," - + "778,928,365,536,935,093,407,075,033,972,099,821,153,102,564,152," - + "490,980,180,778,657,888,151,737,016,910,267,884,609,166,473,806," - + "445,896,331,617,118,664,246,696,549,595,652,408,289,446,337,476," - + "354,361,838,599,762,500,808,052,368,249,716,736"; - number = form.parse(doubleMax2, new ParsePosition(0)); - assertTrue(number instanceof BigDecimal); - BigDecimal result = (BigDecimal)number; - assertEquals(new BigDecimal(Double.MAX_VALUE).add(new BigDecimal( - Double.MAX_VALUE)), result); - - // Test whether the parsed object is of type float. (To be specific, - // they are of type Double) - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - - number = form.parse("23.1f", new ParsePosition(0)); - assertTrue(number instanceof Double); - - form.setParseBigDecimal(true); - number = form.parse("23.1f", new ParsePosition(0)); - assertTrue(number instanceof BigDecimal); - assertEquals(new BigDecimal("23.1"), number); - - // Integer will be parsed to Long, unless parseBigDecimal is set to true - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - - number = form.parse("123", new ParsePosition(0)); - assertTrue(number instanceof Long); - - form.setParseBigDecimal(true); - number = form.parse("123", new ParsePosition(0)); - assertTrue(number instanceof BigDecimal); - assertEquals(new BigDecimal("123"), number); - - // NaN will be parsed to Double, no matter parseBigDecimal set or not. - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - symbols = new DecimalFormatSymbols(); - number = form.parse(symbols.getNaN() + "", new ParsePosition(0)); - assertTrue(number instanceof Double); - - form.setParseBigDecimal(true); - number = form.parse(symbols.getNaN() + "", new ParsePosition(0)); - assertTrue(number instanceof Double); - - // Infinity will be parsed to Double, no matter parseBigDecimal set or - // not. - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - symbols = new DecimalFormatSymbols(); - - number = form.parse(symbols.getInfinity(), new ParsePosition(0)); - - assertTrue(number instanceof Double); - assertEquals("Infinity", number.toString()); - // When set bigDecimal to true, the result of parsing infinity - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - symbols = new DecimalFormatSymbols(); - form.setParseBigDecimal(true); - - number = form.parse(symbols.getInfinity(), new ParsePosition(0)); - assertTrue(number instanceof Double); - assertEquals("Infinity", number.toString()); - - // Negative infinity will be parsed to double no matter parseBigDecimal - // set or not - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - symbols = new DecimalFormatSymbols(); - - number = form.parse("-" + symbols.getInfinity(), new ParsePosition(0)); - - assertTrue(number instanceof Double); - assertEquals("-Infinity", number.toString()); - - // When set bigDecimal to true, the result of parsing minus infinity - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - symbols = new DecimalFormatSymbols(); - form.setParseBigDecimal(true); - - number = form.parse("-" + symbols.getInfinity(), new ParsePosition(0)); - - assertTrue(number instanceof Double); - assertEquals("-Infinity", number.toString()); - - // -0.0 will be parsed to different type according to the combination of - // parseBigDecimal and parseIntegerOnly - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - - // parseBigDecimal == true; - // parseIntegerOnly == false; - form.setParseBigDecimal(true); - number = form.parse("-0", new ParsePosition(0)); - assertTrue(number instanceof BigDecimal); - - number = form.parse("-0.0", new ParsePosition(0)); - assertTrue(number instanceof BigDecimal); - - // parseBigDecimal == false; - // parseIntegerOnly == true; - form.setParseBigDecimal(false); - form.setParseIntegerOnly(true); - number = form.parse("-0", new ParsePosition(0)); - - assertTrue(number instanceof Long); - - number = form.parse("-0.0", new ParsePosition(0)); - assertTrue(number instanceof Long); - - // parseBigDecimal == false; - // parseIntegerOnly == false; - form.setParseBigDecimal(false); - form.setParseIntegerOnly(false); - number = form.parse("-0", new ParsePosition(0)); - assertTrue(number instanceof Double); - - number = form.parse("-0.0", new ParsePosition(0)); - assertTrue(number instanceof Double); - - // parseBigDecimal == true; - // parseIntegerOnly == true; - // parseBigDecimal take precedence of parseBigInteger - form.setParseBigDecimal(true); - form.setParseIntegerOnly(true); - number = form.parse("-0", new ParsePosition(0)); - assertTrue(number instanceof BigDecimal); - - number = form.parse("-0.0", new ParsePosition(0)); - assertTrue(number instanceof BigDecimal); - - number = form.parse("12.4", new ParsePosition(0)); - assertTrue(number instanceof BigDecimal); - - // When parseBigDecimal is set to false, no matter how massive the - // mantissa part of a number is, the number will be parsed into Double - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - - number = form.parse("9,223,372,036,854,775,808.00", - new ParsePosition(0)); - - assertTrue(number instanceof Double); - assertEquals("9.223372036854776E18", number.toString()); - - number = form.parse("-9,223,372,036,854,775,8080.00", - new ParsePosition(0)); - assertTrue(number instanceof Double); - assertEquals("-9.223372036854776E19", number.toString()); - - // When parseBigDecimal is set to true, if mantissa part of number - // exceeds Long.MAX_VALUE, the number will be parsed into BigDecimal - - form = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - - form.setParseBigDecimal(true); - number = form.parse("9,223,372,036,854,775,808.00", - new ParsePosition(0)); - - assertTrue(number instanceof BigDecimal); - - assertEquals(9.223372036854776E18, number.doubleValue(), 0); - - number = form.parse("-9,223,372,036,854,775,8080.00", - new ParsePosition(0)); - - assertTrue(number instanceof BigDecimal); - assertEquals(-9.223372036854776E19, number.doubleValue(), 0); - - // The minimum value of Long will be parsed to Long when parseBigDecimal - // is not set - - ParsePosition pos = new ParsePosition(0); - DecimalFormat df = new DecimalFormat(); - pos = new ParsePosition(0); - Number nb = df.parse("" + Long.MIN_VALUE, pos); - assertTrue(nb instanceof Long); - - // The maximum value of Long will be parsed to Long when parseBigDecimal - // is set - pos = new ParsePosition(0); - df = new DecimalFormat(); - pos = new ParsePosition(0); - nb = df.parse("" + Long.MAX_VALUE, pos); - assertTrue(nb instanceof Long); - - // When parsing invalid string( which is neither consist of digits nor - // NaN/Infinity), a null will be returned. - - pos = new ParsePosition(0); - df = new DecimalFormat(); - try { - nb = df.parse("invalid", pos); - assertNull(nb); - } catch (NullPointerException e) { - fail("Should not throw NPE"); - } - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMaximumFractionDigits", - args = {} - ) - public void test_getMaximumFractionDigits() { - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - DecimalFormat form = (DecimalFormat) nform; - - // getMaximumFractionDigits of NumberFormat default to 3 - // getMaximumFractionDigits of DecimalFormat default to 3 - assertEquals(3, nform.getMaximumFractionDigits()); - assertEquals(3, form.getMaximumFractionDigits()); - - // Greater than 340 (critical number used to distinguish - // BigInteger and BigDecimal) - nform.setMaximumFractionDigits(500); - assertEquals(500, nform.getMaximumFractionDigits()); - assertEquals(500, form.getMaximumFractionDigits()); - - form.setMaximumFractionDigits(500); - assertEquals(500, nform.getMaximumFractionDigits()); - assertEquals(500, form.getMaximumFractionDigits()); - - form.format(12.3); - assertEquals(500, nform.getMaximumFractionDigits()); - assertEquals(500, form.getMaximumFractionDigits()); - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMinimumFractionDigits", - args = {} - ) - public void test_getMinimumFractionDigits() { - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - DecimalFormat form = (DecimalFormat) nform; - - // getMinimumFractionDigits from NumberFormat (default to 0) - // getMinimumFractionDigits from DecimalFormat (default to 0) - assertEquals(0, nform.getMinimumFractionDigits()); - assertEquals(0, form.getMinimumFractionDigits()); - - // Greater than 340 (critical number used to distinguish - // BigInteger and BigDecimal) - nform.setMinimumFractionDigits(500); - assertEquals(500, nform.getMinimumFractionDigits()); - assertEquals(500, form.getMinimumFractionDigits()); - - form.setMaximumFractionDigits(400); - assertEquals(400, nform.getMinimumFractionDigits()); - assertEquals(400, form.getMinimumFractionDigits()); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "getMinimumIntegerDigits", - args = {} - ) - public void test_getMaximumIntegerDigits() { - final int maxIntDigit = 309; - - // When use default locale, in this case zh_CN - // the returned instance of NumberFormat is a DecimalFormat - DecimalFormat form = new DecimalFormat("00.###E0"); - assertEquals(2, form.getMaximumIntegerDigits()); - - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - form = null; - if (nform instanceof DecimalFormat) { - form = (DecimalFormat) nform; - } - - // Greater than 309 (critical number used to distinguish - // BigInteger and BigDecimal) - nform.setMaximumIntegerDigits(500); - assertEquals(500, nform.getMaximumIntegerDigits()); - assertEquals(500, form.getMaximumIntegerDigits()); - - form = new DecimalFormat("00.###E0"); - assertEquals(2, form.getMaximumIntegerDigits()); - - form.setMaximumIntegerDigits(500); - assertEquals(500, nform.getMaximumIntegerDigits()); - assertEquals(500, form.getMaximumIntegerDigits()); - form.format(12.3); - assertEquals(500, nform.getMaximumIntegerDigits()); - assertEquals(500, form.getMaximumIntegerDigits()); - - nform = DecimalFormat.getInstance(Locale.US); - form = null; - if (nform instanceof DecimalFormat) { - form = (DecimalFormat) nform; - } - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "getMinimumIntegerDigits", - args = {} - ) - @AndroidOnly("Difference to RI") - public void test_getMaximumIntegerDigits_AndroidOnly() { - final int maxIntDigit = 309; - - // When use default locale, in this case zh_CN - // the returned instance of NumberFormat is a DecimalFormat - DecimalFormat form = new DecimalFormat("00.###E0"); - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - nform = DecimalFormat.getInstance(Locale.US); - form = null; - if (nform instanceof DecimalFormat) { - form = (DecimalFormat) nform; - } - // getMaximumIntegerDigits from NumberFormat default to 309 - // getMaximumIntegerDigits from DecimalFormat default to 309 - // the following 2 assertions will fail on RI implementation, since the - // implementation of ICU and RI are not identical. RI does not give - // DecimalFormat an initial bound about its maximumIntegerDigits - // (default to Integer.MAX_VALUE: 2147483647 ) - assertEquals(maxIntDigit, nform.getMaximumIntegerDigits()); - assertEquals(maxIntDigit, form.getMaximumIntegerDigits()); - } - - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - method = "getMinimumIntegerDigits", - args = {} - ) - @AndroidOnly("second 0 needs to be quoted in icu." + - "(quoting special characters in prefix and suffix necessary)") - public void test_getMaximumIntegerDigits2() { - // regression test for HARMONY-878 - assertTrue(new DecimalFormat("0\t'0'").getMaximumIntegerDigits() > 0); - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMinimumIntegerDigits", - args = {} - ) - public void test_getMinimumIntegerDigits() { - final int minIntDigit = 1; - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - DecimalFormat form = (DecimalFormat) nform; - - // getMaximumIntegerDigits from NumberFormat (default to 1) - // getMaximumIntegerDigits from DecimalFormat (default to 1) - assertEquals(minIntDigit, nform.getMinimumIntegerDigits()); - assertEquals(minIntDigit, form.getMinimumIntegerDigits()); - - // Greater than 309 (critical number used to distinguish - // BigInteger and BigDecimal) - nform.setMinimumIntegerDigits(500); - assertEquals(500, nform.getMinimumIntegerDigits()); - assertEquals(500, form.getMinimumIntegerDigits()); - - form.setMaximumIntegerDigits(400); - assertEquals(400, nform.getMinimumIntegerDigits()); - assertEquals(400, form.getMinimumIntegerDigits()); - - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "format", - args = {java.lang.Object.class, java.lang.StringBuffer.class, java.text.FieldPosition.class} - ) - public void test_formatLjava_lang_Obj_Ljava_StringBuffer_Ljava_text_FieldPosition() { - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - DecimalFormat form = (DecimalFormat) nform; - - // If Object(including null) is not of type Number, - // IllegalArgumentException will be thrown out - try { - form.format(new Object(), new StringBuffer(), new FieldPosition(0)); - fail("Should throw IAE"); - } catch (IllegalArgumentException e) { - // expected - } - try { - form.format(null, new StringBuffer(), new FieldPosition(0)); - fail("Should throw IAE"); - } catch (IllegalArgumentException e) { - // expected - } - - // When StringBuffer == null || FieldPosition == null - // NullPointerException will be thrown out. - try { - form.format(new Double(1.9), null, new FieldPosition(0)); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // expected - } - - try { - form.format(new Double(1.3), new StringBuffer(), null); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // expected - } - - try { - form.format(new Double(1.4), null, null); - fail("Should throw NPE"); - } catch (NullPointerException e) { - // expected - } - - try { - form.format(new Object(), null, null); - fail("Should throw IllegalArgumentException"); - } catch (IllegalArgumentException e) { - // expected - } - - FieldPosition pos; - StringBuffer out; - DecimalFormat format = (DecimalFormat) NumberFormat - .getInstance(Locale.US); - - // format maxLong - pos = new FieldPosition(0); - out = format.format(new Long(Long.MAX_VALUE), new StringBuffer(), pos); - assertTrue("Wrong result L1: " + out, out.toString().equals( - "9,223,372,036,854,775,807")); - - // format minLong - pos = new FieldPosition(0); - out = format.format(new Long(Long.MIN_VALUE), new StringBuffer(), pos); - assertTrue("Wrong result L2: " + out, out.toString().equals( - "-9,223,372,036,854,775,808")); - - // format maxLong of type BigInteger - pos = new FieldPosition(0); - out = format.format(new java.math.BigInteger(String - .valueOf(Long.MAX_VALUE)), new StringBuffer(), pos); - assertTrue("Wrong result BI1: " + out, out.toString().equals( - "9,223,372,036,854,775,807")); - - // format minLong of type BigInteger - pos = new FieldPosition(0); - out = format.format(new java.math.BigInteger(String - .valueOf(Long.MIN_VALUE)), new StringBuffer(), pos); - assertTrue("Wrong result BI2: " + out, out.toString().equals( - "-9,223,372,036,854,775,808")); - - // format maxLong + 1 - java.math.BigInteger big; - pos = new FieldPosition(0); - big = new java.math.BigInteger(String.valueOf(Long.MAX_VALUE)) - .add(new java.math.BigInteger("1")); - out = format.format(big, new StringBuffer(), pos); - assertTrue("Wrong result BI3: " + out, out.toString().equals( - "9,223,372,036,854,775,808")); - - // format minLong - 1 - pos = new FieldPosition(0); - big = new java.math.BigInteger(String.valueOf(Long.MIN_VALUE)) - .add(new java.math.BigInteger("-1")); - out = format.format(big, new StringBuffer(), pos); - assertTrue("Wrong result BI4: " + out, out.toString().equals( - "-9,223,372,036,854,775,809")); - - // format big decimal - pos = new FieldPosition(0); - out = format.format(new java.math.BigDecimal("51.348"), - new StringBuffer(), pos); - assertTrue("Wrong result BD1: " + out, out.toString().equals("51.348")); - - // format big decimal - pos = new FieldPosition(0); - out = format.format(new java.math.BigDecimal("51"), new StringBuffer(), - pos); - assertTrue("Wrong result BD2: " + out, out.toString().equals("51")); - - // format big decimal Double.MAX_VALUE * 2 - java.math.BigDecimal bigDecimal; - pos = new FieldPosition(0); - final String doubleMax2 = "359,538,626,972,463,141,629,054,847,463,408," - + "713,596,141,135,051,689,993,197,834,953,606,314,521,560,057,077," - + "521,179,117,265,533,756,343,080,917,907,028,764,928,468,642,653," - + "778,928,365,536,935,093,407,075,033,972,099,821,153,102,564,152," - + "490,980,180,778,657,888,151,737,016,910,267,884,609,166,473,806," - + "445,896,331,617,118,664,246,696,549,595,652,408,289,446,337,476," - + "354,361,838,599,762,500,808,052,368,249,716,736"; - bigDecimal = new BigDecimal(Double.MAX_VALUE).add(new BigDecimal( - Double.MAX_VALUE)); - out = format.format(bigDecimal, new StringBuffer(), pos); - assertTrue("Wrong result BDmax2: " + out, out.toString().equals( - doubleMax2)); - - // format big decimal Double.MIN_VALUE + Double.MIN_VALUE - // and Double.MIN_VALUE - Double.MIN_VALUE - pos = new FieldPosition(0); - - bigDecimal = new BigDecimal(Double.MIN_VALUE).add(new BigDecimal( - Double.MIN_VALUE)); - out = format.format(bigDecimal, new StringBuffer(), pos); - - bigDecimal = new BigDecimal(Float.MAX_VALUE).add(new BigDecimal( - Float.MAX_VALUE)); - out = format.format(bigDecimal, new StringBuffer(), pos); - final String BDFloatMax2 = "680,564,693,277,057,719,623,408,366,969,033,850,880"; - assertTrue("Wrong result BDFloatMax2: " + out, out.toString().equals( - BDFloatMax2)); - // format big decimal Float.MIN_VALUE + Float.MIN_VALUE - // and Float.MIN_VALUE - Float.MIN_VALUE - bigDecimal = new BigDecimal(Float.MIN_VALUE).add(new BigDecimal( - Float.MIN_VALUE)); - out = format.format(bigDecimal, new StringBuffer(), pos); - final String BDFloatMin2 = "0"; - - bigDecimal = new BigDecimal(Float.MIN_VALUE).subtract(new BigDecimal( - Float.MIN_VALUE)); - out = format.format(bigDecimal, new StringBuffer(), pos); - - assertTrue("Wrong result BDFloatMax2: " + out, out.toString().equals( - BDFloatMin2)); - - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMaximumFractionDigits", - args = {int.class} - ) - public void test_setMaximumFractionDigitsLjava_lang_Integer() { - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - DecimalFormat form = (DecimalFormat) nform; - - form.setMaximumFractionDigits(-2); - assertEquals(0, form.getMaximumFractionDigits()); - - form.setMaximumFractionDigits(341); - assertEquals(341, form.getMaximumFractionDigits()); - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMinimumFractionDigits", - args = {int.class} - ) - public void test_setMinimumFractionDigitsLjava_lang_Integer() { - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - DecimalFormat form = (DecimalFormat) nform; - - form.setMinimumFractionDigits(-3); - assertEquals(0, form.getMinimumFractionDigits()); - - form.setMinimumFractionDigits(310); - assertEquals(310, form.getMinimumFractionDigits()); - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMaximumIntegerDigits", - args = {int.class} - ) - public void test_setMaximumIntegerDigitsLjava_lang_Integer() { - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - DecimalFormat form = (DecimalFormat) nform; - - form.setMaximumIntegerDigits(-3); - assertEquals(0, form.getMaximumIntegerDigits()); - - form.setMaximumIntegerDigits(310); - assertEquals(310, form.getMaximumIntegerDigits()); - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMinimumIntegerDigits", - args = {int.class} - ) - public void test_setMinimumIntegerDigitsLjava_lang_Integer() { - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - DecimalFormat form = (DecimalFormat) nform; - - form.setMinimumIntegerDigits(-3); - assertEquals(0, form.getMinimumIntegerDigits()); - - form.setMinimumIntegerDigits(310); - assertEquals(310, form.getMinimumIntegerDigits()); - } - - // When MaxFractionDigits is set first and less than MinFractionDigits, max - // will be changed to min value - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMinimumFractionDigits", - args = {int.class} - ) - public void test_setMinimumFactionDigitsLjava_lang_Integer_setMaximumFractionDigitsLjava_lang_Integer() { - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - DecimalFormat form = (DecimalFormat) nform; - - form.setMaximumFractionDigits(100); - form.setMinimumFractionDigits(200); - - assertEquals(200, form.getMaximumFractionDigits()); - assertEquals(200, form.getMinimumFractionDigits()); - - form.setMaximumIntegerDigits(100); - form.setMinimumIntegerDigits(200); - - assertEquals(200, form.getMaximumIntegerDigits()); - assertEquals(200, form.getMinimumIntegerDigits()); - } - - // When MinFractionDigits is set first and less than MaxFractionDigits, min - // will be changed to max value - @TestTargets({ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "When MinFractionDigits is set first and less than MaxFractionDigits, min will be changed to max value", - method = "setMaximumFractionDigits", - args = {int.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "When MinFractionDigits is set first and less than MaxFractionDigits, min will be changed to max value", - method = "setMinimumFractionDigits", - args = {int.class} - ) - }) - public void test_setMaximumFactionDigitsLjava_lang_Integer_setMinimumFractionDigitsLjava_lang_Integer() { - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - DecimalFormat form = (DecimalFormat) nform; - - form.setMinimumFractionDigits(200); - form.setMaximumFractionDigits(100); - - assertEquals(100, form.getMaximumFractionDigits()); - assertEquals(100, form.getMinimumFractionDigits()); - - form.setMinimumIntegerDigits(200); - form.setMaximumIntegerDigits(100); - - assertEquals(100, form.getMaximumIntegerDigits()); - assertEquals(100, form.getMinimumIntegerDigits()); - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "equals", - args = {java.lang.Object.class} - ) - @BrokenTest("Behaves differently between cts host and run-core-tests") - public void test_equalsLjava_lang_Object() { - DecimalFormat format = (DecimalFormat) DecimalFormat - .getInstance(Locale.US); - DecimalFormat cloned = (DecimalFormat) format.clone(); - cloned.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); - assertEquals(format, cloned); - - Currency c = Currency.getInstance(Locale.US); - cloned.setCurrency(c); - - assertEquals(format, cloned); - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setPositivePrefix", - args = {java.lang.String.class} - ) - public void test_setPositivePrefixLjava_lang_String() { - DecimalFormat format = new DecimalFormat(); - assertEquals("", format.getPositivePrefix()); - - format.setPositivePrefix("PosPrf"); - assertEquals("PosPrf", format.getPositivePrefix()); - try { - assertTrue(format.parse("PosPrf123.45").doubleValue() == 123.45); - } catch(java.text.ParseException pe) { - fail("ParseException was thrown."); - } - - format.setPositivePrefix(""); - assertEquals("", format.getPositivePrefix()); - - format.setPositivePrefix(null); - assertNull(format.getPositivePrefix()); - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setPositiveSuffix", - args = {java.lang.String.class} - ) - public void test_setPositiveSuffixLjava_lang_String() { - DecimalFormat format = new DecimalFormat(); - assertEquals("", format.getPositiveSuffix()); - - format.setPositiveSuffix("PosSfx"); - assertEquals("PosSfx", format.getPositiveSuffix()); - try { - assertTrue(format.parse("123.45PosSfx").doubleValue() == 123.45); - } catch(java.text.ParseException pe) { - fail("ParseException was thrown."); - } - - format.setPositiveSuffix(""); - assertEquals("", format.getPositiveSuffix()); - - format.setPositiveSuffix(null); - assertNull(format.getPositiveSuffix()); - } - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setNegativePrefix", - args = {java.lang.String.class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getNegativePrefix", - args = {} - ) - }) - public void test_setNegativePrefixLjava_lang_String() { - DecimalFormat format = new DecimalFormat(); - assertEquals("-", format.getNegativePrefix()); - - format.setNegativePrefix("NegPrf"); - assertEquals("NegPrf", format.getNegativePrefix()); - try { - assertTrue(format.parse("NegPrf123.45").doubleValue() == -123.45); - } catch(java.text.ParseException pe) { - fail("ParseException was thrown."); - } - format.setNegativePrefix(""); - assertEquals("", format.getNegativePrefix()); - - format.setNegativePrefix(null); - assertNull(format.getNegativePrefix()); - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setNegativeSuffix", - args = {java.lang.String.class} - ) - public void test_setNegativeSuffixLjava_lang_String() { - DecimalFormat format = new DecimalFormat(); - assertEquals("", format.getNegativeSuffix()); - - format.setNegativeSuffix("NegSfx"); - assertEquals("NegSfx", format.getNegativeSuffix()); - try { - assertTrue(format.parse("123.45NegPfx").doubleValue() == 123.45); - } catch(java.text.ParseException pe) { - fail("ParseException was thrown."); - } - - format.setNegativeSuffix(""); - assertEquals("", format.getNegativeSuffix()); - - format.setNegativeSuffix(null); - assertNull(format.getNegativeSuffix()); - } - - /** - * @tests java.text.DecimalFormat#toLocalizedPattern() Test of method - * java.text.DecimalFormat#toLocalizedPattern(). - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toLocalizedPattern", - args = {} - ) - public void test_toLocalizedPattern() { - DecimalFormat format = new DecimalFormat(); - format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); - try { - format.applyLocalizedPattern("#.#"); - assertEquals("Wrong pattern 1", "#0.#", format.toLocalizedPattern()); - format.applyLocalizedPattern("#."); - assertEquals("Wrong pattern 2", "#0.", format.toLocalizedPattern()); - format.applyLocalizedPattern("#"); - assertEquals("Wrong pattern 3", "#", format.toLocalizedPattern()); - format.applyLocalizedPattern(".#"); - assertEquals("Wrong pattern 4", "#.0", format.toLocalizedPattern()); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * @tests java.text.DecimalFormat#toPattern() Test of method - * java.text.DecimalFormat#toPattern(). - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toPattern", - args = {} - ) - public void test_toPattern() { - DecimalFormat format = new DecimalFormat(); - try { - format.applyPattern("#.#"); - assertEquals("Wrong pattern 1", "#0.#", format.toPattern()); - format.applyPattern("#."); - assertEquals("Wrong pattern 2", "#0.", format.toPattern()); - format.applyPattern("#"); - assertEquals("Wrong pattern 3", "#", format.toPattern()); - format.applyPattern(".#"); - assertEquals("Wrong pattern 4", "#.0", format.toPattern()); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setGroupingUsed", - args = {boolean.class} - ) - public void test_setGroupingUse() { - DecimalFormat format = new DecimalFormat(); - - StringBuffer buf = new StringBuffer(); - format.setGroupingUsed(false); - format.format(new Long(1970), buf, new FieldPosition(0)); - assertEquals("1970", buf.toString()); - assertFalse(format.isGroupingUsed()); - format.format(new Long(1970), buf, new FieldPosition(0)); - assertEquals("19701970", buf.toString()); - assertFalse(format.isGroupingUsed()); - - format.setGroupingUsed(true); - format.format(new Long(1970), buf, new FieldPosition(0)); - assertEquals("197019701,970", buf.toString()); - assertTrue(format.isGroupingUsed()); - } - - /** - * @tests java.text.DecimalFormat#DecimalFormat() Test of method - * java.text.DecimalFormat#DecimalFormat(). - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "DecimalFormat", - args = {} - ) - public void test_Constructor() { - // Test for method java.text.DecimalFormat() - // the constructor form that specifies a pattern is equal to the form - // constructed with no pattern and applying that pattern using the - // applyPattern call - try { - DecimalFormat format1 = new DecimalFormat(); - format1.applyPattern("'$'1000.0000"); - DecimalFormat format2 = new DecimalFormat(); - format2.applyPattern("'$'1000.0000"); - assertTrue( - "Constructed format did not match applied format object", - format2.equals(format1)); - DecimalFormat format3 = new DecimalFormat("'$'1000.0000"); - assertTrue( - "Constructed format did not match applied format object", - format3.equals(format1)); - DecimalFormat format4 = new DecimalFormat("'$'8000.0000"); - assertTrue( - "Constructed format did not match applied format object", - !format4.equals(format1)); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * @tests java.text.DecimalFormat#DecimalFormat(java.lang.String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "DecimalFormat", - args = {java.lang.String.class} - ) - public void test_ConstructorLjava_lang_String() { - // Test for method java.text.DecimalFormat(java.lang.String) - // the constructor form that specifies a pattern is equal to the form - // constructed with no pattern and applying that pattern using the - // applyPattern call - DecimalFormat format = new DecimalFormat("'$'0000.0000"); - DecimalFormat format1 = new DecimalFormat(); - format1.applyPattern("'$'0000.0000"); - assertTrue("Constructed format did not match applied format object", - format.equals(format1)); - - String [] patterns = {"####.##", "######.######", "000000.000000", - "######.000000", "000000.######", " ###.###", "$#####.######", - "$$####.######", "%#,##,###,####", "#,##0.00;(#,##0.00)"}; - - for(String str:patterns) { - new DecimalFormat(str); - } - - try { - new DecimalFormat(null); - fail("NullPointerException wasn't thrown."); - } catch(NullPointerException npe){ - //expected - } - - String [] incPatterns = {"%#,##,###,####'", "#.##0.00"}; - for(String str:incPatterns) { - try { - new DecimalFormat(str); - fail("IllegalArgumentException wasn't thrown for pattern: " + str); - } catch(IllegalArgumentException iae){ - //expected - } - } - } - - /** - * @tests java.text.DecimalFormat#DecimalFormat(java.lang.String, - * java.text.DecimalFormatSymbols) Test of method - * java.text.DecimalFormat#DecimalFormat(java.lang.String, - * java.text.DecimalFormatSymbols). Case 1: Try to construct object - * using correct pattern and fromat symbols. Case 2: Try to construct - * object using null arguments. Case 3: Try to construct object using - * incorrect pattern. - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "DecimalFormat", - args = {java.lang.String.class, java.text.DecimalFormatSymbols.class} - ) - public void test_ConstructorLjava_lang_StringLjava_text_DecimalFormatSymbols() { - try { - // case 1: Try to construct object using correct pattern and fromat - // symbols. - DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.CANADA); - DecimalFormat format1 = new DecimalFormat("'$'1000.0000", dfs); - DecimalFormat format2 = new DecimalFormat(); - format2.applyPattern("'$'1000.0000"); - format2.setDecimalFormatSymbols(dfs); - assertTrue( - "Constructed format did not match applied format object", - format2.equals(format1)); - assertTrue( - "Constructed format did not match applied format object", - !format1.equals(new DecimalFormat("'$'1000.0000", - new DecimalFormatSymbols(Locale.CHINA)))); - - // case 2: Try to construct object using null arguments. - try { - new DecimalFormat("'$'1000.0000", null); - fail("Expected NullPointerException was not thrown"); - } catch (NullPointerException e) { - // expected - } - try { - new DecimalFormat(null, new DecimalFormatSymbols()); - fail("Expected NullPointerException was not thrown"); - } catch (NullPointerException e) { - // expected - } - try { - new DecimalFormat(null, null); - fail("Expected NullPointerException was not thrown"); - } catch (NullPointerException e) { - // expected - } - - // case 3: Try to construct object using incorrect pattern. - try { - new DecimalFormat("$'", new DecimalFormatSymbols()); - fail("Expected IllegalArgumentException was not thrown"); - } catch (IllegalArgumentException e) { - // expected - } - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * @tests java.text.DecimalFormat#applyLocalizedPattern(java.lang.String) - * Test of method - * java.text.DecimalFormat#applyLocalizedPattern(java.lang.String). - * Case 1: Try to apply correct variants of pattern. Case 2: Try to - * apply malformed patten. Case 3: Try to apply null patern. - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "applyLocalizedPattern", - args = {java.lang.String.class} - ) - public void test_applyLocalizedPatternLjava_lang_String() { - DecimalFormat format = new DecimalFormat(); - try { - // case 1: Try to apply correct variants of pattern. - format.applyLocalizedPattern("#.#"); - assertEquals("Wrong pattern 1", "#0.#", format.toLocalizedPattern()); - format.applyLocalizedPattern("#."); - assertEquals("Wrong pattern 2", "#0.", format.toLocalizedPattern()); - format.applyLocalizedPattern("#"); - assertEquals("Wrong pattern 3", "#", format.toLocalizedPattern()); - format.applyLocalizedPattern(".#"); - assertEquals("Wrong pattern 4", "#.0", format.toLocalizedPattern()); - - // case 2: Try to apply malformed patten. - try { - format.applyLocalizedPattern("'#,#:#0.0#;(#)"); - fail("Expected IllegalArgumentException was not thrown"); - } catch (IllegalArgumentException e) { - // expected - } - - // case 3: Try to apply null patern. - try { - format.applyLocalizedPattern((String) null); - fail("Expected NullPointerException was not thrown"); - } catch (NullPointerException e) { - // expected - } - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * @tests java.text.DecimalFormat#applyPattern(java.lang.String) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "applyPattern", - args = {java.lang.String.class} - ) - public void test_applyPatternLjava_lang_String() { - DecimalFormat format = new DecimalFormat("#.#"); - assertEquals("Wrong pattern 1", "#0.#", format.toPattern()); - format = new DecimalFormat("#."); - assertEquals("Wrong pattern 2", "#0.", format.toPattern()); - format = new DecimalFormat("#"); - assertEquals("Wrong pattern 3", "#", format.toPattern()); - format = new DecimalFormat(".#"); - assertEquals("Wrong pattern 4", "#.0", format.toPattern()); - - DecimalFormat decFormat = new DecimalFormat("#.#"); - - try { - decFormat.applyPattern(null); - fail("NullPointerException was not thrown."); - } catch(NullPointerException npe) { - //expected - } - - String [] incPatterns = {"%#,##,###,####'", "#.##0.00"}; - for(String str:incPatterns) { - try { - decFormat.applyPattern(str); - fail("IllegalArgumentException was not thrown for pattern: " + - str); - } catch(IllegalArgumentException iae) { - //expected - } - } - } - - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "applyPattern", - args = {java.lang.String.class} - ) - @AndroidOnly("icu supports 2 grouping sizes.") - public void test_applyPatternLjava_lang_String2() { - DecimalFormat decFormat = new DecimalFormat("#.#"); - String [] patterns = {"####.##", "######.######", "000000.000000", - "######.000000", "000000.######", " ###.###", "$#####.######", - "$$####.######", "%#,##,###,####", "#,##0.00;(#,##0.00)", - "##.##-E"}; - - String [] expResult = {"#0.##", "#0.######", "#000000.000000", - "#.000000", "#000000.######", " #0.###", "$#0.######", - "$$#0.######", - "%#,###,####", // icu only. icu supports two grouping sizes - "#,##0.00;(#,##0.00)", - "#0.##-'E'"}; // icu only. E in the suffix does not need to be - // quoted. This is done automatically. - - for (int i = 0; i < patterns.length; i++) { - decFormat.applyPattern(patterns[i]); - String result = decFormat.toPattern(); - assertEquals("Failed to apply following pattern: " + patterns[i] + - " expected: " + expResult[i] + " returned: " + result, - expResult[i], result); - } - } - - /** - * @tests java.text.DecimalFormat#clone() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "clone", - args = {} - ) - public void test_clone() { - DecimalFormat format = (DecimalFormat) DecimalFormat - .getInstance(Locale.US); - DecimalFormat cloned = (DecimalFormat) format.clone(); - assertEquals(cloned.getDecimalFormatSymbols(), format - .getDecimalFormatSymbols()); - - format = new DecimalFormat("'$'0000.0000"); - DecimalFormat format1 = (DecimalFormat) (format.clone()); - // make sure the objects are equal - assertTrue("Object's clone isn't equal!", format.equals(format1)); - // change the content of the clone and make sure it's not equal anymore - // verifies that it's data is now distinct from the original - format1.applyPattern("'$'0000.####"); - assertTrue("Object's changed clone should not be equal!", !format - .equals(format1)); - } - - private void compare(String testName, String format, String expected) { - assertTrue(testName + " got: " + format + " expected: " + expected, - format.equals(expected)); - } - - private boolean compare(int count, String format, String expected) { - boolean result = format.equals(expected); - if (!result) - System.out.println("Failure test: " + count + " got: " + format - + " expected: " + expected); - return result; - } - - /** - * @tests java.text.DecimalFormat#format(double, java.lang.StringBuffer, - * java.text.FieldPosition) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "format", - args = {double.class, java.lang.StringBuffer.class, java.text.FieldPosition.class} - ) - public void test_formatDLjava_lang_StringBufferLjava_text_FieldPosition() { - new Support_DecimalFormat( - "test_formatDLjava_lang_StringBufferLjava_text_FieldPosition") - .t_format_with_FieldPosition(); - - int failCount = 0; - BitSet failures = new BitSet(); - - final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US); - - DecimalFormat df = new DecimalFormat("00.0#E0", dfs); - compare("00.0#E0: 0.0", df.format(0.0), "00.0E0"); - compare("00.0#E0: 1.0", df.format(1.0), "10.0E-1"); - compare("00.0#E0: 12.0", df.format(12.0), "12.0E0"); - compare("00.0#E0: 123.0", df.format(123.0), "12.3E1"); - compare("00.0#E0: 1234.0", df.format(1234.0), "12.34E2"); - compare("00.0#E0: 12346.0", df.format(12346.0), "12.35E3"); - compare("00.0#E0: 99999.0", df.format(99999.0), "10.0E4"); - compare("00.0#E0: 1.2", df.format(1.2), "12.0E-1"); - compare("00.0#E0: 12.3", df.format(12.3), "12.3E0"); - compare("00.0#E0: 123.4", df.format(123.4), "12.34E1"); - compare("00.0#E0: 1234.6", df.format(1234.6), "12.35E2"); - compare("00.0#E0: 9999.9", df.format(9999.9), "10.0E3"); - compare("00.0#E0: 0.1", df.format(0.1), "10.0E-2"); - compare("00.0#E0: 0.12", df.format(0.12), "12.0E-2"); - compare("00.0#E0: 0.123", df.format(0.123), "12.3E-2"); - compare("00.0#E0: 0.1234", df.format(0.1234), "12.34E-2"); - compare("00.0#E0: 0.12346", df.format(0.12346), "12.35E-2"); - compare("00.0#E0: 0.99999", df.format(0.99999), "10.0E-1"); - compare("00.0#E0: -0.0", df.format(-0.0), "-00.0E0"); - compare("00.0#E0: -1.0", df.format(-1.0), "-10.0E-1"); - compare("00.0#E0: -12.0", df.format(-12.0), "-12.0E0"); - compare("00.0#E0: -123.0", df.format(-123.0), "-12.3E1"); - compare("00.0#E0: -1234.0", df.format(-1234.0), "-12.34E2"); - compare("00.0#E0: -12346.0", df.format(-12346.0), "-12.35E3"); - compare("00.0#E0: -99999.0", df.format(-99999.0), "-10.0E4"); - - df = new DecimalFormat("##0.0E0", dfs); - compare("##0.0E0: -0.0", df.format(-0.0), "-0.0E0"); - compare("##0.0E0: 0.0", df.format(0.0), "0.0E0"); - compare("##0.0E0: 1.0", df.format(1.0), "1.0E0"); - compare("##0.0E0: 12.0", df.format(12.0), "12E0"); - compare("##0.0E0: 123.0", df.format(123.0), "123E0"); // Android fails, here! - compare("##0.0E0: 1234.0", df.format(1234.0), "1.234E3"); - compare("##0.0E0: 12346.0", df.format(12346.0), "12.35E3"); - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(99999.0), "100E3")) - failures.set(failCount); - failCount++; - compare("##0.0E0: 999999.0", df.format(999999.0), "1.0E6"); - - df = new DecimalFormat("#00.0##E0", dfs); - compare("#00.0##E0: 0.1", df.format(0.1), "100E-3"); - compare("#00.0##E0: 0.12", df.format(0.12), "120E-3"); - compare("#00.0##E0: 0.123", df.format(0.123), "123E-3"); - compare("#00.0##E0: 0.1234", df.format(0.1234), "123.4E-3"); - compare("#00.0##E0: 0.1234567", df.format(0.1234567), "123.457E-3"); - compare("#00.0##E0: 0.01", df.format(0.01), "10.0E-3"); - compare("#00.0##E0: 0.012", df.format(0.012), "12.0E-3"); - compare("#00.0##E0: 0.0123", df.format(0.0123), "12.3E-3"); - compare("#00.0##E0: 0.01234", df.format(0.01234), "12.34E-3"); - compare("#00.0##E0: 0.01234567", df.format(0.01234567), "12.3457E-3"); - compare("#00.0##E0: 0.001", df.format(0.001), "1.00E-3"); - compare("#00.0##E0: 0.0012", df.format(0.0012), "1.20E-3"); - compare("#00.0##E0: 0.00123", df.format(0.00123), "1.23E-3"); - compare("#00.0##E0: 0.001234", df.format(0.001234), "1.234E-3"); - compare("#00.0##E0: 0.001234567", df.format(0.001234567), "1.23457E-3"); - compare("#00.0##E0: 0.0001", df.format(0.0001), "100E-6"); - compare("#00.0##E0: 0.00012", df.format(0.00012), "120E-6"); - compare("#00.0##E0: 0.000123", df.format(0.000123), "123E-6"); - compare("#00.0##E0: 0.0001234", df.format(0.0001234), "123.4E-6"); - compare("#00.0##E0: 0.0001234567", df.format(0.0001234567), - "123.457E-6"); - - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(0.0), "0.00E0")) - failures.set(failCount); - failCount++; - compare("#00.0##E0: 1.0", df.format(1.0), "1.00E0"); - compare("#00.0##E0: 12.0", df.format(12.0), "12.0E0"); - compare("#00.0##E0: 123.0", df.format(123.0), "123E0"); - compare("#00.0##E0: 1234.0", df.format(1234.0), "1.234E3"); - compare("#00.0##E0: 12345.0", df.format(12345.0), "12.345E3"); - compare("#00.0##E0: 123456.0", df.format(123456.0), "123.456E3"); - compare("#00.0##E0: 1234567.0", df.format(1234567.0), "1.23457E6"); - compare("#00.0##E0: 12345678.0", df.format(12345678.0), "12.3457E6"); - compare("#00.0##E0: 99999999.0", df.format(99999999.0), "100E6"); - - df = new DecimalFormat("#.0E0", dfs); - compare("#.0E0: -0.0", df.format(-0.0), "-.0E0"); - compare("#.0E0: 0.0", df.format(0.0), ".0E0"); - compare("#.0E0: 1.0", df.format(1.0), ".1E1"); - compare("#.0E0: 12.0", df.format(12.0), ".12E2"); - compare("#.0E0: 123.0", df.format(123.0), ".12E3"); - compare("#.0E0: 1234.0", df.format(1234.0), ".12E4"); - compare("#.0E0: 9999.0", df.format(9999.0), ".1E5"); - - df = new DecimalFormat("0.#E0", dfs); - compare("0.#E0: -0.0", df.format(-0.0), "-0E0"); - compare("0.#E0: 0.0", df.format(0.0), "0E0"); - compare("0.#E0: 1.0", df.format(1.0), "1E0"); - compare("0.#E0: 12.0", df.format(12.0), "1.2E1"); - compare("0.#E0: 123.0", df.format(123.0), "1.2E2"); - compare("0.#E0: 1234.0", df.format(1234.0), "1.2E3"); - compare("0.#E0: 9999.0", df.format(9999.0), "1E4"); - - df = new DecimalFormat(".0E0", dfs); - compare(".0E0: -0.0", df.format(-0.0), "-.0E0"); - compare(".0E0: 0.0", df.format(0.0), ".0E0"); - compare(".0E0: 1.0", df.format(1.0), ".1E1"); - compare(".0E0: 12.0", df.format(12.0), ".1E2"); - compare(".0E0: 123.0", df.format(123.0), ".1E3"); - compare(".0E0: 1234.0", df.format(1234.0), ".1E4"); - compare(".0E0: 9999.0", df.format(9999.0), ".1E5"); - - df = new DecimalFormat("0.E0", dfs); - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(0.0), "0.E0")) - failures.set(failCount); - failCount++; - if (!compare(failCount, df.format(1.0), "1.E0")) - failures.set(failCount); - failCount++; - if (!compare(failCount, df.format(12.0), "1.E1")) - failures.set(failCount); - failCount++; - if (!compare(failCount, df.format(123.0), "1.E2")) - failures.set(failCount); - failCount++; - if (!compare(failCount, df.format(1234.0), "1.E3")) - failures.set(failCount); - failCount++; - if (!compare(failCount, df.format(9999.0), "1.E4")) - failures.set(failCount); - failCount++; - - df = new DecimalFormat("##0.00#E0", dfs); - compare("##0.00#E0: 0.1", df.format(0.1), "100E-3"); - compare("##0.00#E0: 0.1234567", df.format(0.1234567), "123.457E-3"); - compare("##0.00#E0: 0.9999999", df.format(0.9999999), "1.00E0"); - compare("##0.00#E0: 0.01", df.format(0.01), "10.0E-3"); - compare("##0.00#E0: 0.01234567", df.format(0.01234567), "12.3457E-3"); - compare("##0.00#E0: 0.09999999", df.format(0.09999999), "100E-3"); - compare("##0.00#E0: 0.001", df.format(0.001), "1.00E-3"); - compare("##0.00#E0: 0.001234567", df.format(0.001234567), "1.23457E-3"); - compare("##0.00#E0: 0.009999999", df.format(0.009999999), "10.0E-3"); - compare("##0.00#E0: 0.0001", df.format(0.0001), "100E-6"); - compare("##0.00#E0: 0.0001234567", df.format(0.0001234567), - "123.457E-6"); - compare("##0.00#E0: 0.0009999999", df.format(0.0009999999), "1.00E-3"); - - df = new DecimalFormat("###0.00#E0", dfs); - compare("###0.00#E0: 0.1", df.format(0.1), "1000E-4"); - compare("###0.00#E0: 0.12345678", df.format(0.12345678), "1234.568E-4"); - compare("###0.00#E0: 0.99999999", df.format(0.99999999), "1.00E0"); - compare("###0.00#E0: 0.01", df.format(0.01), "100E-4"); - compare("###0.00#E0: 0.012345678", df.format(0.012345678), - "123.4568E-4"); - compare("###0.00#E0: 0.099999999", df.format(0.099999999), "1000E-4"); - compare("###0.00#E0: 0.001", df.format(0.001), "10.0E-4"); - compare("###0.00#E0: 0.0012345678", df.format(0.0012345678), - "12.34568E-4"); - compare("###0.00#E0: 0.0099999999", df.format(0.0099999999), "100E-4"); - compare("###0.00#E0: 0.0001", df.format(0.0001), "1.00E-4"); - compare("###0.00#E0: 0.00012345678", df.format(0.00012345678), - "1.234568E-4"); - compare("###0.00#E0: 0.00099999999", df.format(0.00099999999), - "10.0E-4"); - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(0.00001), "1000E-8")) - failures.set(failCount); - failCount++; - compare("###0.00#E0: 0.000012345678", df.format(0.000012345678), - "1234.568E-8"); - compare("###0.00#E0: 0.000099999999", df.format(0.000099999999), - "1.00E-4"); - - df = new DecimalFormat("###0.0#E0", dfs); - compare("###0.0#E0: 0.1", df.format(0.1), "1000E-4"); - compare("###0.0#E0: 0.1234567", df.format(0.1234567), "1234.57E-4"); - compare("###0.0#E0: 0.9999999", df.format(0.9999999), "1.0E0"); - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(0.01), "100E-4")) - failures.set(failCount); - failCount++; - compare("###0.0#E0: 0.01234567", df.format(0.01234567), "123.457E-4"); - compare("###0.0#E0: 0.09999999", df.format(0.09999999), "1000E-4"); - compare("###0.0#E0: 0.001", df.format(0.001), "10E-4"); - compare("###0.0#E0: 0.001234567", df.format(0.001234567), "12.3457E-4"); - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(0.009999999), "100E-4")) - failures.set(failCount); - failCount++; - compare("###0.0#E0: 0.0001", df.format(0.0001), "1.0E-4"); - compare("###0.0#E0: 0.0001234567", df.format(0.0001234567), - "1.23457E-4"); - compare("###0.0#E0: 0.0009999999", df.format(0.0009999999), "10E-4"); - // Fails in JDK 1.2.2 - if (!compare(failCount, df.format(0.00001), "1000E-8")) - failures.set(failCount); - failCount++; - compare("###0.0#E0: 0.00001234567", df.format(0.00001234567), - "1234.57E-8"); - compare("###0.0#E0: 0.00009999999", df.format(0.00009999999), "1.0E-4"); - - assertTrue("Failed " + failures + " of " + failCount, - failures.length() == 0); - - String formatString = "##0.#"; - df = new DecimalFormat(formatString, dfs); - df.setMinimumFractionDigits(30); - compare(formatString + ": 0.000000000000000000000000000000", df - .format(0.0), "0.000000000000000000000000000000"); - compare(formatString + ": -0.000000000000000000000000000000", df - .format(-0.0), "-0.000000000000000000000000000000"); - compare(formatString + ": 1.000000000000000000000000000000", df - .format(1.0), "1.000000000000000000000000000000"); - compare(formatString + ": -1.000000000000000000000000000000", df - .format(-1.0), "-1.000000000000000000000000000000"); - - df = new DecimalFormat(formatString); - df.setMaximumFractionDigits(30); - compare(formatString + ": 0", df.format(0.0), "0"); - compare(formatString + ": -0", df.format(-0.0), "-0"); - compare(formatString + ": 1", df.format(1.0), "1"); - compare(formatString + ": -1", df.format(-1.0), "-1"); - } - - /** - * @tests java.text.DecimalFormat#format(long, java.lang.StringBuffer, - * java.text.FieldPosition) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "format", - args = {long.class, java.lang.StringBuffer.class, java.text.FieldPosition.class} - ) - public void test_formatJLjava_lang_StringBufferLjava_text_FieldPosition() { - int failCount = 0; - BitSet failures = new BitSet(); - - final DecimalFormatSymbols dfs = new DecimalFormatSymbols(Locale.US); - - DecimalFormat df = new DecimalFormat("00.0#E0", dfs); - assertEquals("00.0#E0: 0", "00.0E0", df.format(0)); - assertEquals("00.0#E0: 1", "10.0E-1", df.format(1)); - assertEquals("00.0#E0: 12", "12.0E0", df.format(12)); - assertEquals("00.0#E0: 123", "12.3E1", df.format(123)); - assertEquals("00.0#E0: 1234", "12.34E2", df.format(1234)); - assertEquals("00.0#E0: 12346", "12.35E3", df.format(12346)); - assertEquals("00.0#E0: 99999", "10.0E4", df.format(99999)); - assertEquals("00.0#E0: -1", "-10.0E-1", df.format(-1)); - assertEquals("00.0#E0: -12", "-12.0E0", df.format(-12)); - assertEquals("00.0#E0: -123", "-12.3E1", df.format(-123)); - assertEquals("00.0#E0: -1234", "-12.34E2", df.format(-1234)); - assertEquals("00.0#E0: -12346", "-12.35E3", df.format(-12346)); - assertEquals("00.0#E0: -99999", "-10.0E4", df.format(-99999)); - - df = new DecimalFormat("##0.0E0", dfs); - assertEquals("##0.0E0: 0", "0.0E0", df.format(0)); - assertEquals("##0.0E0: 1", "1.0E0", df.format(1)); - assertEquals("##0.0E0: 12", "12E0", df.format(12)); - assertEquals("##0.0E0: 123", "123E0", df.format(123)); // Android fails, here! - assertEquals("##0.0E0: 1234", "1.234E3", df.format(1234)); - assertEquals("##0.0E0: 12346", "12.35E3", df.format(12346)); - // Fails in JDK 1.2.2 - if (!df.format(99999).equals("100E3")) - failures.set(failCount); - failCount++; - assertEquals("##0.0E0: 999999", "1.0E6", df.format(999999)); - - df = new DecimalFormat("#00.0##E0", dfs); - // Fails in JDK 1.2.2 - if (!df.format(0).equals("0.00E0")) - failures.set(failCount); - failCount++; - assertEquals("#00.0##E0: 1", "1.00E0", df.format(1)); - assertEquals("#00.0##E0: 12", "12.0E0", df.format(12)); - assertEquals("#00.0##E0: 123", "123E0", df.format(123)); - assertEquals("#00.0##E0: 1234", "1.234E3", df.format(1234)); - assertEquals("#00.0##E0: 12345", "12.345E3", df.format(12345)); - assertEquals("#00.0##E0: 123456", "123.456E3", df.format(123456)); - assertEquals("#00.0##E0: 1234567", "1.23457E6", df.format(1234567)); - assertEquals("#00.0##E0: 12345678", "12.3457E6", df.format(12345678)); - assertEquals("#00.0##E0: 99999999", "100E6", df.format(99999999)); - - df = new DecimalFormat("#.0E0", dfs); - assertEquals("#.0E0: 0", ".0E0", df.format(0)); - assertEquals("#.0E0: 1", ".1E1", df.format(1)); - assertEquals("#.0E0: 12", ".12E2", df.format(12)); - assertEquals("#.0E0: 123", ".12E3", df.format(123)); - assertEquals("#.0E0: 1234", ".12E4", df.format(1234)); - assertEquals("#.0E0: 9999", ".1E5", df.format(9999)); - - df = new DecimalFormat("0.#E0", dfs); - assertEquals("0.#E0: 0", "0E0", df.format(0)); - assertEquals("0.#E0: 1", "1E0", df.format(1)); - assertEquals("0.#E0: 12", "1.2E1", df.format(12)); - assertEquals("0.#E0: 123", "1.2E2", df.format(123)); - assertEquals("0.#E0: 1234", "1.2E3", df.format(1234)); - assertEquals("0.#E0: 9999", "1E4", df.format(9999)); - - assertTrue("Failed " + failures + " of " + failCount, - failures.length() == 0); - } - - /** - * @tests java.text.DecimalFormat#formatToCharacterIterator(java.lang.Object) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "formatToCharacterIterator", - args = {java.lang.Object.class} - ) - @KnownFailure("Fails in CTS but passes under run-core-tests") - public void test_formatToCharacterIteratorLjava_lang_Object() { - try { - // Regression for HARMONY-466 - new DecimalFormat().formatToCharacterIterator(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // expected - } - - new Support_DecimalFormat( - "test_formatToCharacterIteratorLjava_lang_Object") - .t_formatToCharacterIterator(); - } - - /** - * @tests java.text.DecimalFormat#format(double) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "format", - args = {double.class} - ) - public void test_formatD() { - DecimalFormat format = (DecimalFormat) NumberFormat - .getInstance(Locale.ENGLISH); - format.setGroupingUsed(false); - format.setMaximumFractionDigits(400); - - for (int i = 0; i < 309; i++) { - String tval = "1"; - for (int j = 0; j < i; j++) - tval += "0"; - double d = Double.parseDouble(tval); - String result = format.format(d); - assertEquals(i + ") e:" + tval + " r:" + result, tval, result); - } - - for (int i = 0; i < 322; i++) { - String tval = "0."; - for (int j = 0; j < i; j++) - tval += "0"; - tval += "1"; - double d = Double.parseDouble(tval); - String result = format.format(d); - assertEquals(i + ") e:" + tval + " r:" + result, tval, result); - } - assertEquals("123456789012345", format.format(123456789012345.)); - assertEquals("1", "12345678901234.5", format.format(12345678901234.5)); - assertEquals("2", "1234567890123.25", format.format(1234567890123.25)); - assertEquals("3", "999999999999.375", format.format(999999999999.375)); - assertEquals("4", "99999999999.0625", format.format(99999999999.0625)); - assertEquals("5", "9999999999.03125", format.format(9999999999.03125)); - assertEquals("6", "999999999.015625", format.format(999999999.015625)); - assertEquals("7", "99999999.0078125", format.format(99999999.0078125)); - assertEquals("8", "9999999.00390625", format.format(9999999.00390625)); - assertEquals("9", "999999.001953125", format.format(999999.001953125)); - assertEquals("10", "9999.00048828125", format.format(9999.00048828125)); - assertEquals("11", "999.000244140625", format.format(999.000244140625)); - assertEquals("12", "99.0001220703125", format.format(99.0001220703125)); - assertEquals("13", "9.00006103515625", format.format(9.00006103515625)); - assertEquals("14", "0.000030517578125", format.format(0.000030517578125)); - } - - /** - * @tests java.text.DecimalFormat#getDecimalFormatSymbols() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getDecimalFormatSymbols", - args = {} - ) - public void test_getDecimalFormatSymbols() { - DecimalFormat df = (DecimalFormat) NumberFormat - .getInstance(Locale.ENGLISH); - DecimalFormatSymbols dfs = df.getDecimalFormatSymbols(); - assertTrue("Identical symbols", dfs != df.getDecimalFormatSymbols()); - } - - /** - * @tests java.text.DecimalFormat#getCurrency() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getCurrency", - args = {} - ) - public void test_getCurrency() { - Currency currK = Currency.getInstance("KRW"); - Currency currX = Currency.getInstance("XXX"); - Currency currE = Currency.getInstance("EUR"); - Currency curr01; - - DecimalFormat df = (DecimalFormat) NumberFormat - .getCurrencyInstance(new Locale("ko", "KR")); - assertTrue("Test1: Returned incorrect currency", - df.getCurrency() == currK); - - df = (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale("", - "KR")); - assertTrue("Test2: Returned incorrect currency", - df.getCurrency() == currK); - - df = (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale("ko", - "")); - assertTrue("Test3: Returned incorrect currency", - df.getCurrency() == currX); - - df = (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale("fr", - "FR")); - assertTrue("Test4: Returned incorrect currency", - df.getCurrency() == currE); - - // Regression for HARMONY-1351 - df = (DecimalFormat) NumberFormat.getCurrencyInstance(new Locale( - "QWERTY")); - assertTrue("Test5: Returned incorrect currency", - df.getCurrency() == currX); - - // JDK fails these tests since it doesn't have the PREEURO variant - // df = (DecimalFormat)NumberFormat.getCurrencyInstance(new Locale("fr", - // "FR","PREEURO")); - // assertTrue("Test5: Returned incorrect currency", df.getCurrency() == - // currF); - } - - /** - * @tests java.text.DecimalFormat#getGroupingSize() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getGroupingSize", - args = {} - ) - public void test_getGroupingSize() { - DecimalFormat df = new DecimalFormat("###0.##"); - assertEquals("Wrong unset size", 0, df.getGroupingSize()); - df = new DecimalFormat("#,##0.##"); - assertEquals("Wrong set size", 3, df.getGroupingSize()); - df = new DecimalFormat("#,###,###0.##"); - assertEquals("Wrong multiple set size", 4, df.getGroupingSize()); - } - - /** - * @tests java.text.DecimalFormat#getMultiplier() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getMultiplier", - args = {} - ) - public void test_getMultiplier() { - final int defaultMultiplier = 1; - NumberFormat nform = DecimalFormat.getInstance(Locale.US); - DecimalFormat form = (DecimalFormat) nform; - assertEquals(defaultMultiplier, form.getMultiplier()); - - DecimalFormat df = new DecimalFormat("###0.##"); - assertEquals("Wrong unset multiplier", 1, df.getMultiplier()); - df = new DecimalFormat("###0.##%"); - assertEquals("Wrong percent multiplier", 100, df.getMultiplier()); - df = new DecimalFormat("###0.##\u2030"); - assertEquals("Wrong mille multiplier", 1000, df.getMultiplier()); - } - - /** - * @tests java.text.DecimalFormat#getNegativePrefix() Test of method - * java.text.DecimalFormat#getNegativePrefix(). - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getNegativePrefix", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setNegativePrefix", - args = {java.lang.String.class} - ) - }) - public void test_getNegativePrefix() { - DecimalFormat df = new DecimalFormat(); - try { - df.setNegativePrefix("--"); - assertTrue("Incorrect negative prefix", df.getNegativePrefix() - .equals("--")); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * @tests java.text.DecimalFormat#getNegativeSuffix() Test of method - * java.text.DecimalFormat#getNegativeSuffix(). - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getNegativeSuffix", - args = {} - ) - public void test_getNegativeSuffix() { - DecimalFormat df = new DecimalFormat(); - try { - df.setNegativeSuffix("&"); - assertTrue("Incorrect negative suffix", df.getNegativeSuffix() - .equals("&")); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * @tests java.text.DecimalFormat#getPositivePrefix() Test of method - * java.text.DecimalFormat#getPositivePrefix(). - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getPositivePrefix", - args = {} - ) - public void test_getPositivePrefix() { - DecimalFormat df = new DecimalFormat(); - try { - df.setPositivePrefix("++"); - assertTrue("Incorrect positive prefix", df.getPositivePrefix() - .equals("++")); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * @tests java.text.DecimalFormat#getPositiveSuffix() Test of method - * java.text.DecimalFormat#getPositiveSuffix(). - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getPositiveSuffix", - args = {} - ) - public void test_getPositiveSuffix() { - DecimalFormat df = new DecimalFormat(); - try { - df.setPositiveSuffix("%"); - assertTrue("Incorrect positive prefix", df.getPositiveSuffix() - .equals("%")); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * @tests java.text.DecimalFormat#hashCode() Test of method - * java.text.DecimalFormat#hashCode(). - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "hashCode", - args = {} - ) - public void test_hashCode() { - try { - DecimalFormat df1 = new DecimalFormat(); - DecimalFormat df2 = (DecimalFormat) df1.clone(); - assertTrue("Hash codes of equals object are not equal", df2 - .hashCode() == df1.hashCode()); - } catch (Exception e) { - fail("Unexpected exception " + e.toString()); - } - } - - /** - * @tests java.text.DecimalFormat#isDecimalSeparatorAlwaysShown() - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isDecimalSeparatorAlwaysShown", - args = {} - ) - public void test_isDecimalSeparatorAlwaysShown() { - DecimalFormat df = new DecimalFormat("###0.##"); - assertTrue("Wrong unset value", !df.isDecimalSeparatorAlwaysShown()); - df = new DecimalFormat("###0.00"); - assertTrue("Wrong unset2 value", !df.isDecimalSeparatorAlwaysShown()); - df = new DecimalFormat("###0."); - assertTrue("Wrong set value", df.isDecimalSeparatorAlwaysShown()); - } - - /** - * @tests java.text.DecimalFormat#parse(java.lang.String, - * java.text.ParsePosition) - */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Vrifies boundary values.", - method = "parse", - args = {java.lang.String.class, java.text.ParsePosition.class} - ) - public void test_parseLjava_lang_StringLjava_text_ParsePosition() { - DecimalFormat format = (DecimalFormat) NumberFormat - .getNumberInstance(Locale.ENGLISH); - ParsePosition pos = new ParsePosition(0); - Number result = format.parse("9223372036854775807", pos); - assertTrue("Wrong result type for Long.MAX_VALUE", - result.getClass() == Long.class); - assertEquals("Wrong result Long.MAX_VALUE", - Long.MAX_VALUE, result.longValue()); - pos = new ParsePosition(0); - result = format.parse("-9223372036854775808", pos); - assertTrue("Wrong result type for Long.MIN_VALUE", - result.getClass() == Long.class); - assertTrue("Wrong result Long.MIN_VALUE: " + result.longValue(), result - .longValue() == Long.MIN_VALUE); - pos = new ParsePosition(0); - result = format.parse("9223372036854775808", pos); - assertTrue("Wrong result type for Long.MAX_VALUE+1", - result.getClass() == Double.class); - assertEquals("Wrong result Long.MAX_VALUE + 1", - (double) Long.MAX_VALUE + 1, result.doubleValue()); - pos = new ParsePosition(0); - result = format.parse("-9223372036854775809", pos); - assertTrue("Wrong result type for Long.MIN_VALUE - 1", - result.getClass() == Double.class); - assertEquals("Wrong result Long.MIN_VALUE - 1", - (double) Long.MIN_VALUE - 1, result.doubleValue()); - - pos = new ParsePosition(0); - result = format.parse("18446744073709551629", pos); - assertTrue("Wrong result type for overflow", - result.getClass() == Double.class); - assertEquals("Wrong result for overflow", - 18446744073709551629d, result.doubleValue()); - - pos = new ParsePosition(0); - result = format.parse("42325917317067571199", pos); - assertTrue("Wrong result type for overflow a: " + result, result - .getClass() == Double.class); - assertTrue("Wrong result for overflow a: " + result, result - .doubleValue() == 42325917317067571199d); - pos = new ParsePosition(0); - result = format.parse("4232591731706757119E1", pos); - assertTrue("Wrong result type for overflow b: " + result, result - .getClass() == Double.class); - assertEquals("Wrong result for overflow b: " + result, - 42325917317067571190d, result.doubleValue()); - pos = new ParsePosition(0); - result = format.parse(".42325917317067571199E20", pos); - assertTrue("Wrong result type for overflow c: " + result, result - .getClass() == Double.class); - assertTrue("Wrong result for overflow c: " + result, result - .doubleValue() == 42325917317067571199d); - pos = new ParsePosition(0); - result = format.parse("922337203685477580.9E1", pos); - assertTrue("Wrong result type for overflow d: " + result, result - .getClass() == Double.class); - assertTrue("Wrong result for overflow d: " + result, result - .doubleValue() == 9223372036854775809d); - pos = new ParsePosition(0); - result = format.parse("9.223372036854775809E18", pos); - assertTrue("Wrong result type for overflow e: " + result, result - .getClass() == Double.class); - assertTrue("Wrong result for overflow e: " + result, result - .doubleValue() == 9223372036854775809d); - - // test parse with multipliers - format.setMultiplier(100); - result = format.parse("9223372036854775807", new ParsePosition(0)); - assertTrue("Wrong result type multiplier 100: " + result, result - .getClass() == Long.class); - // RI on windows and linux both answer with a slightly rounded result - assertTrue("Wrong result for multiplier 100: " + result, result - .longValue() == 92233720368547760L); - format.setMultiplier(1000); - result = format.parse("9223372036854775807", new ParsePosition(0)); - assertTrue("Wrong result type multiplier 1000: " + result, result - .getClass() == Long.class); - assertTrue("Wrong result for multiplier 1000: " + result, result - .longValue() == 9223372036854776L); - - format.setMultiplier(10000); - result = format.parse("9223372036854775807", new ParsePosition(0)); - assertTrue("Wrong result type multiplier 10000: " + result, result - .getClass() == Double.class); - assertTrue("Wrong result for multiplier 10000: " + result, result - .doubleValue() == 922337203685477.5807d); - - } - - /** - * @tests java.text.DecimalFormat#setDecimalFormatSymbols(java.text.DecimalFormatSymbols) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setDecimalFormatSymbols", - args = {java.text.DecimalFormatSymbols.class} - ) - public void test_setDecimalFormatSymbolsLjava_text_DecimalFormatSymbols() { - DecimalFormat df = new DecimalFormat("###0.##"); - DecimalFormatSymbols dfs = new DecimalFormatSymbols(); - dfs.setDecimalSeparator('@'); - df.setDecimalFormatSymbols(dfs); - assertTrue("Not set", df.getDecimalFormatSymbols().equals(dfs)); - assertEquals("Symbols not used", "1@2", df.format(1.2)); - - // The returned symbols may be cloned in two spots - // 1. When set - // 2. When returned - DecimalFormat format = new DecimalFormat(); - DecimalFormatSymbols symbols = new DecimalFormatSymbols(); - format.setDecimalFormatSymbols(symbols); - DecimalFormatSymbols symbolsOut = format.getDecimalFormatSymbols(); - assertNotSame(symbols, symbolsOut); - } - - /** - * @tests java.text.DecimalFormat#setDecimalSeparatorAlwaysShown(boolean) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setDecimalSeparatorAlwaysShown", - args = {boolean.class} - ) - public void test_setDecimalSeparatorAlwaysShownZ() { - DecimalFormat df = new DecimalFormat("###0.##", - new DecimalFormatSymbols(Locale.US)); - assertEquals("Wrong default result", "5", df.format(5)); - df.setDecimalSeparatorAlwaysShown(true); - assertTrue("Not set", df.isDecimalSeparatorAlwaysShown()); - assertEquals("Wrong set result", "7.", df.format(7)); - - df.setDecimalSeparatorAlwaysShown(false); - assertFalse("Returns true", df.isDecimalSeparatorAlwaysShown()); - assertEquals("Wrong set result", "8", df.format(8)); - } - - /** - * @tests java.text.DecimalFormat#setCurrency(java.util.Currency) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setCurrency", - args = {java.util.Currency.class} - ) - public void test_setCurrencyLjava_util_Currency() { - Locale locale = Locale.CANADA; - DecimalFormat df = ((DecimalFormat) NumberFormat - .getCurrencyInstance(locale)); - - try { - df.setCurrency(null); - fail("Expected NullPointerException"); - } catch (NullPointerException e) { - } - - Currency currency = Currency.getInstance("AED"); - df.setCurrency(currency); - assertTrue("Returned incorrect currency", currency == df.getCurrency()); - assertTrue("Returned incorrect currency symbol", currency.getSymbol( - locale) - .equals(df.getDecimalFormatSymbols().getCurrencySymbol())); - assertTrue("Returned incorrect international currency symbol", currency - .getCurrencyCode().equals( - df.getDecimalFormatSymbols() - .getInternationalCurrencySymbol())); - } - - /** - * @tests java.text.DecimalFormat#setGroupingSize(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setGroupingSize", - args = {int.class} - ) - public void test_setGroupingSizeI() { - DecimalFormat df = new DecimalFormat("###0.##", - new DecimalFormatSymbols(Locale.ENGLISH)); - df.setGroupingUsed(true); - df.setGroupingSize(2); - assertEquals("Value not set", 2, df.getGroupingSize()); - String result = df.format(123); - assertTrue("Invalid format:" + result, result.equals("1,23")); - } - - /** - * @tests java.text.DecimalFormat#setMaximumFractionDigits(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMaximumFractionDigits", - args = {int.class} - ) - public void test_setMaximumFractionDigitsI() { - DecimalFormat df = new DecimalFormat("###0.##", - new DecimalFormatSymbols(Locale.US)); - df.setMaximumFractionDigits(3); - assertEquals("Not set", 3, df.getMaximumFractionDigits()); - assertEquals("Wrong maximum", "1.235", df.format(1.23456)); - df.setMinimumFractionDigits(4); - assertEquals("Not changed", 4, df.getMaximumFractionDigits()); - assertEquals("Incorrect fraction", "456.0000", df.format(456)); - } - - /** - * @tests java.text.DecimalFormat#setMaximumIntegerDigits(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMaximumIntegerDigits", - args = {int.class} - ) - public void test_setMaximumIntegerDigitsI() { - DecimalFormat df = new DecimalFormat("###0.##"); - df.setMaximumIntegerDigits(2); - assertEquals("Not set", 2, df.getMaximumIntegerDigits()); - assertEquals("Wrong maximum", "34", df.format(1234)); - df.setMinimumIntegerDigits(4); - assertEquals("Not changed", 4, df.getMaximumIntegerDigits()); - assertEquals("Incorrect integer", "0026", df.format(26)); - } - - /** - * @tests java.text.DecimalFormat#setMinimumFractionDigits(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMinimumFractionDigits", - args = {int.class} - ) - public void test_setMinimumFractionDigitsI() { - DecimalFormat df = new DecimalFormat("###0.##", - new DecimalFormatSymbols(Locale.US)); - df.setMinimumFractionDigits(4); - assertEquals("Not set", 4, df.getMinimumFractionDigits()); - assertEquals("Wrong minimum", "1.2300", df.format(1.23)); - df.setMaximumFractionDigits(2); - assertEquals("Not changed", 2, df.getMinimumFractionDigits()); - assertEquals("Incorrect fraction", "456.00", df.format(456)); - } - - /** - * @tests java.text.DecimalFormat#setMinimumIntegerDigits(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMinimumIntegerDigits", - args = {int.class} - ) - public void test_setMinimumIntegerDigitsI() { - DecimalFormat df = new DecimalFormat("###0.##", - new DecimalFormatSymbols(Locale.US)); - df.setMinimumIntegerDigits(3); - assertEquals("Not set", 3, df.getMinimumIntegerDigits()); - assertEquals("Wrong minimum", "012", df.format(12)); - df.setMaximumIntegerDigits(2); - assertEquals("Not changed", 2, df.getMinimumIntegerDigits()); - assertEquals("Incorrect integer", "00.7", df.format(0.7)); - } - - /** - * @tests java.text.DecimalFormat#setMultiplier(int) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setMultiplier", - args = {int.class} - ) - public void test_setMultiplierI() { - DecimalFormat df = new DecimalFormat("###0.##"); - df.setMultiplier(10); - assertEquals("Wrong multiplier", 10, df.getMultiplier()); - assertEquals("Wrong format", "50", df.format(5)); - assertEquals("Wrong parse", 5, df.parse("50", new ParsePosition(0)) - .intValue()); - - // regression test for HARMONY-879 - df.setMultiplier(-1); - assertEquals("Wrong multiplier for negative value", -1, df - .getMultiplier()); - } - - /** - * @tests serialization/deserialization compatibility. - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization/deserialization compatibility.", - method = "!SerializationSelf", - args = {} - ) - - public void testSerializationSelf() throws Exception { - // SerializationTest.verifySelf(new DecimalFormat()); - } - - /** - * @tests serialization compatibility with RI - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies serialization compatibility.", - method = "!SerializationGolden", - args = {} - ) - public void test_serializationHarmonyRICompatible() throws Exception { - Locale[] requiredLocales = {Locale.FRANCE}; - if (!Support_Locale.areLocalesAvailable(requiredLocales)) { - // locale dependent test, bug 1943269 - return; - } - NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE); - - DecimalFormat df = null; - if (!(nf instanceof DecimalFormat)) { - throw new Error("This NumberFormat is not a DecimalFormat"); - - } - df = (DecimalFormat) nf; - - ObjectInputStream oinput = null; - - DecimalFormat deserializedDF = null; - - try { - oinput = new ObjectInputStream(this.getClass().getResource( - "/serialization/java/text/DecimalFormat.ser").openStream()); - deserializedDF = (DecimalFormat) oinput.readObject(); - } finally { - try { - if (null != oinput) { - oinput.close(); - } - } catch (Exception e) { - // ignore - } - } - - assertEquals(df.getNegativePrefix(), deserializedDF.getNegativePrefix()); - assertEquals(df.getNegativeSuffix(), deserializedDF.getNegativeSuffix()); - assertEquals(df.getPositivePrefix(), deserializedDF.getPositivePrefix()); - assertEquals(df.getPositiveSuffix(), deserializedDF.getPositiveSuffix()); - assertEquals(df.getCurrency(), deserializedDF.getCurrency()); - - DecimalFormatSymbolsTest.assertDecimalFormatSymbolsRIFrance(deserializedDF.getDecimalFormatSymbols()); - - assertEquals(df.getGroupingSize(), df.getGroupingSize()); - assertEquals(df.getMaximumFractionDigits(), deserializedDF - .getMaximumFractionDigits()); - - assertEquals(df.getMaximumIntegerDigits(), deserializedDF - .getMaximumIntegerDigits()); - - assertEquals(df.getMinimumFractionDigits(), deserializedDF - .getMinimumFractionDigits()); - assertEquals(df.getMinimumIntegerDigits(), deserializedDF - .getMinimumIntegerDigits()); - assertEquals(df.getMultiplier(), deserializedDF.getMultiplier()); - - // Deliberately omitted this assertion. Since different data resource - // will cause the assertion fail. - // assertEquals(df, deserializedDF); - - } - - /** - * Test whether DecimalFormat can parse Positive infinity correctly - */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Regression test.", - method = "parse", - args = {java.lang.String.class, java.text.ParsePosition.class} - ) - public void testParseInfinityBigDecimalFalse() { - // Regression test for HARMONY-106 - DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(); - DecimalFormatSymbols symbols = new DecimalFormatSymbols(); - Number number = format.parse(symbols.getInfinity(), - new ParsePosition(0)); - assertTrue(number instanceof Double); - assertTrue(Double.isInfinite(number.doubleValue())); - } - - /** - * Test whether DecimalFormat can parse Negative infinity correctly - */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Regression test.", - method = "parse", - args = {java.lang.String.class, java.text.ParsePosition.class} - ) - public void testParseMinusInfinityBigDecimalFalse() { - // Regression test for HARMONY-106 - DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(); - DecimalFormatSymbols symbols = new DecimalFormatSymbols(); - Number number = format.parse("-" + symbols.getInfinity(), - new ParsePosition(0)); - assertTrue(number instanceof Double); - assertTrue(Double.isInfinite(number.doubleValue())); - } - - /** - * Test if setDecimalFormatSymbols method wont throw NullPointerException - * when it is called with null parameter. - */ - @TestTargetNew( - level = TestLevel.PARTIAL, - notes = "Verifies null as a parameter.", - method = "setDecimalFormatSymbols", - args = {java.text.DecimalFormatSymbols.class} - ) - public void testSetDecimalFormatSymbolsAsNull() { - // Regression for HARMONY-1070 - DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(); - format.setDecimalFormatSymbols(null); - } - - // BEGIN android-added: brought back from the harmony java6 branch. - public void test_SetRoudingMode_Ljava_math_RoundingMode() { - DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.US); - // ignore the fraction part of a given value - decimalFormat.setMaximumFractionDigits(0); - - // set RoundingMode.HALF_DOWN of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN); - String result = decimalFormat.format(11.3); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11", result); - - result = decimalFormat.format(11.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11", result); - - result = decimalFormat.format(11.6); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "12", result); - - // set RoundingMode.CEILING of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.CEILING); - result = decimalFormat.format(11.3); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.CEILING", "12", result); - - result = decimalFormat.format(-11.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.CEILING", "-11", result); - - // set RoundingMode.DOWN of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.DOWN); - result = decimalFormat.format(11.3); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "11", result); - - result = decimalFormat.format(-11.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "-11", result); - - result = decimalFormat.format(0); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "0", result); - - // set RoundingMode.FLOOR of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.FLOOR); - result = decimalFormat.format(11.3); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "11", result); - - result = decimalFormat.format(-11.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "-12", result); - - result = decimalFormat.format(0); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "0", result); - - // set RoundingMode.HALF_EVEN of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.HALF_EVEN); - result = decimalFormat.format(5.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "6", result); - - result = decimalFormat.format(-5.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "-6", result); - - result = decimalFormat.format(0.2); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "0", result); - - // set RoundingMode.HALF_UP of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.HALF_UP); - result = decimalFormat.format(5.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "6", result); - - result = decimalFormat.format(-5.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "-6", result); - - result = decimalFormat.format(0.2); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "0", result); - - // BEGIN android-changed: we're RI-compatible. - // the following assertion will fail on RI implementation, since the - // implementation of ICU and RI are not identical. - result = decimalFormat.format(-0.2); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "-0", result); - // END android-changed - - // set RoundingMode.UP of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.UP); - result = decimalFormat.format(5.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "6", result); - - result = decimalFormat.format(-5.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "-6", result); - - result = decimalFormat.format(0.2); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "1", result); - - result = decimalFormat.format(-0.2); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "-1", result); - - // set RoundingMode.UNNECESSARY of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.UNNECESSARY); - - try { - // when rounding is needed but RoundingMode is set to RoundingMode.UNNECESSARY, throw ArithmeticException - result = decimalFormat.format(5.5); - fail("ArithmeticException expected: RoundingMode.UNNECESSARY"); - } catch (ArithmeticException e) { - // expected - } - - result = decimalFormat.format(1.0); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UNNECESSARY", "1", result); - - result = decimalFormat.format(-1.0); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UNNECESSARY", "-1", result); - - try { - // when the given RoundingMode is null, throw NullPointerException - decimalFormat.setRoundingMode(null); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // expected - } - - // set MaxFractionDigits to 3, test different DecimalFormat format - // function with differnt RoundingMode - decimalFormat.setMaximumFractionDigits(3); - - // set RoundingMode.HALF_DOWN of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN); - result = decimalFormat.format(11.5653); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11.565", result); - - result = decimalFormat.format(11.5655); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11.565", result); - - result = decimalFormat.format(11.5656); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11.566", result); - - // set RoundingMode.CEILING of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.CEILING); - result = decimalFormat.format(11.5653); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.CEILING", "11.566", result); - - result = decimalFormat.format(-11.5653); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.CEILING", "-11.565", result); - - // set RoundingMode.DOWN of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.DOWN); - result = decimalFormat.format(11.5653); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "11.565", result); - - result = decimalFormat.format(-11.5653); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "-11.565", result); - - result = decimalFormat.format(0); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "0", result); - - // set RoundingMode.FLOOR of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.FLOOR); - result = decimalFormat.format(11.5653); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "11.565", result); - - result = decimalFormat.format(-11.5655); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "-11.566", result); - - result = decimalFormat.format(0); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "0", result); - - // set RoundingMode.HALF_EVEN of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.HALF_EVEN); - result = decimalFormat.format(11.5653); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "11.565", result); - - result = decimalFormat.format(-11.5655); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "-11.566", result); - - result = decimalFormat.format(11.5656); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "11.566", result); - - // set RoundingMode.HALF_UP of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.HALF_UP); - result = decimalFormat.format(11.5653); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "11.565", result); - - result = decimalFormat.format(-11.5655); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "-11.566", result); - - result = decimalFormat.format(11.5656); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "11.566", result); - - // set RoundingMode.UP of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.UP); - result = decimalFormat.format(11.5653); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "11.566", result); - - result = decimalFormat.format(-11.5655); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "-11.566", result); - - // set RoundingMode.UNNECESSARY of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.UNNECESSARY); - result = decimalFormat.format(-11.565); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UNNECESSARY", "-11.565", result); - - result = decimalFormat.format(11.565); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UNNECESSARY", "11.565", result); - - // when setting MaxFractionDigits to negative value -2, default it as - // zero, test different DecimalFormat format - // function with differnt RoundingMode - decimalFormat.setMaximumFractionDigits(-2); - - // set RoundingMode.HALF_DOWN of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN); - result = decimalFormat.format(11.3); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11", result); - - result = decimalFormat.format(11.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "11", result); - - result = decimalFormat.format(11.6); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_DOWN", "12", result); - - // set RoundingMode.CEILING of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.CEILING); - result = decimalFormat.format(11.3); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.CEILING", "12", result); - - result = decimalFormat.format(-11.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.CEILING", "-11", result); - - // set RoundingMode.DOWN of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.DOWN); - result = decimalFormat.format(11.3); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "11", result); - - result = decimalFormat.format(-11.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "-11", result); - - result = decimalFormat.format(0); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.DOWN", "0", result); - - // set RoundingMode.FLOOR of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.FLOOR); - result = decimalFormat.format(11.3); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "11", result); - - result = decimalFormat.format(-11.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "-12", result); - - result = decimalFormat.format(0); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.FLOOR", "0", result); - - // set RoundingMode.HALF_EVEN of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.HALF_EVEN); - result = decimalFormat.format(5.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "6", result); - - result = decimalFormat.format(-5.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "-6", result); - - result = decimalFormat.format(0.2); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_EVEN", "0", result); - - // set RoundingMode.HALF_UP of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.HALF_UP); - result = decimalFormat.format(5.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "6", result); - - result = decimalFormat.format(-5.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "-6", result); - - result = decimalFormat.format(0.2); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "0", result); - - result = decimalFormat.format(-0.2); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.HALF_UP", "-0", result); - - // set RoundingMode.UP of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.UP); - result = decimalFormat.format(5.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "6", result); - - result = decimalFormat.format(-5.5); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "-6", result); - - result = decimalFormat.format(0.2); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "1", result); - - result = decimalFormat.format(-0.2); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UP", "-1", result); - - // set RoundingMode.UNNECESSARY of this DecimalFormat and test its - // behavior - decimalFormat.setRoundingMode(RoundingMode.UNNECESSARY); - - result = decimalFormat.format(1.0); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UNNECESSARY", "1", result); - - result = decimalFormat.format(-1.0); - assertEquals("Incorrect RoundingMode behavior: RoundingMode.UNNECESSARY", "-1", result); - } -} diff --git a/luni/src/test/java/tests/api/java/net/AllTests.java b/luni/src/test/java/tests/api/java/net/AllTests.java index 61c9555..7733b96 100644 --- a/luni/src/test/java/tests/api/java/net/AllTests.java +++ b/luni/src/test/java/tests/api/java/net/AllTests.java @@ -16,6 +16,7 @@ package tests.api.java.net; +import java.net.OldURLClassLoaderTest; import junit.framework.Test; import junit.framework.TestSuite; @@ -39,7 +40,6 @@ public class AllTests { suite.addTestSuite(DatagramSocketImplFactoryTest.class); suite.addTestSuite(DatagramSocketImplTest.class); suite.addTestSuite(DatagramSocketTest.class); - suite.addTestSuite(ExcludedProxyTest.class); suite.addTestSuite(FileNameMapTest.class); suite.addTestSuite(HttpRetryExceptionTest.class); suite.addTestSuite(IDNTest.class); @@ -67,7 +67,6 @@ public class AllTests { suite.addTestSuite(UnixSocketTest.class); suite.addTestSuite(URISyntaxExceptionTest.class); suite.addTestSuite(URITest.class); - suite.addTestSuite(URLClassLoaderTest.class); suite.addTestSuite(URLDecoderTest.class); suite.addTestSuite(URLEncoderTest.class); suite.addTestSuite(UnknownHostExceptionTest.class); diff --git a/luni/src/test/java/tests/api/java/net/ExcludedProxyTest.java b/luni/src/test/java/tests/api/java/net/ExcludedProxyTest.java deleted file mode 100644 index 7e01e18..0000000 --- a/luni/src/test/java/tests/api/java/net/ExcludedProxyTest.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 tests.api.java.net; - -import dalvik.annotation.BrokenTest; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.Socket; -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.net.SocketAddress; -import java.net.URL; -import java.net.URLConnection; - -import tests.support.Support_Configuration; -import tests.support.resource.Support_Resources; -import junit.framework.TestCase; -import tests.util.TestEnvironment; - -/* - * This test is designed for collecting all the testcases which needs a proxy - * server. They will be moved to corresponding test class when ProxyHandler of - * Jetty is ready in the future. - * - */ - -@TestTargetClass(Proxy.class) -public class ExcludedProxyTest extends TestCase { - - @Override protected void setUp() throws Exception { - super.setUp(); - TestEnvironment.reset(); - } - - /** - * @tests java.net.HttpURLConnection#usingProxy() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Tests Proxy functionality. Indirect test.", - method = "Proxy", - args = {java.net.Proxy.Type.class, java.net.SocketAddress.class} - ) - @BrokenTest("the host address isn't working anymore") - public void test_usingProxy() throws Exception { - try { - System.setProperty("http.proxyHost", - Support_Configuration.ProxyServerTestHost); - - URL u1 = new URL("http://" + Support_Configuration.HomeAddress); - URLConnection conn1 = u1.openConnection(); - conn1.getInputStream(); - - boolean exception = false; - try { - System.setProperty("http.proxyPort", "81"); - URL u3 = new URL("http://" - + Support_Configuration.InetTestAddress); - URLConnection conn3 = u3.openConnection(); - conn3.getInputStream(); - fail("Should throw IOException"); - } catch (IOException e) { - // expected - } - - System.setProperty("http.proxyPort", "80"); - - URL u2 = new URL("http://" - + Support_Configuration.ProxyServerTestHost - + "/cgi-bin/test.pl"); - java.net.HttpURLConnection conn2 = (java.net.HttpURLConnection) u2 - .openConnection(); - conn2.setDoOutput(true); - conn2.setRequestMethod("POST"); - OutputStream out2 = conn2.getOutputStream(); - String posted2 = "this is a test"; - out2.write(posted2.getBytes()); - out2.close(); - conn2.getResponseCode(); - InputStream is2 = conn2.getInputStream(); - String response2 = ""; - byte[] b2 = new byte[1024]; - int count2 = 0; - while ((count2 = is2.read(b2)) > 0) - response2 += new String(b2, 0, count2); - assertTrue("Response to POST method invalid", response2 - .equals(posted2)); - - String posted4 = "just a test"; - URL u4 = new URL("http://" - + Support_Configuration.ProxyServerTestHost - + "/cgi-bin/test.pl"); - java.net.HttpURLConnection conn4 = (java.net.HttpURLConnection) u4 - .openConnection(); - conn4.setDoOutput(true); - conn4.setRequestMethod("POST"); - conn4.setRequestProperty("Content-length", String.valueOf(posted4 - .length())); - OutputStream out = conn4.getOutputStream(); - out.write(posted4.getBytes()); - out.close(); - conn4.getResponseCode(); - InputStream is = conn4.getInputStream(); - String response = ""; - byte[] b4 = new byte[1024]; - int count = 0; - while ((count = is.read(b4)) > 0) - response += new String(b4, 0, count); - assertTrue("Response to POST method invalid", response - .equals(posted4)); - } finally { - System.setProperties(null); - } - } - - /** - * @tests java.net.SocketImpl#SocketImpl() - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Tests Proxy functionality. Indirect test.", - method = "Proxy", - args = {java.net.Proxy.Type.class, java.net.SocketAddress.class} - ) - @BrokenTest("the host address isn't working anymore") - public void test_Constructor() { - try { - try { - System.setProperty("socksProxyHost", - Support_Configuration.SocksServerTestHost); - System.setProperty("socksProxyPort", String - .valueOf(Support_Configuration.SocksServerTestPort)); - Socket s = new Socket(Support_Configuration.HomeAddress, 80); - OutputStream os = s.getOutputStream(); - os.write("GET / HTTP/1.0\r\n\r\n".getBytes()); - s.getInputStream(); - } catch (IOException e) { - fail("Could not open socket: " - + Support_Configuration.HomeAddress + " " + e); - } - boolean exception = false; - try { - System.setProperty("socksProxyHost", - Support_Configuration.SocksServerTestHost); - System - .setProperty( - "socksProxyPort", - String - .valueOf(Support_Configuration.SocksServerTestPort + 1)); - Socket s = new Socket(Support_Configuration.HomeAddress, 80); - OutputStream os = s.getOutputStream(); - os.write("GET / HTTP/1.0\r\n\r\n".getBytes()); - s.getInputStream(); - } catch (IOException e) { - exception = true; - } - assertTrue("Exception should have been thrown", exception); - } finally { - System.setProperties(null); - } - } - - /** - * @tests java.net.URL#openConnection(Proxy) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Tests Proxy functionality. Indirect test.", - method = "Proxy", - args = {java.net.Proxy.Type.class, java.net.SocketAddress.class} - ) - @BrokenTest("the host address isn't working anymore") - public void test_openConnectionLjava_net_Proxy() throws IOException { - SocketAddress addr1 = new InetSocketAddress( - Support_Configuration.ProxyServerTestHost, 808); - SocketAddress addr2 = new InetSocketAddress( - Support_Configuration.ProxyServerTestHost, 1080); - Proxy proxy1 = new Proxy(Proxy.Type.HTTP, addr1); - Proxy proxy2 = new Proxy(Proxy.Type.SOCKS, addr2); - Proxy proxyList[] = { proxy1, proxy2 }; - for (int i = 0; i < proxyList.length; ++i) { - String posted = "just a test"; - URL u = new URL("http://" - + Support_Configuration.ProxyServerTestHost - + "/cgi-bin/test.pl"); - java.net.HttpURLConnection conn = (java.net.HttpURLConnection) u - .openConnection(proxyList[i]); - conn.setDoOutput(true); - conn.setRequestMethod("POST"); - conn.setRequestProperty("Content-length", String.valueOf(posted - .length())); - OutputStream out = conn.getOutputStream(); - out.write(posted.getBytes()); - out.close(); - conn.getResponseCode(); - InputStream is = conn.getInputStream(); - String response = ""; - byte[] b = new byte[1024]; - int count = 0; - while ((count = is.read(b)) > 0) { - response += new String(b, 0, count); - } - assertTrue("Response to POST method invalid", response - .equals(posted)); - } - - URL httpUrl = new URL("http://abc.com"); - URL jarUrl = new URL("jar:" - + Support_Resources.getResourceURL("/JUC/lf.jar!/plus.bmp")); - URL ftpUrl = new URL("ftp://" + Support_Configuration.FTPTestAddress - + "/nettest.txt"); - URL fileUrl = new URL("file://abc"); - URL[] urlList = { httpUrl, jarUrl, ftpUrl, fileUrl }; - for (int i = 0; i < urlList.length; ++i) { - try { - urlList[i].openConnection(null); - } catch (IllegalArgumentException iae) { - // expected - } - } - // should not throw exception - fileUrl.openConnection(Proxy.NO_PROXY); - } -} diff --git a/luni/src/test/java/tests/targets/security/cert/CertPathBuilderTest.java b/luni/src/test/java/tests/security/CertPathBuilderTest.java index 2ac8131..1c82999 100644 --- a/luni/src/test/java/tests/targets/security/cert/CertPathBuilderTest.java +++ b/luni/src/test/java/tests/security/CertPathBuilderTest.java @@ -13,18 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security.cert; +package tests.security; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargets; - -import junit.framework.TestCase; - import java.security.cert.CertPath; import java.security.cert.CertPathBuilder; import java.security.cert.CertPathBuilderResult; import java.security.cert.CertPathParameters; +import junit.framework.TestCase; public abstract class CertPathBuilderTest extends TestCase { private final String algorithmName; @@ -41,8 +39,8 @@ public abstract class CertPathBuilderTest extends TestCase { params = getCertPathParameters(); } - abstract CertPathParameters getCertPathParameters() throws Exception; - abstract void validateCertPath(CertPath path); + public abstract CertPathParameters getCertPathParameters() throws Exception; + public abstract void validateCertPath(CertPath path); @TestTargets({ @TestTargetNew( diff --git a/luni/src/test/java/tests/targets/security/cert/CertPathValidatorTest.java b/luni/src/test/java/tests/security/CertPathValidatorTest.java index db5942d..2821f47 100644 --- a/luni/src/test/java/tests/targets/security/cert/CertPathValidatorTest.java +++ b/luni/src/test/java/tests/security/CertPathValidatorTest.java @@ -13,18 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security.cert; +package tests.security; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargets; - -import junit.framework.TestCase; - import java.security.cert.CertPath; import java.security.cert.CertPathParameters; import java.security.cert.CertPathValidator; import java.security.cert.CertPathValidatorResult; +import junit.framework.TestCase; public abstract class CertPathValidatorTest extends TestCase { @@ -35,9 +33,9 @@ public abstract class CertPathValidatorTest extends TestCase { this.algorithmName = algorithmName; } - abstract CertPathParameters getParams(); - abstract CertPath getCertPath(); - abstract void validateResult(CertPathValidatorResult validatorResult); + public abstract CertPathParameters getParams(); + public abstract CertPath getCertPath(); + public abstract void validateResult(CertPathValidatorResult validatorResult); @TestTargets({ @TestTargetNew( diff --git a/luni/src/test/java/tests/targets/security/cert/CertificateFactoryTest.java b/luni/src/test/java/tests/security/CertificateFactoryTest.java index a5d7a46..1bfa2aa 100644 --- a/luni/src/test/java/tests/targets/security/cert/CertificateFactoryTest.java +++ b/luni/src/test/java/tests/security/CertificateFactoryTest.java @@ -13,19 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security.cert; +package tests.security; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargets; - -import junit.framework.TestCase; - import java.io.ByteArrayInputStream; import java.io.InputStream; import java.security.cert.Certificate; -import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; +import junit.framework.TestCase; public abstract class CertificateFactoryTest extends TestCase { diff --git a/luni/src/test/java/tests/targets/security/SecureRandomTest.java b/luni/src/test/java/tests/security/SecureRandomTest.java index 3203902..cf9c6dc 100644 --- a/luni/src/test/java/tests/targets/security/SecureRandomTest.java +++ b/luni/src/test/java/tests/security/SecureRandomTest.java @@ -13,17 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package tests.targets.security; +package tests.security; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargets; - -import junit.framework.TestCase; - import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Arrays; +import junit.framework.TestCase; public abstract class SecureRandomTest extends TestCase { diff --git a/luni/src/test/java/tests/security/cert/AllTests.java b/luni/src/test/java/tests/security/cert/AllTests.java index e5b9d47..ab86e89 100644 --- a/luni/src/test/java/tests/security/cert/AllTests.java +++ b/luni/src/test/java/tests/security/cert/AllTests.java @@ -16,6 +16,7 @@ package tests.security.cert; +import java.security.cert.OldPKIXParametersTest; import junit.framework.Test; import junit.framework.TestSuite; @@ -64,7 +65,6 @@ public class AllTests { suite.addTestSuite(PKIXCertPathBuilderResultTest.class); suite.addTestSuite(PKIXCertPathCheckerTest.class); suite.addTestSuite(PKIXCertPathValidatorResultTest.class); - suite.addTestSuite(PKIXParametersTest.class); suite.addTestSuite(PolicyQualifierInfoTest.class); suite.addTestSuite(TrustAnchorTest.class); suite.addTestSuite(X509CRL2Test.class); diff --git a/luni/src/test/java/tests/security/cert/PKIXParametersTest.java b/luni/src/test/java/tests/security/cert/PKIXParametersTest.java deleted file mode 100644 index 1b88b58..0000000 --- a/luni/src/test/java/tests/security/cert/PKIXParametersTest.java +++ /dev/null @@ -1,1879 +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. - */ - -/** - * @author Vladimir N. Molotkov - * @version $Revision$ - */ - -package tests.security.cert; - -import dalvik.annotation.AndroidOnly; -import dalvik.annotation.BrokenTest; -import dalvik.annotation.TestTargets; -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargetClass; - -import junit.framework.TestCase; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertPathParameters; -import java.security.cert.CertPathValidatorException; -import java.security.cert.CertStore; -import java.security.cert.CertificateFactory; -import java.security.cert.CollectionCertStoreParameters; -import java.security.cert.PKIXCertPathChecker; -import java.security.cert.PKIXParameters; -import java.security.cert.TrustAnchor; -import java.security.cert.X509CertSelector; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.harmony.security.tests.support.cert.TestUtils; - -import tests.targets.security.KeyStoreTestPKCS12; - -/** - * Tests for <code>PKIXParameters</code> fields and methods - */ -@TestTargetClass(PKIXParameters.class) -public class PKIXParametersTest extends TestCase { - /** - * Some valid issuer name - */ - private final static String testIssuer = - "CN=VM,OU=DRL Security,O=Intel,L=Novosibirsk,ST=NSO,C=RU"; - - // - // Tests - // - - /** - * Test #1 for <code>PKIXParameters(Set)</code> constructor<br> - * Assertion: Creates an instance of <code>PKIXParameters</code> with the - * specified <code>Set</code> of most-trusted CAs. Each element of the set - * is a <code>TrustAnchor</code> - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies positive case.", - method = "PKIXParameters", - args = {java.util.Set.class} - ) - public final void testPKIXParametersSet01() - throws InvalidAlgorithmParameterException { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - // use valid parameter - CertPathParameters cpp = new PKIXParameters(taSet); - assertTrue(cpp instanceof PKIXParameters); - } - - /** - * Test #2 for <code>PKIXParameters(Set)</code> constructor<br> - * Assertion: ... the <code>Set</code> is copied to protect against - * subsequent modifications - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify exceptions.", - method = "PKIXParameters", - args = {java.util.Set.class} - ) - @SuppressWarnings("unchecked") - public final void testPKIXParametersSet02() - throws InvalidAlgorithmParameterException { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - HashSet<TrustAnchor> originalSet = (HashSet<TrustAnchor>) taSet; - HashSet<TrustAnchor> originalSetCopy = (HashSet<TrustAnchor>) originalSet - .clone(); - // create test object using originalSet - PKIXParameters pp = new PKIXParameters(originalSetCopy); - // modify originalSet - originalSetCopy.clear(); - // check that test object's internal state - // has not been affected by the above modification - Set returnedSet = pp.getTrustAnchors(); - assertEquals(originalSet, returnedSet); - } - - /** - * Test #3 for <code>PKIXParameters(Set)</code> constructor<br> - * Assertion: <code>NullPointerException</code> - if the specified - * <code>Set</code> is null - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NullPointerException.", - method = "PKIXParameters", - args = {java.util.Set.class} - ) - public final void testPKIXParametersSet03() throws Exception { - try { - // pass null - new PKIXParameters((Set<TrustAnchor>) null); - fail("NPE expected"); - } catch (NullPointerException e) { - } - } - - /** - * Test #4 for <code>PKIXParameters(Set)</code> constructor<br> - * Assertion: <code>InvalidAlgorithmParameterException</code> - if the - * specified <code>Set</code> is empty ( - * <code>trustAnchors.isEmpty() == true</code>) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies InvalidAlgorithmParameterException.", - method = "PKIXParameters", - args = {java.util.Set.class} - ) - public final void testPKIXParametersSet04() { - try { - // use empty set - new PKIXParameters(new HashSet<TrustAnchor>()); - fail("InvalidAlgorithmParameterException expected"); - } catch (InvalidAlgorithmParameterException e) { - } - } - - /** - * Test #5 for <code>PKIXParameters(Set)</code> constructor<br> - * Assertion: <code>ClassCastException</code> - if any of the elements in - * the <code>Set</code> are not of type - * <code>java.security.cert.TrustAnchor</code> - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies ClassCastException.", - method = "PKIXParameters", - args = {java.util.Set.class} - ) - @SuppressWarnings("unchecked") - public final void testPKIXParametersSet05() throws Exception { - Set taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - // add wrong object to valid set - assertTrue(taSet.add(new Object())); - try { - new PKIXParameters(taSet); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - } - } - - /** - * Test #3 for <code>PKIXParameters(KeyStore)</code> constructor<br> - * Assertion: <code>NullPointerException</code> - if the - * <code>keystore</code> is <code>null</code> - * - * @throws InvalidAlgorithmParameterException - * @throws KeyStoreException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NullPointerException.", - method = "PKIXParameters", - args = {java.security.KeyStore.class} - ) - public final void testPKIXParametersKeyStore03() throws Exception { - try { - // pass null - new PKIXParameters((KeyStore) null); - fail("NPE expected"); - } catch (NullPointerException e) { - } - } - - /** - * Test for <code>clone()</code> method<br> - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "clone", - args = {} - ) - public final void testClone() throws InvalidAlgorithmParameterException { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters cpp = new PKIXParameters(taSet); - PKIXParameters cppc = (PKIXParameters) cpp.clone(); - - assertEquals(cpp.getPolicyQualifiersRejected(), cppc - .getPolicyQualifiersRejected()); - assertEquals(cpp.getCertPathCheckers(), cppc.getCertPathCheckers()); - assertEquals(cpp.getCertStores(), cppc.getCertStores()); - assertEquals(cpp.getDate(), cppc.getDate()); - assertEquals(cpp.getInitialPolicies(), cppc.getInitialPolicies()); - assertEquals(cpp.getSigProvider(), cppc.getSigProvider()); - assertEquals(cpp.getTargetCertConstraints(), cppc - .getTargetCertConstraints()); - assertEquals(cpp.getTrustAnchors(), cppc.getTrustAnchors()); - - assertEquals(cpp.isAnyPolicyInhibited(), cppc.isAnyPolicyInhibited()); - assertEquals(cpp.isExplicitPolicyRequired(), cppc - .isExplicitPolicyRequired()); - assertEquals(cpp.isPolicyMappingInhibited(), cppc - .isPolicyMappingInhibited()); - assertEquals(cpp.isRevocationEnabled(), cppc.isRevocationEnabled()); - - cpp.setDate(Calendar.getInstance().getTime()); - cpp.setPolicyQualifiersRejected(!cppc.getPolicyQualifiersRejected()); - assertFalse(cpp.getDate().equals(cppc.getDate())); - assertFalse(cpp.getPolicyQualifiersRejected() == cppc - .getPolicyQualifiersRejected()); - - cppc.setExplicitPolicyRequired(!cpp.isExplicitPolicyRequired()); - cppc.setRevocationEnabled(!cpp.isRevocationEnabled()); - - assertFalse(cpp.isExplicitPolicyRequired() == cppc - .isExplicitPolicyRequired()); - assertFalse(cpp.isRevocationEnabled() == cppc.isRevocationEnabled()); - - PKIXParameters cpp1 = null; - try { - cpp1.clone(); - } catch (NullPointerException e) { - // expected - } - } - - /** - * Test #1 for <code>getPolicyQualifiersRejected()</code> method<br> - * Assertion: When a <code>PKIXParameters</code> object is created, this - * flag is set to <code>true</code><br> - * Assertion: returns the current value of the PolicyQualifiersRejected flag - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getPolicyQualifiersRejected", - args = {} - ) - public final void testGetPolicyQualifiersRejected() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - assertTrue(p.getPolicyQualifiersRejected()); - } - - /** - * Test for <code>setPolicyQualifiersRejected()</code> method<br> - * Assertion: set the new value of the <code>PolicyQualifiersRejected</code> - * flag - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setPolicyQualifiersRejected", - args = {boolean.class} - ) - public final void testSetPolicyQualifiersRejected() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - p.setPolicyQualifiersRejected(false); - assertFalse("setFalse", p.getPolicyQualifiersRejected()); - p.setPolicyQualifiersRejected(true); - assertTrue("setTrue", p.getPolicyQualifiersRejected()); - } - - /** - * Test for <code>isAnyPolicyInhibited()</code> method<br> - * Assertion: returns <code>true</code> if the any policy OID is inhibited, - * <code>false</code> otherwise<br> - * Assertion: By default, the any policy OID is not inhibited ( - * <code>isAnyPolicyInhibited()</code> returns false). - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isAnyPolicyInhibited", - args = {} - ) - public final void testIsAnyPolicyInhibited() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - assertFalse(p.isAnyPolicyInhibited()); - } - - /** - * Test for <code>setAnyPolicyInhibited()</code> method<br> - * Assertion: sets state to determine if the any policy OID should be - * processed if it is included in a certificate - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setAnyPolicyInhibited", - args = {boolean.class} - ) - public final void testSetAnyPolicyInhibited() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - p.setAnyPolicyInhibited(true); - assertTrue("setTrue", p.isAnyPolicyInhibited()); - p.setAnyPolicyInhibited(false); - assertFalse("setFalse", p.isAnyPolicyInhibited()); - } - - /** - * Test for <code>isExplicitPolicyRequired()</code> method<br> - * Assertion: returns <code>true</code> if explicit policy is required, - * <code>false</code> otherwise<br> - * Assertion: by default, the ExplicitPolicyRequired flag is false - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isExplicitPolicyRequired", - args = {} - ) - public final void testIsExplicitPolicyRequired() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - assertFalse(p.isExplicitPolicyRequired()); - } - - /** - * Test for <code>setExplicitPolicyRequired()</code> method<br> - * Assertion: sets the ExplicitPolicyRequired flag - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setExplicitPolicyRequired", - args = {boolean.class} - ) - public final void testSetExplicitPolicyRequired() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - p.setExplicitPolicyRequired(true); - assertTrue("setTrue", p.isExplicitPolicyRequired()); - p.setExplicitPolicyRequired(false); - assertFalse("setFalse", p.isExplicitPolicyRequired()); - } - - /** - * Test for <code>isPolicyMappingInhibited()</code> method<br> - * Assertion: returns true if policy mapping is inhibited, false otherwise - * Assertion: by default, policy mapping is not inhibited (the flag is - * false) - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isPolicyMappingInhibited", - args = {} - ) - public final void testIsPolicyMappingInhibited() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - assertFalse(p.isPolicyMappingInhibited()); - - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - TestUtils.initCertPathSSCertChain(); - Set<TrustAnchor> taSet2 = Collections.singleton(new TrustAnchor( - TestUtils.rootCertificateSS, null)); - p = new PKIXParameters(taSet2); - - assertFalse(p.isPolicyMappingInhibited()); - p.setPolicyMappingInhibited(true); - assertTrue(p.isRevocationEnabled()); - } - - /** - * Test for <code>setPolicyMappingInhibited()</code> method<br> - * Assertion: sets the PolicyMappingInhibited flag - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setPolicyMappingInhibited", - args = {boolean.class} - ) - public final void testSetPolicyMappingInhibited() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - p.setPolicyMappingInhibited(true); - assertTrue("setTrue", p.isPolicyMappingInhibited()); - p.setPolicyMappingInhibited(false); - assertFalse("setFalse", p.isPolicyMappingInhibited()); - } - - /** - * Test for <code>isPolicyMappingInhibited()</code> method<br> - * Assertion: returns the current value of the RevocationEnabled flag - * Assertion: when a <code>PKIXParameters</code> object is created, this - * flag is set to true - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "isRevocationEnabled", - args = {} - ) - public final void testIsRevocationEnabled() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - assertTrue(p.isRevocationEnabled()); - - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - TestUtils.initCertPathSSCertChain(); - Set<TrustAnchor> taSet2 = Collections.singleton(new TrustAnchor( - TestUtils.rootCertificateSS, null)); - p = new PKIXParameters(taSet2); - - assertTrue(p.isRevocationEnabled()); - p.setRevocationEnabled(false); - assertFalse(p.isRevocationEnabled()); - } - - /** - * Test for <code>isPolicyMappingInhibited()</code> method<br> - * Assertion: sets the RevocationEnabled flag - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setRevocationEnabled", - args = {boolean.class} - ) - public final void testSetRevocationEnabled() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - p.setRevocationEnabled(false); - assertFalse("setFalse", p.isRevocationEnabled()); - p.setRevocationEnabled(true); - assertTrue("setTrue", p.isRevocationEnabled()); - } - - /** - * Test for <code>getSigProvider()</code> method<br> - * Assertion: returns the signature provider's name, or null if not set - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "getSigProvider", - args = {} - ) - public final void testGetSigProvider() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - assertNull("not set", p.getSigProvider()); - p.setSigProvider("Some Provider"); - assertNotNull("set", p.getSigProvider()); - } - - /** - * Test for <code>setSigProvider(String)</code> method<br> - * Assertion: sets the signature provider's name - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setSigProvider", - args = {java.lang.String.class} - ) - public final void testSetSigProvider() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - String sigProviderName = "Some Provider"; - p.setSigProvider(sigProviderName); - assertTrue("set", sigProviderName.equals(p.getSigProvider())); - p.setSigProvider(null); - assertNull("unset", p.getSigProvider()); - } - - /** - * Test #1 for <code>getTargetCertConstraints()</code> method<br> - * Assertion: returns a <code>CertSelector</code> specifying the constraints - * on the target certificate (or <code>null</code>) - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that getTargetCertConstraints method returns null, if no constraints are defined.", - method = "getTargetCertConstraints", - args = {} - ) - public final void testGetTargetCertConstraints01() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - assertNull(p.getTargetCertConstraints()); - } - - /** - * Test #2 for <code>getTargetCertConstraints()</code> method<br> - * Assertion: note that the <code>CertSelector</code> returned is cloned to - * protect against subsequent modifications - * - * @throws InvalidAlgorithmParameterException - * @throws IOException - */ - @TestTargets({ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "Verifies that returned CertSelector is cloned to protect against subsequent modifications.", - method = "setTargetCertConstraints", - args = {java.security.cert.CertSelector.class} - ), - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getTargetCertConstraints", - args = {} - ) - }) - public final void testGetTargetCertConstraints02() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - X509CertSelector x509cs = new X509CertSelector(); - PKIXParameters p = new PKIXParameters(taSet); - p.setTargetCertConstraints(x509cs); - // get cert selector - X509CertSelector cs1 = (X509CertSelector)p.getTargetCertConstraints(); - X509CertSelector cs3 = (X509CertSelector)p.getTargetCertConstraints(); - assertNotNull(cs1); - // modify returned selector - cs1.setIssuer(testIssuer); - // get cert selector again - X509CertSelector cs2 = (X509CertSelector)p.getTargetCertConstraints(); - // check that selector is not the same - assertNotSame("notTheSame", cs1, cs2); - // check that selector's internal state has - // not been changed by above modification - assertFalse("internal stateNotChanged", testIssuer.equals(cs2.getIssuerAsString())); - } - - /** - * Test for <code>setTargetCertConstraints(CertSelector)</code> method<br> - * Assertion: sets the required constraints on the target certificate. The - * constraints are specified as an instance of CertSelector<br> - * Assertion: ... If <code>null</code>, no constraints are defined - * - * @throws IOException - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "setTargetCertConstraints", - args = {java.security.cert.CertSelector.class} - ) - public final void testSetTargetCertConstraints01() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - X509CertSelector x509cs = new X509CertSelector(); - x509cs.setIssuer(testIssuer); - PKIXParameters p = new PKIXParameters(taSet); - p.setTargetCertConstraints(x509cs); - assertEquals("set", testIssuer, ((X509CertSelector) p - .getTargetCertConstraints()).getIssuerAsString()); - p.setTargetCertConstraints(null); - assertNull("unset", p.getTargetCertConstraints()); - } - - /** - * Test #2 for <code>setTargetCertConstraints(CertSelector)</code> method<br> - * Assertion: ... the CertSelector specified is cloned to protect against - * subsequent modifications - * - * @throws IOException - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Additional test.", - method = "setTargetCertConstraints", - args = {java.security.cert.CertSelector.class} - ) - public final void testSetTargetCertConstraints02() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - X509CertSelector x509cs = new X509CertSelector(); - PKIXParameters p = new PKIXParameters(taSet); - p.setTargetCertConstraints(x509cs); - // modify selector - x509cs.setIssuer(testIssuer); - // get selector - X509CertSelector x509cs1 = (X509CertSelector) p - .getTargetCertConstraints(); - // check that selector's internal state has - // not been changed by above modification - assertFalse(testIssuer.equals(x509cs1.getIssuerAsString())); - } - - /** - * Test #1 for <code>getCertStores()</code> method<br> - * Assertion: list ... (may be empty, but never <code>null</code>) - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that getCertStores method returns empty list, but not null.", - method = "getCertStores", - args = {} - ) - public final void testGetCertStores01() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - assertNotNull("notNull", p.getCertStores()); - assertTrue("isEmpty", p.getCertStores().isEmpty()); - } - - /** - * Test #2 for <code>getCertStores()</code> method<br> - * Assertion: returns an immutable <code>List</code> of - * <code>CertStores</code> - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that getCertStores method returns an immutable List of CertStores.", - method = "getCertStores", - args = {} - ) - public final void testGetCertStores02() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - List<CertStore> cs = p.getCertStores(); - - try { - // try to modify returned list - cs.add((CertStore) (new Object())); - fail("must be immutable"); - } catch (Exception e) { - } - } - - /** - * Test #1 for <code>setCertStores(List)</code> method<br> - * Assertion: Sets the list of CertStores ... - * - * @throws NoSuchAlgorithmException - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify ClassCastException.", - method = "setCertStores", - args = {java.util.List.class} - ) - public final void testSetCertStores01() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - p.setCertStores(TestUtils.getCollectionCertStoresList()); - // check that list has been set - assertFalse(p.getCertStores().isEmpty()); - } - - /** - * Test #2 for <code>setCertStores(List)</code> method<br> - * Assertion: list ... may be <code>null</code> - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify ClassCastException.", - method = "setCertStores", - args = {java.util.List.class} - ) - public final void testSetCertStores02() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - // add null - p.setCertStores(null); - // check that we have non null empty list now - assertNotNull("notNull1", p.getCertStores()); - assertTrue("isEmpty1", p.getCertStores().isEmpty()); - // add empty - p.setCertStores(new ArrayList<CertStore>()); - assertNotNull("notNull2", p.getCertStores()); - assertTrue("isEmpty2", p.getCertStores().isEmpty()); - } - - /** - * Test #3 for <code>setCertStores(List)</code> method<br> - * Assertion: list is copied to protect against subsequent modifications - * - * @throws NoSuchAlgorithmException - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that the list is copied to protect against subsequent modifications.", - method = "setCertStores", - args = {java.util.List.class} - ) - public final void testSetCertStores03() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - List<CertStore> l = TestUtils.getCollectionCertStoresList(); - p.setCertStores(l); - // modify list just set - l.clear(); - // check that list maintained internally has - // not been changed by the above modification - assertFalse(p.getCertStores().isEmpty()); - } - - /** - * Test #4 for <code>setCertStores(List)</code> method<br> - * Assertion: <code>ClassCastException</code> - if any of the elements in - * the list are not of type <code>java.security.cert.CertStore</code> - * - * @throws InvalidAlgorithmParameterException - * @throws NoSuchAlgorithmException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies ClassCastException.", - method = "setCertStores", - args = {java.util.List.class} - ) - @SuppressWarnings("unchecked") - public final void testSetCertStores04() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - List l = TestUtils.getCollectionCertStoresList(); - // add wrong object to valid set - assertTrue(l.add(new Object())); - - try { - p.setCertStores(l); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - } - } - - /** - * Test #1 for <code>addCertStore(CertStore)</code> method<br> - * Assertion: adds a <code>CertStore</code> to the end of the list of - * <code>CertStores</code> - * - * @throws InvalidAlgorithmParameterException - * @throws NoSuchAlgorithmException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify ClassCastException.", - method = "addCertStore", - args = {java.security.cert.CertStore.class} - ) - public final void testAddCertStore01() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - p.addCertStore(CertStore.getInstance("Collection", - new CollectionCertStoreParameters())); - assertFalse(p.getCertStores().isEmpty()); - } - - /** - * Test #2 for <code>addCertStore(CertStore)</code> method<br> - * Assertion: if <code>null</code>, the store is ignored (not added to list) - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies null as a parameter.", - method = "addCertStore", - args = {java.security.cert.CertStore.class} - ) - public final void testAddCertStore02() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - p.addCertStore(null); - assertTrue(p.getCertStores().isEmpty()); - } - - /** - * Test #1 for <code>getCertPathCheckers()</code> method<br> - * Assertion: list ... may be empty, but not <code>null</code> - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that getCertPathCheckers method returns not empty list.", - method = "getCertPathCheckers", - args = {} - ) - public final void testGetCertPathCheckers01() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - List l = p.getCertPathCheckers(); - assertNotNull("notNull", l); - assertTrue("isEmpty", l.isEmpty()); - } - - /** - * Test #2 for <code>getCertPathCheckers()</code> method<br> - * Assertion: returns an immutable <code>List</code> of - * <code>PKIXCertPathChecker</code>s - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that getCertPathCheckers method returns an immutable List of PKIXCertPathChecker objects.", - method = "getCertPathCheckers", - args = {} - ) - public final void testGetCertPathCheckers02() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - List<PKIXCertPathChecker> l = p.getCertPathCheckers(); - - try { - // try to modify returned list - l.add((PKIXCertPathChecker) new Object()); - fail("must be immutable"); - } catch (Exception e) { - } - } - - /** - * Test #3 for <code>getCertPathCheckers()</code> method<br> - * Assertion: The returned List is immutable, and each - * <code>PKIXCertPathChecker</code> in the <code>List</code> is cloned to - * protect against subsequent modifications - * - * @throws InvalidAlgorithmParameterException - * @throws CertPathValidatorException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that the returned List is immutable, and each PKIXCertPathChecker in the List is cloned to protect against subsequent modifications.", - method = "getCertPathCheckers", - args = {} - ) - public final void testGetCertPathCheckers03() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - PKIXCertPathChecker cpc = TestUtils.getTestCertPathChecker(); - List<PKIXCertPathChecker> l = new ArrayList<PKIXCertPathChecker>(); - assertTrue("addedOk", l.add(cpc)); - p.setCertPathCheckers(l); - // retrieve checker and modify it - PKIXCertPathChecker cpc1 = p.getCertPathCheckers().get(0); - cpc1.init(true); - assertTrue("modifiedOk", cpc1.isForwardCheckingSupported()); - // retrieve checker again and check - // that its state has not been changed - // by the above modification - PKIXCertPathChecker cpc2 = p.getCertPathCheckers().get(0); - assertFalse("isCloned", cpc2.isForwardCheckingSupported()); - } - - /** - * Test #1 for <code>setCertPathCheckers(List)</code> method<br> - * Assertion: sets a <code>List</code> of additional certification path - * checkers - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify exceptions.", - method = "setCertPathCheckers", - args = {java.util.List.class} - ) - public final void testSetCertPathCheckers01() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - PKIXCertPathChecker cpc = TestUtils.getTestCertPathChecker(); - List<PKIXCertPathChecker> l = new ArrayList<PKIXCertPathChecker>(); - assertTrue("addedOk", l.add(cpc)); - p.setCertPathCheckers(l); - List l1 = p.getCertPathCheckers(); - assertNotNull("notNull", l1); - assertFalse("isNotEmpty", l1.isEmpty()); - } - - /** - * Test #2 for <code>setCertPathCheckers(List)</code> method<br> - * Assertion: <code>List</code> ... may be null - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify exceptions.", - method = "setCertPathCheckers", - args = {java.util.List.class} - ) - public final void testSetCertPathCheckers02() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - p.setCertPathCheckers(null); - List<PKIXCertPathChecker> l1 = p.getCertPathCheckers(); - assertNotNull("notNull1", l1); - assertTrue("isEmpty1", l1.isEmpty()); - p.setCertPathCheckers(new ArrayList<PKIXCertPathChecker>()); - List l2 = p.getCertPathCheckers(); - assertNotNull("notNull2", l2); - assertTrue("isEmpty2", l2.isEmpty()); - } - - /** - * Test #3 for <code>setCertPathCheckers(List)</code> method<br> - * Assertion: <code>List</code> supplied here is copied and each - * <code>PKIXCertPathChecker</code> in the list is cloned to protect against - * subsequent modifications - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify exceptions.", - method = "setCertPathCheckers", - args = {java.util.List.class} - ) - public final void testSetCertPathCheckers03() throws Exception { - // checks that list copied - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - PKIXCertPathChecker cpc = TestUtils.getTestCertPathChecker(); - List<PKIXCertPathChecker> l = new ArrayList<PKIXCertPathChecker>(); - assertTrue("addedOk", l.add(cpc)); - p.setCertPathCheckers(l); - // modify list - l.clear(); - // retrieve list and check - // that its state has not been changed - // by the above modification - assertFalse("isCopied", p.getCertPathCheckers().isEmpty()); - } - - /** - * Test #4 for <code>setCertPathCheckers(List)</code> method<br> - * Assertion: <code>List</code> supplied here is copied and each - * <code>PKIXCertPathChecker</code> in the list is cloned to protect against - * subsequent modifications - * - * @throws InvalidAlgorithmParameterException - * @throws InvalidAlgorithmParameterException - * @throws CertPathValidatorException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify exceptions.", - method = "setCertPathCheckers", - args = {java.util.List.class} - ) - public final void testSetCertPathCheckers04() throws Exception { - // checks that checkers cloned - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - PKIXCertPathChecker cpc = TestUtils.getTestCertPathChecker(); - List<PKIXCertPathChecker> l = new ArrayList<PKIXCertPathChecker>(); - assertTrue("addedOk", l.add(cpc)); - p.setCertPathCheckers(l); - // modify checker - cpc.init(true); - // retrieve list and check that CertPathChecker's - // state it contains has not been changed by the - // above modification - PKIXCertPathChecker cpc1 = p.getCertPathCheckers().get(0); - assertFalse("isCopied", cpc1.isForwardCheckingSupported()); - } - - /** - * Test #5 for <code>setCertPathCheckers(List)</code> method<br> - * Assertion: <code>ClassCastException</code> - if any of the elements in - * the list are not of type - * <code>java.security.cert.PKIXCertPathChecker</code> - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verify exception.", - method = "setCertPathCheckers", - args = {java.util.List.class} - ) - @SuppressWarnings("unchecked") - public final void testSetCertPathCheckers05() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - PKIXCertPathChecker cpc = TestUtils.getTestCertPathChecker(); - List l = new ArrayList<PKIXCertPathChecker>(); - assertTrue("addedOk", l.add(cpc)); - // add wrong object to the list - assertTrue("addedOk", l.add(new Object())); - - try { - p.setCertPathCheckers(l); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - } - } - - /** - * Test #1 for <code>addCertPathChecker(PKIXCertPathChecker)</code> method<br> - * Assertion: adds a <code>CertPathChecker</code> to the end of the list of - * <code>CertPathChecker</code>s - * - * @throws CertPathValidatorException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "addCertPathChecker", - args = {java.security.cert.PKIXCertPathChecker.class} - ) - public final void testAddCertPathChecker01() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - PKIXCertPathChecker cpc = TestUtils.getTestCertPathChecker(); - List<PKIXCertPathChecker> l = new ArrayList<PKIXCertPathChecker>(); - assertTrue("addedOk", l.add(cpc)); - p.setCertPathCheckers(l); - // create one more PKIXCertPathChecker - PKIXCertPathChecker cpc1 = TestUtils.getTestCertPathChecker(); - cpc1.init(true); - p.addCertPathChecker(cpc1); - // check that we have two PKIXCertPathCheckers and - // they are in right order - List l1 = p.getCertPathCheckers(); - assertEquals("listSize", 2, l1.size()); - assertFalse("order1", ((PKIXCertPathChecker) l1.get(0)) - .isForwardCheckingSupported()); - assertTrue("order2", ((PKIXCertPathChecker) l1.get(1)) - .isForwardCheckingSupported()); - } - - /** - * Test #2 for <code>addCertPathChecker(PKIXCertPathChecker)</code> method<br> - * Assertion: if null, the checker is ignored (not added to list). - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that if PKIXCertPathChecker parameter is null, the checker is ignored (not added to list).", - method = "addCertPathChecker", - args = {java.security.cert.PKIXCertPathChecker.class} - ) - public final void testAddCertPathChecker02() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - PKIXCertPathChecker cpc = TestUtils.getTestCertPathChecker(); - List<PKIXCertPathChecker> l = new ArrayList<PKIXCertPathChecker>(); - assertTrue("addedOk", l.add(cpc)); - p.setCertPathCheckers(l); - // try to add null - p.addCertPathChecker(null); - // check that we have one PKIXCertPathChecker - List l1 = p.getCertPathCheckers(); - assertEquals("listSize", 1, l1.size()); - } - - /** - * Test #3 for <code>addCertPathChecker(PKIXCertPathChecker)</code> method<br> - * Assertion: <code>PKIXCertPathChecker</code> is cloned to protect against - * subsequent modifications - * - * @throws InvalidAlgorithmParameterException - * @throws CertPathValidatorException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that PKIXCertPathChecker is cloned to protect against subsequent modifications.", - method = "addCertPathChecker", - args = {java.security.cert.PKIXCertPathChecker.class} - ) - public final void testAddCertPathChecker03() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - // checks that checkers cloned - PKIXParameters p = new PKIXParameters(taSet); - PKIXCertPathChecker cpc = TestUtils.getTestCertPathChecker(); - - p.addCertPathChecker(cpc); - // modify checker - cpc.init(true); - // retrieve list and check that CertPathChecker's - // state it contains has not been changed by the - // above modification - List l = p.getCertPathCheckers(); - PKIXCertPathChecker cpc1 = (PKIXCertPathChecker) l.get(0); - assertEquals("listSize", 1, l.size()); - assertFalse("isCopied", cpc1.isForwardCheckingSupported()); - } - - /** - * Test #1 for <code>getDate()</code> method<br> - * Assertion: the <code>Date</code>, or <code>null</code> if not set - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "", - method = "getDate", - args = {} - ) - public final void testGetDate01() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - // the Date has not been set - // the method must return null - assertNull("null", p.getDate()); - Date currentDate = new Date(); - p.setDate(currentDate); - // the Date returned must match - assertEquals("notNull", currentDate, p.getDate()); - } - - /** - * Test #2 for <code>getDate()</code> method<br> - * Assertion: <code>Date</code> returned is copied to protect against - * subsequent modifications - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that returned Date is copied to protect against subsequent modifications.", - method = "getDate", - args = {} - ) - public final void testGetDate02() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - Date currentDate = new Date(); - p.setDate((Date) currentDate.clone()); - Date ret1 = p.getDate(); - // modify Date returned - ret1.setTime(0L); - // check that internal Date has not been - // changed by the above modification - assertEquals(currentDate, p.getDate()); - } - - /** - * @tests java.security.cert.PKIXParameters#setDate(Date) - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "setDate", - args = {java.util.Date.class} - ) - @AndroidOnly("On the RI p.setDate(null) does not reset the date to null " - + "as specified.") - public final void test_setDateLjava_util_Date() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - assertNotNull("could not create test TrustAnchor set", taSet); - - // test: 'date' is unset and param is null - PKIXParameters p = new PKIXParameters(taSet); - p.setDate(null); - assertNull(p.getDate()); - - // test: 'date' is not null - p = new PKIXParameters(taSet); - Date toBeSet = new Date(555L); - p.setDate(toBeSet); - assertEquals(555L, p.getDate().getTime()); - // modify initial 'date' - it should be copied by constructor - toBeSet.setTime(0L); - // check that internal 'date' has not been - // changed by the above modification - assertEquals(555L, p.getDate().getTime()); - // set another 'date' - p.setDate(new Date(333L)); - assertEquals(333L, p.getDate().getTime()); - - // Regression for HARMONY-2882 (non-bug difference from RI) - p = new PKIXParameters(taSet); - p.setDate(new Date(555L)); - p.setDate(null); // reset 'date' back to current time - assertNull(p.getDate()); - } - - /** - * Test #1 for <code>getInitialPolicies()</code> method<br> - * Assertion: The default return value is an empty <code>Set</code> - * Assertion: Never returns <code>null</code> - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that getInitialPolicies method returns an empty Set and never null.", - method = "getInitialPolicies", - args = {} - ) - public final void testGetInitialPolicies01() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - assertNotNull("notNull", p.getInitialPolicies()); - assertTrue("isEmpty", p.getInitialPolicies().isEmpty()); - } - - /** - * Test #2 for <code>getInitialPolicies()</code> method<br> - * Assertion: returns an immutable <code>Set</code> of initial policy OIDs - * in <code>String</code> format<br> - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that getInitialPolicies method returns an immutable Set of initial policy in String format.", - method = "getInitialPolicies", - args = {} - ) - public final void testGetInitialPolicies02() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - Set<String> s = p.getInitialPolicies(); - try { - // try to modify returned set - s.add((String) new Object()); - fail("must be immutable"); - } catch (Exception e) { - } - } - - /** - * Test #1 for <code>setInitialPolicies(Set)</code> method<br> - * Assertion: sets the <code>Set</code> of initial policy identifiers (OID - * strings) - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify ClassCastException.", - method = "setInitialPolicies", - args = {java.util.Set.class} - ) - public final void testSetInitialPolicies01() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - Set<String> s = new HashSet<String>(); - s.add("1.2.3.4.5.6.7"); - PKIXParameters p = new PKIXParameters(taSet); - p.setInitialPolicies(s); - assertEquals(1, p.getInitialPolicies().size()); - } - - /** - * Test #2 for <code>setInitialPolicies(Set)</code> method<br> - * Assertion: <code>Set</code> may be <code>null</code> - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies null as a parameter.", - method = "setInitialPolicies", - args = {java.util.Set.class} - ) - public final void testSetInitialPolicies02() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - p.setInitialPolicies(null); - assertTrue(p.getInitialPolicies().isEmpty()); - } - - /** - * Test #3 for <code>setInitialPolicies(Set)</code> method<br> - * Assertion: <code>Set</code> may be empty - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify ClassCastException.", - method = "setInitialPolicies", - args = {java.util.Set.class} - ) - public final void testSetInitialPolicies03() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - p.setInitialPolicies(new HashSet<String>()); - assertTrue(p.getInitialPolicies().isEmpty()); - } - - /** - * Test #4 for <code>setInitialPolicies(Set)</code> method<br> - * Assertion: <code>Set</code> is copied to protect against subsequent - * modifications - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that Set is copied to protect against subsequent modifications.", - method = "setInitialPolicies", - args = {java.util.Set.class} - ) - public final void testSetInitialPolicies04() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - Set<String> s = new HashSet<String>(); - s.add("1.2.3.4.5.6.7"); - s.add("1.2.3.4.5.6.8"); - PKIXParameters p = new PKIXParameters(taSet); - p.setInitialPolicies(s); - // modify original set - s.clear(); - // check that set maintained internally has - // not been changed by the above modification - assertEquals(2, p.getInitialPolicies().size()); - } - - /** - * Test #5 for <code>setInitialPolicies(Set)</code> method<br> - * Assertion: <code>ClassCastException</code> - if any of the elements in - * the set are not of type <code>String</code> - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies ClassCastException.", - method = "setInitialPolicies", - args = {java.util.Set.class} - ) - @SuppressWarnings("unchecked") - public final void testSetInitialPolicies05() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - Set s = new HashSet(); - s.add("1.2.3.4.5.6.7"); - s.add(new Object()); - PKIXParameters p = new PKIXParameters(taSet); - try { - p.setInitialPolicies(s); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - } - } - - /** - * Test #1 for <code>getTrustAnchors()</code> method<br> - * Assertion: an immutable <code>Set</code> of <code>TrustAnchors</code> - * (never <code>null</code>) - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that getTrustAnchors returns an immutable Set of TrustAnchors, and never null.", - method = "getTrustAnchors", - args = {} - ) - public final void testGetTrustAnchors01() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - assertNotNull("notNull", p.getTrustAnchors()); - } - - /** - * Test #2 for <code>getTrustAnchors()</code> method<br> - * Assertion: an immutable <code>Set</code> of <code>TrustAnchors</code> - * (never <code>null</code>) - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies that getTrustAnchors returns an immutable set of TrustAnchors, and never null.", - method = "getTrustAnchors", - args = {} - ) - public final void testGetTrustAnchors02() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - Set<TrustAnchor> s = p.getTrustAnchors(); - try { - // try to modify returned set - s.add((TrustAnchor) new Object()); - fail("must be immutable"); - } catch (Exception e) { - } - } - - /** - * Test #1 for <code>setTrustAnchors(Set)</code> method<br> - * Assertion: Sets the <code>Set</code> of most-trusted CAs - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Doesn't verify exceptions.", - method = "setTrustAnchors", - args = {java.util.Set.class} - ) - public final void testSetTrustAnchors01() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - Set<TrustAnchor> taSet1 = TestUtils.getTrustAnchorSet(); - PKIXParameters p = new PKIXParameters(taSet); - p.setTrustAnchors(taSet1); - assertFalse(p.getTrustAnchors().isEmpty()); - } - - /** - * Test #2 for <code>setTrustAnchors(Set)</code> method<br> - * Assertion: <code>InvalidAlgorithmParameterException</code> - if the - * specified <code>Set</code> is empty ( - * <code>trustAnchors.isEmpty() == true</code>) - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies InvalidAlgorithmParameterException.", - method = "setTrustAnchors", - args = {java.util.Set.class} - ) - public final void testSetTrustAnchors02() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - try { - // use empty set - p.setTrustAnchors(new HashSet<TrustAnchor>()); - fail("InvalidAlgorithmParameterException expected"); - } catch (InvalidAlgorithmParameterException e) { - } - } - - /** - * Test #3 for <code>setTrustAnchors(Set)</code> method<br> - * Assertion: <code>NullPointerException</code> - if the specified - * <code>Set</code> is <code>null</code>) - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies NullPointerException.", - method = "setTrustAnchors", - args = {java.util.Set.class} - ) - public final void testSetTrustAnchors03() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - try { - // use null - p.setTrustAnchors(null); - fail("NPE expected"); - } catch (NullPointerException e) { - } - } - - /** - * Test #4 for <code>setTrustAnchors(Set)</code> method<br> - * Assertion: <code>ClassCastException</code> - if any of the elements in - * the set are not of type <code>java.security.cert.TrustAnchor</code> - * - * @throws InvalidAlgorithmParameterException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies ClassCastException.", - method = "setTrustAnchors", - args = {java.util.Set.class} - ) - @SuppressWarnings("unchecked") - public final void testSetTrustAnchors04() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - Set s = new HashSet(p.getTrustAnchors()); - s.add(new Object()); - try { - p.setTrustAnchors(s); - fail("ClassCastException expected"); - } catch (ClassCastException e) { - } - } - - /** - * Test for <code>toString</code> method<br> - */ - @TestTargetNew( - level = TestLevel.COMPLETE, - notes = "", - method = "toString", - args = {} - ) - public final void testToString() throws Exception { - Set<TrustAnchor> taSet = TestUtils.getTrustAnchorSet(); - if (taSet == null) { - fail(getName() - + ": not performed (could not create test TrustAnchor set)"); - } - - PKIXParameters p = new PKIXParameters(taSet); - assertNotNull(p.toString()); - - PKIXParameters p1 = null; - try { - p1.toString(); - fail("NullPointerException expected"); - } catch (NullPointerException e) { - // expected - } - } - - /** - * Test #4 for <code>PKIXParameters(KeyStore)</code> constructor<br> - * - * @throws InvalidAlgorithmParameterException - * @throws KeyStoreException - */ - @TestTargetNew( - level = TestLevel.PARTIAL_COMPLETE, - notes = "Verifies everything except null argument", - method = "PKIXParameters", - args = {java.security.KeyStore.class} - ) - @BrokenTest("Fails in CTS environment, but passes in CoreTestRunner") - public final void testPKIXParametersKeyStore04() throws Exception { - - - KeyStore store = KeyStore.getInstance("PKCS12"); - KeyStoreTestPKCS12 k = new KeyStoreTestPKCS12(); - ByteArrayInputStream stream = new ByteArrayInputStream(k.keyStoreData); - - try { - PKIXParameters p = new PKIXParameters(store); - } catch (KeyStoreException e) { - // ok - } - - store = KeyStore.getInstance("PKCS12"); - store.load(stream, new String(KeyStoreTestPKCS12.keyStorePassword) - .toCharArray()); - stream.close(); - - try { - PKIXParameters p = new PKIXParameters(store); - } catch (InvalidAlgorithmParameterException e) { - // ok - } - - - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(null,null); - keystore.setCertificateEntry("test", TestUtils.rootCertificateSS); - - - PKIXParameters p = new PKIXParameters(keystore); - } -} diff --git a/luni/src/test/java/tests/targets/security/AlgorithmParameterGeneratorTest.java b/luni/src/test/java/tests/targets/security/AlgorithmParameterGeneratorTest.java deleted file mode 100644 index 108b433..0000000 --- a/luni/src/test/java/tests/targets/security/AlgorithmParameterGeneratorTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2009 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 tests.targets.security; - -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; - -import junit.framework.TestCase; - -import java.security.AlgorithmParameterGenerator; -import java.security.AlgorithmParameters; -import java.security.NoSuchAlgorithmException; - -public abstract class AlgorithmParameterGeneratorTest extends TestCase { - - private final String algorithmName; - private final TestHelper<AlgorithmParameters> helper; - - protected AlgorithmParameterGeneratorTest(String algorithmName, TestHelper<AlgorithmParameters> helper) { - this.algorithmName = algorithmName; - this.helper = helper; - } - - @TestTargets({ - @TestTargetNew( - level=TestLevel.ADDITIONAL, - method="getInstance", - args={String.class} - ), - @TestTargetNew( - level=TestLevel.ADDITIONAL, - method="init", - args={int.class} - ), - @TestTargetNew( - level=TestLevel.COMPLETE, - method="method", - args={} - ) - }) - public void testAlgorithmParameterGenerator() { - AlgorithmParameterGenerator generator = null; - try { - generator = AlgorithmParameterGenerator.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - fail(e.getMessage()); - } - - generator.init(1024); - - AlgorithmParameters parameters = generator.generateParameters(); - - assertNotNull("generated parameters are null", parameters); - - helper.test(parameters); - } -}
\ No newline at end of file diff --git a/luni/src/test/java/tests/targets/security/AlgorithmParametersTest.java b/luni/src/test/java/tests/targets/security/AlgorithmParametersTest.java deleted file mode 100644 index 02f2691..0000000 --- a/luni/src/test/java/tests/targets/security/AlgorithmParametersTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (C) 2009 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 tests.targets.security; - -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; - -import junit.framework.TestCase; - -import java.security.AlgorithmParameters; -import java.security.NoSuchAlgorithmException; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.InvalidParameterSpecException; - -public class AlgorithmParametersTest extends TestCase { - - private final String algorithmName; - private final TestHelper<AlgorithmParameters> helper; - private final AlgorithmParameterSpec parameterData; - - public AlgorithmParametersTest(String algorithmName, - TestHelper<AlgorithmParameters> helper, AlgorithmParameterSpec parameterData) { - this.algorithmName = algorithmName; - this.helper = helper; - this.parameterData = parameterData; - } - - protected void setUp() throws Exception { - super.setUp(); - } - - @TestTargets({ - @TestTargetNew( - level=TestLevel.ADDITIONAL, - method="getInstance", - args={String.class} - ), - @TestTargetNew( - level=TestLevel.ADDITIONAL, - method="init", - args={byte[].class} - ), - @TestTargetNew( - level=TestLevel.COMPLETE, - method="method", - args={} - ) - }) - public void testAlgorithmParameters() { - AlgorithmParameters algorithmParameters = null; - try { - algorithmParameters = AlgorithmParameters - .getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - fail(e.getMessage()); - } - - try { - algorithmParameters.init(parameterData); - } catch (InvalidParameterSpecException e) { - fail(e.getMessage()); - } - - helper.test(algorithmParameters); - } -} diff --git a/luni/src/test/java/tests/targets/security/AllTests.java b/luni/src/test/java/tests/targets/security/AllTests.java index 2a509a7..e8f8f1c 100644 --- a/luni/src/test/java/tests/targets/security/AllTests.java +++ b/luni/src/test/java/tests/targets/security/AllTests.java @@ -32,14 +32,6 @@ public class AllTests { suite.addTestSuite(MessageDigestTestSHA384.class); suite.addTestSuite(MessageDigestTestSHA512.class); - suite.addTestSuite(KeyPairGeneratorTestRSA.class); - suite.addTestSuite(KeyPairGeneratorTestDSA.class); - suite.addTestSuite(KeyPairGeneratorTestDH.class); - - suite.addTestSuite(KeyFactoryTestRSA.class); - suite.addTestSuite(KeyFactoryTestDSA.class); - suite.addTestSuite(KeyFactoryTestDH.class); - suite.addTestSuite(SignatureTestMD2withRSA.class); suite.addTestSuite(SignatureTestMD5withRSA.class); suite.addTestSuite(SignatureTestNONEwithDSA.class); @@ -50,23 +42,10 @@ public class AllTests { suite.addTestSuite(SignatureTestSHA384withRSA.class); suite.addTestSuite(SignatureTestSHA512withRSA.class); - suite.addTestSuite(AlgorithmParameterGeneratorTestAES.class); - suite.addTestSuite(AlgorithmParameterGeneratorTestDH.class); - suite.addTestSuite(AlgorithmParameterGeneratorTestDSA.class); - - suite.addTestSuite(AlgorithmParametersTestDES.class); - suite.addTestSuite(AlgorithmParametersTestDESede.class); - suite.addTestSuite(AlgorithmParametersTestDSA.class); - suite.addTestSuite(AlgorithmParametersTestOAEP.class); - suite.addTestSuite(AlgorithmParametersTestAES.class); - suite.addTestSuite(AlgorithmParametersTestDH.class); - suite.addTestSuite(KeyStoreTestPKCS12.class); suite.addTestSuite(SecureRandomTestSHA1PRNG.class); - suite.addTestSuite(DHTest.class); - // $JUnit-END$ return suite; } diff --git a/luni/src/test/java/tests/targets/security/CipherHelper.java b/luni/src/test/java/tests/targets/security/CipherHelper.java deleted file mode 100644 index a6ff89a..0000000 --- a/luni/src/test/java/tests/targets/security/CipherHelper.java +++ /dev/null @@ -1,535 +0,0 @@ -/* - * Copyright (C) 2009 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 tests.targets.security; - -import junit.framework.Assert; - -import java.security.AlgorithmParameters; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.spec.AlgorithmParameterSpec; -import java.security.spec.InvalidParameterSpecException; -import java.util.Arrays; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.KeyAgreement; -import javax.crypto.KeyGenerator; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; - -abstract class TestHelper<T/*, U*/> { - void test(T testObject) { - Assert.fail("test called unimplemented method"); - } - -// void test(T testObject1, U testObject2) { -// Assert.fail("test called unimplemented method"); -// } -} - - -abstract class CipherHelper<T/*, U*/> extends TestHelper<T/*, Key*/> { - - private final String algorithmName; - private final String plainData; - private final int mode1; - private final int mode2; - - CipherHelper(String algorithmName, String plainData, int mode1, int mode2) { - this.algorithmName = algorithmName; - this.plainData = plainData; - this.mode1 = mode1; - this.mode2 = mode2; - } - - - -// @Override - void test(Key encryptKey, Key decryptKey) { - Cipher cipher = null; - try { - cipher = Cipher.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - Assert.fail(e.getMessage()); - } catch (NoSuchPaddingException e) { - Assert.fail(e.getMessage()); - } - try { - cipher.init(mode1, encryptKey); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } - - byte[] encrypted = crypt(cipher, plainData.getBytes()); - - try { - cipher.init(mode2, decryptKey); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } - - byte[] decrypted = crypt(cipher, encrypted); - - String decryptedString = new String(decrypted); - - Assert.assertEquals("transformed data does not match", plainData, - decryptedString); - } - - byte[] crypt(Cipher cipher, byte[] input) { - try { - return cipher.doFinal(input); - } catch (IllegalBlockSizeException e) { - Assert.fail(e.getMessage()); - } catch (BadPaddingException e) { - Assert.fail(e.getMessage()); - } - return null; - } -} - - -class CipherAsymmetricCryptHelper extends CipherHelper<KeyPair/*, U*/> { - - private static final String plainData = "some data to encrypt and decrypt test"; - - CipherAsymmetricCryptHelper(String algorithmName) { - super(algorithmName, plainData, Cipher.ENCRYPT_MODE, - Cipher.DECRYPT_MODE); - } - - @Override - void test(KeyPair keyPair) { - test(keyPair.getPrivate(), keyPair.getPublic()); - } -} - - -class CipherSymmetricCryptHelper extends CipherHelper<SecretKey/*, U*/> { - - private static final String plainData = "some data to encrypt and decrypt test"; - - CipherSymmetricCryptHelper(String algorithmName) { - super(algorithmName, plainData, Cipher.ENCRYPT_MODE, - Cipher.DECRYPT_MODE); - } - - @Override - void test(SecretKey key) { - test(key, key); - } -} - -class SignatureHelper extends TestHelper<KeyPair> { - - private final String algorithmName; - private final String plainData = "some data do sign and verify"; - - protected SignatureHelper(String algorithmName) { - this.algorithmName = algorithmName; - } - - @Override - void test(KeyPair keyPair) { - test(keyPair.getPrivate(), keyPair.getPublic()); - } - -// @Override - void test(PrivateKey encryptKey, PublicKey decryptKey) { - - Signature signature = null; - try { - signature = Signature.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - Assert.fail(e.getMessage()); - } - - try { - signature.initSign(encryptKey); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } - - try { - signature.update(plainData.getBytes()); - } catch (SignatureException e) { - Assert.fail(e.getMessage()); - } - - byte[] signed = null; - try { - signed = signature.sign(); - } catch (SignatureException e) { - Assert.fail(e.getMessage()); - } - - try { - signature.initVerify(decryptKey); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } - - try { - signature.update(plainData.getBytes()); - } catch (SignatureException e) { - Assert.fail(e.getMessage()); - } - - try { - Assert.assertTrue("signature could not be verified", signature - .verify(signed)); - } catch (SignatureException e) { - Assert.fail(e.getMessage()); - } - } -} - - -class KeyAgreementHelper extends TestHelper<KeyPair> { - - private final String algorithmName; - - protected KeyAgreementHelper(String algorithmName) { - this.algorithmName = algorithmName; - } - - @Override - void test(KeyPair keyPair) { - test(keyPair.getPrivate(), keyPair.getPublic()); - } -// @Override - void test(PrivateKey encryptKey, PublicKey decryptKey) { - - KeyAgreement keyAgreement = null; - try { - keyAgreement = KeyAgreement.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - Assert.fail(e.getMessage()); - } - - try { - keyAgreement.init(encryptKey); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } - try { - keyAgreement.doPhase(decryptKey, true); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } catch (IllegalStateException e) { - Assert.fail(e.getMessage()); - } - Assert.assertNotNull("generated secret is null", keyAgreement - .generateSecret()); - - } -} - -class AlgorithmParameterAsymmetricHelper extends TestHelper<AlgorithmParameters> { - - private static final String plainData = "some data to encrypt and decrypt"; - private final String algorithmName; - - protected AlgorithmParameterAsymmetricHelper(String algorithmName) { - this.algorithmName = algorithmName; - } - - @Override - void test(AlgorithmParameters parameters) { - - KeyPairGenerator generator = null; - try { - generator = KeyPairGenerator.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - Assert.fail(e.getMessage()); - } - - generator.initialize(1024); - - KeyPair keyPair = generator.generateKeyPair(); - - - Cipher cipher = null; - try { - cipher = Cipher.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - Assert.fail(e.getMessage()); - } catch (NoSuchPaddingException e) { - Assert.fail(e.getMessage()); - } - - try { - cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic(), parameters); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } catch (InvalidAlgorithmParameterException e) { - Assert.fail(e.getMessage()); - } - - byte[] bs = null; - try { - bs = cipher.doFinal(plainData.getBytes()); - } catch (IllegalBlockSizeException e) { - Assert.fail(e.getMessage()); - } catch (BadPaddingException e) { - Assert.fail(e.getMessage()); - } - - try { - cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate(), parameters); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } catch (InvalidAlgorithmParameterException e) { - Assert.fail(e.getMessage()); - } - - byte[] decrypted = null; - try { - decrypted = cipher.doFinal(bs); - } catch (IllegalBlockSizeException e) { - Assert.fail(e.getMessage()); - } catch (BadPaddingException e) { - Assert.fail(e.getMessage()); - } - - Assert.assertTrue(Arrays.equals(plainData.getBytes(), decrypted)); - } -} - -class AlgorithmParameterSymmetricHelper extends TestHelper<AlgorithmParameters> { - - private static final String plainData = "some data to encrypt and decrypt"; - private final String algorithmName; - private final int keySize; - private String blockmode; - - protected AlgorithmParameterSymmetricHelper(String algorithmName, int keySize) { - this.algorithmName = algorithmName; - this.keySize = keySize; - } - - protected AlgorithmParameterSymmetricHelper(String algorithmName, String blockmode, int keySize) { - this(algorithmName, keySize); - this.blockmode = blockmode; - } - - @Override - void test(AlgorithmParameters parameters) { - - KeyGenerator generator = null; - try { - generator = KeyGenerator.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - Assert.fail(e.getMessage()); - } - - generator.init(keySize); - - Key key = generator.generateKey(); - - - Cipher cipher = null; - try { - String transformation = algorithmName; - if (blockmode != null) - { - transformation += "/" + blockmode; - } - cipher = Cipher.getInstance(transformation); - } catch (NoSuchAlgorithmException e) { - Assert.fail(e.getMessage()); - } catch (NoSuchPaddingException e) { - Assert.fail(e.getMessage()); - } - - try { - cipher.init(Cipher.ENCRYPT_MODE, key, parameters); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } catch (InvalidAlgorithmParameterException e) { - Assert.fail(e.getMessage()); - } - - byte[] bs = null; - try { - bs = cipher.doFinal(plainData.getBytes()); - } catch (IllegalBlockSizeException e) { - Assert.fail(e.getMessage()); - } catch (BadPaddingException e) { - Assert.fail(e.getMessage()); - } - - try { - cipher.init(Cipher.DECRYPT_MODE, key, parameters); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } catch (InvalidAlgorithmParameterException e) { - Assert.fail(e.getMessage()); - } - - byte[] decrypted = null; - try { - decrypted = cipher.doFinal(bs); - } catch (IllegalBlockSizeException e) { - Assert.fail(e.getMessage()); - } catch (BadPaddingException e) { - Assert.fail(e.getMessage()); - } - - Assert.assertTrue(Arrays.equals(plainData.getBytes(), decrypted)); - } -} - - -class AlgorithmParameterSignatureHelper<T extends AlgorithmParameterSpec> extends TestHelper<AlgorithmParameters> { - - private final String algorithmName; - private final String plainData = "some data do sign and verify"; - private final Class<T> parameterSpecClass; - - protected AlgorithmParameterSignatureHelper(String algorithmName, Class<T> parameterSpecCla1ss) { - this.algorithmName = algorithmName; - this.parameterSpecClass = parameterSpecCla1ss; - } - - @Override - void test(AlgorithmParameters parameters) { - - Signature signature = null; - try { - signature = Signature.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - Assert.fail(e.getMessage()); - } - - - T parameterSpec = null; - try { - parameterSpec = parameters.getParameterSpec(parameterSpecClass); - } catch (InvalidParameterSpecException e) { - Assert.fail(e.getMessage()); - } - - KeyPairGenerator generator = null; - try { - generator = KeyPairGenerator.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - Assert.fail(e.getMessage()); - } - - try { - generator.initialize(parameterSpec); - } catch (InvalidAlgorithmParameterException e) { - Assert.fail(e.getMessage()); - } - - KeyPair keyPair = generator.genKeyPair(); - - try { - signature.initSign(keyPair.getPrivate()); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } - - try { - signature.update(plainData.getBytes()); - } catch (SignatureException e) { - Assert.fail(e.getMessage()); - } - - byte[] signed = null; - try { - signed = signature.sign(); - } catch (SignatureException e) { - Assert.fail(e.getMessage()); - } - - try { - signature.initVerify(keyPair.getPublic()); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } - - try { - signature.update(plainData.getBytes()); - } catch (SignatureException e) { - Assert.fail(e.getMessage()); - } - - try { - Assert.assertTrue("signature could not be verified", signature - .verify(signed)); - } catch (SignatureException e) { - Assert.fail(e.getMessage()); - } - } -} - -class AlgorithmParameterKeyAgreementHelper extends TestHelper<AlgorithmParameters> { - - private final String algorithmName; - - protected AlgorithmParameterKeyAgreementHelper(String algorithmName) { - this.algorithmName = algorithmName; - } - - @Override - void test(AlgorithmParameters parameters) { - - KeyPairGenerator generator = null; - try { - generator = KeyPairGenerator.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - Assert.fail(e.getMessage()); - } - - generator.initialize(1024); - - KeyPair keyPair = generator.generateKeyPair(); - - KeyAgreement keyAgreement = null; - try { - keyAgreement = KeyAgreement.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - Assert.fail(e.getMessage()); - } - - try { - keyAgreement.init(keyPair.getPrivate()); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } - try { - keyAgreement.doPhase(keyPair.getPublic(), true); - } catch (InvalidKeyException e) { - Assert.fail(e.getMessage()); - } catch (IllegalStateException e) { - Assert.fail(e.getMessage()); - } - Assert.assertNotNull("generated secret is null", keyAgreement - .generateSecret()); - } -}
\ No newline at end of file diff --git a/luni/src/test/java/tests/targets/security/DefaultKeys.java b/luni/src/test/java/tests/targets/security/DefaultKeys.java deleted file mode 100644 index c8ae8d5..0000000 --- a/luni/src/test/java/tests/targets/security/DefaultKeys.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (C) 2009 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 tests.targets.security; - -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; -import java.security.spec.PKCS8EncodedKeySpec; -import java.security.spec.X509EncodedKeySpec; -import java.util.HashMap; - -public class DefaultKeys { - private static final byte[] RSA_private = new byte[] { - (byte) 0x30, (byte) 0x82, (byte) 0x02, (byte) 0x75, (byte) 0x02, (byte) 0x01, (byte) 0x00, (byte) 0x30, (byte) 0x0D, (byte) 0x06, (byte) 0x09, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0x86, (byte) 0xF7, (byte) 0x0D, - (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x82, (byte) 0x02, (byte) 0x5F, (byte) 0x30, (byte) 0x82, (byte) 0x02, (byte) 0x5B, (byte) 0x02, (byte) 0x01, (byte) 0x00, (byte) 0x02, - (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0x99, (byte) 0xA5, (byte) 0x96, (byte) 0x72, (byte) 0xAE, (byte) 0xBB, (byte) 0x59, (byte) 0x36, (byte) 0xA8, (byte) 0x12, (byte) 0x17, (byte) 0x05, (byte) 0x4C, (byte) 0x63, - (byte) 0x9E, (byte) 0xB8, (byte) 0x85, (byte) 0xD4, (byte) 0x2D, (byte) 0x71, (byte) 0xD7, (byte) 0x29, (byte) 0xB9, (byte) 0x05, (byte) 0x0F, (byte) 0xB4, (byte) 0x57, (byte) 0xFB, (byte) 0xD3, (byte) 0x95, (byte) 0x5C, - (byte) 0x21, (byte) 0xEC, (byte) 0xB5, (byte) 0xEB, (byte) 0x67, (byte) 0xA2, (byte) 0x4F, (byte) 0xC1, (byte) 0x93, (byte) 0xEF, (byte) 0x96, (byte) 0x41, (byte) 0x05, (byte) 0x3D, (byte) 0xC5, (byte) 0x3E, (byte) 0x04, - (byte) 0x4D, (byte) 0xC6, (byte) 0xCF, (byte) 0x32, (byte) 0x7C, (byte) 0x1F, (byte) 0x66, (byte) 0xA3, (byte) 0xC5, (byte) 0x27, (byte) 0x79, (byte) 0xEC, (byte) 0x2E, (byte) 0x67, (byte) 0xFA, (byte) 0x19, (byte) 0x5B, - (byte) 0xE3, (byte) 0xB1, (byte) 0x69, (byte) 0xDA, (byte) 0x63, (byte) 0xBC, (byte) 0xDA, (byte) 0xD3, (byte) 0xBB, (byte) 0xAD, (byte) 0x8C, (byte) 0x38, (byte) 0x7B, (byte) 0x4A, (byte) 0x9C, (byte) 0xD4, (byte) 0x4D, - (byte) 0xD2, (byte) 0x33, (byte) 0xB7, (byte) 0x4E, (byte) 0x04, (byte) 0xB6, (byte) 0xDF, (byte) 0x62, (byte) 0x55, (byte) 0x48, (byte) 0x5C, (byte) 0x94, (byte) 0x02, (byte) 0xF7, (byte) 0x84, (byte) 0xE6, (byte) 0x9B, - (byte) 0x57, (byte) 0xFF, (byte) 0x17, (byte) 0x2A, (byte) 0xA1, (byte) 0x74, (byte) 0x8D, (byte) 0x07, (byte) 0xD8, (byte) 0xCE, (byte) 0xF7, (byte) 0x0B, (byte) 0x59, (byte) 0xFB, (byte) 0x13, (byte) 0x6E, (byte) 0xF1, - (byte) 0xC3, (byte) 0xAB, (byte) 0x3E, (byte) 0x72, (byte) 0x1B, (byte) 0x62, (byte) 0x09, (byte) 0xE8, (byte) 0xD8, (byte) 0x41, (byte) 0x69, (byte) 0xE1, (byte) 0x02, (byte) 0x03, (byte) 0x01, (byte) 0x00, (byte) 0x01, - (byte) 0x02, (byte) 0x81, (byte) 0x80, (byte) 0x57, (byte) 0xD6, (byte) 0x1C, (byte) 0x2E, (byte) 0x2F, (byte) 0xCA, (byte) 0x16, (byte) 0xF4, (byte) 0x72, (byte) 0x1C, (byte) 0xF5, (byte) 0x60, (byte) 0x28, (byte) 0x0D, - (byte) 0x83, (byte) 0x7D, (byte) 0x85, (byte) 0xB4, (byte) 0x88, (byte) 0xCE, (byte) 0x5D, (byte) 0xED, (byte) 0x12, (byte) 0x42, (byte) 0xDC, (byte) 0x79, (byte) 0x83, (byte) 0x1B, (byte) 0x0A, (byte) 0x18, (byte) 0x86, - (byte) 0xF5, (byte) 0x35, (byte) 0xF7, (byte) 0xC2, (byte) 0x3E, (byte) 0x1A, (byte) 0xC2, (byte) 0x71, (byte) 0xAD, (byte) 0xFA, (byte) 0xF7, (byte) 0xF0, (byte) 0xEF, (byte) 0xE8, (byte) 0x22, (byte) 0x4C, (byte) 0x93, - (byte) 0xF5, (byte) 0x4A, (byte) 0xC4, (byte) 0xC4, (byte) 0xDD, (byte) 0xC4, (byte) 0xAD, (byte) 0xCE, (byte) 0xCE, (byte) 0x35, (byte) 0x05, (byte) 0x34, (byte) 0x8A, (byte) 0x4B, (byte) 0x12, (byte) 0xE4, (byte) 0x69, - (byte) 0xE6, (byte) 0xDA, (byte) 0x07, (byte) 0x1A, (byte) 0x77, (byte) 0x5C, (byte) 0xA7, (byte) 0x21, (byte) 0x41, (byte) 0x89, (byte) 0x8C, (byte) 0x95, (byte) 0x6A, (byte) 0x5D, (byte) 0x9C, (byte) 0x3C, (byte) 0xAE, - (byte) 0xC3, (byte) 0xE4, (byte) 0x64, (byte) 0x54, (byte) 0xDA, (byte) 0xFB, (byte) 0xBA, (byte) 0xA6, (byte) 0xE5, (byte) 0x8A, (byte) 0x7F, (byte) 0xFA, (byte) 0x1A, (byte) 0x3F, (byte) 0x9B, (byte) 0xAB, (byte) 0xDA, - (byte) 0x3D, (byte) 0x3B, (byte) 0x43, (byte) 0xF0, (byte) 0x0C, (byte) 0x06, (byte) 0x57, (byte) 0x43, (byte) 0x45, (byte) 0xEE, (byte) 0x8C, (byte) 0x27, (byte) 0x05, (byte) 0xAF, (byte) 0xCD, (byte) 0x5A, (byte) 0x47, - (byte) 0xB9, (byte) 0xEA, (byte) 0xD9, (byte) 0xAA, (byte) 0x66, (byte) 0xDB, (byte) 0xE3, (byte) 0xDC, (byte) 0x54, (byte) 0x47, (byte) 0x60, (byte) 0x01, (byte) 0x02, (byte) 0x41, (byte) 0x00, (byte) 0xED, (byte) 0xE9, - (byte) 0xBD, (byte) 0xD5, (byte) 0x02, (byte) 0x6D, (byte) 0x44, (byte) 0x0E, (byte) 0x3F, (byte) 0x74, (byte) 0x0C, (byte) 0x45, (byte) 0x54, (byte) 0x88, (byte) 0xFE, (byte) 0x5C, (byte) 0xFC, (byte) 0xF2, (byte) 0x31, - (byte) 0x7B, (byte) 0xAF, (byte) 0x15, (byte) 0x77, (byte) 0x7A, (byte) 0xDC, (byte) 0xC6, (byte) 0x9E, (byte) 0x7E, (byte) 0xC1, (byte) 0xCA, (byte) 0x84, (byte) 0xC7, (byte) 0x4B, (byte) 0xC4, (byte) 0x41, (byte) 0xE1, - (byte) 0x85, (byte) 0xE4, (byte) 0x5A, (byte) 0xA7, (byte) 0x3D, (byte) 0x54, (byte) 0x87, (byte) 0x0D, (byte) 0x7A, (byte) 0xC5, (byte) 0x47, (byte) 0x5C, (byte) 0xF2, (byte) 0xAD, (byte) 0x14, (byte) 0x4D, (byte) 0x63, - (byte) 0xB0, (byte) 0xDC, (byte) 0x34, (byte) 0xB5, (byte) 0xDA, (byte) 0x17, (byte) 0x0D, (byte) 0x4E, (byte) 0x2B, (byte) 0x9E, (byte) 0x81, (byte) 0x02, (byte) 0x41, (byte) 0x00, (byte) 0xA5, (byte) 0x53, (byte) 0xDB, - (byte) 0xD8, (byte) 0x28, (byte) 0x57, (byte) 0x65, (byte) 0x2B, (byte) 0xFA, (byte) 0xF2, (byte) 0x21, (byte) 0xB8, (byte) 0x60, (byte) 0xAE, (byte) 0x43, (byte) 0x4B, (byte) 0x51, (byte) 0x85, (byte) 0xCB, (byte) 0xDA, - (byte) 0x89, (byte) 0x5A, (byte) 0x7D, (byte) 0x05, (byte) 0xDA, (byte) 0xFC, (byte) 0xAF, (byte) 0x46, (byte) 0x86, (byte) 0xBC, (byte) 0x3F, (byte) 0xD1, (byte) 0xEA, (byte) 0xA4, (byte) 0x56, (byte) 0xA3, (byte) 0xE6, - (byte) 0xD4, (byte) 0xA2, (byte) 0x08, (byte) 0x93, (byte) 0x63, (byte) 0x21, (byte) 0x0E, (byte) 0xC5, (byte) 0x3C, (byte) 0x97, (byte) 0x7E, (byte) 0x71, (byte) 0x0B, (byte) 0x79, (byte) 0xF8, (byte) 0x60, (byte) 0x73, - (byte) 0xD1, (byte) 0xF9, (byte) 0xD4, (byte) 0x66, (byte) 0x29, (byte) 0x7D, (byte) 0xDC, (byte) 0x22, (byte) 0xDB, (byte) 0x61, (byte) 0x02, (byte) 0x40, (byte) 0x5D, (byte) 0x3D, (byte) 0xEF, (byte) 0x85, (byte) 0x4D, - (byte) 0x27, (byte) 0x2F, (byte) 0xB5, (byte) 0xF9, (byte) 0xCE, (byte) 0x6C, (byte) 0x84, (byte) 0xBB, (byte) 0x85, (byte) 0xD9, (byte) 0x52, (byte) 0xEE, (byte) 0x5B, (byte) 0xA9, (byte) 0x63, (byte) 0x15, (byte) 0x12, - (byte) 0x6F, (byte) 0xBA, (byte) 0x3A, (byte) 0x4E, (byte) 0xA9, (byte) 0x8D, (byte) 0x7A, (byte) 0x3B, (byte) 0xF9, (byte) 0xDF, (byte) 0xF5, (byte) 0xE4, (byte) 0xDC, (byte) 0x01, (byte) 0x1C, (byte) 0x2D, (byte) 0x8C, - (byte) 0x0D, (byte) 0xE1, (byte) 0x6E, (byte) 0x80, (byte) 0x63, (byte) 0x9B, (byte) 0x0B, (byte) 0x38, (byte) 0x55, (byte) 0xC8, (byte) 0x52, (byte) 0x67, (byte) 0x13, (byte) 0x91, (byte) 0x8F, (byte) 0x9E, (byte) 0x2E, - (byte) 0x16, (byte) 0x5B, (byte) 0x7C, (byte) 0x0F, (byte) 0x5D, (byte) 0xE4, (byte) 0xA0, (byte) 0x81, (byte) 0x02, (byte) 0x40, (byte) 0x20, (byte) 0x12, (byte) 0x11, (byte) 0x5E, (byte) 0x70, (byte) 0x0C, (byte) 0xEC, - (byte) 0x02, (byte) 0x49, (byte) 0x0E, (byte) 0xB9, (byte) 0x3D, (byte) 0xD3, (byte) 0xFB, (byte) 0x59, (byte) 0xF0, (byte) 0x7D, (byte) 0x62, (byte) 0xEF, (byte) 0xF5, (byte) 0x77, (byte) 0x99, (byte) 0x87, (byte) 0x11, - (byte) 0x20, (byte) 0xB6, (byte) 0xCD, (byte) 0xA5, (byte) 0x67, (byte) 0xB3, (byte) 0x92, (byte) 0xC9, (byte) 0xBC, (byte) 0xB3, (byte) 0x9E, (byte) 0x5E, (byte) 0xF3, (byte) 0x03, (byte) 0x22, (byte) 0x5F, (byte) 0x79, - (byte) 0x7F, (byte) 0xCC, (byte) 0x44, (byte) 0xDA, (byte) 0x3B, (byte) 0xF3, (byte) 0xC3, (byte) 0x42, (byte) 0x58, (byte) 0x90, (byte) 0x93, (byte) 0x7E, (byte) 0xDA, (byte) 0x58, (byte) 0xCC, (byte) 0x16, (byte) 0xC8, - (byte) 0xAE, (byte) 0x99, (byte) 0xCC, (byte) 0x9F, (byte) 0x32, (byte) 0x61, (byte) 0x02, (byte) 0x40, (byte) 0x02, (byte) 0x29, (byte) 0xDB, (byte) 0x00, (byte) 0x0F, (byte) 0x0A, (byte) 0x17, (byte) 0x33, (byte) 0x7E, - (byte) 0xC5, (byte) 0xEC, (byte) 0x21, (byte) 0x47, (byte) 0x65, (byte) 0xDC, (byte) 0xE5, (byte) 0xC2, (byte) 0x0D, (byte) 0x42, (byte) 0x28, (byte) 0xE1, (byte) 0x17, (byte) 0x1A, (byte) 0x00, (byte) 0xBD, (byte) 0xBE, - (byte) 0x1C, (byte) 0x7D, (byte) 0xCA, (byte) 0x93, (byte) 0x67, (byte) 0x8F, (byte) 0x28, (byte) 0xB7, (byte) 0x60, (byte) 0x8E, (byte) 0xF0, (byte) 0x5D, (byte) 0xCD, (byte) 0xFA, (byte) 0xDD, (byte) 0x6B, (byte) 0x72, - (byte) 0xF7, (byte) 0x48, (byte) 0xD9, (byte) 0x3C, (byte) 0x40, (byte) 0x7C, (byte) 0xB0, (byte) 0xD7, (byte) 0x58, (byte) 0xC2, (byte) 0x53, (byte) 0xAD, (byte) 0x04, (byte) 0xF6, (byte) 0x0B, (byte) 0x35, (byte) 0x51, - (byte) 0x45, (byte) 0xB9, (byte) 0x4F, (byte) 0x49 }; - private static final byte[] RSA_public = new byte[] { - (byte) 0x30, (byte) 0x81, (byte) 0x9F, (byte) 0x30, (byte) 0x0D, (byte) 0x06, (byte) 0x09, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0x86, (byte) 0xF7, (byte) 0x0D, (byte) 0x01, (byte) 0x01, (byte) 0x01, (byte) 0x05, - (byte) 0x00, (byte) 0x03, (byte) 0x81, (byte) 0x8D, (byte) 0x00, (byte) 0x30, (byte) 0x81, (byte) 0x89, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0x99, (byte) 0xA5, (byte) 0x96, (byte) 0x72, (byte) 0xAE, - (byte) 0xBB, (byte) 0x59, (byte) 0x36, (byte) 0xA8, (byte) 0x12, (byte) 0x17, (byte) 0x05, (byte) 0x4C, (byte) 0x63, (byte) 0x9E, (byte) 0xB8, (byte) 0x85, (byte) 0xD4, (byte) 0x2D, (byte) 0x71, (byte) 0xD7, (byte) 0x29, - (byte) 0xB9, (byte) 0x05, (byte) 0x0F, (byte) 0xB4, (byte) 0x57, (byte) 0xFB, (byte) 0xD3, (byte) 0x95, (byte) 0x5C, (byte) 0x21, (byte) 0xEC, (byte) 0xB5, (byte) 0xEB, (byte) 0x67, (byte) 0xA2, (byte) 0x4F, (byte) 0xC1, - (byte) 0x93, (byte) 0xEF, (byte) 0x96, (byte) 0x41, (byte) 0x05, (byte) 0x3D, (byte) 0xC5, (byte) 0x3E, (byte) 0x04, (byte) 0x4D, (byte) 0xC6, (byte) 0xCF, (byte) 0x32, (byte) 0x7C, (byte) 0x1F, (byte) 0x66, (byte) 0xA3, - (byte) 0xC5, (byte) 0x27, (byte) 0x79, (byte) 0xEC, (byte) 0x2E, (byte) 0x67, (byte) 0xFA, (byte) 0x19, (byte) 0x5B, (byte) 0xE3, (byte) 0xB1, (byte) 0x69, (byte) 0xDA, (byte) 0x63, (byte) 0xBC, (byte) 0xDA, (byte) 0xD3, - (byte) 0xBB, (byte) 0xAD, (byte) 0x8C, (byte) 0x38, (byte) 0x7B, (byte) 0x4A, (byte) 0x9C, (byte) 0xD4, (byte) 0x4D, (byte) 0xD2, (byte) 0x33, (byte) 0xB7, (byte) 0x4E, (byte) 0x04, (byte) 0xB6, (byte) 0xDF, (byte) 0x62, - (byte) 0x55, (byte) 0x48, (byte) 0x5C, (byte) 0x94, (byte) 0x02, (byte) 0xF7, (byte) 0x84, (byte) 0xE6, (byte) 0x9B, (byte) 0x57, (byte) 0xFF, (byte) 0x17, (byte) 0x2A, (byte) 0xA1, (byte) 0x74, (byte) 0x8D, (byte) 0x07, - (byte) 0xD8, (byte) 0xCE, (byte) 0xF7, (byte) 0x0B, (byte) 0x59, (byte) 0xFB, (byte) 0x13, (byte) 0x6E, (byte) 0xF1, (byte) 0xC3, (byte) 0xAB, (byte) 0x3E, (byte) 0x72, (byte) 0x1B, (byte) 0x62, (byte) 0x09, (byte) 0xE8, - (byte) 0xD8, (byte) 0x41, (byte) 0x69, (byte) 0xE1, (byte) 0x02, (byte) 0x03, (byte) 0x01, (byte) 0x00, (byte) 0x01 }; - private static final byte[] DSA_private = new byte[] { - (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x4B, (byte) 0x02, (byte) 0x01, (byte) 0x00, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x2C, (byte) 0x06, (byte) 0x07, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0xCE, - (byte) 0x38, (byte) 0x04, (byte) 0x01, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x1F, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xFD, (byte) 0x7F, (byte) 0x53, (byte) 0x81, (byte) 0x1D, (byte) 0x75, - (byte) 0x12, (byte) 0x29, (byte) 0x52, (byte) 0xDF, (byte) 0x4A, (byte) 0x9C, (byte) 0x2E, (byte) 0xEC, (byte) 0xE4, (byte) 0xE7, (byte) 0xF6, (byte) 0x11, (byte) 0xB7, (byte) 0x52, (byte) 0x3C, (byte) 0xEF, (byte) 0x44, - (byte) 0x00, (byte) 0xC3, (byte) 0x1E, (byte) 0x3F, (byte) 0x80, (byte) 0xB6, (byte) 0x51, (byte) 0x26, (byte) 0x69, (byte) 0x45, (byte) 0x5D, (byte) 0x40, (byte) 0x22, (byte) 0x51, (byte) 0xFB, (byte) 0x59, (byte) 0x3D, - (byte) 0x8D, (byte) 0x58, (byte) 0xFA, (byte) 0xBF, (byte) 0xC5, (byte) 0xF5, (byte) 0xBA, (byte) 0x30, (byte) 0xF6, (byte) 0xCB, (byte) 0x9B, (byte) 0x55, (byte) 0x6C, (byte) 0xD7, (byte) 0x81, (byte) 0x3B, (byte) 0x80, - (byte) 0x1D, (byte) 0x34, (byte) 0x6F, (byte) 0xF2, (byte) 0x66, (byte) 0x60, (byte) 0xB7, (byte) 0x6B, (byte) 0x99, (byte) 0x50, (byte) 0xA5, (byte) 0xA4, (byte) 0x9F, (byte) 0x9F, (byte) 0xE8, (byte) 0x04, (byte) 0x7B, - (byte) 0x10, (byte) 0x22, (byte) 0xC2, (byte) 0x4F, (byte) 0xBB, (byte) 0xA9, (byte) 0xD7, (byte) 0xFE, (byte) 0xB7, (byte) 0xC6, (byte) 0x1B, (byte) 0xF8, (byte) 0x3B, (byte) 0x57, (byte) 0xE7, (byte) 0xC6, (byte) 0xA8, - (byte) 0xA6, (byte) 0x15, (byte) 0x0F, (byte) 0x04, (byte) 0xFB, (byte) 0x83, (byte) 0xF6, (byte) 0xD3, (byte) 0xC5, (byte) 0x1E, (byte) 0xC3, (byte) 0x02, (byte) 0x35, (byte) 0x54, (byte) 0x13, (byte) 0x5A, (byte) 0x16, - (byte) 0x91, (byte) 0x32, (byte) 0xF6, (byte) 0x75, (byte) 0xF3, (byte) 0xAE, (byte) 0x2B, (byte) 0x61, (byte) 0xD7, (byte) 0x2A, (byte) 0xEF, (byte) 0xF2, (byte) 0x22, (byte) 0x03, (byte) 0x19, (byte) 0x9D, (byte) 0xD1, - (byte) 0x48, (byte) 0x01, (byte) 0xC7, (byte) 0x02, (byte) 0x15, (byte) 0x00, (byte) 0x97, (byte) 0x60, (byte) 0x50, (byte) 0x8F, (byte) 0x15, (byte) 0x23, (byte) 0x0B, (byte) 0xCC, (byte) 0xB2, (byte) 0x92, (byte) 0xB9, - (byte) 0x82, (byte) 0xA2, (byte) 0xEB, (byte) 0x84, (byte) 0x0B, (byte) 0xF0, (byte) 0x58, (byte) 0x1C, (byte) 0xF5, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xF7, (byte) 0xE1, (byte) 0xA0, (byte) 0x85, - (byte) 0xD6, (byte) 0x9B, (byte) 0x3D, (byte) 0xDE, (byte) 0xCB, (byte) 0xBC, (byte) 0xAB, (byte) 0x5C, (byte) 0x36, (byte) 0xB8, (byte) 0x57, (byte) 0xB9, (byte) 0x79, (byte) 0x94, (byte) 0xAF, (byte) 0xBB, (byte) 0xFA, - (byte) 0x3A, (byte) 0xEA, (byte) 0x82, (byte) 0xF9, (byte) 0x57, (byte) 0x4C, (byte) 0x0B, (byte) 0x3D, (byte) 0x07, (byte) 0x82, (byte) 0x67, (byte) 0x51, (byte) 0x59, (byte) 0x57, (byte) 0x8E, (byte) 0xBA, (byte) 0xD4, - (byte) 0x59, (byte) 0x4F, (byte) 0xE6, (byte) 0x71, (byte) 0x07, (byte) 0x10, (byte) 0x81, (byte) 0x80, (byte) 0xB4, (byte) 0x49, (byte) 0x16, (byte) 0x71, (byte) 0x23, (byte) 0xE8, (byte) 0x4C, (byte) 0x28, (byte) 0x16, - (byte) 0x13, (byte) 0xB7, (byte) 0xCF, (byte) 0x09, (byte) 0x32, (byte) 0x8C, (byte) 0xC8, (byte) 0xA6, (byte) 0xE1, (byte) 0x3C, (byte) 0x16, (byte) 0x7A, (byte) 0x8B, (byte) 0x54, (byte) 0x7C, (byte) 0x8D, (byte) 0x28, - (byte) 0xE0, (byte) 0xA3, (byte) 0xAE, (byte) 0x1E, (byte) 0x2B, (byte) 0xB3, (byte) 0xA6, (byte) 0x75, (byte) 0x91, (byte) 0x6E, (byte) 0xA3, (byte) 0x7F, (byte) 0x0B, (byte) 0xFA, (byte) 0x21, (byte) 0x35, (byte) 0x62, - (byte) 0xF1, (byte) 0xFB, (byte) 0x62, (byte) 0x7A, (byte) 0x01, (byte) 0x24, (byte) 0x3B, (byte) 0xCC, (byte) 0xA4, (byte) 0xF1, (byte) 0xBE, (byte) 0xA8, (byte) 0x51, (byte) 0x90, (byte) 0x89, (byte) 0xA8, (byte) 0x83, - (byte) 0xDF, (byte) 0xE1, (byte) 0x5A, (byte) 0xE5, (byte) 0x9F, (byte) 0x06, (byte) 0x92, (byte) 0x8B, (byte) 0x66, (byte) 0x5E, (byte) 0x80, (byte) 0x7B, (byte) 0x55, (byte) 0x25, (byte) 0x64, (byte) 0x01, (byte) 0x4C, - (byte) 0x3B, (byte) 0xFE, (byte) 0xCF, (byte) 0x49, (byte) 0x2A, (byte) 0x04, (byte) 0x16, (byte) 0x02, (byte) 0x14, (byte) 0x0E, (byte) 0x90, (byte) 0xB7, (byte) 0x92, (byte) 0x01, (byte) 0x98, (byte) 0xCD, (byte) 0x85, - (byte) 0x87, (byte) 0x77, (byte) 0x2F, (byte) 0xB4, (byte) 0x31, (byte) 0xFD, (byte) 0xDE, (byte) 0xFA, (byte) 0x08, (byte) 0x6D, (byte) 0x0C, (byte) 0xE3 }; - private static final byte[] DSA_public = new byte[] { - (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0xB8, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x2C, (byte) 0x06, (byte) 0x07, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0xCE, (byte) 0x38, (byte) 0x04, (byte) 0x01, - (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x1F, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xFD, (byte) 0x7F, (byte) 0x53, (byte) 0x81, (byte) 0x1D, (byte) 0x75, (byte) 0x12, (byte) 0x29, (byte) 0x52, - (byte) 0xDF, (byte) 0x4A, (byte) 0x9C, (byte) 0x2E, (byte) 0xEC, (byte) 0xE4, (byte) 0xE7, (byte) 0xF6, (byte) 0x11, (byte) 0xB7, (byte) 0x52, (byte) 0x3C, (byte) 0xEF, (byte) 0x44, (byte) 0x00, (byte) 0xC3, (byte) 0x1E, - (byte) 0x3F, (byte) 0x80, (byte) 0xB6, (byte) 0x51, (byte) 0x26, (byte) 0x69, (byte) 0x45, (byte) 0x5D, (byte) 0x40, (byte) 0x22, (byte) 0x51, (byte) 0xFB, (byte) 0x59, (byte) 0x3D, (byte) 0x8D, (byte) 0x58, (byte) 0xFA, - (byte) 0xBF, (byte) 0xC5, (byte) 0xF5, (byte) 0xBA, (byte) 0x30, (byte) 0xF6, (byte) 0xCB, (byte) 0x9B, (byte) 0x55, (byte) 0x6C, (byte) 0xD7, (byte) 0x81, (byte) 0x3B, (byte) 0x80, (byte) 0x1D, (byte) 0x34, (byte) 0x6F, - (byte) 0xF2, (byte) 0x66, (byte) 0x60, (byte) 0xB7, (byte) 0x6B, (byte) 0x99, (byte) 0x50, (byte) 0xA5, (byte) 0xA4, (byte) 0x9F, (byte) 0x9F, (byte) 0xE8, (byte) 0x04, (byte) 0x7B, (byte) 0x10, (byte) 0x22, (byte) 0xC2, - (byte) 0x4F, (byte) 0xBB, (byte) 0xA9, (byte) 0xD7, (byte) 0xFE, (byte) 0xB7, (byte) 0xC6, (byte) 0x1B, (byte) 0xF8, (byte) 0x3B, (byte) 0x57, (byte) 0xE7, (byte) 0xC6, (byte) 0xA8, (byte) 0xA6, (byte) 0x15, (byte) 0x0F, - (byte) 0x04, (byte) 0xFB, (byte) 0x83, (byte) 0xF6, (byte) 0xD3, (byte) 0xC5, (byte) 0x1E, (byte) 0xC3, (byte) 0x02, (byte) 0x35, (byte) 0x54, (byte) 0x13, (byte) 0x5A, (byte) 0x16, (byte) 0x91, (byte) 0x32, (byte) 0xF6, - (byte) 0x75, (byte) 0xF3, (byte) 0xAE, (byte) 0x2B, (byte) 0x61, (byte) 0xD7, (byte) 0x2A, (byte) 0xEF, (byte) 0xF2, (byte) 0x22, (byte) 0x03, (byte) 0x19, (byte) 0x9D, (byte) 0xD1, (byte) 0x48, (byte) 0x01, (byte) 0xC7, - (byte) 0x02, (byte) 0x15, (byte) 0x00, (byte) 0x97, (byte) 0x60, (byte) 0x50, (byte) 0x8F, (byte) 0x15, (byte) 0x23, (byte) 0x0B, (byte) 0xCC, (byte) 0xB2, (byte) 0x92, (byte) 0xB9, (byte) 0x82, (byte) 0xA2, (byte) 0xEB, - (byte) 0x84, (byte) 0x0B, (byte) 0xF0, (byte) 0x58, (byte) 0x1C, (byte) 0xF5, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xF7, (byte) 0xE1, (byte) 0xA0, (byte) 0x85, (byte) 0xD6, (byte) 0x9B, (byte) 0x3D, - (byte) 0xDE, (byte) 0xCB, (byte) 0xBC, (byte) 0xAB, (byte) 0x5C, (byte) 0x36, (byte) 0xB8, (byte) 0x57, (byte) 0xB9, (byte) 0x79, (byte) 0x94, (byte) 0xAF, (byte) 0xBB, (byte) 0xFA, (byte) 0x3A, (byte) 0xEA, (byte) 0x82, - (byte) 0xF9, (byte) 0x57, (byte) 0x4C, (byte) 0x0B, (byte) 0x3D, (byte) 0x07, (byte) 0x82, (byte) 0x67, (byte) 0x51, (byte) 0x59, (byte) 0x57, (byte) 0x8E, (byte) 0xBA, (byte) 0xD4, (byte) 0x59, (byte) 0x4F, (byte) 0xE6, - (byte) 0x71, (byte) 0x07, (byte) 0x10, (byte) 0x81, (byte) 0x80, (byte) 0xB4, (byte) 0x49, (byte) 0x16, (byte) 0x71, (byte) 0x23, (byte) 0xE8, (byte) 0x4C, (byte) 0x28, (byte) 0x16, (byte) 0x13, (byte) 0xB7, (byte) 0xCF, - (byte) 0x09, (byte) 0x32, (byte) 0x8C, (byte) 0xC8, (byte) 0xA6, (byte) 0xE1, (byte) 0x3C, (byte) 0x16, (byte) 0x7A, (byte) 0x8B, (byte) 0x54, (byte) 0x7C, (byte) 0x8D, (byte) 0x28, (byte) 0xE0, (byte) 0xA3, (byte) 0xAE, - (byte) 0x1E, (byte) 0x2B, (byte) 0xB3, (byte) 0xA6, (byte) 0x75, (byte) 0x91, (byte) 0x6E, (byte) 0xA3, (byte) 0x7F, (byte) 0x0B, (byte) 0xFA, (byte) 0x21, (byte) 0x35, (byte) 0x62, (byte) 0xF1, (byte) 0xFB, (byte) 0x62, - (byte) 0x7A, (byte) 0x01, (byte) 0x24, (byte) 0x3B, (byte) 0xCC, (byte) 0xA4, (byte) 0xF1, (byte) 0xBE, (byte) 0xA8, (byte) 0x51, (byte) 0x90, (byte) 0x89, (byte) 0xA8, (byte) 0x83, (byte) 0xDF, (byte) 0xE1, (byte) 0x5A, - (byte) 0xE5, (byte) 0x9F, (byte) 0x06, (byte) 0x92, (byte) 0x8B, (byte) 0x66, (byte) 0x5E, (byte) 0x80, (byte) 0x7B, (byte) 0x55, (byte) 0x25, (byte) 0x64, (byte) 0x01, (byte) 0x4C, (byte) 0x3B, (byte) 0xFE, (byte) 0xCF, - (byte) 0x49, (byte) 0x2A, (byte) 0x03, (byte) 0x81, (byte) 0x85, (byte) 0x00, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0x98, (byte) 0x33, (byte) 0x90, (byte) 0x14, (byte) 0x79, (byte) 0xC7, (byte) 0xC8, - (byte) 0x57, (byte) 0xE1, (byte) 0x82, (byte) 0x53, (byte) 0x5B, (byte) 0x6E, (byte) 0x01, (byte) 0x07, (byte) 0x1E, (byte) 0xA5, (byte) 0x98, (byte) 0xC4, (byte) 0x57, (byte) 0x5D, (byte) 0x23, (byte) 0xAB, (byte) 0x72, - (byte) 0x9A, (byte) 0xB3, (byte) 0x2F, (byte) 0x39, (byte) 0xCB, (byte) 0xC5, (byte) 0xD0, (byte) 0x97, (byte) 0xD5, (byte) 0x62, (byte) 0x8C, (byte) 0xD9, (byte) 0xE6, (byte) 0xE2, (byte) 0x05, (byte) 0xC6, (byte) 0x05, - (byte) 0x71, (byte) 0x16, (byte) 0xE3, (byte) 0xE8, (byte) 0x04, (byte) 0xE8, (byte) 0x46, (byte) 0x12, (byte) 0x0C, (byte) 0xF8, (byte) 0xFC, (byte) 0x8E, (byte) 0x15, (byte) 0x26, (byte) 0x32, (byte) 0xF7, (byte) 0x8C, - (byte) 0x04, (byte) 0x3B, (byte) 0x53, (byte) 0x68, (byte) 0x9A, (byte) 0xA3, (byte) 0xB7, (byte) 0x4D, (byte) 0x13, (byte) 0x40, (byte) 0x0F, (byte) 0xBE, (byte) 0x03, (byte) 0x87, (byte) 0xD8, (byte) 0xF1, (byte) 0xFE, - (byte) 0x4B, (byte) 0xF5, (byte) 0x44, (byte) 0x19, (byte) 0x29, (byte) 0xBB, (byte) 0x0D, (byte) 0x0C, (byte) 0x52, (byte) 0xC6, (byte) 0x84, (byte) 0x33, (byte) 0x62, (byte) 0x73, (byte) 0x5D, (byte) 0x03, (byte) 0xFF, - (byte) 0x6F, (byte) 0x0A, (byte) 0x5A, (byte) 0xF3, (byte) 0x9E, (byte) 0x52, (byte) 0xF2, (byte) 0xC2, (byte) 0xC8, (byte) 0x00, (byte) 0x52, (byte) 0xC7, (byte) 0x75, (byte) 0xA4, (byte) 0xFD, (byte) 0x71, (byte) 0x2D, - (byte) 0x7B, (byte) 0x7A, (byte) 0x31, (byte) 0x27, (byte) 0x6E, (byte) 0xAC, (byte) 0xB6, (byte) 0x40, (byte) 0x14, (byte) 0x4E, (byte) 0xB4, (byte) 0xBB, (byte) 0xB1, (byte) 0x51, (byte) 0x63, (byte) 0x29, (byte) 0x81, - (byte) 0x06, (byte) 0xF9 }; - private static final byte[] DH_private = new byte[] { - (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0xA8, (byte) 0x02, (byte) 0x01, (byte) 0x00, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x1B, (byte) 0x06, (byte) 0x09, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0x86, - (byte) 0xF7, (byte) 0x0D, (byte) 0x01, (byte) 0x03, (byte) 0x01, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x0C, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xFD, (byte) 0x7F, (byte) 0x53, (byte) 0x81, - (byte) 0x1D, (byte) 0x75, (byte) 0x12, (byte) 0x29, (byte) 0x52, (byte) 0xDF, (byte) 0x4A, (byte) 0x9C, (byte) 0x2E, (byte) 0xEC, (byte) 0xE4, (byte) 0xE7, (byte) 0xF6, (byte) 0x11, (byte) 0xB7, (byte) 0x52, (byte) 0x3C, - (byte) 0xEF, (byte) 0x44, (byte) 0x00, (byte) 0xC3, (byte) 0x1E, (byte) 0x3F, (byte) 0x80, (byte) 0xB6, (byte) 0x51, (byte) 0x26, (byte) 0x69, (byte) 0x45, (byte) 0x5D, (byte) 0x40, (byte) 0x22, (byte) 0x51, (byte) 0xFB, - (byte) 0x59, (byte) 0x3D, (byte) 0x8D, (byte) 0x58, (byte) 0xFA, (byte) 0xBF, (byte) 0xC5, (byte) 0xF5, (byte) 0xBA, (byte) 0x30, (byte) 0xF6, (byte) 0xCB, (byte) 0x9B, (byte) 0x55, (byte) 0x6C, (byte) 0xD7, (byte) 0x81, - (byte) 0x3B, (byte) 0x80, (byte) 0x1D, (byte) 0x34, (byte) 0x6F, (byte) 0xF2, (byte) 0x66, (byte) 0x60, (byte) 0xB7, (byte) 0x6B, (byte) 0x99, (byte) 0x50, (byte) 0xA5, (byte) 0xA4, (byte) 0x9F, (byte) 0x9F, (byte) 0xE8, - (byte) 0x04, (byte) 0x7B, (byte) 0x10, (byte) 0x22, (byte) 0xC2, (byte) 0x4F, (byte) 0xBB, (byte) 0xA9, (byte) 0xD7, (byte) 0xFE, (byte) 0xB7, (byte) 0xC6, (byte) 0x1B, (byte) 0xF8, (byte) 0x3B, (byte) 0x57, (byte) 0xE7, - (byte) 0xC6, (byte) 0xA8, (byte) 0xA6, (byte) 0x15, (byte) 0x0F, (byte) 0x04, (byte) 0xFB, (byte) 0x83, (byte) 0xF6, (byte) 0xD3, (byte) 0xC5, (byte) 0x1E, (byte) 0xC3, (byte) 0x02, (byte) 0x35, (byte) 0x54, (byte) 0x13, - (byte) 0x5A, (byte) 0x16, (byte) 0x91, (byte) 0x32, (byte) 0xF6, (byte) 0x75, (byte) 0xF3, (byte) 0xAE, (byte) 0x2B, (byte) 0x61, (byte) 0xD7, (byte) 0x2A, (byte) 0xEF, (byte) 0xF2, (byte) 0x22, (byte) 0x03, (byte) 0x19, - (byte) 0x9D, (byte) 0xD1, (byte) 0x48, (byte) 0x01, (byte) 0xC7, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xF7, (byte) 0xE1, (byte) 0xA0, (byte) 0x85, (byte) 0xD6, (byte) 0x9B, (byte) 0x3D, (byte) 0xDE, - (byte) 0xCB, (byte) 0xBC, (byte) 0xAB, (byte) 0x5C, (byte) 0x36, (byte) 0xB8, (byte) 0x57, (byte) 0xB9, (byte) 0x79, (byte) 0x94, (byte) 0xAF, (byte) 0xBB, (byte) 0xFA, (byte) 0x3A, (byte) 0xEA, (byte) 0x82, (byte) 0xF9, - (byte) 0x57, (byte) 0x4C, (byte) 0x0B, (byte) 0x3D, (byte) 0x07, (byte) 0x82, (byte) 0x67, (byte) 0x51, (byte) 0x59, (byte) 0x57, (byte) 0x8E, (byte) 0xBA, (byte) 0xD4, (byte) 0x59, (byte) 0x4F, (byte) 0xE6, (byte) 0x71, - (byte) 0x07, (byte) 0x10, (byte) 0x81, (byte) 0x80, (byte) 0xB4, (byte) 0x49, (byte) 0x16, (byte) 0x71, (byte) 0x23, (byte) 0xE8, (byte) 0x4C, (byte) 0x28, (byte) 0x16, (byte) 0x13, (byte) 0xB7, (byte) 0xCF, (byte) 0x09, - (byte) 0x32, (byte) 0x8C, (byte) 0xC8, (byte) 0xA6, (byte) 0xE1, (byte) 0x3C, (byte) 0x16, (byte) 0x7A, (byte) 0x8B, (byte) 0x54, (byte) 0x7C, (byte) 0x8D, (byte) 0x28, (byte) 0xE0, (byte) 0xA3, (byte) 0xAE, (byte) 0x1E, - (byte) 0x2B, (byte) 0xB3, (byte) 0xA6, (byte) 0x75, (byte) 0x91, (byte) 0x6E, (byte) 0xA3, (byte) 0x7F, (byte) 0x0B, (byte) 0xFA, (byte) 0x21, (byte) 0x35, (byte) 0x62, (byte) 0xF1, (byte) 0xFB, (byte) 0x62, (byte) 0x7A, - (byte) 0x01, (byte) 0x24, (byte) 0x3B, (byte) 0xCC, (byte) 0xA4, (byte) 0xF1, (byte) 0xBE, (byte) 0xA8, (byte) 0x51, (byte) 0x90, (byte) 0x89, (byte) 0xA8, (byte) 0x83, (byte) 0xDF, (byte) 0xE1, (byte) 0x5A, (byte) 0xE5, - (byte) 0x9F, (byte) 0x06, (byte) 0x92, (byte) 0x8B, (byte) 0x66, (byte) 0x5E, (byte) 0x80, (byte) 0x7B, (byte) 0x55, (byte) 0x25, (byte) 0x64, (byte) 0x01, (byte) 0x4C, (byte) 0x3B, (byte) 0xFE, (byte) 0xCF, (byte) 0x49, - (byte) 0x2A, (byte) 0x02, (byte) 0x02, (byte) 0x03, (byte) 0xFE, (byte) 0x04, (byte) 0x81, (byte) 0x83, (byte) 0x02, (byte) 0x81, (byte) 0x80, (byte) 0x35, (byte) 0xFE, (byte) 0x44, (byte) 0x0A, (byte) 0xA3, (byte) 0xA0, - (byte) 0xCB, (byte) 0x52, (byte) 0xC2, (byte) 0x32, (byte) 0xCA, (byte) 0x38, (byte) 0x1F, (byte) 0x18, (byte) 0xEB, (byte) 0x27, (byte) 0x6E, (byte) 0x77, (byte) 0x25, (byte) 0x40, (byte) 0x1F, (byte) 0x64, (byte) 0x5D, - (byte) 0x4B, (byte) 0x59, (byte) 0x41, (byte) 0xB6, (byte) 0xCB, (byte) 0xDF, (byte) 0x73, (byte) 0xE0, (byte) 0x01, (byte) 0x5A, (byte) 0x79, (byte) 0x0D, (byte) 0x8D, (byte) 0x08, (byte) 0xE6, (byte) 0x7F, (byte) 0x86, - (byte) 0x58, (byte) 0xCF, (byte) 0x7F, (byte) 0x4B, (byte) 0x2E, (byte) 0xDB, (byte) 0x4C, (byte) 0xDF, (byte) 0x75, (byte) 0xB5, (byte) 0x16, (byte) 0xC4, (byte) 0xA9, (byte) 0x49, (byte) 0xEE, (byte) 0x00, (byte) 0x56, - (byte) 0xA0, (byte) 0x60, (byte) 0x08, (byte) 0x8E, (byte) 0x0D, (byte) 0xC7, (byte) 0xC9, (byte) 0x45, (byte) 0x0C, (byte) 0x5D, (byte) 0xB7, (byte) 0x4C, (byte) 0xC4, (byte) 0x7E, (byte) 0xAB, (byte) 0x1F, (byte) 0xEA, - (byte) 0xCF, (byte) 0x08, (byte) 0x6D, (byte) 0x05, (byte) 0xA1, (byte) 0x7F, (byte) 0x63, (byte) 0x6F, (byte) 0xB3, (byte) 0x91, (byte) 0xA3, (byte) 0xE1, (byte) 0xB0, (byte) 0x36, (byte) 0x02, (byte) 0x3F, (byte) 0x55, - (byte) 0x71, (byte) 0x38, (byte) 0x37, (byte) 0x9A, (byte) 0x19, (byte) 0xA3, (byte) 0xAF, (byte) 0xC8, (byte) 0xD5, (byte) 0x22, (byte) 0xDD, (byte) 0x00, (byte) 0x81, (byte) 0x19, (byte) 0xB6, (byte) 0x3C, (byte) 0x5F, - (byte) 0xD9, (byte) 0xDF, (byte) 0xFD, (byte) 0x58, (byte) 0xB1, (byte) 0xE6, (byte) 0xD1, (byte) 0xD2, (byte) 0x58, (byte) 0xEF, (byte) 0x44, (byte) 0x6E, (byte) 0x66, (byte) 0x92, (byte) 0x1E, (byte) 0x30, (byte) 0x0B, - (byte) 0x90, (byte) 0x8E, (byte) 0x29 }; - private static final byte[] DH_public = new byte[] { - (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0xA7, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x1B, (byte) 0x06, (byte) 0x09, (byte) 0x2A, (byte) 0x86, (byte) 0x48, (byte) 0x86, (byte) 0xF7, (byte) 0x0D, (byte) 0x01, - (byte) 0x03, (byte) 0x01, (byte) 0x30, (byte) 0x82, (byte) 0x01, (byte) 0x0C, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xFD, (byte) 0x7F, (byte) 0x53, (byte) 0x81, (byte) 0x1D, (byte) 0x75, (byte) 0x12, - (byte) 0x29, (byte) 0x52, (byte) 0xDF, (byte) 0x4A, (byte) 0x9C, (byte) 0x2E, (byte) 0xEC, (byte) 0xE4, (byte) 0xE7, (byte) 0xF6, (byte) 0x11, (byte) 0xB7, (byte) 0x52, (byte) 0x3C, (byte) 0xEF, (byte) 0x44, (byte) 0x00, - (byte) 0xC3, (byte) 0x1E, (byte) 0x3F, (byte) 0x80, (byte) 0xB6, (byte) 0x51, (byte) 0x26, (byte) 0x69, (byte) 0x45, (byte) 0x5D, (byte) 0x40, (byte) 0x22, (byte) 0x51, (byte) 0xFB, (byte) 0x59, (byte) 0x3D, (byte) 0x8D, - (byte) 0x58, (byte) 0xFA, (byte) 0xBF, (byte) 0xC5, (byte) 0xF5, (byte) 0xBA, (byte) 0x30, (byte) 0xF6, (byte) 0xCB, (byte) 0x9B, (byte) 0x55, (byte) 0x6C, (byte) 0xD7, (byte) 0x81, (byte) 0x3B, (byte) 0x80, (byte) 0x1D, - (byte) 0x34, (byte) 0x6F, (byte) 0xF2, (byte) 0x66, (byte) 0x60, (byte) 0xB7, (byte) 0x6B, (byte) 0x99, (byte) 0x50, (byte) 0xA5, (byte) 0xA4, (byte) 0x9F, (byte) 0x9F, (byte) 0xE8, (byte) 0x04, (byte) 0x7B, (byte) 0x10, - (byte) 0x22, (byte) 0xC2, (byte) 0x4F, (byte) 0xBB, (byte) 0xA9, (byte) 0xD7, (byte) 0xFE, (byte) 0xB7, (byte) 0xC6, (byte) 0x1B, (byte) 0xF8, (byte) 0x3B, (byte) 0x57, (byte) 0xE7, (byte) 0xC6, (byte) 0xA8, (byte) 0xA6, - (byte) 0x15, (byte) 0x0F, (byte) 0x04, (byte) 0xFB, (byte) 0x83, (byte) 0xF6, (byte) 0xD3, (byte) 0xC5, (byte) 0x1E, (byte) 0xC3, (byte) 0x02, (byte) 0x35, (byte) 0x54, (byte) 0x13, (byte) 0x5A, (byte) 0x16, (byte) 0x91, - (byte) 0x32, (byte) 0xF6, (byte) 0x75, (byte) 0xF3, (byte) 0xAE, (byte) 0x2B, (byte) 0x61, (byte) 0xD7, (byte) 0x2A, (byte) 0xEF, (byte) 0xF2, (byte) 0x22, (byte) 0x03, (byte) 0x19, (byte) 0x9D, (byte) 0xD1, (byte) 0x48, - (byte) 0x01, (byte) 0xC7, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xF7, (byte) 0xE1, (byte) 0xA0, (byte) 0x85, (byte) 0xD6, (byte) 0x9B, (byte) 0x3D, (byte) 0xDE, (byte) 0xCB, (byte) 0xBC, (byte) 0xAB, - (byte) 0x5C, (byte) 0x36, (byte) 0xB8, (byte) 0x57, (byte) 0xB9, (byte) 0x79, (byte) 0x94, (byte) 0xAF, (byte) 0xBB, (byte) 0xFA, (byte) 0x3A, (byte) 0xEA, (byte) 0x82, (byte) 0xF9, (byte) 0x57, (byte) 0x4C, (byte) 0x0B, - (byte) 0x3D, (byte) 0x07, (byte) 0x82, (byte) 0x67, (byte) 0x51, (byte) 0x59, (byte) 0x57, (byte) 0x8E, (byte) 0xBA, (byte) 0xD4, (byte) 0x59, (byte) 0x4F, (byte) 0xE6, (byte) 0x71, (byte) 0x07, (byte) 0x10, (byte) 0x81, - (byte) 0x80, (byte) 0xB4, (byte) 0x49, (byte) 0x16, (byte) 0x71, (byte) 0x23, (byte) 0xE8, (byte) 0x4C, (byte) 0x28, (byte) 0x16, (byte) 0x13, (byte) 0xB7, (byte) 0xCF, (byte) 0x09, (byte) 0x32, (byte) 0x8C, (byte) 0xC8, - (byte) 0xA6, (byte) 0xE1, (byte) 0x3C, (byte) 0x16, (byte) 0x7A, (byte) 0x8B, (byte) 0x54, (byte) 0x7C, (byte) 0x8D, (byte) 0x28, (byte) 0xE0, (byte) 0xA3, (byte) 0xAE, (byte) 0x1E, (byte) 0x2B, (byte) 0xB3, (byte) 0xA6, - (byte) 0x75, (byte) 0x91, (byte) 0x6E, (byte) 0xA3, (byte) 0x7F, (byte) 0x0B, (byte) 0xFA, (byte) 0x21, (byte) 0x35, (byte) 0x62, (byte) 0xF1, (byte) 0xFB, (byte) 0x62, (byte) 0x7A, (byte) 0x01, (byte) 0x24, (byte) 0x3B, - (byte) 0xCC, (byte) 0xA4, (byte) 0xF1, (byte) 0xBE, (byte) 0xA8, (byte) 0x51, (byte) 0x90, (byte) 0x89, (byte) 0xA8, (byte) 0x83, (byte) 0xDF, (byte) 0xE1, (byte) 0x5A, (byte) 0xE5, (byte) 0x9F, (byte) 0x06, (byte) 0x92, - (byte) 0x8B, (byte) 0x66, (byte) 0x5E, (byte) 0x80, (byte) 0x7B, (byte) 0x55, (byte) 0x25, (byte) 0x64, (byte) 0x01, (byte) 0x4C, (byte) 0x3B, (byte) 0xFE, (byte) 0xCF, (byte) 0x49, (byte) 0x2A, (byte) 0x02, (byte) 0x02, - (byte) 0x03, (byte) 0xFE, (byte) 0x03, (byte) 0x81, (byte) 0x85, (byte) 0x00, (byte) 0x02, (byte) 0x81, (byte) 0x81, (byte) 0x00, (byte) 0xD4, (byte) 0xC2, (byte) 0xC2, (byte) 0x84, (byte) 0xEB, (byte) 0xEC, (byte) 0xB6, - (byte) 0xF1, (byte) 0x29, (byte) 0x2B, (byte) 0xAB, (byte) 0x8F, (byte) 0xC1, (byte) 0x48, (byte) 0x4C, (byte) 0x47, (byte) 0xCE, (byte) 0x0B, (byte) 0x97, (byte) 0x4C, (byte) 0xFC, (byte) 0x27, (byte) 0x10, (byte) 0x0A, - (byte) 0x5F, (byte) 0x3E, (byte) 0xE6, (byte) 0xF9, (byte) 0x9B, (byte) 0x15, (byte) 0xDF, (byte) 0x83, (byte) 0x01, (byte) 0xFA, (byte) 0x69, (byte) 0x57, (byte) 0xEC, (byte) 0x6B, (byte) 0x68, (byte) 0xC7, (byte) 0x96, - (byte) 0x33, (byte) 0x98, (byte) 0xA4, (byte) 0xB0, (byte) 0xA3, (byte) 0x18, (byte) 0x01, (byte) 0x66, (byte) 0x7A, (byte) 0x4A, (byte) 0xF3, (byte) 0x3C, (byte) 0xD9, (byte) 0x2A, (byte) 0x48, (byte) 0xFD, (byte) 0x3A, - (byte) 0x31, (byte) 0xFC, (byte) 0x97, (byte) 0x52, (byte) 0x36, (byte) 0x20, (byte) 0x0E, (byte) 0x69, (byte) 0xB6, (byte) 0x32, (byte) 0x8B, (byte) 0x4E, (byte) 0xDA, (byte) 0x8B, (byte) 0x04, (byte) 0x88, (byte) 0xF8, - (byte) 0x30, (byte) 0xA9, (byte) 0x65, (byte) 0x68, (byte) 0x47, (byte) 0xBB, (byte) 0xA1, (byte) 0xF6, (byte) 0xD6, (byte) 0x18, (byte) 0x11, (byte) 0x48, (byte) 0x8D, (byte) 0x8F, (byte) 0x4B, (byte) 0xC1, (byte) 0xE1, - (byte) 0xA4, (byte) 0x43, (byte) 0x83, (byte) 0x1F, (byte) 0x6B, (byte) 0x6D, (byte) 0xEE, (byte) 0xA7, (byte) 0xA3, (byte) 0x5F, (byte) 0xD2, (byte) 0x95, (byte) 0x09, (byte) 0xD4, (byte) 0xEA, (byte) 0x85, (byte) 0x0C, - (byte) 0xA5, (byte) 0xC9, (byte) 0x93, (byte) 0xCE, (byte) 0xC1, (byte) 0x1D, (byte) 0x30, (byte) 0x73, (byte) 0xA3, (byte) 0xE1, (byte) 0x69, (byte) 0xA8, (byte) 0x11, (byte) 0x98, (byte) 0x78, (byte) 0xF3, (byte) 0xF9, - (byte) 0x8F, (byte) 0x04 }; - - - - private static final HashMap<String, KeySpec> keys = new HashMap<String, KeySpec>(); - static { - keys.put("DH_public", new X509EncodedKeySpec(DH_public)); - keys.put("DH_private", new PKCS8EncodedKeySpec(DH_private)); - keys.put("DSA_public", new X509EncodedKeySpec(DSA_public)); - keys.put("DSA_private", new PKCS8EncodedKeySpec(DSA_private)); - keys.put("RSA_public", new X509EncodedKeySpec(RSA_public)); - keys.put("RSA_private", new PKCS8EncodedKeySpec(RSA_private)); - } - - public static PrivateKey getPrivateKey(String algorithmName) throws NoSuchAlgorithmException, InvalidKeySpecException - { - KeyFactory factory = KeyFactory.getInstance(algorithmName); - return factory.generatePrivate(keys.get(algorithmName + "_private")); - } - - public static PublicKey getPublicKey(String algorithmName) throws NoSuchAlgorithmException, InvalidKeySpecException - { - KeyFactory factory = KeyFactory.getInstance(algorithmName); - return factory.generatePublic(keys.get(algorithmName + "_public")); - } -} diff --git a/luni/src/test/java/tests/targets/security/KeyFactoryTest.java b/luni/src/test/java/tests/targets/security/KeyFactoryTest.java deleted file mode 100644 index 26cd8a3..0000000 --- a/luni/src/test/java/tests/targets/security/KeyFactoryTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (C) 2009 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 tests.targets.security; - -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; - -import junit.framework.TestCase; - -import java.security.Key; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.KeySpec; -public abstract class KeyFactoryTest<PublicKeySpec extends KeySpec, PrivateKeySpec extends KeySpec> - extends TestCase { - - private final String algorithmName; - private final Class<PublicKeySpec> publicKeySpecClass; - private final Class<PrivateKeySpec> privateKeySpecClass; - - private KeyFactory factory; - private final TestHelper<KeyPair> helper; - - - public KeyFactoryTest(String algorithmName, TestHelper<KeyPair> helper, - Class<PublicKeySpec> publicKeySpecClass, - Class<PrivateKeySpec> privateKeySpecClass) { - this.algorithmName = algorithmName; - this.helper = helper; - this.publicKeySpecClass = publicKeySpecClass; - this.privateKeySpecClass = privateKeySpecClass; - } - - protected void setUp() throws Exception { - super.setUp(); - factory = getFactory(); - } - - private KeyFactory getFactory() { - try { - return KeyFactory.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - fail(e.getMessage()); - } - return null; - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "getKeySpec", - args = {Key.class, Class.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "generatePrivate", - args = {KeySpec.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "generatePublic", - args = {KeySpec.class} - ), - @TestTargetNew( - level=TestLevel.COMPLETE, - method="method", - args={} - ) - }) - public void testKeyFactory() { - PrivateKeySpec privateKeySpec = null; - try { - privateKeySpec = factory.getKeySpec(DefaultKeys.getPrivateKey(algorithmName), - privateKeySpecClass); - } catch (InvalidKeySpecException e) { - fail(e.getMessage()); - } catch (NoSuchAlgorithmException e) { - fail(e.getMessage()); - } - - PrivateKey privateKey = null; - try { - privateKey = factory.generatePrivate(privateKeySpec); - } catch (InvalidKeySpecException e) { - fail(e.getMessage()); - } - - PublicKeySpec publicKeySpec = null; - try { - publicKeySpec = factory.getKeySpec(DefaultKeys.getPublicKey(algorithmName), - publicKeySpecClass); - } catch (InvalidKeySpecException e) { - fail(e.getMessage()); - } catch (NoSuchAlgorithmException e) { - fail(e.getMessage()); - } - - PublicKey publicKey = null; - try { - publicKey = factory.generatePublic(publicKeySpec); - } catch (InvalidKeySpecException e) { - fail(e.getMessage()); - } - - KeyPair keyPair = new KeyPair(publicKey, privateKey); - - helper.test(keyPair); - } -} diff --git a/luni/src/test/java/tests/targets/security/KeyPairGeneratorTest.java b/luni/src/test/java/tests/targets/security/KeyPairGeneratorTest.java deleted file mode 100644 index e7a8b35..0000000 --- a/luni/src/test/java/tests/targets/security/KeyPairGeneratorTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2008 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 tests.targets.security; - -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; - -import junit.framework.TestCase; - -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; - -public abstract class KeyPairGeneratorTest extends TestCase { - - private final String algorithmName; - private final TestHelper<KeyPair> helper; - - private KeyPairGenerator generator; - - protected KeyPairGeneratorTest(String algorithmName, TestHelper<KeyPair> helper) { - this.algorithmName = algorithmName; - this.helper = helper; - } - - /* (non-Javadoc) - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - generator = getKeyPairGenerator(); - } - - private KeyPairGenerator getKeyPairGenerator() { - try { - return KeyPairGenerator.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - fail("cannot get KeyPairGenerator: " + e); - return null; - } - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "initialize", - args = {int.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "generateKeyPair", - args = {} - ), - @TestTargetNew( - level=TestLevel.COMPLETE, - method="method", - args={} - ) - }) - public void testKeyPairGenerator() { - generator.initialize(1024); - - KeyPair keyPair = generator.generateKeyPair(); - - assertNotNull("no keypair generated", keyPair); - assertNotNull("no public key generated", keyPair.getPublic()); - assertNotNull("no private key generated", keyPair.getPrivate()); - - helper.test(keyPair); - } -} diff --git a/luni/src/test/java/tests/targets/security/KeyStoreTest.java b/luni/src/test/java/tests/targets/security/KeyStoreTest.java index 6a86966..41d0f9a 100644 --- a/luni/src/test/java/tests/targets/security/KeyStoreTest.java +++ b/luni/src/test/java/tests/targets/security/KeyStoreTest.java @@ -18,9 +18,6 @@ package tests.targets.security; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargets; - -import junit.framework.TestCase; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -28,17 +25,18 @@ import java.io.InputStream; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.UnrecoverableEntryException; import java.security.KeyStore.Entry; import java.security.KeyStore.PasswordProtection; import java.security.KeyStore.PrivateKeyEntry; import java.security.KeyStore.ProtectionParameter; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.UnrecoverableEntryException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; +import junit.framework.TestCase; public class KeyStoreTest extends TestCase { diff --git a/luni/src/test/java/tests/targets/security/KeyStoreTestPKCS12.java b/luni/src/test/java/tests/targets/security/KeyStoreTestPKCS12.java index 33778b2..3455487 100644 --- a/luni/src/test/java/tests/targets/security/KeyStoreTestPKCS12.java +++ b/luni/src/test/java/tests/targets/security/KeyStoreTestPKCS12.java @@ -15,8 +15,6 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; - public class KeyStoreTestPKCS12 extends KeyStoreTest { public KeyStoreTestPKCS12() { diff --git a/luni/src/test/java/tests/targets/security/MessageDigestTest.java b/luni/src/test/java/tests/targets/security/MessageDigestTest.java deleted file mode 100644 index bbb6c1b..0000000 --- a/luni/src/test/java/tests/targets/security/MessageDigestTest.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright (C) 2009 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 tests.targets.security; - -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; - -import junit.framework.TestCase; - -import java.io.IOException; -import java.io.InputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -public abstract class MessageDigestTest extends TestCase { - - private String digestAlgorithmName; - - protected MessageDigestTest(String digestAlgorithmName) { - super(); - this.digestAlgorithmName = digestAlgorithmName; - } - - private MessageDigest digest; - private InputStream sourceData; - private byte[] checkDigest; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - this.source3 = getLongMessage(1000000); - this.digest = getMessageDigest(); - this.sourceData = getSourceData(); - this.checkDigest = getCheckDigest(); - } - - @Override - public void tearDown() throws Exception { - super.tearDown(); - - // This is critical. The MessageDigest tests consume a lot of memory due - // to the 1 MB buffers being allocated. We need to make sure all data is - // freed after each test. Otherwise the Android runtime simply dies at - // some point. - source1 = null; - source2 = null; - source3 = null; - - expected1 = null; - expected2 = null; - expected3 = null; - - digest = null; - sourceData = null; - checkDigest = null; - - System.gc(); - } - - MessageDigest getMessageDigest() - { - try { - return MessageDigest.getInstance(digestAlgorithmName); - } catch (NoSuchAlgorithmException e) { - fail("failed to get digest instance: " + e); - return null; - } - } - - InputStream getSourceData() - { - InputStream sourceStream = getClass().getResourceAsStream( - digestAlgorithmName + ".data"); - assertNotNull("digest source data not found: " + digestAlgorithmName, - sourceStream); - return sourceStream; - } - - byte[] getCheckDigest() - { - InputStream checkDigestStream = getClass().getResourceAsStream( - digestAlgorithmName + ".check"); - byte[] checkDigest = new byte[digest.getDigestLength()]; - int read = 0; - int index = 0; - try { - while ((read = checkDigestStream.read()) != -1) - { - checkDigest[index++] = (byte)read; - } - } catch (IOException e) { - fail("failed to read digest golden data: " + digestAlgorithmName); - } - return checkDigest; - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "update", - args = {byte[].class,int.class,int.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "digest", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "method", - args = {} - ) - }) - public void testMessageDigest1() - { - byte[] buf = new byte[128]; - int read = 0; - try { - while ((read = sourceData.read(buf)) != -1) - { - digest.update(buf, 0, read); - } - } catch (IOException e) { - fail("failed to read digest data"); - } - - byte[] computedDigest = digest.digest(); - - assertNotNull("computed digest is is null", computedDigest); - assertEquals("digest length mismatch", checkDigest.length, - computedDigest.length); - - for (int i = 0; i < checkDigest.length; i++) - { - assertEquals("byte " + i + " of computed and check digest differ", - checkDigest[i], computedDigest[i]); - } - - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "update", - args = {byte.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "digest", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "method", - args = {} - ) - }) - public void testMessageDigest2() - { - int val; - try { - while ((val = sourceData.read()) != -1) - { - digest.update((byte)val); - } - } catch (IOException e) { - fail("failed to read digest data"); - } - - byte[] computedDigest = digest.digest(); - - assertNotNull("computed digest is is null", computedDigest); - assertEquals("digest length mismatch", checkDigest.length, - computedDigest.length); - for (int i = 0; i < checkDigest.length; i++) - { - assertEquals("byte " + i + " of computed and check digest differ", - checkDigest[i], computedDigest[i]); - } - - } - - - /** - * Official FIPS180-2 testcases - */ - - protected String source1, source2, source3; - protected String expected1, expected2, expected3; - - String getLongMessage(int length) { - StringBuilder sourceBuilder = new StringBuilder(length); - for (int i = 0; i < length / 10; i++) { - sourceBuilder.append("aaaaaaaaaa"); - } - return sourceBuilder.toString(); - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "update", - args = {byte.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "digest", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "method", - args = {} - ) - }) - public void testfips180_2_singleblock() { - - digest.update(source1.getBytes(), 0, source1.length()); - - byte[] computedDigest = digest.digest(); - - assertNotNull("computed digest is null", computedDigest); - - StringBuilder sb = new StringBuilder(); - String res; - for (int i = 0; i < computedDigest.length; i++) - { - res = Integer.toHexString(computedDigest[i] & 0xFF); - sb.append((res.length() == 1 ? "0" : "") + res); - } - assertEquals("computed and check digest differ", expected1, - sb.toString()); - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "update", - args = {byte.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "digest", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "method", - args = {} - ) - }) - public void testfips180_2_multiblock() { - - digest.update(source2.getBytes(), 0, source2.length()); - - byte[] computedDigest = digest.digest(); - - assertNotNull("computed digest is null", computedDigest); - - StringBuilder sb = new StringBuilder(); - String res; - for (int i = 0; i < computedDigest.length; i++) - { - res = Integer.toHexString(computedDigest[i] & 0xFF); - sb.append((res.length() == 1 ? "0" : "") + res); - } - assertEquals("computed and check digest differ", expected2, - sb.toString()); - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "update", - args = {byte.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "digest", - args = {} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "method", - args = {} - ) - }) - public void testfips180_2_longMessage() { - - digest.update(source3.getBytes(), 0, source3.length()); - - byte[] computedDigest = digest.digest(); - - assertNotNull("computed digest is null", computedDigest); - - StringBuilder sb = new StringBuilder(); - String res; - for (int i = 0; i < computedDigest.length; i++) - { - res = Integer.toHexString(computedDigest[i] & 0xFF); - sb.append((res.length() == 1 ? "0" : "") + res); - } - assertEquals("computed and check digest differ", expected3, - sb.toString()); - } -} diff --git a/luni/src/test/java/tests/targets/security/MessageDigestTestMD2.java b/luni/src/test/java/tests/targets/security/MessageDigestTestMD2.java index 6b6e705..ab24067 100644 --- a/luni/src/test/java/tests/targets/security/MessageDigestTestMD2.java +++ b/luni/src/test/java/tests/targets/security/MessageDigestTestMD2.java @@ -17,15 +17,12 @@ package tests.targets.security; import dalvik.annotation.AndroidOnly; import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; - -import junit.framework.TestCase; - import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.Security; +import junit.framework.TestCase; public class MessageDigestTestMD2 extends TestCase { diff --git a/luni/src/test/java/tests/targets/security/MessageDigestTestMD5.java b/luni/src/test/java/tests/targets/security/MessageDigestTestMD5.java index 190d24c..a997b1e 100644 --- a/luni/src/test/java/tests/targets/security/MessageDigestTestMD5.java +++ b/luni/src/test/java/tests/targets/security/MessageDigestTestMD5.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.MessageDigestTest; public class MessageDigestTestMD5 extends MessageDigestTest { diff --git a/luni/src/test/java/tests/targets/security/MessageDigestTestSHA1.java b/luni/src/test/java/tests/targets/security/MessageDigestTestSHA1.java index c772b24..a73da37 100644 --- a/luni/src/test/java/tests/targets/security/MessageDigestTestSHA1.java +++ b/luni/src/test/java/tests/targets/security/MessageDigestTestSHA1.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.MessageDigestTest; public class MessageDigestTestSHA1 extends MessageDigestTest { diff --git a/luni/src/test/java/tests/targets/security/MessageDigestTestSHA224.java b/luni/src/test/java/tests/targets/security/MessageDigestTestSHA224.java index c7e0d10..b66ed35 100644 --- a/luni/src/test/java/tests/targets/security/MessageDigestTestSHA224.java +++ b/luni/src/test/java/tests/targets/security/MessageDigestTestSHA224.java @@ -15,6 +15,8 @@ */ package tests.targets.security; +import tests.security.MessageDigestTest; + public class MessageDigestTestSHA224 extends MessageDigestTest { public MessageDigestTestSHA224() { diff --git a/luni/src/test/java/tests/targets/security/MessageDigestTestSHA256.java b/luni/src/test/java/tests/targets/security/MessageDigestTestSHA256.java index 5340775..4813396 100644 --- a/luni/src/test/java/tests/targets/security/MessageDigestTestSHA256.java +++ b/luni/src/test/java/tests/targets/security/MessageDigestTestSHA256.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.MessageDigestTest; public class MessageDigestTestSHA256 extends MessageDigestTest { diff --git a/luni/src/test/java/tests/targets/security/MessageDigestTestSHA384.java b/luni/src/test/java/tests/targets/security/MessageDigestTestSHA384.java index e7e87e3..29f9477 100644 --- a/luni/src/test/java/tests/targets/security/MessageDigestTestSHA384.java +++ b/luni/src/test/java/tests/targets/security/MessageDigestTestSHA384.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.MessageDigestTest; public class MessageDigestTestSHA384 extends MessageDigestTest { diff --git a/luni/src/test/java/tests/targets/security/MessageDigestTestSHA512.java b/luni/src/test/java/tests/targets/security/MessageDigestTestSHA512.java index 0cee6ff..b0f2c6b 100644 --- a/luni/src/test/java/tests/targets/security/MessageDigestTestSHA512.java +++ b/luni/src/test/java/tests/targets/security/MessageDigestTestSHA512.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.MessageDigestTest; public class MessageDigestTestSHA512 extends MessageDigestTest { diff --git a/luni/src/test/java/tests/targets/security/SecureRandomTestSHA1PRNG.java b/luni/src/test/java/tests/targets/security/SecureRandomTestSHA1PRNG.java index db0c3db..daf04fc 100644 --- a/luni/src/test/java/tests/targets/security/SecureRandomTestSHA1PRNG.java +++ b/luni/src/test/java/tests/targets/security/SecureRandomTestSHA1PRNG.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.SecureRandomTest; public class SecureRandomTestSHA1PRNG extends SecureRandomTest { diff --git a/luni/src/test/java/tests/targets/security/SignatureTest.java b/luni/src/test/java/tests/targets/security/SignatureTest.java deleted file mode 100644 index 55748fb..0000000 --- a/luni/src/test/java/tests/targets/security/SignatureTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright (C) 2009 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 tests.targets.security; - -import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; -import dalvik.annotation.TestTargets; - -import junit.framework.TestCase; - -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Signature; -import java.security.SignatureException; -public abstract class SignatureTest extends TestCase { - - private final String algorithmName; - private final String keyAlgorithmName; - private static final String signData = "some data to sign an"; //d verify"; - KeyPairGenerator generator; - KeyPair keyPair; - - public SignatureTest(String algorithmName, String keyAlgorithmName) { - this.algorithmName = algorithmName; - this.keyAlgorithmName = keyAlgorithmName; - } - - protected void setUp() throws Exception { - super.setUp(); - generator = getGenerator(); - keyPair = getKeyPair(); - } - - private KeyPair getKeyPair() { - return generator.generateKeyPair(); - } - - private KeyPairGenerator getGenerator() { - try { - return KeyPairGenerator.getInstance(keyAlgorithmName); - } catch (NoSuchAlgorithmException e) { - fail(e.getMessage()); - } - return null; - } - - @TestTargets({ - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "getInstance", - args = {String.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "initSign", - args = {PrivateKey.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "update", - args = {byte[].class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "sign", - args = {} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "initVerify", - args = {PublicKey.class} - ), - @TestTargetNew( - level = TestLevel.ADDITIONAL, - method = "verify", - args = {byte[].class} - ), - @TestTargetNew( - level = TestLevel.COMPLETE, - method = "method", - args = {} - ) - }) - public void testSignature() { - Signature signature = null; - try { - signature = Signature.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - fail(e.getMessage()); - } - - try { - signature.initSign(keyPair.getPrivate()); - } catch (InvalidKeyException e) { - fail(e.getMessage()); - } - - try { - signature.update(signData.getBytes()); - } catch (SignatureException e) { - fail(e.getMessage()); - } - - byte[] sign = null; - try { - sign = signature.sign(); - } catch (SignatureException e) { - fail(e.getMessage()); - } - - try { - signature.initVerify(keyPair.getPublic()); - } catch (InvalidKeyException e) { - fail(e.getMessage()); - } - - try { - signature.update(signData.getBytes()); - } catch (SignatureException e) { - fail(e.getMessage()); - } - - try { - assertTrue(signature.verify(sign)); - } catch (SignatureException e) { - fail(e.getMessage()); - } - } -} diff --git a/luni/src/test/java/tests/targets/security/SignatureTestMD2withRSA.java b/luni/src/test/java/tests/targets/security/SignatureTestMD2withRSA.java index ab69528..2041d41 100644 --- a/luni/src/test/java/tests/targets/security/SignatureTestMD2withRSA.java +++ b/luni/src/test/java/tests/targets/security/SignatureTestMD2withRSA.java @@ -17,11 +17,7 @@ package tests.targets.security; import dalvik.annotation.AndroidOnly; import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; - -import junit.framework.TestCase; - import java.security.InvalidKeyException; import java.security.InvalidParameterException; import java.security.NoSuchAlgorithmException; @@ -31,6 +27,7 @@ import java.security.PublicKey; import java.security.Security; import java.security.Signature; import java.security.SignatureException; +import junit.framework.TestCase; public class SignatureTestMD2withRSA extends TestCase { diff --git a/luni/src/test/java/tests/targets/security/SignatureTestMD5withRSA.java b/luni/src/test/java/tests/targets/security/SignatureTestMD5withRSA.java index 41710e2..7996b32 100644 --- a/luni/src/test/java/tests/targets/security/SignatureTestMD5withRSA.java +++ b/luni/src/test/java/tests/targets/security/SignatureTestMD5withRSA.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.SignatureTest; public class SignatureTestMD5withRSA extends SignatureTest { diff --git a/luni/src/test/java/tests/targets/security/SignatureTestNONEwithDSA.java b/luni/src/test/java/tests/targets/security/SignatureTestNONEwithDSA.java index 1d8de6b..be19c3e 100644 --- a/luni/src/test/java/tests/targets/security/SignatureTestNONEwithDSA.java +++ b/luni/src/test/java/tests/targets/security/SignatureTestNONEwithDSA.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.SignatureTest; public class SignatureTestNONEwithDSA extends SignatureTest { diff --git a/luni/src/test/java/tests/targets/security/SignatureTestSHA1withDSA.java b/luni/src/test/java/tests/targets/security/SignatureTestSHA1withDSA.java index f2e62bd..117f8df 100644 --- a/luni/src/test/java/tests/targets/security/SignatureTestSHA1withDSA.java +++ b/luni/src/test/java/tests/targets/security/SignatureTestSHA1withDSA.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.SignatureTest; public class SignatureTestSHA1withDSA extends SignatureTest { diff --git a/luni/src/test/java/tests/targets/security/SignatureTestSHA1withRSA.java b/luni/src/test/java/tests/targets/security/SignatureTestSHA1withRSA.java index def4e54..7729fce 100644 --- a/luni/src/test/java/tests/targets/security/SignatureTestSHA1withRSA.java +++ b/luni/src/test/java/tests/targets/security/SignatureTestSHA1withRSA.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.SignatureTest; public class SignatureTestSHA1withRSA extends SignatureTest { diff --git a/luni/src/test/java/tests/targets/security/SignatureTestSHA224withRSA.java b/luni/src/test/java/tests/targets/security/SignatureTestSHA224withRSA.java index a6d357d..ad89a7b 100644 --- a/luni/src/test/java/tests/targets/security/SignatureTestSHA224withRSA.java +++ b/luni/src/test/java/tests/targets/security/SignatureTestSHA224withRSA.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.SignatureTest; public class SignatureTestSHA224withRSA extends SignatureTest { diff --git a/luni/src/test/java/tests/targets/security/SignatureTestSHA256withRSA.java b/luni/src/test/java/tests/targets/security/SignatureTestSHA256withRSA.java index 59632e5..c7ed4aa 100644 --- a/luni/src/test/java/tests/targets/security/SignatureTestSHA256withRSA.java +++ b/luni/src/test/java/tests/targets/security/SignatureTestSHA256withRSA.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.SignatureTest; public class SignatureTestSHA256withRSA extends SignatureTest { diff --git a/luni/src/test/java/tests/targets/security/SignatureTestSHA384withRSA.java b/luni/src/test/java/tests/targets/security/SignatureTestSHA384withRSA.java index b55e1cf..32ea0ad 100644 --- a/luni/src/test/java/tests/targets/security/SignatureTestSHA384withRSA.java +++ b/luni/src/test/java/tests/targets/security/SignatureTestSHA384withRSA.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.SignatureTest; public class SignatureTestSHA384withRSA extends SignatureTest { diff --git a/luni/src/test/java/tests/targets/security/SignatureTestSHA512withRSA.java b/luni/src/test/java/tests/targets/security/SignatureTestSHA512withRSA.java index 845e1da..530d751 100644 --- a/luni/src/test/java/tests/targets/security/SignatureTestSHA512withRSA.java +++ b/luni/src/test/java/tests/targets/security/SignatureTestSHA512withRSA.java @@ -15,7 +15,7 @@ */ package tests.targets.security; -import dalvik.annotation.TestTargetClass; +import tests.security.SignatureTest; public class SignatureTestSHA512withRSA extends SignatureTest { diff --git a/luni/src/test/java/tests/targets/security/cert/CertPathBuilderTestPKIX.java b/luni/src/test/java/tests/targets/security/cert/CertPathBuilderTestPKIX.java index f64239c..fc67261 100644 --- a/luni/src/test/java/tests/targets/security/cert/CertPathBuilderTestPKIX.java +++ b/luni/src/test/java/tests/targets/security/cert/CertPathBuilderTestPKIX.java @@ -15,8 +15,6 @@ */ package tests.targets.security.cert; -import dalvik.annotation.TestTargetClass; - import java.io.ByteArrayInputStream; import java.security.KeyStore; import java.security.cert.CertPath; @@ -31,8 +29,8 @@ import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; - import javax.security.auth.x500.X500Principal; +import tests.security.CertPathBuilderTest; public class CertPathBuilderTestPKIX extends CertPathBuilderTest { @@ -41,7 +39,7 @@ public class CertPathBuilderTestPKIX extends CertPathBuilderTest { } @Override - CertPathParameters getCertPathParameters() throws Exception { + public CertPathParameters getCertPathParameters() throws Exception { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); @@ -75,7 +73,7 @@ public class CertPathBuilderTestPKIX extends CertPathBuilderTest { } @Override - void validateCertPath(CertPath path) { + public void validateCertPath(CertPath path) { List<? extends Certificate> certificates = path.getCertificates(); Certificate certificate = certificates.get(0); diff --git a/luni/src/test/java/tests/targets/security/cert/CertPathValidatorTestPKIX.java b/luni/src/test/java/tests/targets/security/cert/CertPathValidatorTestPKIX.java index d7152f4..af4037f 100644 --- a/luni/src/test/java/tests/targets/security/cert/CertPathValidatorTestPKIX.java +++ b/luni/src/test/java/tests/targets/security/cert/CertPathValidatorTestPKIX.java @@ -15,8 +15,6 @@ */ package tests.targets.security.cert; -import dalvik.annotation.TestTargetClass; - import java.io.ByteArrayInputStream; import java.security.KeyStore; import java.security.cert.CertPath; @@ -36,6 +34,7 @@ import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; +import tests.security.CertPathValidatorTest; public class CertPathValidatorTestPKIX extends CertPathValidatorTest { @@ -47,7 +46,7 @@ public class CertPathValidatorTestPKIX extends CertPathValidatorTest { } @Override - CertPath getCertPath() { + public CertPath getCertPath() { return certPath; } @@ -92,12 +91,12 @@ public class CertPathValidatorTestPKIX extends CertPathValidatorTest { } @Override - CertPathParameters getParams() { + public CertPathParameters getParams() { return params; } @Override - void validateResult(CertPathValidatorResult validatorResult) { + public void validateResult(CertPathValidatorResult validatorResult) { assertNotNull("validator result is null", validatorResult); assertTrue("validator result is not PKIX", validatorResult instanceof PKIXCertPathValidatorResult); diff --git a/luni/src/test/java/tests/targets/security/cert/CertificateFactoryTestX509.java b/luni/src/test/java/tests/targets/security/cert/CertificateFactoryTestX509.java index 125027a..dcf4081 100644 --- a/luni/src/test/java/tests/targets/security/cert/CertificateFactoryTestX509.java +++ b/luni/src/test/java/tests/targets/security/cert/CertificateFactoryTestX509.java @@ -15,7 +15,7 @@ */ package tests.targets.security.cert; -import dalvik.annotation.TestTargetClass; +import tests.security.CertificateFactoryTest; public class CertificateFactoryTestX509 extends CertificateFactoryTest { diff --git a/luni/src/test/java/tests/targets/security/cert/CertificateTest.java b/luni/src/test/java/tests/targets/security/cert/CertificateTest.java index 114dcfe..78619a5 100644 --- a/luni/src/test/java/tests/targets/security/cert/CertificateTest.java +++ b/luni/src/test/java/tests/targets/security/cert/CertificateTest.java @@ -18,9 +18,6 @@ package tests.targets.security.cert; import dalvik.annotation.AndroidOnly; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetNew; - -import junit.framework.TestCase; - import java.io.ByteArrayInputStream; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; @@ -37,6 +34,7 @@ import java.security.cert.PKIXParameters; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; +import junit.framework.TestCase; public class CertificateTest extends TestCase { diff --git a/luni/src/test/java/tests/xml/SimpleBuilderTest.java b/luni/src/test/java/tests/xml/SimpleBuilderTest.java index 585050e..a6c6a1d 100644 --- a/luni/src/test/java/tests/xml/SimpleBuilderTest.java +++ b/luni/src/test/java/tests/xml/SimpleBuilderTest.java @@ -16,26 +16,20 @@ package tests.xml; -import dalvik.annotation.BrokenTest; -import dalvik.annotation.TestTargets; import dalvik.annotation.TestLevel; -import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargetClass; - +import dalvik.annotation.TestTargetNew; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; import junit.framework.TestCase; - import org.w3c.dom.Comment; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - @TestTargetClass(DocumentBuilder.class) public class SimpleBuilderTest extends TestCase { @@ -122,41 +116,17 @@ public class SimpleBuilderTest extends TestCase { assertEquals("The quick brown fox jumps over the lazy dog.", proinst); assertEquals(" Fragile! Handle me with care! ", comment); } + @TestTargetNew( level = TestLevel.ADDITIONAL, method = "!todo parse", args = {java.io.InputStream.class} ) - @BrokenTest("Doesn't verify anything.") public void testGoodFile2() throws Exception { Document document = builder.parse(getClass().getResourceAsStream( "/staffNS.xml")); Element root = document.getDocumentElement(); assertNotNull(root); - - // dump("", root); - } - - private void dump(String prefix, Element element) { - System.out.print(prefix + "<" + element.getTagName()); - - NamedNodeMap attrs = element.getAttributes(); - for (int i = 0; i < attrs.getLength(); i++) { - Node item = attrs.item(i); - System.out.print(" " + item.getNodeName() + "=" + item.getNodeValue()); - } - - System.out.println(">"); - - NodeList children = element.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - Node item = children.item(i); - if (item instanceof Element) { - dump(prefix + " ", (Element)item); - } - } - - System.out.println(prefix + "</" + element.getTagName() + ">"); } } |