summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--expectations/knownfailures.txt35
-rw-r--r--luni/src/main/java/java/net/ServerSocket.java29
-rw-r--r--luni/src/main/java/java/net/URLStreamHandler.java32
-rw-r--r--luni/src/main/java/javax/net/ServerSocketFactory.java31
-rw-r--r--luni/src/test/java/libcore/java/net/OldAuthenticatorRequestorTypeTest.java (renamed from luni/src/test/java/tests/api/java/net/AuthenticatorRequestorTypeTest.java)31
-rw-r--r--luni/src/test/java/libcore/java/net/OldAuthenticatorTest.java68
-rw-r--r--luni/src/test/java/libcore/java/net/OldCookieHandlerTest.java91
-rw-r--r--luni/src/test/java/libcore/java/net/OldDatagramPacketTest.java123
-rw-r--r--luni/src/test/java/libcore/java/net/OldDatagramSocketImplFactoryTest.java (renamed from luni/src/test/java/tests/api/java/net/DatagramSocketImplFactoryTest.java)64
-rw-r--r--luni/src/test/java/libcore/java/net/OldFileNameMapTest.java (renamed from luni/src/test/java/tests/api/java/net/FileNameMapTest.java)11
-rw-r--r--luni/src/test/java/libcore/java/net/OldHttpRetryExceptionTest.java (renamed from luni/src/test/java/tests/api/java/net/HttpRetryExceptionTest.java)60
-rw-r--r--luni/src/test/java/libcore/java/net/OldJarURLConnectionTest.java (renamed from luni/src/test/java/tests/api/java/net/JarURLConnectionTest.java)234
-rw-r--r--luni/src/test/java/libcore/java/net/OldNetPermissionTest.java (renamed from luni/src/test/java/tests/api/java/net/TestServerSocketInit.java)15
-rw-r--r--luni/src/test/java/libcore/java/net/OldPasswordAuthenticationTest.java39
-rw-r--r--luni/src/test/java/libcore/java/net/OldProxyTest.java70
-rw-r--r--luni/src/test/java/libcore/java/net/OldServerSocketTest.java394
-rw-r--r--luni/src/test/java/libcore/java/net/OldSocketImplFactoryTest.java (renamed from luni/src/test/java/tests/api/java/net/SocketImplFactoryTest.java)42
-rw-r--r--luni/src/test/java/libcore/java/net/OldSocketPermissionTest.java45
-rw-r--r--luni/src/test/java/libcore/java/net/OldSocketTest.java (renamed from luni/src/test/java/tests/api/java/net/SocketTest.java)617
-rw-r--r--luni/src/test/java/libcore/java/net/OldSocketTestCase.java (renamed from luni/src/test/java/tests/api/java/net/SocketTestCase.java)18
-rw-r--r--luni/src/test/java/libcore/java/net/OldURITest.java150
-rw-r--r--luni/src/test/java/libcore/java/net/OldURLDecoderTest.java (renamed from luni/src/test/java/tests/api/java/net/URLDecoderTest.java)69
-rw-r--r--luni/src/test/java/libcore/java/net/OldURLEncoderTest.java (renamed from luni/src/test/java/tests/api/java/net/URLEncoderTest.java)60
-rw-r--r--luni/src/test/java/libcore/java/net/OldURLStreamHandlerTest.java (renamed from luni/src/test/java/tests/api/java/net/URLStreamHandlerTest.java)168
-rw-r--r--luni/src/test/java/libcore/java/net/OldURLTest.java31
-rw-r--r--luni/src/test/java/libcore/java/net/URLConnectionTest.java19
-rw-r--r--luni/src/test/java/libcore/javax/net/ServerSocketFactoryTest.java131
-rw-r--r--luni/src/test/java/tests/api/java/net/AllTests.java75
-rw-r--r--luni/src/test/java/tests/api/java/net/AuthenticatorTest.java423
-rw-r--r--luni/src/test/java/tests/api/java/net/BindExceptionTest.java85
-rw-r--r--luni/src/test/java/tests/api/java/net/CacheRequestTest.java87
-rw-r--r--luni/src/test/java/tests/api/java/net/CacheResponseTest.java83
-rw-r--r--luni/src/test/java/tests/api/java/net/ConnectExceptionTest.java56
-rw-r--r--luni/src/test/java/tests/api/java/net/CookieHandlerTest.java234
-rw-r--r--luni/src/test/java/tests/api/java/net/DatagramPacketTest.java440
-rw-r--r--luni/src/test/java/tests/api/java/net/DatagramSocketImplTest.java349
-rw-r--r--luni/src/test/java/tests/api/java/net/IDNTest.java160
-rw-r--r--luni/src/test/java/tests/api/java/net/MalformedURLExceptionTest.java91
-rw-r--r--luni/src/test/java/tests/api/java/net/MulticastSocketTest.java1165
-rw-r--r--luni/src/test/java/tests/api/java/net/NetPermissionTest.java81
-rw-r--r--luni/src/test/java/tests/api/java/net/NetworkInterfaceTest.java561
-rw-r--r--luni/src/test/java/tests/api/java/net/NoRouteToHostExceptionTest.java88
-rw-r--r--luni/src/test/java/tests/api/java/net/PasswordAuthenticationTest.java94
-rw-r--r--luni/src/test/java/tests/api/java/net/PortUnreachableExceptionTest.java56
-rw-r--r--luni/src/test/java/tests/api/java/net/ProtocolExceptionTest.java85
-rw-r--r--luni/src/test/java/tests/api/java/net/ProxySelectorTest.java727
-rw-r--r--luni/src/test/java/tests/api/java/net/ProxyTest.java343
-rw-r--r--luni/src/test/java/tests/api/java/net/ProxyTypeTest.java84
-rw-r--r--luni/src/test/java/tests/api/java/net/SecureCacheResponseTest.java177
-rw-r--r--luni/src/test/java/tests/api/java/net/ServerSocketTest.java1495
-rw-r--r--luni/src/test/java/tests/api/java/net/SocketExceptionTest.java83
-rw-r--r--luni/src/test/java/tests/api/java/net/SocketImplTest.java265
-rw-r--r--luni/src/test/java/tests/api/java/net/SocketPermissionTest.java340
-rw-r--r--luni/src/test/java/tests/api/java/net/SocketTimeoutExceptionTest.java40
-rw-r--r--luni/src/test/java/tests/api/java/net/URISyntaxExceptionTest.java166
-rw-r--r--luni/src/test/java/tests/api/java/net/URITest.java2174
-rw-r--r--luni/src/test/java/tests/api/java/net/UnknownHostExceptionTest.java87
-rw-r--r--luni/src/test/java/tests/api/java/net/UnknownServiceExceptionTest.java88
-rw-r--r--luni/src/test/java/tests/luni/AllTestsNet.java3
59 files changed, 1318 insertions, 11644 deletions
diff --git a/expectations/knownfailures.txt b/expectations/knownfailures.txt
index 8d31ce3..32489af 100644
--- a/expectations/knownfailures.txt
+++ b/expectations/knownfailures.txt
@@ -3,6 +3,25 @@
*/
[
{
+ description: "",
+ name: "libcore.java.lang.SystemTest#testBackFromTheDead",
+ bug: 2645458
+},
+{
+ description: "Concurrent close tests fail on the device",
+ names: [
+ "libcore.java.net.ConcurrentCloseTest#test_connect",
+ "libcore.java.net.ConcurrentCloseTest#test_connect_nonBlocking"
+ ],
+ modes: [ "device" ],
+ bug: 3044772
+},
+{
+ description: "HTTPS connections should not be pooled.",
+ name: "libcore.java.net.URLConnectionTest#testConnectViaHttpsReusingConnectionsDifferentFactories",
+ bug: 3042192
+},
+{
description: "Cookie tests failing on the host",
bug: 3041920,
names: [
@@ -871,23 +890,23 @@
},
{
description: "NO SERVER CERTIFICATE FOUND - selectSuite should not pick a suite that needs a certificate if it is missing",
- result: EXEC_FAILED,
- name: "javax.net.ssl.SSLEngineTest#test_SSLEngine_beginHandshake_noKeyStore"
+ bug: 3045163,
+ name: "libcore.javax.net.ssl.SSLEngineTest#test_SSLEngine_beginHandshake_noKeyStore"
},
{
description: "AlertException instead of SSLException",
- result: EXEC_FAILED,
- name: "javax.net.ssl.SSLEngineTest#test_SSLEngine_setEnableSessionCreation_client"
+ bug: 3045163,
+ name: "libcore.javax.net.ssl.SSLEngineTest#test_SSLEngine_setEnableSessionCreation_client"
},
{
description: "SSLException instead of failure to handshake",
- result: EXEC_FAILED,
- name: "javax.net.ssl.SSLEngineTest#test_SSLEngine_setEnableSessionCreation_server"
+ bug: 3045163,
+ name: "libcore.javax.net.ssl.SSLEngineTest#test_SSLEngine_setEnableSessionCreation_server"
},
{
description: "SSLHandshakeException instead of failure to handshake",
- result: EXEC_FAILED,
- name: "javax.net.ssl.SSLEngineTest#test_SSLEngine_setUseClientMode"
+ bug: 3045163,
+ name: "libcore.javax.net.ssl.SSLEngineTest#test_SSLEngine_setUseClientMode"
},
{
description: "method test fails once in a while. Cannot be sure that exception is thrown in every test execution.",
diff --git a/luni/src/main/java/java/net/ServerSocket.java b/luni/src/main/java/java/net/ServerSocket.java
index 6ddf59e..e7e7f9f 100644
--- a/luni/src/main/java/java/net/ServerSocket.java
+++ b/luni/src/main/java/java/net/ServerSocket.java
@@ -336,10 +336,10 @@ public class ServerSocket {
}
/**
- * Binds this server socket to the given local socket address. The default
- * number of pending connections may be backlogged. If the {@code localAddr}
- * is set to {@code null} the socket will be bound to an available local
- * address on any free port of the system.
+ * Binds this server socket to the given local socket address with a maximum
+ * backlog of 50 unaccepted connections. If the {@code localAddr} is set to
+ * {@code null} the socket will be bound to an available local address on
+ * any free port of the system.
*
* @param localAddr
* the local address and port to bind on.
@@ -356,20 +356,15 @@ public class ServerSocket {
/**
* Binds this server socket to the given local socket address. If the
* {@code localAddr} is set to {@code null} the socket will be bound to an
- * available local address on any free port of the system. The value for
- * {@code backlog} must e greater than {@code 0} otherwise the default value
- * will be used.
+ * available local address on any free port of the system.
*
- * @param localAddr
- * the local machine address and port to bind on.
- * @param backlog
- * the number of pending connection requests, before requests
- * will be rejected.
- * @throws IllegalArgumentException
- * if the {@code SocketAddress} is not supported.
- * @throws IOException
- * if the socket is already bound or a problem occurs during
- * binding.
+ * @param localAddr the local machine address and port to bind on.
+ * @param backlog the maximum number of unaccepted connections. Passing 0 or
+ * a negative value yields the default backlog of 50.
+ * @throws IllegalArgumentException if the {@code SocketAddress} is not
+ * supported.
+ * @throws IOException if the socket is already bound or a problem occurs
+ * during binding.
*/
public void bind(SocketAddress localAddr, int backlog) throws IOException {
checkClosedAndCreate(true);
diff --git a/luni/src/main/java/java/net/URLStreamHandler.java b/luni/src/main/java/java/net/URLStreamHandler.java
index d95b2a5..dae193b 100644
--- a/luni/src/main/java/java/net/URLStreamHandler.java
+++ b/luni/src/main/java/java/net/URLStreamHandler.java
@@ -387,17 +387,33 @@ public abstract class URLStreamHandler {
/**
* Compares two URL objects whether they refer to the same host.
*
- * @param url1
- * the first URL to be compared.
- * @param url2
- * the second URL to be compared.
+ * @param a the first URL to be compared.
+ * @param b the second URL to be compared.
* @return {@code true} if both URLs refer to the same host, {@code false}
* otherwise.
*/
- protected boolean hostsEqual(URL url1, URL url2) {
- String host1 = getHost(url1), host2 = getHost(url2);
- return (host1 != null && host1.equalsIgnoreCase(host2))
- || Objects.equal(getHostAddress(url1), getHostAddress(url2));
+ protected boolean hostsEqual(URL a, URL b) {
+ /*
+ * URLs with the same case-insensitive host name have equal hosts
+ */
+ String aHost = getHost(a);
+ String bHost = getHost(b);
+ if (aHost != null && aHost.equalsIgnoreCase(bHost)) {
+ return true;
+ }
+
+ /*
+ * Call out to DNS to resolve the host addresses. If this succeeds for
+ * both addresses and both addresses yield the same InetAddress, report
+ * equality.
+ *
+ * Although it's consistent with historical behavior of the RI, this
+ * approach is fundamentally broken. In particular, acting upon this
+ * result is bogus because a single server may serve content for many
+ * unrelated host names.
+ */
+ InetAddress aResolved = getHostAddress(a);
+ return aResolved != null && aResolved.equals(getHostAddress(b));
}
/**
diff --git a/luni/src/main/java/javax/net/ServerSocketFactory.java b/luni/src/main/java/javax/net/ServerSocketFactory.java
index f2d2c0d..15ab773 100644
--- a/luni/src/main/java/javax/net/ServerSocketFactory.java
+++ b/luni/src/main/java/javax/net/ServerSocketFactory.java
@@ -64,10 +64,10 @@ public abstract class ServerSocketFactory {
}
/**
- * Creates a new server socket which is bound to the given port.
+ * Creates a new server socket which is bound to the given port with a
+ * maximum backlog of 50 unaccepted connections.
*
- * @param port
- * the port on which the created socket has to listen.
+ * @param port the port on which the created socket has to listen.
* @return the created bound server socket.
* @throws IOException
* if an error occurs while creating a new server socket.
@@ -78,13 +78,11 @@ public abstract class ServerSocketFactory {
* Creates a new server socket which is bound to the given port and
* configures its maximum of queued connections.
*
- * @param port
- * the port on which the created socket has to listen.
- * @param backlog
- * the maximum of queued connections.
+ * @param port the port on which the created socket has to listen.
+ * @param backlog the maximum number of unaccepted connections. Passing 0 or
+ * a negative value yields the default backlog of 50.
* @return the created bound server socket.
- * @throws IOException
- * if an error occurs while creating a new server socket.
+ * @throws IOException if an error occurs while creating a new server socket.
*/
public abstract ServerSocket createServerSocket(int port, int backlog) throws IOException;
@@ -92,16 +90,13 @@ public abstract class ServerSocketFactory {
* Creates a new server socket which is bound to the given address on the
* specified port and configures its maximum of queued connections.
*
- * @param port
- * the port on which the created socket has to listen.
- * @param backlog
- * the maximum of queued connections.
- * @param iAddress
- * the address of the network interface which is used by the
- * created socket.
+ * @param port the port on which the created socket has to listen.
+ * @param backlog the maximum number of unaccepted connections. Passing 0 or
+ * a negative value yields the default backlog of 50.
+ * @param iAddress the address of the network interface which is used by the
+ * created socket.
* @return the created bound server socket.
- * @throws IOException
- * if an error occurs while creating a new server socket.
+ * @throws IOException if an error occurs while creating a new server socket.
*/
public abstract ServerSocket createServerSocket(int port, int backlog, InetAddress iAddress)
throws IOException;
diff --git a/luni/src/test/java/tests/api/java/net/AuthenticatorRequestorTypeTest.java b/luni/src/test/java/libcore/java/net/OldAuthenticatorRequestorTypeTest.java
index 725043a..2ed6d72 100644
--- a/luni/src/test/java/tests/api/java/net/AuthenticatorRequestorTypeTest.java
+++ b/luni/src/test/java/libcore/java/net/OldAuthenticatorRequestorTypeTest.java
@@ -14,26 +14,13 @@
* limitations under the License.
*/
-package tests.api.java.net;
-
-import junit.framework.TestCase;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
+package libcore.java.net;
import java.net.Authenticator;
+import junit.framework.TestCase;
-@TestTargetClass(Authenticator.RequestorType.class)
-public class AuthenticatorRequestorTypeTest extends TestCase {
+public class OldAuthenticatorRequestorTypeTest extends TestCase {
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class}
- )
public void test_valueOfLjava_lang_String() {
assertEquals(Authenticator.RequestorType.PROXY,
Authenticator.RequestorType.valueOf("PROXY"));
@@ -42,25 +29,17 @@ public class AuthenticatorRequestorTypeTest extends TestCase {
try {
Authenticator.RequestorType.valueOf("TEST");
fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
+ } catch(IllegalArgumentException expected) {
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
public void test_values () {
Authenticator.RequestorType[] expectedTypes = {
Authenticator.RequestorType.PROXY,
Authenticator.RequestorType.SERVER
};
- Authenticator.RequestorType[] types =
- Authenticator.RequestorType.values();
+ Authenticator.RequestorType[] types = Authenticator.RequestorType.values();
assertEquals(expectedTypes.length, types.length);
for(int i = 0; i < expectedTypes.length; i++) {
diff --git a/luni/src/test/java/libcore/java/net/OldAuthenticatorTest.java b/luni/src/test/java/libcore/java/net/OldAuthenticatorTest.java
new file mode 100644
index 0000000..53f7017
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/OldAuthenticatorTest.java
@@ -0,0 +1,68 @@
+/* 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 libcore.java.net;
+
+import java.net.Authenticator;
+import java.net.InetAddress;
+import java.net.PasswordAuthentication;
+import java.net.URL;
+import java.net.UnknownHostException;
+import junit.framework.TestCase;
+
+public class OldAuthenticatorTest extends TestCase {
+
+ public void test_setDefault() throws UnknownHostException {
+ InetAddress addr = InetAddress.getLocalHost();
+ PasswordAuthentication pa = Authenticator.requestPasswordAuthentication(
+ addr, 8080, "http", "promt", "HTTP");
+ assertNull(pa);
+
+ MockAuthenticator mock = new MockAuthenticator();
+ Authenticator.setDefault(mock);
+
+ addr = InetAddress.getLocalHost();
+ pa = Authenticator.requestPasswordAuthentication(addr, 80, "http", "promt", "HTTP");
+ assertNull(pa);
+
+ Authenticator.setDefault(null);
+ }
+
+ public void test_Constructor() {
+ MockAuthenticator ma = new MockAuthenticator();
+ assertNull(ma.getRequestingURL());
+ assertNull(ma.getRequestorType());
+ }
+
+ public void test_getPasswordAuthentication() {
+ MockAuthenticator ma = new MockAuthenticator();
+ assertNull(ma.getPasswordAuthentication());
+ }
+
+ class MockAuthenticator extends Authenticator {
+ public URL getRequestingURL() {
+ return super.getRequestingURL();
+ }
+
+ public Authenticator.RequestorType getRequestorType() {
+ return super.getRequestorType();
+ }
+
+ public PasswordAuthentication getPasswordAuthentication() {
+ return super.getPasswordAuthentication();
+ }
+ }
+}
diff --git a/luni/src/test/java/libcore/java/net/OldCookieHandlerTest.java b/luni/src/test/java/libcore/java/net/OldCookieHandlerTest.java
new file mode 100644
index 0000000..249c326
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/OldCookieHandlerTest.java
@@ -0,0 +1,91 @@
+/* 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 libcore.java.net;
+
+import java.io.IOException;
+import java.net.CookieHandler;
+import java.net.URI;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Map;
+import junit.framework.TestCase;
+import tests.support.Support_Configuration;
+
+public class OldCookieHandlerTest extends TestCase {
+
+ URI getURI, putURI;
+ String link = "http://" + Support_Configuration.SpecialInetTestAddress + "/";
+ boolean isGetCalled = false;
+ boolean isPutCalled = false;
+ boolean completedSuccessfully = false;
+
+ public void test_CookieHandler() {
+ assertNull(CookieHandler.getDefault());
+ }
+
+ public void test_get_put() {
+ MockCookieHandler mch = new MockCookieHandler();
+ CookieHandler defaultHandler = CookieHandler.getDefault();
+ CookieHandler.setDefault(mch);
+
+ class TestThread extends Thread {
+ public void run() {
+ try {
+ URL url = new URL(link);
+ URLConnection conn = url.openConnection();
+ conn.getContent();
+ url = new URL(link);
+ conn = url.openConnection();
+ conn.getContent();
+ completedSuccessfully = true;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ try {
+ TestThread thread = new TestThread();
+
+ thread.start();
+ try {
+ thread.join();
+ } catch (InterruptedException e) {
+ fail("InterruptedException was thrown.");
+ }
+
+ assertTrue(isGetCalled);
+ assertTrue(isPutCalled);
+ assertTrue(completedSuccessfully);
+ } finally {
+ CookieHandler.setDefault(defaultHandler);
+ }
+ }
+
+ class MockCookieHandler extends CookieHandler {
+
+ public Map get(URI uri, Map requestHeaders) throws IOException {
+ getURI = uri;
+ isGetCalled = true;
+ return requestHeaders;
+ }
+
+ public void put(URI uri, Map responseHeaders) throws IOException {
+ putURI = uri;
+ isPutCalled = true;
+ }
+ }
+}
diff --git a/luni/src/test/java/libcore/java/net/OldDatagramPacketTest.java b/luni/src/test/java/libcore/java/net/OldDatagramPacketTest.java
new file mode 100644
index 0000000..a77a44d
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/OldDatagramPacketTest.java
@@ -0,0 +1,123 @@
+/*
+ * 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 libcore.java.net;
+
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+import tests.support.Support_PortManager;
+
+public class OldDatagramPacketTest extends junit.framework.TestCase {
+
+ DatagramPacket dp;
+
+ volatile boolean started = false;
+
+ public void test_getPort() throws IOException {
+ dp = new DatagramPacket("Hello".getBytes(), 5, InetAddress.getLocalHost(), 1000);
+ assertEquals("Incorrect port returned", 1000, dp.getPort());
+
+ InetAddress localhost = InetAddress.getByName("localhost");
+
+ int[] ports = Support_PortManager.getNextPortsForUDP(2);
+ final int port = ports[0];
+ final Object lock = new Object();
+
+ Thread thread = new Thread(new Runnable() {
+ public void run() {
+ DatagramSocket socket = null;
+ try {
+ socket = new DatagramSocket(port);
+ synchronized (lock) {
+ started = true;
+ lock.notifyAll();
+ }
+ socket.setSoTimeout(3000);
+ DatagramPacket packet = new DatagramPacket(new byte[256],
+ 256);
+ socket.receive(packet);
+ socket.send(packet);
+ socket.close();
+ } catch (IOException e) {
+ System.out.println("thread exception: " + e);
+ if (socket != null)
+ socket.close();
+ }
+ }
+ });
+ thread.start();
+
+ DatagramSocket socket = null;
+ try {
+ socket = new DatagramSocket(ports[1]);
+ socket.setSoTimeout(3000);
+ DatagramPacket packet = new DatagramPacket(new byte[] { 1, 2, 3, 4,
+ 5, 6 }, 6, localhost, port);
+ synchronized (lock) {
+ try {
+ if (!started)
+ lock.wait();
+ } catch (InterruptedException e) {
+ fail(e.toString());
+ }
+ }
+ socket.send(packet);
+ socket.receive(packet);
+ socket.close();
+ assertTrue("datagram received wrong port: " + packet.getPort(),
+ packet.getPort() == port);
+ } finally {
+ if (socket != null) {
+ socket.close();
+ }
+ }
+ }
+
+ public void test_setLengthI() {
+ try {
+ new DatagramPacket("Hello".getBytes(), 6);
+ fail("IllegalArgumentException was not thrown.");
+ } catch(IllegalArgumentException expected) {
+ }
+
+ try {
+ new DatagramPacket("Hello".getBytes(), -1);
+ fail("IllegalArgumentException was not thrown.");
+ } catch(IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_setData$BII() {
+ dp = new DatagramPacket("Hello".getBytes(), 5);
+ try {
+ dp.setData(null, 2, 3);
+ fail("NullPointerException was not thrown.");
+ } catch(NullPointerException expected) {
+ }
+ }
+
+ public void test_setData$B() {
+ dp = new DatagramPacket("Hello".getBytes(), 5);
+ try {
+ dp.setData(null);
+ fail("NullPointerException was not thrown.");
+ } catch(NullPointerException expected) {
+ }
+ }
+}
diff --git a/luni/src/test/java/tests/api/java/net/DatagramSocketImplFactoryTest.java b/luni/src/test/java/libcore/java/net/OldDatagramSocketImplFactoryTest.java
index 35e19eb..62dac1e 100644
--- a/luni/src/test/java/tests/api/java/net/DatagramSocketImplFactoryTest.java
+++ b/luni/src/test/java/libcore/java/net/OldDatagramSocketImplFactoryTest.java
@@ -14,14 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.net;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
+package libcore.java.net;
import java.io.IOException;
import java.lang.reflect.Field;
@@ -33,9 +26,9 @@ import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.net.SocketException;
+import junit.framework.TestCase;
-@TestTargetClass(DatagramSocketImplFactory.class)
-public class DatagramSocketImplFactoryTest extends TestCase {
+public class OldDatagramSocketImplFactoryTest extends TestCase {
DatagramSocketImplFactory oldFactory = null;
Field factoryField = null;
@@ -45,32 +38,15 @@ public class DatagramSocketImplFactoryTest extends TestCase {
boolean isDatagramSocketImplCalled = false;
boolean isCreateDatagramSocketImpl = false;
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createDatagramSocketImpl",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies SecurityException.",
- clazz = DatagramSocket.class,
- method = "setDatagramSocketImplFactory",
- args = {java.net.DatagramSocketImplFactory.class}
- )
- })
- public void test_createDatagramSocketImpl() throws IllegalArgumentException,
- IOException {
-
- if(isTestable) {
+ public void test_createDatagramSocketImpl() throws IllegalArgumentException, IOException {
+ if (isTestable) {
DatagramSocketImplFactory factory = new TestDatagramSocketImplFactory();
assertFalse(isCreateDatagramSocketImpl);
DatagramSocket.setDatagramSocketImplFactory(factory);
try {
- DatagramSocket ds = new java.net.DatagramSocket();
+ new java.net.DatagramSocket();
assertTrue(isCreateDatagramSocketImpl);
assertTrue(isDatagramSocketImplCalled);
} catch (Exception e) {
@@ -101,7 +77,6 @@ public class DatagramSocketImplFactoryTest extends TestCase {
} catch (SocketException e) {
fail("SocketException was thrown.");
}
-
}
}
@@ -157,14 +132,10 @@ public class DatagramSocketImplFactoryTest extends TestCase {
@Override
protected void bind(int arg0, InetAddress arg1) throws SocketException {
- // TODO Auto-generated method stub
-
}
@Override
protected void close() {
- // TODO Auto-generated method stub
-
}
@Override
@@ -174,84 +145,61 @@ public class DatagramSocketImplFactoryTest extends TestCase {
@Override
protected byte getTTL() throws IOException {
- // TODO Auto-generated method stub
return 0;
}
@Override
protected int getTimeToLive() throws IOException {
- // TODO Auto-generated method stub
return 0;
}
@Override
protected void join(InetAddress arg0) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected void joinGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected void leave(InetAddress arg0) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
public int peek(InetAddress arg0) throws IOException {
- // TODO Auto-generated method stub
return 10;
}
@Override
protected int peekData(DatagramPacket arg0) throws IOException {
- // TODO Auto-generated method stub
return 0;
}
@Override
protected void receive(DatagramPacket arg0) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected void send(DatagramPacket arg0) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected void setTTL(byte arg0) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected void setTimeToLive(int arg0) throws IOException {
- // TODO Auto-generated method stub
-
}
public Object getOption(int arg0) throws SocketException {
- // TODO Auto-generated method stub
return null;
}
public void setOption(int arg0, Object arg1) throws SocketException {
- // TODO Auto-generated method stub
-
}
}
}
diff --git a/luni/src/test/java/tests/api/java/net/FileNameMapTest.java b/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java
index 49799a7..02d7c8e 100644
--- a/luni/src/test/java/tests/api/java/net/FileNameMapTest.java
+++ b/luni/src/test/java/libcore/java/net/OldFileNameMapTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package tests.api.java.net;
+package libcore.java.net;
import dalvik.annotation.TestTargets;
import dalvik.annotation.TestLevel;
@@ -26,15 +26,8 @@ import junit.framework.TestCase;
import java.net.FileNameMap;
import java.net.URLConnection;
-@TestTargetClass(FileNameMap.class)
-public class FileNameMapTest extends TestCase {
+public class OldFileNameMapTest extends TestCase {
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getContentTypeFor",
- args = {java.lang.String.class}
- )
public void test_getContentTypeFor() {
String [] files = {"text", "txt", "htm", "html"};
diff --git a/luni/src/test/java/tests/api/java/net/HttpRetryExceptionTest.java b/luni/src/test/java/libcore/java/net/OldHttpRetryExceptionTest.java
index a1bf477..e71eaba 100644
--- a/luni/src/test/java/tests/api/java/net/HttpRetryExceptionTest.java
+++ b/luni/src/test/java/libcore/java/net/OldHttpRetryExceptionTest.java
@@ -14,41 +14,13 @@
* limitations under the License.
*/
-package tests.api.java.net;
+package libcore.java.net;
-import junit.framework.TestCase;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.net.FileNameMap;
import java.net.HttpRetryException;
+import junit.framework.TestCase;
-@TestTargetClass(HttpRetryException.class)
-public class HttpRetryExceptionTest extends TestCase {
+public class OldHttpRetryExceptionTest extends TestCase {
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HttpRetryException",
- args = {java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "responseCode",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getReason",
- args = {}
- )
- })
public void test_ConstructorLStringI() {
String [] message = {"Test message", "", "Message", "~!@#$% &*(", null};
int [] codes = {400, 404, 200, 500, 0};
@@ -62,32 +34,6 @@ public class HttpRetryExceptionTest extends TestCase {
}
}
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "HttpRetryException",
- args = {java.lang.String.class, int.class, java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocation",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "responseCode",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getReason",
- args = {}
- )
- })
public void test_ConstructorLStringILString() {
String [] message = {"Test message", "", "Message", "~!@#$% &*(", null};
int [] codes = {400, -1, Integer.MAX_VALUE, Integer.MIN_VALUE, 0};
diff --git a/luni/src/test/java/tests/api/java/net/JarURLConnectionTest.java b/luni/src/test/java/libcore/java/net/OldJarURLConnectionTest.java
index d7e55a6..2954552 100644
--- a/luni/src/test/java/tests/api/java/net/JarURLConnectionTest.java
+++ b/luni/src/test/java/libcore/java/net/OldJarURLConnectionTest.java
@@ -15,11 +15,7 @@
* limitations under the License.
*/
-package tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
+package libcore.java.net;
import java.io.BufferedOutputStream;
import java.io.File;
@@ -31,11 +27,9 @@ import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.Certificate;
-import java.util.Collection;
-import java.util.Map;
-import java.util.Set;
import java.util.Arrays;
import java.util.HashSet;
+import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
@@ -43,26 +37,12 @@ import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
-
import tests.support.resource.Support_Resources;
-@TestTargetClass(JarURLConnection.class)
-public class JarURLConnectionTest extends junit.framework.TestCase {
+public class OldJarURLConnectionTest extends junit.framework.TestCase {
JarURLConnection juc;
- URLConnection uc;
-
- private static final URL BASE = getBaseURL();
-
- private static URL getBaseURL() {
- String clazz = JarURLConnectionTest.class.getName();
- int p = clazz.lastIndexOf(".");
- String pack = (p == -1 ? "" : clazz.substring(0, p)).replace('.', File.separatorChar);
-
- return JarURLConnectionTest.class.getClassLoader().getResource(pack);
- }
-
private URL createContent(String jarFile, String inFile)
throws MalformedURLException {
@@ -70,33 +50,16 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
Support_Resources.copyFile(resources, "net", jarFile);
File file = new File(resources.toString() + "/net/" + jarFile);
- URL fUrl1 = new URL("jar:file:" + file.getPath() + "!/" + inFile);
- return fUrl1;
+ return new URL("jar:file:" + file.getPath() + "!/" + inFile);
}
- /**
- * @tests java.net.JarURLConnection#getAttributes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAttributes",
- args = {}
- )
public void test_getAttributes() throws Exception {
- //URL u = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/swt.dll");
-
URL u = createContent("lf.jar", "swt.dll");
juc = (JarURLConnection) u.openConnection();
java.util.jar.Attributes a = juc.getAttributes();
assertEquals("Returned incorrect Attributes", "SHA MD5", a
.get(new java.util.jar.Attributes.Name("Digest-Algorithms")));
-
- //URL invURL = new URL("jar:"
- // + BASE.toString()+"/InvalidJar.jar!/Test.class");
-
URL invURL = createContent("InvalidJar.jar", "Test.class");
JarURLConnection juConn = (JarURLConnection) invURL.openConnection();
@@ -108,17 +71,7 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCertificates",
- args = {}
- )
public void test_getCertificates() throws Exception {
-
- //URL u = new URL("jar:"
- // + BASE.toString()+"/TestCodeSigners.jar!/Test.class");
-
URL u = createContent("TestCodeSigners.jar", "Test.class");
juc = (JarURLConnection) u.openConnection();
@@ -132,9 +85,6 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
Certificate [] certs = juc.getCertificates();
assertEquals(3, certs.length);
- //URL invURL = new URL("jar:"
- // + BASE.toString()+"/InvalidJar.jar!/Test.class");
-
URL invURL = createContent("InvalidJar.jar", "Test.class");
JarURLConnection juConn = (JarURLConnection) invURL.openConnection();
@@ -146,17 +96,7 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getManifest",
- args = {}
- )
public void test_getManifest() throws Exception {
-
- //URL u = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/swt.dll");
-
URL u = createContent("lf.jar", "swt.dll");
juc = (JarURLConnection) u.openConnection();
@@ -165,9 +105,6 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
assertEquals(new HashSet<String>(Arrays.asList("plus.bmp", "swt.dll")),
attr.keySet());
- //URL invURL = new URL("jar:"
- // + BASE.toString()+"/InvalidJar.jar!/Test.class");
-
URL invURL = createContent("InvalidJar.jar", "Test.class");
JarURLConnection juConn = (JarURLConnection) invURL.openConnection();
@@ -179,66 +116,35 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
}
}
- /**
- * @throws Exception
- * @tests java.net.JarURLConnection#getEntryName()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getEntryName",
- args = {}
- )
public void test_getEntryName() throws Exception {
- //URL u = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/plus.bmp");
-
URL u = createContent("lf.jar", "plus.bmp");
juc = (JarURLConnection) u.openConnection();
assertEquals("Returned incorrect entryName", "plus.bmp", juc
.getEntryName());
- //u = new URL("jar:" + BASE.toString()+"/lf.jar!/");
-
u = createContent("lf.jar", "");
juc = (JarURLConnection) u.openConnection();
assertNull("Returned incorrect entryName", juc.getEntryName());
-// Regression test for harmony-3053
+ // Regression test for harmony-3053
URL url = new URL("jar:file:///bar.jar!/foo.jar!/Bugs/HelloWorld.class");
assertEquals("foo.jar!/Bugs/HelloWorld.class",((JarURLConnection)url.openConnection()).getEntryName());
}
- /**
- * @tests java.net.JarURLConnection#getJarEntry()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getJarEntry",
- args = {}
- )
public void test_getJarEntry() throws Exception {
- //URL u = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/plus.bmp");
-
URL u = createContent("lf.jar", "plus.bmp");
juc = (JarURLConnection) u.openConnection();
assertEquals("Returned incorrect JarEntry", "plus.bmp", juc
.getJarEntry().getName());
- //u = new URL("jar:" + BASE.toString()+"/lf.jar!/");
u = createContent("lf.jar", "");
juc = (JarURLConnection) u.openConnection();
assertNull("Returned incorrect JarEntry", juc.getJarEntry());
- //URL invURL = new URL("jar:"
- // + BASE.toString()+"/InvalidJar.jar!/Test.class");
-
URL invURL = createContent("InvalidJar.jar", "Test.class");
JarURLConnection juConn = (JarURLConnection) invURL.openConnection();
@@ -250,24 +156,10 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
}
}
- /**
- * @tests java.net.JarURLConnection#getJarFile()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getJarFile",
- args = {}
- )
- public void test_getJarFile() throws MalformedURLException, IOException {
- URL url = null;
- //url = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/missing");
-
- url = createContent("lf.jar", "missing");
-
- JarURLConnection connection = null;
- connection = (JarURLConnection) url.openConnection();
+ public void test_getJarFile() throws IOException {
+ URL url = createContent("lf.jar", "missing");
+
+ JarURLConnection connection = (JarURLConnection) url.openConnection();
try {
connection.connect();
fail("Did not throw exception on connect");
@@ -282,9 +174,6 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
// expected
}
- //URL invURL = new URL("jar:"
- // + BASE.toString()+"/InvalidJar.jar!/Test.class");
-
URL invURL = createContent("InvalidJar.jar", "Test.class");
JarURLConnection juConn = (JarURLConnection) invURL.openConnection();
@@ -309,7 +198,6 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
assertTrue("File should exist", file.exists());
fUrl1 = createContent("lf.jar", "");
- //new URL("jar:" + BASE.toString()+"/lf.jar!/");
con1 = (JarURLConnection) fUrl1.openConnection();
jf1 = con1.getJarFile();
@@ -319,17 +207,6 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
jf1.close();
}
- /**
- * @tests java.net.JarURLConnection.getJarFile()
- *
- * Regression test for HARMONY-29
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Regression test.",
- method = "getJarFile",
- args = {}
- )
public void test_getJarFile29() throws Exception {
File jarFile = File.createTempFile("1+2 3", "test.jar");
jarFile.deleteOnExit();
@@ -345,12 +222,6 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
}
//Regression for HARMONY-3436
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "Exceptions checking missed.",
- method = "setUseCaches",
- args = {boolean.class}
- )
public void test_setUseCaches() throws Exception {
File resources = Support_Resources.createTempFolder();
Support_Resources.copyFile(resources, null, "hyts_att.jar");
@@ -359,8 +230,8 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
JarURLConnection connection = (JarURLConnection) url.openConnection();
connection.setUseCaches(false);
+ connection.getInputStream();
InputStream in = connection.getInputStream();
- in = connection.getInputStream();
JarFile jarFile1 = connection.getJarFile();
JarEntry jarEntry1 = connection.getJarEntry();
in.read();
@@ -378,20 +249,7 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
}
}
- /**
- * @tests java.net.JarURLConnection#getJarFileURL()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getJarFileURL",
- args = {}
- )
public void test_getJarFileURL() throws Exception {
- //URL fileURL = new URL(BASE.toString()+"/lf.jar");
- //URL u = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/plus.bmp");
-
URL u = createContent("lf.jar", "plus.bmp");
URL fileURL = new URL(u.getPath().substring(0, u.getPath().indexOf("!")));
@@ -404,18 +262,7 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
assertEquals("file:/bar.jar",((JarURLConnection)url.openConnection()).getJarFileURL().toString());
}
- /**
- * @tests java.net.JarURLConnection#getMainAttributes()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMainAttributes",
- args = {}
- )
public void test_getMainAttributes() throws Exception {
- //URL u = new URL("jar:"
- // + BASE.toString()+"/lf.jar!/swt.dll");
URL u = createContent("lf.jar", "swt.dll");
juc = (JarURLConnection) u.openConnection();
@@ -423,8 +270,6 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
assertEquals("Returned incorrect Attributes", "1.0", a
.get(java.util.jar.Attributes.Name.MANIFEST_VERSION));
- //URL invURL = new URL("jar:"
- // + BASE.toString()+"/InvalidJar.jar!/Test.class");
URL invURL = createContent("InvalidJar.jar", "Test.class");
JarURLConnection juConn = (JarURLConnection) invURL.openConnection();
@@ -436,23 +281,13 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
}
}
- /**
- * @tests java.net.JarURLConnection#getInputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Test fails: IOException expected but IllegalStateException is thrown: ticket 128",
- method = "getInputStream",
- args = {}
- )
public void test_getInputStream_DeleteJarFileUsingURLConnection()
throws Exception {
- String jarFileName = "";
String entry = "text.txt";
String cts = System.getProperty("java.io.tmpdir");
File tmpDir = new File(cts);
- File jarFile = tmpDir.createTempFile("file", ".jar", tmpDir);
- jarFileName = jarFile.getPath();
+ File jarFile = File.createTempFile("file", ".jar", tmpDir);
+ String jarFileName = jarFile.getPath();
FileOutputStream jarFileOutputStream = new FileOutputStream(jarFileName);
JarOutputStream out = new JarOutputStream(new BufferedOutputStream(
jarFileOutputStream));
@@ -468,25 +303,8 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
is.close();
assertTrue(jarFile.delete());
-
- /*
- try {
- conn.getInputStream();
- fail("Exception was not thrown.");
- } catch (IOException e) {
- //ok
- }
-
- */
-
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "JarURLConnection",
- args = {java.net.URL.class}
- )
public void test_Constructor() {
try {
String jarFileName = "file.jar";
@@ -499,29 +317,22 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
}
try {
- URL [] urls = {new URL("file:file.jar"),
- new URL("http://foo.com/foo/foo.jar")};
-
- for(URL url:urls) {
- try {
- new TestJarURLConnection(url);
- fail("MalformedURLException was not thrown.");
- } catch(MalformedURLException me) {
- //expected
+ URL [] urls = {new URL("file:file.jar"),
+ new URL("http://foo.com/foo/foo.jar")};
+
+ for(URL url : urls) {
+ try {
+ new TestJarURLConnection(url);
+ fail("MalformedURLException was not thrown.");
+ } catch(MalformedURLException me) {
+ //expected
+ }
}
- }
} catch(MalformedURLException me) {
fail("MalformedURLException was thrown.");
}
}
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-
class TestJarURLConnection extends JarURLConnection {
protected TestJarURLConnection(URL arg0) throws MalformedURLException {
@@ -537,7 +348,6 @@ public class JarURLConnectionTest extends junit.framework.TestCase {
public void connect() throws IOException {
}
-
}
}
diff --git a/luni/src/test/java/tests/api/java/net/TestServerSocketInit.java b/luni/src/test/java/libcore/java/net/OldNetPermissionTest.java
index 5727d7e..81ab2cf 100644
--- a/luni/src/test/java/tests/api/java/net/TestServerSocketInit.java
+++ b/luni/src/test/java/libcore/java/net/OldNetPermissionTest.java
@@ -15,16 +15,15 @@
* limitations under the License.
*/
-package tests.api.java.net;
+package libcore.java.net;
-import java.io.IOException;
-import java.net.ServerSocket;
+import java.net.NetPermission;
+import junit.framework.TestCase;
-public class TestServerSocketInit {
+public class OldNetPermissionTest extends TestCase {
- public static void main(String[] args) throws IOException {
- ServerSocket serverSocket = new ServerSocket();
- serverSocket.setReuseAddress(true);
- serverSocket.close();
+ public void test_ConstructorLjava_lang_StringLjava_lang_String() {
+ NetPermission n1 = new NetPermission("requestPasswordAuthentication", "");
+ assertEquals("", n1.getActions());
}
}
diff --git a/luni/src/test/java/libcore/java/net/OldPasswordAuthenticationTest.java b/luni/src/test/java/libcore/java/net/OldPasswordAuthenticationTest.java
new file mode 100644
index 0000000..9d5e147
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/OldPasswordAuthenticationTest.java
@@ -0,0 +1,39 @@
+/*
+ * 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 libcore.java.net;
+
+import java.net.PasswordAuthentication;
+import junit.framework.TestCase;
+
+public class OldPasswordAuthenticationTest extends TestCase {
+
+ public void test_ConstructorLjava_lang_String$C() {
+ String name = "name";
+ char[] password = "hunter2".toCharArray();
+ try {
+ new PasswordAuthentication(name, null);
+ fail("NullPointerException was not thrown.");
+ } catch (NullPointerException npe) {
+ //expected
+ }
+
+ PasswordAuthentication pa = new PasswordAuthentication(null, password);
+ assertNull(pa.getUserName());
+ assertEquals(password.length, pa.getPassword().length);
+ }
+}
diff --git a/luni/src/test/java/libcore/java/net/OldProxyTest.java b/luni/src/test/java/libcore/java/net/OldProxyTest.java
new file mode 100644
index 0000000..015bbd0
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/OldProxyTest.java
@@ -0,0 +1,70 @@
+/* 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 libcore.java.net;
+
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.SocketAddress;
+import junit.framework.TestCase;
+
+public class OldProxyTest extends TestCase {
+
+ private SocketAddress address = new InetSocketAddress("127.0.0.1", 1234);
+
+ public void test_address() {
+ Proxy proxy = new Proxy(Proxy.Type.SOCKS, address);
+ assertEquals(address, proxy.address());
+
+ try {
+ new Proxy(Proxy.Type.SOCKS, null);
+ fail("IllegalArgumentException was thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+ }
+
+ public void test_hashCode() {
+ SocketAddress address1 = new InetSocketAddress("127.0.0.1", 1234);
+
+ Proxy proxy1 = new Proxy(Proxy.Type.HTTP, address1);
+ Proxy proxy2 = new Proxy(Proxy.Type.HTTP, address1);
+ assertTrue(proxy1.hashCode() == proxy2.hashCode());
+
+ new Proxy(Proxy.Type.SOCKS, address1);
+ Proxy proxy4 = new Proxy(Proxy.Type.SOCKS, address1);
+ assertTrue(proxy1.hashCode() == proxy2.hashCode());
+
+ assertTrue(proxy1.hashCode() != proxy4.hashCode());
+
+ SocketAddress address2 = new InetSocketAddress("127.0.0.1", 1235);
+
+ Proxy proxy5 = new Proxy(Proxy.Type.SOCKS, address1);
+ Proxy proxy6 = new Proxy(Proxy.Type.SOCKS, address2);
+ assertTrue(proxy5.hashCode() != proxy6.hashCode());
+ }
+
+ public void test_type() {
+
+ Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
+ assertEquals(Proxy.Type.HTTP, proxy.type());
+
+ proxy = new Proxy(Proxy.Type.SOCKS, address);
+ assertEquals(Proxy.Type.SOCKS, proxy.type());
+
+ proxy = Proxy.NO_PROXY;
+ assertEquals(Proxy.Type.DIRECT, proxy.type());
+ }
+}
diff --git a/luni/src/test/java/libcore/java/net/OldServerSocketTest.java b/luni/src/test/java/libcore/java/net/OldServerSocketTest.java
new file mode 100644
index 0000000..af47a5a
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/OldServerSocketTest.java
@@ -0,0 +1,394 @@
+/*
+ * 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 libcore.java.net;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+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.net.SocketImpl;
+import java.net.SocketImplFactory;
+import java.net.SocketTimeoutException;
+import java.nio.channels.IllegalBlockingModeException;
+import java.nio.channels.ServerSocketChannel;
+import java.security.Permission;
+import java.util.Properties;
+import tests.support.Support_PortManager;
+
+public class OldServerSocketTest extends OldSocketTestCase {
+
+ boolean isCreateCalled = false;
+ ServerSocket s;
+ Socket sconn;
+ Thread t;
+
+ public void test_setPerformancePreference_Int_Int_Int() throws Exception {
+ performancePreferenceTest(1, 0, 0);
+ performancePreferenceTest(1, 1, 1);
+ performancePreferenceTest(0, 1, 2);
+ performancePreferenceTest(Integer.MAX_VALUE, Integer.MAX_VALUE,
+ Integer.MAX_VALUE);
+ }
+
+ void performancePreferenceTest(int connectionTime, int latency,
+ int bandwidth) throws Exception {
+ ServerSocket theSocket = new ServerSocket();
+ theSocket.setPerformancePreferences(connectionTime, latency, bandwidth);
+
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), 0);
+ theSocket.bind(theAddress);
+ int portNumber = theSocket.getLocalPort();
+ assertTrue(
+ "Returned incorrect InetSocketAddress(2):"
+ + theSocket.getLocalSocketAddress().toString()
+ + "Expected: "
+ + (new InetSocketAddress(InetAddress.getLocalHost(),
+ portNumber)).toString(), theSocket
+ .getLocalSocketAddress().equals(
+ new InetSocketAddress(InetAddress
+ .getLocalHost(), portNumber)));
+ assertTrue("Server socket not bound when it should be:", theSocket
+ .isBound());
+
+ // now make sure that it is actually bound and listening on the
+ // address we provided
+ Socket clientSocket = new Socket();
+ InetSocketAddress clAddress = new InetSocketAddress(InetAddress
+ .getLocalHost(), portNumber);
+ clientSocket.connect(clAddress);
+ Socket servSock = theSocket.accept();
+
+ assertEquals(clAddress, clientSocket.getRemoteSocketAddress());
+ theSocket.close();
+ servSock.close();
+ clientSocket.close();
+ }
+
+ public void test_ConstructorII() throws IOException {
+ int freePortNumber = Support_PortManager.getNextPort();
+ s = new ServerSocket(freePortNumber, 1);
+ s.setSoTimeout(2000);
+ startClient(freePortNumber);
+ sconn = s.accept();
+ sconn.close();
+ s.close();
+ }
+
+ static class SSClient implements Runnable {
+ Socket cs;
+
+ int port;
+
+ public SSClient(int prt) {
+ port = prt;
+ }
+
+ public void run() {
+ try {
+ // Go to sleep so the server can setup and wait for connection
+ Thread.sleep(1000);
+ cs = new Socket(InetAddress.getLocalHost().getHostName(), port);
+ // Sleep again to allow server side processing. Thread is
+ // stopped by server.
+ Thread.sleep(10000);
+ } catch (InterruptedException e) {
+ return;
+ } catch (Throwable e) {
+ System.out.println("Error establishing client: " + e.toString());
+ } finally {
+ try {
+ if (cs != null)
+ cs.close();
+ } catch (Exception e) {
+ }
+ }
+ }
+ }
+
+ public void test_Constructor() throws IOException {
+ ServerSocket ss = new ServerSocket();
+ assertEquals(-1, ss.getLocalPort());
+ ss.close();
+ }
+
+ public void test_ConstructorI() throws Exception {
+ int portNumber = Support_PortManager.getNextPort();
+ s = new ServerSocket(portNumber);
+ try {
+ new ServerSocket(portNumber);
+ fail("IOException was not thrown.");
+ } catch(IOException ioe) {
+ //expected
+ }
+ try {
+ startClient(s.getLocalPort());
+ sconn = s.accept();
+ assertNotNull("Was unable to accept connection", sconn);
+ sconn.close();
+ } finally {
+ s.close();
+ }
+
+ s = new ServerSocket(0);
+ try {
+ startClient(s.getLocalPort());
+ sconn = s.accept();
+ assertNotNull("Was unable to accept connection", sconn);
+ sconn.close();
+ } finally {
+ s.close();
+ }
+ }
+
+ public void test_ConstructorIILjava_net_InetAddress() throws IOException {
+ int freePortNumber = Support_PortManager.getNextPort();
+
+ ServerSocket ss = new ServerSocket(freePortNumber, 10, InetAddress.getLocalHost());
+ try {
+ new ServerSocket(freePortNumber, 10, InetAddress.getLocalHost());
+ fail("IOException was not thrown.");
+ } catch(IOException expected) {
+ }
+ ss.close();
+
+ try {
+ new ServerSocket(65536, 10, InetAddress.getLocalHost());
+ fail("IllegalArgumentException was not thrown.");
+ } catch(IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_LocalPort() throws IOException {
+ ServerSocket ss1 = new ServerSocket(4242);
+ assertEquals(ss1.getLocalPort(), 4242);
+ ss1.close();
+
+ ServerSocket ss2 = new ServerSocket();
+ ss2.bind(new InetSocketAddress("127.0.0.1", 4343));
+ assertEquals(ss2.getLocalPort(), 4343);
+ ss2.close();
+
+ ServerSocket ss3 = new ServerSocket(0);
+ assertTrue(ss3.getLocalPort() != 0);
+ ss3.close();
+ }
+
+ class MockSocketFactory implements SocketImplFactory {
+ public SocketImpl createSocketImpl() {
+ return new MockSocketImpl();
+ }
+ }
+
+ public void test_ConstructorI_SocksSet() throws IOException {
+ // Harmony-623 regression test
+ ServerSocket ss = null;
+ Properties props = (Properties) System.getProperties().clone();
+ try {
+ System.setProperty("socksProxyHost", "127.0.0.1");
+ System.setProperty("socksProxyPort", "12345");
+ ss = new ServerSocket(0);
+ } finally {
+ System.setProperties(props);
+ if (null != ss) {
+ ss.close();
+ }
+ }
+ }
+
+ public void test_accept() throws IOException {
+ int portNumber = Support_PortManager.getNextPort();
+
+ ServerSocket newSocket = new ServerSocket(portNumber);
+ newSocket.setSoTimeout(500);
+ try {
+ Socket accepted = newSocket.accept();
+ fail("SocketTimeoutException was not thrown: " + accepted);
+ } catch(SocketTimeoutException expected) {
+ }
+ newSocket.close();
+
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ServerSocket ss = ssc.socket();
+
+ try {
+ ss.accept();
+ fail("IllegalBlockingModeException was not thrown.");
+ } catch(IllegalBlockingModeException ibme) {
+ //expected
+ } finally {
+ ss.close();
+ ssc.close();
+ }
+ }
+
+ public void test_getSoTimeout() throws IOException {
+ ServerSocket newSocket = new ServerSocket();
+ newSocket.close();
+ try {
+ newSocket.setSoTimeout(100);
+ fail("SocketException was not thrown.");
+ } catch(SocketException e) {
+ //expected
+ }
+ }
+
+ public void test_setSoTimeoutI() throws IOException {
+ ServerSocket newSocket = new ServerSocket();
+ newSocket.close();
+ try {
+ newSocket.setSoTimeout(100);
+ fail("SocketException was not thrown.");
+ } catch(SocketException se) {
+ //expected
+ }
+ }
+
+ public void test_toString() throws Exception {
+ s = new ServerSocket(0);
+ int portNumber = s.getLocalPort();
+ assertTrue(s.toString().contains("" + portNumber));
+ s.close();
+ }
+
+ public void test_setReuseAddressZ() throws IOException {
+ ServerSocket newSocket = new ServerSocket();
+ newSocket.close();
+ try {
+ newSocket.setReuseAddress(true);
+ fail("SocketException was not thrown.");
+ } catch(SocketException expected) {
+ }
+ }
+
+ public void test_getReuseAddress() throws IOException {
+ ServerSocket newSocket = new ServerSocket();
+ newSocket.close();
+ try {
+ newSocket.getReuseAddress();
+ fail("SocketException was not thrown.");
+ } catch(SocketException e) {
+ //expected
+ }
+ }
+
+ public void test_setReceiveBufferSizeI() throws IOException {
+ ServerSocket newSocket = new ServerSocket();
+ newSocket.close();
+ try {
+ newSocket.setReceiveBufferSize(10);
+ fail("SocketException was not thrown.");
+ } catch(SocketException se) {
+ //expected
+ }
+ }
+
+ public void test_getReceiveBufferSize() throws IOException {
+ ServerSocket newSocket = new ServerSocket();
+ newSocket.close();
+ try {
+ newSocket.getReceiveBufferSize();
+ fail("SocketException was not thrown.");
+ } catch (SocketException e) {
+ //expected
+ }
+ }
+
+ protected void tearDown() {
+ try {
+ if (s != null)
+ s.close();
+ if (sconn != null)
+ sconn.close();
+ if (t != null)
+ t.interrupt();
+ } catch (Exception e) {
+ }
+ }
+
+ /**
+ * Sets up the fixture, for example, open a network connection. This method
+ * is called before a test is executed.
+ */
+ protected void startClient(int port) {
+ t = new Thread(new SSClient(port), "SSClient");
+ t.start();
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ System.out.println("Exception during startClinet()" + e.toString());
+ }
+ }
+
+ class MockSocketImpl extends SocketImpl {
+ public MockSocketImpl() {
+ isCreateCalled = true;
+ }
+
+ protected void create(boolean arg0) throws IOException {
+ }
+
+ protected void connect(String arg0, int arg1) throws IOException {
+ }
+
+ protected void connect(InetAddress arg0, int arg1) throws IOException {
+ }
+
+ protected void connect(SocketAddress arg0, int arg1) throws IOException {
+ }
+
+ protected void bind(InetAddress arg0, int arg1) throws IOException {
+ }
+
+ protected void listen(int arg0) throws IOException {
+ }
+
+ protected void accept(SocketImpl arg0) throws IOException {
+ }
+
+ protected InputStream getInputStream() throws IOException {
+ return null;
+ }
+
+ protected OutputStream getOutputStream() throws IOException {
+ return null;
+ }
+
+ protected int available() throws IOException {
+ return 0;
+ }
+
+ protected void close() throws IOException {
+ }
+
+ protected void sendUrgentData(int arg0) throws IOException {
+ }
+
+ public void setOption(int arg0, Object arg1) throws SocketException {
+ }
+
+ public Object getOption(int arg0) throws SocketException {
+ return null;
+ }
+ }
+}
diff --git a/luni/src/test/java/tests/api/java/net/SocketImplFactoryTest.java b/luni/src/test/java/libcore/java/net/OldSocketImplFactoryTest.java
index bd6fee2..9c13337 100644
--- a/luni/src/test/java/tests/api/java/net/SocketImplFactoryTest.java
+++ b/luni/src/test/java/libcore/java/net/OldSocketImplFactoryTest.java
@@ -1,11 +1,4 @@
-package tests.api.java.net;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargets;
-
-import junit.framework.TestCase;
+package libcore.java.net;
import java.io.IOException;
import java.io.InputStream;
@@ -17,10 +10,10 @@ import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketImpl;
import java.net.SocketImplFactory;
+import junit.framework.TestCase;
-@TestTargetClass(SocketImplFactory.class)
-public class SocketImplFactoryTest extends TestCase {
+public class OldSocketImplFactoryTest extends TestCase {
SocketImplFactory oldFactory = null;
Field factoryField = null;
@@ -30,35 +23,18 @@ public class SocketImplFactoryTest extends TestCase {
boolean iSocketImplCalled = false;
boolean isCreateSocketImpl = false;
- @TestTargets ({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "createSocketImpl",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies positive case, and SocketException.",
- clazz = Socket.class,
- method = "setSocketImplFactory",
- args = {java.net.SocketImplFactory.class}
- )
- })
public void test_createSocketImpl() throws IOException {
MockSocketImplFactory factory = new MockSocketImplFactory();
if(isTestable) {
-
assertFalse(isCreateSocketImpl);
Socket.setSocketImplFactory(factory);
try {
- Socket ds = new Socket();
+ new Socket();
assertTrue(isCreateSocketImpl);
assertTrue(iSocketImplCalled);
} catch (Exception e) {
fail("Exception during test : " + e.getMessage());
-
}
try {
@@ -142,7 +118,6 @@ public class SocketImplFactoryTest extends TestCase {
}
@Override
protected void accept(SocketImpl arg0) throws IOException {
-
}
@Override
@@ -152,32 +127,26 @@ public class SocketImplFactoryTest extends TestCase {
@Override
protected void bind(InetAddress arg0, int arg1) throws IOException {
-
}
@Override
protected void close() throws IOException {
-
}
@Override
protected void connect(String arg0, int arg1) throws IOException {
-
}
@Override
protected void connect(InetAddress arg0, int arg1) throws IOException {
-
}
@Override
protected void connect(SocketAddress arg0, int arg1) throws IOException {
-
}
@Override
protected void create(boolean arg0) throws IOException {
-
}
@Override
@@ -192,12 +161,10 @@ public class SocketImplFactoryTest extends TestCase {
@Override
protected void listen(int arg0) throws IOException {
-
}
@Override
protected void sendUrgentData(int arg0) throws IOException {
-
}
public Object getOption(int arg0) throws SocketException {
@@ -205,7 +172,6 @@ public class SocketImplFactoryTest extends TestCase {
}
public void setOption(int arg0, Object arg1) throws SocketException {
-
}
}
}
diff --git a/luni/src/test/java/libcore/java/net/OldSocketPermissionTest.java b/luni/src/test/java/libcore/java/net/OldSocketPermissionTest.java
new file mode 100644
index 0000000..656252e
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/OldSocketPermissionTest.java
@@ -0,0 +1,45 @@
+/*
+ * 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 libcore.java.net;
+
+import java.net.SocketPermission;
+import tests.support.Support_Configuration;
+
+public class OldSocketPermissionTest extends junit.framework.TestCase {
+
+ String starName = "*." + Support_Configuration.DomainAddress;
+
+ String wwwName = Support_Configuration.HomeAddress;
+
+ SocketPermission star_All = new SocketPermission(starName, "listen,accept,connect");
+
+ SocketPermission www_All = new SocketPermission(wwwName,
+ "connect,listen,accept");
+
+ public void test_hashCode() {
+ SocketPermission sp1 = new SocketPermission(
+ Support_Configuration.InetTestIP, "resolve,connect");
+ SocketPermission sp2 = new SocketPermission(
+ Support_Configuration.InetTestIP, "resolve,connect");
+ assertTrue("Same IP address should have equal hash codes",
+ sp1.hashCode() == sp2.hashCode());
+
+ assertTrue("Different names but returned equal hash codes",
+ star_All.hashCode() != www_All.hashCode());
+ }
+}
diff --git a/luni/src/test/java/tests/api/java/net/SocketTest.java b/luni/src/test/java/libcore/java/net/OldSocketTest.java
index c946ae8..f9852ac 100644
--- a/luni/src/test/java/tests/api/java/net/SocketTest.java
+++ b/luni/src/test/java/libcore/java/net/OldSocketTest.java
@@ -15,18 +15,10 @@
* limitations under the License.
*/
-package tests.api.java.net;
-
-import dalvik.annotation.AndroidOnly;
-//import dalvik.annotation.KnownFailure;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
+package libcore.java.net;
import java.io.IOException;
import java.io.InputStream;
-import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.Inet4Address;
@@ -44,12 +36,10 @@ import java.net.UnknownHostException;
import java.nio.channels.IllegalBlockingModeException;
import java.nio.channels.SocketChannel;
import java.security.Permission;
-
import tests.support.Support_Configuration;
import tests.support.Support_PortManager;
-@TestTargetClass(Socket.class)
-public class SocketTest extends SocketTestCase {
+public class OldSocketTest extends OldSocketTestCase {
ServerSocket ss;
@@ -57,33 +47,6 @@ public class SocketTest extends SocketTestCase {
Thread t;
- boolean interrupted = false;
-
- 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) {
- }
- }
- }
- }
-
SecurityManager sm = new SecurityManager() {
public void checkPermission(Permission perm) {}
@@ -93,15 +56,6 @@ public class SocketTest extends SocketTestCase {
}
};
- /**
- * @tests java.net.Socket#Socket()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {}
- )
public void test_Constructor() {
// create the socket and then validate some basic state
s = new Socket();
@@ -115,15 +69,6 @@ public class SocketTest extends SocketTestCase {
}
- /**
- * @tests java.net.Socket#Socket(java.lang.String, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.lang.String.class, int.class}
- )
public void test_ConstructorLjava_lang_StringI() throws IOException {
// Test for method java.net.Socket(java.lang.String, int)
int sport = startServer("Cons String,I");
@@ -186,16 +131,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#Socket(java.lang.String, int,
- * java.net.InetAddress, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.lang.String.class, int.class, java.net.InetAddress.class, int.class}
- )
public void test_ConstructorLjava_lang_StringILjava_net_InetAddressI()
throws IOException {
// Test for method java.net.Socket(java.lang.String, int,
@@ -213,7 +148,7 @@ public class SocketTest extends SocketTestCase {
// ALTERNATE IPv6 TEST
if ("true".equals(System.getProperty("run.ipv6tests"))) {
System.out
- .println("Running testConstructorLjava_lang_StringILjava_net_InetAddressI(SocketTest) with IPv6GlobalAddressJcl4: "
+ .println("Running testConstructorLjava_lang_StringILjava_net_InetAddressI(OldSocketTest) with IPv6GlobalAddressJcl4: "
+ Support_Configuration.IPv6GlobalAddressJcl4);
int testPort = Support_PortManager.getNextPort();
Socket s1 = null, s2 = null;
@@ -318,15 +253,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#Socket(java.lang.String, int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.lang.String.class, int.class, boolean.class}
- )
public void test_ConstructorLjava_lang_StringIZ() throws IOException {
// Test for method java.net.Socket(java.lang.String, int, boolean)
int sport = startServer("Cons String,I,Z");
@@ -349,15 +275,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#Socket(java.net.InetAddress, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.net.InetAddress.class, int.class}
- )
public void test_ConstructorLjava_net_InetAddressI() throws IOException {
// Test for method java.net.Socket(java.net.InetAddress, int)
int sport = startServer("Cons InetAddress,I");
@@ -378,16 +295,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#Socket(java.net.InetAddress, int,
- * java.net.InetAddress, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.net.InetAddress.class, int.class, java.net.InetAddress.class, int.class}
- )
public void test_ConstructorLjava_net_InetAddressILjava_net_InetAddressI()
throws IOException {
// Test for method java.net.Socket(java.net.InetAddress, int,
@@ -413,15 +320,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#Socket(java.net.InetAddress, int, boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.net.InetAddress.class, int.class, boolean.class}
- )
public void test_ConstructorLjava_net_InetAddressIZ() throws IOException {
// Test for method java.net.Socket(java.net.InetAddress, int, boolean)
int sport = startServer("Cons InetAddress,I,Z");
@@ -444,15 +342,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#close()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException checking missing.",
- method = "close",
- args = {}
- )
public void test_close() throws IOException {
// Test for method void java.net.Socket.close()
int sport = startServer("SServer close");
@@ -472,34 +361,16 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#getInetAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInetAddress",
- args = {}
- )
public void test_getInetAddress() throws IOException {
// Test for method java.net.InetAddress java.net.Socket.getInetAddress()
int sport = startServer("SServer getInetAddress");
int portNumber = Support_PortManager.getNextPort();
s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
- assertTrue("Returned incorrect InetAdrees", s.getInetAddress().equals(
+ assertTrue("Returned incorrect InetAddress", s.getInetAddress().equals(
InetAddress.getLocalHost()));
}
- /**
- * @tests java.net.Socket#getInputStream()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInputStream",
- args = {}
- )
public void test_getInputStream() throws IOException {
// Simple fetch test
ServerSocket server = new ServerSocket(0);
@@ -511,15 +382,6 @@ public class SocketTest extends SocketTestCase {
server.close();
}
- /**
- * @tests java.net.Socket#getKeepAlive()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getKeepAlive",
- args = {}
- )
public void test_getKeepAlive() {
try {
int sport = startServer("SServer getKeepAlive");
@@ -553,15 +415,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#getLocalAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalAddress",
- args = {}
- )
public void test_getLocalAddress() throws IOException {
// Test for method java.net.InetAddress
// java.net.Socket.getLocalAddress()
@@ -571,7 +424,7 @@ public class SocketTest extends SocketTestCase {
assertEquals("Returned incorrect InetAddress",
InetAddress.getLocalHost(), s.getLocalAddress());
- // now validate thet behaviour when the any address is returned
+ // now validate that behaviour when the any address is returned
String preferIPv4StackValue = System
.getProperty("java.net.preferIPv4Stack");
String preferIPv6AddressesValue = System
@@ -598,15 +451,6 @@ public class SocketTest extends SocketTestCase {
}
- /**
- * @tests java.net.Socket#getLocalPort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalPort",
- args = {}
- )
public void test_getLocalPort() throws IOException {
// Test for method int java.net.Socket.getLocalPort()
int sport = startServer("SServer getLocalPort");
@@ -616,16 +460,7 @@ public class SocketTest extends SocketTestCase {
assertTrue("Returned incorrect port", s.getLocalPort() == portNumber);
}
- /**
- * @tests java.net.Socket#getOutputStream()
- */
@SuppressWarnings("deprecation")
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "IOException checking missing.",
- method = "getOutputStream",
- args = {}
- )
public void test_getOutputStream() throws IOException {
// Test for method java.io.OutputStream
// java.net.Socket.getOutputStream()
@@ -661,15 +496,6 @@ public class SocketTest extends SocketTestCase {
s.close();
}
- /**
- * @tests java.net.Socket#getPort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPort",
- args = {}
- )
public void test_getPort() throws IOException {
// Test for method int java.net.Socket.getPort()
int sport = startServer("SServer getPort");
@@ -679,15 +505,6 @@ public class SocketTest extends SocketTestCase {
s.getPort() == sport);
}
- /**
- * @tests java.net.Socket#getSoLinger()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSoLinger",
- args = {}
- )
public void test_getSoLinger() {
// Test for method int java.net.Socket.getSoLinger()
int sport = startServer("SServer getSoLinger");
@@ -717,15 +534,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#getReceiveBufferSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReceiveBufferSize",
- args = {}
- )
public void test_getReceiveBufferSize() {
try {
int sport = startServer("SServer getReceiveBufferSize");
@@ -753,15 +561,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#getSendBufferSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSendBufferSize",
- args = {}
- )
public void test_getSendBufferSize() {
int sport = startServer("SServer setSendBufferSize");
try {
@@ -789,15 +588,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#getSoTimeout()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSoTimeout",
- args = {}
- )
public void test_getSoTimeout() {
// Test for method int java.net.Socket.getSoTimeout()
int sport = startServer("SServer getSoTimeout");
@@ -825,15 +615,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#getTcpNoDelay()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getTcpNoDelay",
- args = {}
- )
public void test_getTcpNoDelay() {
// Test for method boolean java.net.Socket.getTcpNoDelay()
int sport = startServer("SServer getTcpNoDelay");
@@ -864,15 +645,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#setKeepAlive(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setKeepAlive",
- args = {boolean.class}
- )
public void test_setKeepAliveZ() throws Exception {
// There is not really a good test for this as it is there to detect
// crashed machines. Just make sure we can set it
@@ -905,15 +677,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#setSocketImplFactory(java.net.SocketImplFactory)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Verifies SecurityException.",
- method = "setSocketImplFactory",
- args = {java.net.SocketImplFactory.class}
- )
public void test_setSocketImplFactoryLjava_net_SocketImplFactory() {
// Test for method void
// java.net.Socket.setSocketImplFactory(java.net.SocketImplFactory)
@@ -946,15 +709,6 @@ public class SocketTest extends SocketTestCase {
}
- /**
- * @tests java.net.Socket#setSendBufferSize(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSendBufferSize",
- args = {int.class}
- )
public void test_setSendBufferSizeI() {
try {
int sport = startServer("SServer setSendBufferSizeI");
@@ -979,15 +733,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#setReceiveBufferSize(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setReceiveBufferSize",
- args = {int.class}
- )
public void test_setReceiveBufferSizeI() {
try {
int sport = startServer("SServer setReceiveBufferSizeI");
@@ -1012,15 +757,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#setSoLinger(boolean, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSoLinger",
- args = {boolean.class, int.class}
- )
public void test_setSoLingerZI() {
// Test for method void java.net.Socket.setSoLinger(boolean, int)
try {
@@ -1047,15 +783,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#setSoTimeout(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSoTimeout",
- args = {int.class}
- )
public void test_setSoTimeoutI() {
// Test for method void java.net.Socket.setSoTimeout(int)
try {
@@ -1081,15 +808,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#setTcpNoDelay(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTcpNoDelay",
- args = {boolean.class}
- )
public void test_setTcpNoDelayZ() {
// Test for method void java.net.Socket.setTcpNoDelay(boolean)
try {
@@ -1117,15 +835,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
public void test_toString() throws IOException {
// Test for method java.lang.String java.net.Socket.toString()
int sport = startServer("SServer toString");
@@ -1140,16 +849,7 @@ public class SocketTest extends SocketTestCase {
+ s.getLocalPort() + "]"));
}
- /**
- * @tests java.net.Socket#shutdownInput()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "shutdownInput",
- args = {}
- )
- @AndroidOnly("RI returns wrong value for EOF")
+ // AndroidOnly: RI returns wrong value for EOF
public void test_shutdownInput() throws Exception {
InetAddress addr = InetAddress.getLocalHost();
int port = Support_PortManager.getNextPort();
@@ -1187,15 +887,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#shutdownOutput()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "shutdownOutput",
- args = {}
- )
public void test_shutdownOutput() throws IOException {
InetAddress addr = InetAddress.getLocalHost();
int port = Support_PortManager.getNextPort();
@@ -1229,15 +920,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#getLocalSocketAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalSocketAddress",
- args = {}
- )
public void test_getLocalSocketAddress() throws IOException {
// set up server connect and then validate that we get the right
// response for the local address
@@ -1277,7 +959,7 @@ public class SocketTest extends SocketTestCase {
.getLocalHost(), portNumber)));
theSocket.close();
- // now validate thet behaviour when the any address is returned
+ // now validate that behaviour when the any address is returned
s = new Socket();
s.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
@@ -1325,15 +1007,6 @@ public class SocketTest extends SocketTestCase {
s.close();
}
- /**
- * @tests java.net.Socket#getRemoteSocketAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRemoteSocketAddress",
- args = {}
- )
public void test_getRemoteSocketAddress() throws IOException {
// set up server connect and then validate that we get the right
// response for the remote address
@@ -1371,15 +1044,6 @@ public class SocketTest extends SocketTestCase {
}
- /**
- * @tests java.net.Socket#isBound()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isBound",
- args = {}
- )
public void test_isBound() throws IOException {
InetAddress addr = InetAddress.getLocalHost();
int port = Support_PortManager.getNextPort();
@@ -1407,7 +1071,7 @@ public class SocketTest extends SocketTestCase {
theSocket.close();
serverSocket.close();
- // now test when we bind explicitely
+ // now test when we bind explicitly
InetSocketAddress theLocalAddress = new InetSocketAddress(InetAddress
.getLocalHost(), Support_PortManager.getNextPort());
theSocket = new Socket();
@@ -1421,15 +1085,6 @@ public class SocketTest extends SocketTestCase {
theSocket.isBound());
}
- /**
- * @tests java.net.Socket#isConnected()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isConnected",
- args = {}
- )
public void test_isConnected() throws IOException {
InetAddress addr = InetAddress.getLocalHost();
int port = Support_PortManager.getNextPort();
@@ -1457,15 +1112,6 @@ public class SocketTest extends SocketTestCase {
serverSocket.close();
}
- /**
- * @tests java.net.Socket#isClosed()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isClosed",
- args = {}
- )
public void test_isClosed() throws IOException {
InetAddress addr = InetAddress.getLocalHost();
int port = Support_PortManager.getNextPort();
@@ -1496,15 +1142,6 @@ public class SocketTest extends SocketTestCase {
.isClosed());
}
- /**
- * @tests java.net.Socket#bind(java.net.SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "bind",
- args = {java.net.SocketAddress.class}
- )
public void test_bindLjava_net_SocketAddress() throws IOException {
class mySocketAddress extends SocketAddress {
@@ -1574,7 +1211,7 @@ public class SocketTest extends SocketTestCase {
// now check the error conditions
- // Address that we have allready bound to
+ // Address that we have already bound to
theSocket = new Socket();
Socket theSocket2 = new Socket();
try {
@@ -1598,15 +1235,6 @@ public class SocketTest extends SocketTestCase {
theSocket.close();
}
- /**
- * @tests java.net.Socket#bind(java.net.SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- notes = "Checks bind on proxy.",
- method = "bind",
- args = {java.net.SocketAddress.class}
- )
public void test_bindLjava_net_SocketAddress_Proxy() throws IOException {
//The Proxy will not impact on the bind operation.It can be assigned with any address.
Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 0));
@@ -1625,15 +1253,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#connect(java.net.SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "connect",
- args = {java.net.SocketAddress.class}
- )
public void test_connectLjava_net_SocketAddress() throws Exception {
// needed for some tests
class mySocketAddress extends SocketAddress {
@@ -1727,7 +1346,7 @@ public class SocketTest extends SocketTestCase {
+ e.toString(), (e instanceof ConnectException));
}
- // now validate that we can acutally connect when sombody is listening
+ // now validate that we can actually connect when somebody is listening
theSocket = new Socket();
serverSocket = new ServerSocket();
serverSocket.bind(theAddress);
@@ -1735,7 +1354,7 @@ public class SocketTest extends SocketTestCase {
theSocket.close();
serverSocket.close();
- // now validate that we can acutally connect when sombody is listening
+ // now validate that we can actually connect when somebody is listening
theSocket = new Socket();
serverSocket = new ServerSocket();
serverSocket.bind(theAddress);
@@ -1852,15 +1471,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#connect(java.net.SocketAddress, int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "connect",
- args = {java.net.SocketAddress.class, int.class}
- )
public void test_connectLjava_net_SocketAddressI() throws Exception {
// needed for some tests
@@ -1992,7 +1602,7 @@ public class SocketTest extends SocketTestCase {
+ e.toString(), (e instanceof ConnectException));
}
- // now validate that we can acutally connect when sombody is listening
+ // now validate that we can actually connect when somebody is listening
theSocket = new Socket();
serverSocket = new ServerSocket();
serverSocket.bind(theAddress);
@@ -2043,7 +1653,7 @@ public class SocketTest extends SocketTestCase {
(e instanceof SocketTimeoutException));
}
- // now validate that we can acutally connect when sombody is listening
+ // now validate that we can actually connect when somebody is listening
new InetSocketAddress(InetAddress.getLocalHost(), Support_PortManager
.getNextPort());
theSocket = new Socket();
@@ -2086,10 +1696,10 @@ public class SocketTest extends SocketTestCase {
} catch (Exception e) {
assertTrue(
- "Wrong exception when connecting on socket that is allready connected"
+ "Wrong exception when connecting on socket that is already connected"
+ e.toString(), (e instanceof SocketException));
assertFalse(
- "Wrong exception when connecting on socket that is allready connected"
+ "Wrong exception when connecting on socket that is already connected"
+ e.toString(),
(e instanceof SocketTimeoutException));
try {
@@ -2182,15 +1792,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#isInputShutdown()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isInputShutdown",
- args = {}
- )
public void test_isInputShutdown() throws IOException {
InetSocketAddress theAddress = new InetSocketAddress(InetAddress
.getLocalHost(), Support_PortManager.getNextPort());
@@ -2224,15 +1825,6 @@ public class SocketTest extends SocketTestCase {
}
- /**
- * @tests java.net.Socket#isOutputShutdown()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isOutputShutdown",
- args = {}
- )
public void test_isOutputShutdown() throws IOException {
InetSocketAddress theAddress = new InetSocketAddress(InetAddress
.getLocalHost(), Support_PortManager.getNextPort());
@@ -2266,15 +1858,6 @@ public class SocketTest extends SocketTestCase {
}
- /**
- * @tests java.net.Socket#setReuseAddress(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setReuseAddress",
- args = {boolean.class}
- )
public void test_setReuseAddressZ() {
try {
@@ -2333,7 +1916,7 @@ public class SocketTest extends SocketTestCase {
theSocket.close();
theSocket2.close();
- // try to bind to port that is allready in use with reuseAddress
+ // try to bind to port that is already in use with reuseAddress
// = true
theLocalAddress = new InetSocketAddress(
(InetAddress) allAddresses[0], Support_PortManager
@@ -2407,15 +1990,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#getReuseAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReuseAddress",
- args = {}
- )
public void test_getReuseAddress() {
try {
Socket theSocket = new Socket();
@@ -2444,15 +2018,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#setOOBInline(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setOOBInline",
- args = {boolean.class}
- )
public void test_setOOBInlineZ() {
// mostly tested in getOOBInline. Just set to make sure call works ok
try {
@@ -2478,15 +2043,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#getOOBInline()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getOOBInline",
- args = {}
- )
public void test_getOOBInline() {
try {
@@ -2518,21 +2074,10 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#setTrafficClass(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setTrafficClass",
- args = {int.class}
- )
public void test_setTrafficClassI() {
try {
int IPTOS_LOWCOST = 0x2;
- int IPTOS_RELIABILTY = 0x4;
int IPTOS_THROUGHPUT = 0x8;
- int IPTOS_LOWDELAY = 0x10;
new InetSocketAddress(InetAddress.getLocalHost(),
Support_PortManager.getNextPort());
@@ -2571,22 +2116,8 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#getTrafficClass()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SocketException checking missing.",
- method = "getTrafficClass",
- args = {}
- )
public void test_getTrafficClass() {
try {
- int IPTOS_LOWCOST = 0x2;
- int IPTOS_RELIABILTY = 0x4;
- int IPTOS_THROUGHPUT = 0x8;
- int IPTOS_LOWDELAY = 0x10;
-
new InetSocketAddress(InetAddress.getLocalHost(),
Support_PortManager.getNextPort());
Socket theSocket = new Socket();
@@ -2603,15 +2134,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests java.net.Socket#getChannel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getChannel",
- args = {}
- )
public void test_getChannel() throws Exception {
assertNull(new Socket().getChannel());
@@ -2622,15 +2144,6 @@ public class SocketTest extends SocketTestCase {
channel.close();
}
- /**
- * @tests java.net.Socket#sendUrgentData(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sendUrgentData",
- args = {int.class}
- )
public void test_sendUrgentDataI() {
// Some platforms may not support urgent data in this case we will not
@@ -2944,29 +2457,11 @@ public class SocketTest extends SocketTestCase {
}
}
- /*
- * @tests java.net.Socket#setPerformancePreference()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setPerformancePreferences",
- args = {int.class, int.class, int.class}
- )
public void test_setPerformancePreference_Int_Int_Int() throws Exception {
Socket theSocket = new Socket();
theSocket.setPerformancePreferences(1, 1, 1);
}
- /**
- * @tests java.net.Socket#Socket(Proxy)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Socket",
- args = {java.net.Proxy.class}
- )
public void test_ConstructorLjava_net_Proxy_Exception() {
SocketAddress addr1 = InetSocketAddress.createUnresolved("127.0.0.1",
@@ -3041,12 +2536,6 @@ public class SocketTest extends SocketTestCase {
}
}
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SocketException depends on the underlying protocol.",
- method = "Socket",
- args = {SocketImpl.class}
- )
public void test_ConstructorLSocketImpl() {
MockSocketImpl msi = new MockSocketImpl();
try {
@@ -3056,15 +2545,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests Socket#connect(SocketAddress) try an unknownhost
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "UnknownHostException checking only.",
- method = "connect",
- args = {java.net.SocketAddress.class, int.class}
- )
public void test_connect_unknownhost() throws Exception {
Socket socket = new Socket();
InetSocketAddress socketAddress = new InetSocketAddress("unknownhost", 12345);
@@ -3076,16 +2556,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests Socket#connect(SocketAddress) try an unknownhost created by
- * createUnresolved()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "UnknownHostException checking only.",
- method = "connect",
- args = {java.net.SocketAddress.class, int.class}
- )
public void test_connect_unresolved_unknown() throws Exception {
Socket socket = new Socket();
InetSocketAddress unresolved = InetSocketAddress.createUnresolved("unknownhost", 12345);
@@ -3097,16 +2567,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests Socket#connect(SocketAddress) try a known host created by
- * createUnresolved()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "UnknownHostException checking only.",
- method = "connect",
- args = {java.net.SocketAddress.class, int.class}
- )
public void test_connect_unresolved() throws Exception {
Socket socket = new Socket();
InetSocketAddress unresolvedSocketAddress = InetSocketAddress.createUnresolved(
@@ -3120,15 +2580,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests Socket#getOutputStream()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "SocketException, IllegalBlockingModeException checking.",
- method = "getOutputStream",
- args = {}
- )
public void test_getOutputStream_shutdownOutput() throws Exception {
// regression test for Harmony-873
ServerSocket ss = new ServerSocket(0);
@@ -3165,16 +2616,6 @@ public class SocketTest extends SocketTestCase {
}
}
- /**
- * @tests Socket#shutdownInput()
- * @tests Socket#shutdownOutput()
- */
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- notes = "Regression test.",
- method = "shutdownInput",
- args = {}
- )
public void test_shutdownInputOutput_twice() throws Exception {
// regression test for Harmony-2944
Socket s = new Socket("0.0.0.0", 0, false);
@@ -3263,86 +2704,60 @@ public class SocketTest extends SocketTestCase {
@Override
protected void accept(SocketImpl arg0) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected int available() throws IOException {
- // TODO Auto-generated method stub
return 0;
}
@Override
protected void bind(InetAddress arg0, int arg1) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected void close() throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected void connect(String arg0, int arg1) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected void connect(InetAddress arg0, int arg1) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected void connect(SocketAddress arg0, int arg1) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected void create(boolean arg0) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected InputStream getInputStream() throws IOException {
- // TODO Auto-generated method stub
return null;
}
@Override
protected OutputStream getOutputStream() throws IOException {
- // TODO Auto-generated method stub
return null;
}
@Override
protected void listen(int arg0) throws IOException {
- // TODO Auto-generated method stub
-
}
@Override
protected void sendUrgentData(int arg0) throws IOException {
- // TODO Auto-generated method stub
-
}
public Object getOption(int arg0) throws SocketException {
- // TODO Auto-generated method stub
return null;
}
public void setOption(int arg0, Object arg1) throws SocketException {
- // TODO Auto-generated method stub
-
}
-
}
-
}
diff --git a/luni/src/test/java/tests/api/java/net/SocketTestCase.java b/luni/src/test/java/libcore/java/net/OldSocketTestCase.java
index f9607a9..bcb6af9 100644
--- a/luni/src/test/java/tests/api/java/net/SocketTestCase.java
+++ b/luni/src/test/java/libcore/java/net/OldSocketTestCase.java
@@ -15,12 +15,11 @@
* limitations under the License.
*/
-package tests.api.java.net;
+package libcore.java.net;
-import dalvik.annotation.TestTargetClass;
+import junit.framework.TestCase;
-@TestTargetClass(java.net.Socket.class)
-public abstract class SocketTestCase extends junit.framework.TestCase {
+public abstract class OldSocketTestCase extends TestCase {
public static final int SO_MULTICAST = 0;
@@ -48,21 +47,12 @@ public abstract class SocketTestCase extends junit.framework.TestCase {
public static final int SO_USELOOPBACK = 12;
- public static final String LINUX = "Linux";
-
private static final String osDoesNotSupportOperationString = "The socket does not support the operation";
private static final String osDoesNotSupportOptionString = "The socket option is not supported";
private static final String osDoesNotSupportOptionArgumentString = "The socket option arguments are invalid";
- public SocketTestCase() {
- }
-
- public SocketTestCase(String name) {
- super(name);
- }
-
/**
* Answer whether the OS supports the given socket option.
*/
@@ -129,8 +119,6 @@ public abstract class SocketTestCase extends junit.framework.TestCase {
*/
public void ensureExceptionThrownIfOptionIsUnsupportedOnOS(int option) {
if (!getOptionIsSupported(option)) {
- String platform = System.getProperty("os.name");
- String version = System.getProperty("os.version");
fail("Failed to throw exception for unsupported socket option: "
+ getSocketOptionString(option));
}
diff --git a/luni/src/test/java/libcore/java/net/OldURITest.java b/luni/src/test/java/libcore/java/net/OldURITest.java
new file mode 100644
index 0000000..21d3447
--- /dev/null
+++ b/luni/src/test/java/libcore/java/net/OldURITest.java
@@ -0,0 +1,150 @@
+/*
+ * 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 libcore.java.net;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import junit.framework.TestCase;
+
+public class OldURITest extends TestCase {
+
+ String[] constructorTests = new String[] {
+ "http://user@www.google.com:45/search?q=helpinfo#somefragment",
+ // http with authority, query and fragment
+ "ftp://ftp.is.co.za/rfc/rfc1808.txt", // ftp
+ "gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles", // gopher
+ "mailto:mduerst@ifi.unizh.ch", // mailto
+ "news:comp.infosystems.www.servers.unix", // news
+ "telnet://melvyl.ucop.edu/", // telnet
+ "http://123.24.17.98/test", // IPv4 authority
+ "http://www.google.com:80/test",// domain name authority
+ "http://joe@[3ffe:2a00:100:7031::1]:80/test",
+ // IPv6 authority, with userinfo and port
+ "/relative", // relative starting with /
+ "//relative", // relative starting with //
+ "relative", // relative with no /
+ "#fragment",// relative just with fragment
+ "http://user@host:80", // UI, host,port
+ "http://user@host", // ui, host
+ "http://host", // host
+ "http://host:80", // host,port
+ "http://joe@:80", // ui, port (becomes registry-based)
+ "file:///foo/bar", // empty authority, non empty path
+ "ht?tp://hoe@host:80", // miscellaneous tests
+ "mai/lto:hey?joe#man", "http://host/a%20path#frag",
+ // path with an escaped octet for space char
+ "http://host/a%E2%82%ACpath#frag",
+ // path with escaped octet for unicode char, not USASCII
+ "http://host/a\u20ACpath#frag",
+ // path with unicode char, not USASCII equivalent to
+ // = "http://host/a\u0080path#frag",
+ "http://host%20name/", // escaped octets in host (becomes
+ // registry based)
+ "http://host\u00DFname/", // unicodechar in host (becomes
+ // registry based)
+ // equivalent to = "http://host\u00dfname/",
+ "ht123-+tp://www.google.com:80/test", // legal chars in scheme
+ };
+
+ String[] constructorTestsInvalid = new String[] {
+ "http:///a path#frag", // space char in path, not in escaped
+ // octet form, with no host
+ "http://host/a[path#frag", // an illegal char, not in escaped
+ // octet form, should throw an
+ // exception
+ "http://host/a%path#frag", // invalid escape sequence in path
+ "http://host/a%#frag", // incomplete escape sequence in path
+
+ "http://host#a frag", // space char in fragment, not in
+ // escaped octet form, no path
+ "http://host/a#fr#ag", // illegal char in fragment
+ "http:///path#fr%ag", // invalid escape sequence in fragment,
+ // with no host
+ "http://host/path#frag%", // incomplete escape sequence in
+ // fragment
+
+ "http://host/path?a query#frag", // space char in query, not
+ // in escaped octet form
+ "http://host?query%ag", // invalid escape sequence in query, no
+ // path
+ "http:///path?query%", // incomplete escape sequence in query,
+ // with no host
+
+ "mailto:user^name@fklkf.com" // invalid char in scheme specific part
+ };
+
+ public void test_createLjava_lang_String() {
+ for (String s : constructorTests) {
+ try {
+ new URI(s);
+ } catch (URISyntaxException e) {
+ fail("Failed to construct URI for: " + s + " : " + e);
+ }
+ }
+
+ for (String s : constructorTestsInvalid) {
+ try {
+ URI.create(s);
+ fail("IllegalArgumentException expected but not received.");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+ }
+
+ public void test_relativizeLjava_net_URI() throws URISyntaxException {
+ try {
+ URI b = new URI("http://www.google.com/dir1/dir2");
+ b.relativize(null);
+ fail("NullPointerException was not thrown.");
+ } catch(NullPointerException expected) {
+ }
+ }
+
+ public void test_resolveLjava_net_URI() throws URISyntaxException {
+ try {
+ URI b = new URI("http://www.test.com/dir");
+ b.resolve((URI) null);
+ fail("NullPointerException was not thrown.");
+ } catch(NullPointerException expected) {
+ }
+ }
+
+ public void test_resolveLjava_lang_String() throws URISyntaxException {
+ try {
+ URI b = new URI("http://www.test.com/dir");
+ b.resolve((String) null);
+ fail("NullPointerException was not thrown.");
+ } catch(NullPointerException expected) {
+ }
+
+ try {
+ URI b = new URI("http://www.test.com/dir");
+ b.resolve("http://a/b/c/g?y/./x\n");
+ fail("IllegalArgumentException was not thrown.");
+ } catch(IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_ConstructorLjava_lang_String() throws URISyntaxException {
+ try {
+ new URI(null);
+ fail("NullPointerException was not thrown.");
+ } catch(NullPointerException expected) {
+ }
+ }
+}
diff --git a/luni/src/test/java/tests/api/java/net/URLDecoderTest.java b/luni/src/test/java/libcore/java/net/OldURLDecoderTest.java
index cf206b9..86a2961 100644
--- a/luni/src/test/java/tests/api/java/net/URLDecoderTest.java
+++ b/luni/src/test/java/libcore/java/net/OldURLDecoderTest.java
@@ -15,72 +15,16 @@
* limitations under the License.
*/
-package tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
+package libcore.java.net;
import java.io.UnsupportedEncodingException;
-import java.net.URL;
import java.net.URLDecoder;
-import java.net.URLEncoder;
-
+import junit.framework.TestCase;
import tests.support.Support_Configuration;
-@TestTargetClass(URLDecoder.class)
-public class URLDecoderTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.URLDecoder#URLDecoder()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URLDecoder",
- args = {}
- )
- public void test_Constructor() throws Exception {
- URLDecoder ud = new URLDecoder();
- assertNotNull("Constructor failed.", ud);
- }
-
- /**
- * @tests java.net.URLDecoder#decode(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {java.lang.String.class}
- )
- public void test_decodeLjava_lang_String() throws Exception {
- // Test for method java.lang.String
- // java.net.URLDecoder.decode(java.lang.String)
- final String URL = "http://" + Support_Configuration.HomeAddress;
- final String URL2 = "telnet://justWantToHaveFun.com:400";
- final String URL3 = "file://myServer.org/a file with spaces.jpg";
- assertTrue("1. Incorrect encoding/decoding", URLDecoder.decode(
- URLEncoder.encode(URL)).equals(URL));
- assertTrue("2. Incorrect encoding/decoding", URLDecoder.decode(
- URLEncoder.encode(URL2)).equals(URL2));
- assertTrue("3. Incorrect encoding/decoding", URLDecoder.decode(
- URLEncoder.encode(URL3)).equals(URL3));
- }
+public class OldURLDecoderTest extends TestCase {
- /**
- * @tests java.net.URLDecoder#decode(java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "decode",
- args = {java.lang.String.class, java.lang.String.class}
- )
public void test_decodeLjava_lang_String_Ljava_lang_String() {
- // Regression for HARMONY-467
-
String enc = "UTF-8";
String [] urls = { "http://" + Support_Configuration.HomeAddress +
@@ -109,12 +53,5 @@ public class URLDecoderTest extends junit.framework.TestCase {
} catch (UnsupportedEncodingException e) {
fail("UnsupportedEncodingException: " + e.getMessage());
}
-
- try {
- URLDecoder.decode("", "");
- fail("UnsupportedEncodingException expected");
- } catch (UnsupportedEncodingException e) {
- //expected
- }
}
}
diff --git a/luni/src/test/java/tests/api/java/net/URLEncoderTest.java b/luni/src/test/java/libcore/java/net/OldURLEncoderTest.java
index 12d1c17..8616e2c 100644
--- a/luni/src/test/java/tests/api/java/net/URLEncoderTest.java
+++ b/luni/src/test/java/libcore/java/net/OldURLEncoderTest.java
@@ -15,55 +15,16 @@
* limitations under the License.
*/
-package tests.api.java.net;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
+package libcore.java.net;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
-
+import junit.framework.TestCase;
import tests.support.Support_Configuration;
-@TestTargetClass(URLEncoder.class)
-public class URLEncoderTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.URLEncoder#encode(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "encode",
- args = {java.lang.String.class}
- )
- public void test_encodeLjava_lang_String() {
- // Test for method java.lang.String
- // java.net.URLEncoder.encode(java.lang.String)
- final String URL = "http://" + Support_Configuration.HomeAddress;
- final String URL2 = "telnet://justWantToHaveFun.com:400";
- final String URL3 = "file://myServer.org/a file with spaces.jpg";
- try {
- assertTrue("1. Incorrect encoding/decoding", URLDecoder.decode(
- URLEncoder.encode(URL)).equals(URL));
- assertTrue("2. Incorrect encoding/decoding", URLDecoder.decode(
- URLEncoder.encode(URL2)).equals(URL2));
- assertTrue("3. Incorrect encoding/decoding", URLDecoder.decode(
- URLEncoder.encode(URL3)).equals(URL3));
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
+public class OldURLEncoderTest extends TestCase {
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "encode",
- args = {java.lang.String.class, java.lang.String.class}
- )
public void test_encodeLjava_lang_StringLjava_lang_String() {
String enc = "UTF-8";
@@ -102,20 +63,5 @@ public class URLEncoderTest extends junit.framework.TestCase {
} catch (UnsupportedEncodingException e) {
//expected
}
-
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
}
}
diff --git a/luni/src/test/java/tests/api/java/net/URLStreamHandlerTest.java b/luni/src/test/java/libcore/java/net/OldURLStreamHandlerTest.java
index 6849c9f..a6804be 100644
--- a/luni/src/test/java/tests/api/java/net/URLStreamHandlerTest.java
+++ b/luni/src/test/java/libcore/java/net/OldURLStreamHandlerTest.java
@@ -1,10 +1,4 @@
-package tests.api.java.net;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-import junit.framework.TestCase;
+package libcore.java.net;
import java.io.IOException;
import java.net.InetAddress;
@@ -14,56 +8,33 @@ import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.UnknownHostException;
+import junit.framework.TestCase;
-@TestTargetClass(URLStreamHandler.class)
-public class URLStreamHandlerTest extends TestCase {
+public class OldURLStreamHandlerTest extends TestCase {
MockURLStreamHandler handler = null;
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {URL.class, URL.class}
- )
- public void test_equalsLjava_net_URLLjava_net_URL() {
+ public void test_equalsLjava_net_URLLjava_net_URL() throws MalformedURLException {
+ URL url1 = new URL("ftp://test_url/test?a=b&c=%D0+%D1");
+ URL url2 = new URL("http://test_url/test?a=b&c=%D0+%D1");
+ assertFalse(url1.equals(url2));
+
+ new URL("http://test_url+/test?a=b&c=%D0+%D1");
+ assertFalse(handler.equals(url1,url2));
+
try {
- URL url1 = new URL("ftp://test_url/test?a=b&c=%D0+%D1");
- URL url2 = new URL("http://test_url/test?a=b&c=%D0+%D1");
- assertFalse(url1.equals(url2));
-
- URL url3 = new URL("http://test_url+/test?a=b&c=%D0+%D1");
- assertFalse(handler.equals(url1,url2));
-
- try {
- assertFalse(handler.equals(null, url1));
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- } catch (MalformedURLException e) {
- fail("MalformedURLException was thrown.");
+ assertFalse(handler.equals(null, url1));
+ fail("NullPointerException was not thrown.");
+ } catch(NullPointerException npe) {
+ //expected
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getDefaultPort",
- args = {}
- )
public void test_getDefaultPort() {
assertEquals(-1, handler.getDefaultPort());
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHostAddress",
- args = {URL.class}
- )
- public void test_getHostAddress() throws MalformedURLException,
- UnknownHostException {
+ public void test_getHostAddress() throws MalformedURLException, UnknownHostException {
URL url1 = new URL("ftp://test_url/test?a=b&c=%D0+%D1");
assertNull(handler.getHostAddress(url1));
@@ -74,40 +45,22 @@ public class URLStreamHandlerTest extends TestCase {
assertEquals(InetAddress.getLocalHost(), handler.getHostAddress(url3));
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {URL.class}
- )
- public void test_hashCodeLjava_net_URL() {
+ public void test_hashCodeLjava_net_URL() throws MalformedURLException {
+ URL url1 = new URL("ftp://test_url/test?a=b&c=%D0+%D1");
+ URL url2 = new URL("http://test_url/test?a=b&c=%D0+%D1");
+ assertTrue(handler.hashCode(url1) != handler.hashCode(url2));
+
+ new URL("http://test_url+/test?a=b&c=%D0+%D1");
+ assertFalse(handler.equals(url1,url2));
+
try {
- URL url1 = new URL("ftp://test_url/test?a=b&c=%D0+%D1");
- URL url2 = new URL("http://test_url/test?a=b&c=%D0+%D1");
- assertTrue(handler.hashCode(url1) != handler.hashCode(url2));
-
- URL url3 = new URL("http://test_url+/test?a=b&c=%D0+%D1");
- assertFalse(handler.equals(url1,url2));
-
- try {
- handler.hashCode(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- } catch (MalformedURLException e) {
- fail("MalformedURLException was thrown.");
+ handler.hashCode(null);
+ fail("NullPointerException was not thrown.");
+ } catch(NullPointerException expected) {
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hostsEqual",
- args = {URL.class, URL.class}
- )
- public void test_hostsEqualLjava_net_URLLjava_net_URL() throws
- MalformedURLException {
+ public void test_hostsEqualLjava_net_URLLjava_net_URL() throws MalformedURLException {
URL url1 = new URL("ftp://localhost:21/*test");
URL url2 = new URL("http://127.0.0.1/_test");
assertTrue(handler.hostsEqual(url1, url2));
@@ -116,23 +69,11 @@ public class URLStreamHandlerTest extends TestCase {
assertFalse(handler.hostsEqual(url1, url3));
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "openConnection",
- args = { URL.class }
- )
public void test_openConnectionLjava_net_URL() throws IOException {
// abstract method, it doesn't check anything
assertNull(handler.openConnection(null));
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "openConnection",
- args = {URL.class, Proxy.class}
- )
public void test_openConnectionLjava_net_URLLjava_net_Proxy() {
try {
handler.openConnection(null, null);
@@ -144,13 +85,6 @@ public class URLStreamHandlerTest extends TestCase {
}
}
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Completed testing of this method requres set up " +
- "URLStreamHandlerFactory that can be done at most once.",
- method = "parseURL",
- args = {URL.class, String.class, int.class, int.class}
- )
public void test_parseURLLjava_net_URLLjava_lang_StringII()
throws MalformedURLException {
String str = "http://test.org/foo?a=123&b=%D5D6D7&c=++&d=";
@@ -164,12 +98,6 @@ public class URLStreamHandlerTest extends TestCase {
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "sameFile",
- args = {URL.class, URL.class}
- )
public void test_sameFile() throws MalformedURLException {
URL url1 = new URL("http://test:pwd@localhost:80/foo/foo1.c");
URL url2 = new URL("http://test:pwd@127.0.01:80/foo/foo1.c");
@@ -185,36 +113,16 @@ public class URLStreamHandlerTest extends TestCase {
assertFalse("Test case 5", handler.sameFile(url1, url6));
}
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Completed testing of this method requres set up " +
- "URLStreamHandlerFactory that can be done at most once.",
- method = "setURL",
- args = {java.net.URL.class, java.lang.String.class,
- java.lang.String.class, int.class, java.lang.String.class,
- java.lang.String.class}
- )
public void test_setURL1() throws MalformedURLException {
URL url = new URL("http://test.org");
try {
handler.setURL(url, "http", "localhost", 80, "foo.c", "ref");
fail("SecurityException should be thrown.");
- } catch(SecurityException se) {
- //SecurityException is expected
+ } catch(SecurityException expected) {
}
}
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Completed testing of this method requres set up " +
- "URLStreamHandlerFactory that can be done at most once.",
- method = "setURL",
- args = {java.net.URL.class, 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 test_setURL2() throws MalformedURLException {
URL url = new URL("http://test.org");
@@ -222,34 +130,21 @@ public class URLStreamHandlerTest extends TestCase {
handler.setURL(url, "http", "localhost", 80, "authority",
"user", "foo.c", "query", "ref");
fail("SecurityException should be thrown.");
- } catch(SecurityException se) {
- //SecurityException is expected
+ } catch(SecurityException expected) {
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toExternalForm",
- args = {URL.class}
- )
public void test_toExternalForm() throws MalformedURLException {
URL [] urls = { new URL("ftp://test_url/test?a=b&c=%D0+%D1"),
new URL("http://test_url/test?a=b&c=%D0+%D1"),
new URL("http://test:pwd@localhost:80/foo/foo1.c")};
- for(URL url:urls) {
+ for(URL url : urls) {
assertEquals("Test case for " + url.toString(),
url.toString(), handler.toExternalForm(url));
}
}
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URLStreamHandler",
- args = {}
- )
public void test_Constructor() {
MockURLStreamHandler msh = new MockURLStreamHandler();
assertEquals(-1, msh.getDefaultPort());
@@ -263,7 +158,6 @@ public class URLStreamHandlerTest extends TestCase {
@Override
protected URLConnection openConnection(URL arg0) throws IOException {
- // TODO Auto-generated method stub
return null;
}
diff --git a/luni/src/test/java/libcore/java/net/OldURLTest.java b/luni/src/test/java/libcore/java/net/OldURLTest.java
index 6b3dfa0..9953451 100644
--- a/luni/src/test/java/libcore/java/net/OldURLTest.java
+++ b/luni/src/test/java/libcore/java/net/OldURLTest.java
@@ -292,31 +292,22 @@ public class OldURLTest extends TestCase {
args = {java.lang.Object.class}
)
public void testEqualsObject() throws MalformedURLException {
- URL testURL1 = new URL("http", "www.apache.org:8080", "test.html");
- URL wrongProto = new URL("ftp", "www.apache.org:8080", "test.html");
- URL wrongPort = new URL("http", "www.apache.org:8082", "test.html");
- URL wrongHost = new URL("http", "www.apache2.org:8080", "test.html");
- URL wrongRef = new URL("http", "www.apache.org:8080",
- "test2.html#BOTTOM");
+ URL testURL1 = new URL("http", "www.apache.org", 8080, "test.html");
+ URL wrongProto = new URL("ftp", "www.apache.org", 8080, "test.html");
+ URL wrongPort = new URL("http", "www.apache.org", 8082, "test.html");
+ URL wrongHost = new URL("http", "www.apache2.org", 8080, "test.html");
+ URL wrongRef = new URL("http", "www.apache.org", 8080, "test2.html#BOTTOM");
URL testURL2 = new URL("http://www.apache.org:8080/test.html");
-
- assertFalse("Assert 0: error in equals: not same", testURL1
- .equals(wrongProto));
- assertFalse("Assert 1: error in equals: not same", testURL1
- .equals(wrongPort));
- assertFalse("Assert 2: error in equals: not same", testURL1
- .equals(wrongHost));
- assertFalse("Assert 3: error in equals: not same", testURL1
- .equals(wrongRef));
-
- assertFalse("Assert 4: error in equals: not same", testURL1
- .equals(testURL2));
+ assertFalse("Assert 0: error in equals: not same", testURL1.equals(wrongProto));
+ assertFalse("Assert 1: error in equals: not same", testURL1.equals(wrongPort));
+ assertFalse("Assert 2: error in equals: not same", testURL1.equals(wrongHost));
+ assertFalse("Assert 3: error in equals: not same", testURL1.equals(wrongRef));
+ assertFalse("Assert 4: error in equals: not same", testURL1.equals(testURL2));
URL testURL3 = new URL("http", "www.apache.org", "/test.html");
URL testURL4 = new URL("http://www.apache.org/test.html");
- assertTrue("Assert 4: error in equals: same", testURL3
- .equals(testURL4));
+ assertTrue("Assert 4: error in equals: same", testURL3.equals(testURL4));
}
/**
diff --git a/luni/src/test/java/libcore/java/net/URLConnectionTest.java b/luni/src/test/java/libcore/java/net/URLConnectionTest.java
index 36791c1..32d0385 100644
--- a/luni/src/test/java/libcore/java/net/URLConnectionTest.java
+++ b/luni/src/test/java/libcore/java/net/URLConnectionTest.java
@@ -330,10 +330,21 @@ public class URLConnectionTest extends junit.framework.TestCase {
assertCached(false, 300);
}
- public void test_responseCaching_407() throws Exception {
- // This test will fail on Android because we throw if we're not using a proxy.
- // This isn't true of the RI, but it seems like useful debugging behavior.
- assertCached(false, 407);
+ /**
+ * Response code 407 should only come from proxy servers. Android's client
+ * throws if it is sent by an origin server.
+ */
+ public void testOriginServerSends407() throws Exception {
+ server.enqueue(new MockResponse().setResponseCode(407));
+ server.play();
+
+ URL url = server.getUrl("/");
+ HttpURLConnection conn = (HttpURLConnection) url.openConnection();
+ try {
+ conn.getResponseCode();
+ fail();
+ } catch (IOException expected) {
+ }
}
public void test_responseCaching_410() throws Exception {
diff --git a/luni/src/test/java/libcore/javax/net/ServerSocketFactoryTest.java b/luni/src/test/java/libcore/javax/net/ServerSocketFactoryTest.java
new file mode 100644
index 0000000..77996dd
--- /dev/null
+++ b/luni/src/test/java/libcore/javax/net/ServerSocketFactoryTest.java
@@ -0,0 +1,131 @@
+/*
+ * 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 libcore.javax.net;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import javax.net.ServerSocketFactory;
+import junit.framework.TestCase;
+
+public class ServerSocketFactoryTest extends TestCase {
+
+ public void testCreateServerSocket() throws IOException {
+ ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket();
+ serverSocket.bind(new InetSocketAddress(0));
+ testSocket(serverSocket, 50);
+ }
+
+ public void testCreateServerSocketWithPort() throws IOException {
+ ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(0);
+ testSocket(serverSocket, 50);
+ }
+
+ public void testCreateServerSocketWithPortNoBacklog() throws IOException {
+ ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(0, 1);
+ testSocket(serverSocket, 1);
+ }
+
+ public void testCreateServerSocketWithPortZeroBacklog() throws IOException {
+ ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(0, 0);
+ testSocket(serverSocket, 50);
+ }
+
+ public void testCreateServerSocketWithPortAndBacklog() throws IOException {
+ ServerSocket serverSocket = ServerSocketFactory.getDefault().createServerSocket(0, 50);
+ testSocket(serverSocket, 50);
+ }
+
+ private void testSocket(final ServerSocket serverSocket, int specifiedBacklog)
+ throws IOException {
+ final byte[] data = "abc".getBytes();
+
+ new Thread(new Runnable() {
+ public void run() {
+ try {
+ Socket s = serverSocket.accept();
+ s.getOutputStream().write(data);
+ s.close();
+ } catch (IOException e) {
+ }
+ }
+ }).start();
+
+ Socket socket = new Socket(InetAddress.getLocalHost(), serverSocket.getLocalPort());
+ assertBacklog(specifiedBacklog, new InetSocketAddress(
+ InetAddress.getLocalHost(), serverSocket.getLocalPort()));
+
+ InputStream in = socket.getInputStream();
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ transfer(in, out);
+ assertEquals(Arrays.toString(data), Arrays.toString(out.toByteArray()));
+ socket.close();
+
+ serverSocket.close();
+ }
+
+ /**
+ * Validates that the backlog of the listening address is as specified.
+ */
+ private void assertBacklog(int specifiedBacklog, InetSocketAddress serverAddress)
+ throws IOException {
+ List<Socket> backlog = new ArrayList<Socket>();
+ int peak = 0;
+ try {
+ int max = 100;
+ for (int i = 0; i < max; i++) {
+ Socket socket = new Socket();
+ backlog.add(socket);
+ socket.connect(serverAddress, 500);
+ peak++;
+ }
+ fail("Failed to exhaust backlog after " + max + " connections!");
+ } catch (IOException expected) {
+ }
+
+ System.out.println("backlog peaked at " + peak);
+
+ for (Socket socket : backlog) {
+ socket.close();
+ }
+
+ /*
+ * In 4.5 of UNIX Network Programming, Stevens says:
+ * "Berkeley-derived implementations add a fudge factor to the
+ * backlog: it is multiplied by 1.5."
+ *
+ * We've observed that Linux always adds 3 to the user-specified
+ * backlog.
+ */
+ assertTrue(peak >= specifiedBacklog && peak <= (specifiedBacklog + 3) * 1.5);
+ }
+
+ private void transfer(InputStream in, ByteArrayOutputStream out) throws IOException {
+ byte[] buffer = new byte[1024];
+ int count;
+ while ((count = in.read(buffer)) != -1) {
+ out.write(buffer, 0, count);
+ }
+ }
+}
diff --git a/luni/src/test/java/tests/api/java/net/AllTests.java b/luni/src/test/java/tests/api/java/net/AllTests.java
deleted file mode 100644
index 7fff379..0000000
--- a/luni/src/test/java/tests/api/java/net/AllTests.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2007 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.api.java.net;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * This is autogenerated source file. Includes tests for package tests.api.java.net;
- */
-
-public class AllTests {
- public static Test suite() {
- TestSuite suite = new TestSuite("All tests for package tests.api.java.net;");
- // $JUnit-BEGIN$
-
- suite.addTestSuite(AuthenticatorRequestorTypeTest.class);
- suite.addTestSuite(AuthenticatorTest.class);
- suite.addTestSuite(BindExceptionTest.class);
- suite.addTestSuite(CacheRequestTest.class);
- suite.addTestSuite(CacheResponseTest.class);
- suite.addTestSuite(ConnectExceptionTest.class);
- suite.addTestSuite(CookieHandlerTest.class);
- suite.addTestSuite(DatagramPacketTest.class);
- suite.addTestSuite(DatagramSocketImplFactoryTest.class);
- suite.addTestSuite(DatagramSocketImplTest.class);
- suite.addTestSuite(FileNameMapTest.class);
- suite.addTestSuite(HttpRetryExceptionTest.class);
- suite.addTestSuite(IDNTest.class);
- suite.addTestSuite(JarURLConnectionTest.class);
- suite.addTestSuite(MalformedURLExceptionTest.class);
- suite.addTestSuite(MulticastSocketTest.class);
- suite.addTestSuite(NetPermissionTest.class);
- suite.addTestSuite(NetworkInterfaceTest.class);
- suite.addTestSuite(NoRouteToHostExceptionTest.class);
- suite.addTestSuite(PasswordAuthenticationTest.class);
- suite.addTestSuite(PortUnreachableExceptionTest.class);
- suite.addTestSuite(ProtocolExceptionTest.class);
- suite.addTestSuite(ProxySelectorTest.class);
- suite.addTestSuite(ProxyTest.class);
- suite.addTestSuite(ProxyTypeTest.class);
- suite.addTestSuite(SecureCacheResponseTest.class);
- suite.addTestSuite(ServerSocketTest.class);
- suite.addTestSuite(SocketExceptionTest.class);
- suite.addTestSuite(SocketImplTest.class);
- suite.addTestSuite(SocketImplFactoryTest.class);
- suite.addTestSuite(SocketPermissionTest.class);
- suite.addTestSuite(SocketTest.class);
- suite.addTestSuite(SocketTimeoutExceptionTest.class);
- suite.addTestSuite(URISyntaxExceptionTest.class);
- suite.addTestSuite(URITest.class);
- suite.addTestSuite(URLDecoderTest.class);
- suite.addTestSuite(URLEncoderTest.class);
- suite.addTestSuite(UnknownHostExceptionTest.class);
- suite.addTestSuite(UnknownServiceExceptionTest.class);
- suite.addTestSuite(URLStreamHandlerTest.class);
-
- // $JUnit-END$
- return suite;
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/AuthenticatorTest.java b/luni/src/test/java/tests/api/java/net/AuthenticatorTest.java
deleted file mode 100644
index c6b4b65..0000000
--- a/luni/src/test/java/tests/api/java/net/AuthenticatorTest.java
+++ /dev/null
@@ -1,423 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.Authenticator;
-import java.net.InetAddress;
-import java.net.MalformedURLException;
-import java.net.PasswordAuthentication;
-import java.net.URL;
-import java.net.UnknownHostException;
-import java.net.Authenticator.RequestorType;
-import java.security.Permission;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(value = Authenticator.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRequestingHost",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRequestingPort",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRequestingSite",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRequestingProtocol",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRequestingPrompt",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getRequestingScheme",
- args = {}
- )}
- )
-public class AuthenticatorTest extends TestCase {
-
- /**
- * @tests java.net.Authenticator.RequestorType#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Test for checking RequestorType values.",
- method = "!Constants",
- args = {}
- )
- public void test_RequestorType_valueOfLjava_lang_String() throws Exception {
- assertEquals(RequestorType.PROXY, Authenticator.RequestorType
- .valueOf("PROXY"));
- assertEquals(RequestorType.SERVER, Authenticator.RequestorType
- .valueOf("SERVER"));
- try {
- RequestorType rt = Authenticator.RequestorType.valueOf("BADNAME");
- fail("Must throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // correct
- }
- // Some old RIs throw IllegalArgumentException
- // Latest RIs throw NullPointerException.
- try {
- Authenticator.RequestorType.valueOf(null);
- fail("Must throw an exception");
- } catch (NullPointerException e) {
- // May be caused by some compilers' code
- } catch (IllegalArgumentException e) {
- // other compilers will throw this
- }
- }
-
- /**
- * @tests java.net.Authenticator.RequestorType#values()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "Test for checking RequestorType values.",
- method = "!Constants",
- args = {}
- )
- public void test_RequestorType_values() throws Exception {
- RequestorType[] rt = RequestorType.values();
- assertEquals(RequestorType.PROXY, rt[0]);
- assertEquals(RequestorType.SERVER, rt[1]);
- }
-
- /**
- * @tests java.net.Authenticator#requestPasswordAuthentication(java.net.InetAddress, int, String, String, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "requestPasswordAuthentication",
- args = {java.net.InetAddress.class, int.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_requestPasswordAuthentication_InetAddress_int_String_String_String() throws Exception {
- // Regression test for Harmony-2413
- MockAuthenticator mock = new MockAuthenticator();
- InetAddress addr = InetAddress.getLocalHost();
- Authenticator.setDefault(mock);
- Authenticator.requestPasswordAuthentication(addr, -1, "http", "promt", "HTTP");
- assertEquals(mock.getRequestorType(), RequestorType.SERVER);
-
- SecurityManager sm = new SecurityManager() {
- final String permissionName = "requestPasswordAuthentication";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(permissionName)) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Authenticator.requestPasswordAuthentication("test_host", addr, -1,
- "http", "promt", "HTTP");
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- Authenticator.setDefault(null);
- }
- }
-
- /**
- * @tests java.net.Authenticator#requestPasswordAuthentication(String, java.net.InetAddress, int, String, String, String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "requestPasswordAuthentication",
- args = {java.lang.String.class, java.net.InetAddress.class, int.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_requestPasswordAuthentication_String_InetAddress_int_String_String_String() throws Exception {
- // Regression test for Harmony-2413
- MockAuthenticator mock = new MockAuthenticator();
- InetAddress addr = InetAddress.getLocalHost();
- Authenticator.setDefault(mock);
- Authenticator.requestPasswordAuthentication("test_host", addr, -1, "http", "promt", "HTTP");
- assertEquals(mock.getRequestorType(), RequestorType.SERVER);
-
- SecurityManager sm = new SecurityManager() {
- final String permissionName = "requestPasswordAuthentication";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(permissionName)) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Authenticator.requestPasswordAuthentication("test_host", addr, -1,
- "http", "promt", "HTTP");
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- Authenticator.setDefault(null);
- }
- }
-
- /**
- *
- * @tests java.net.Authenticator#
- * requestPasswordAuthentication_String_InetAddress_int_String_String_String_URL_Authenticator_RequestorType()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "requestPasswordAuthentication",
- args = {java.lang.String.class, java.net.InetAddress.class, int.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.net.URL.class, java.net.Authenticator.RequestorType.class}
- )
- public void test_requestPasswordAuthentication_String_InetAddress_int_String_String_String_URL_Authenticator_RequestorType()
- throws UnknownHostException, MalformedURLException {
- MockAuthenticator mock = new MockAuthenticator();
- URL url = new URL("http://127.0.0.1");
- Authenticator.requestPasswordAuthentication("localhost", InetAddress
- .getByName("127.0.0.1"), 80, "HTTP", "", "", url,
- RequestorType.PROXY);
- assertNull(mock.getRequestingURL());
- assertNull(mock.getRequestorType());
-
- SecurityManager sm = new SecurityManager() {
- final String permissionName = "requestPasswordAuthentication";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(permissionName)) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Authenticator.requestPasswordAuthentication("localhost", InetAddress
- .getByName("127.0.0.1"), 80, "HTTP", "", "", url,
- RequestorType.PROXY);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- Authenticator.setDefault(null);
- }
- }
-
- /**
- *
- * @tests java.net.Authenticator#getRequestingURL()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRequestingURL",
- args = {}
- )
- public void test_getRequestingURL() throws Exception {
- MockAuthenticator mock = new MockAuthenticator();
- assertNull(mock.getRequestingURL());
- }
-
- /**
- *
- * @tests java.net.Authenticator#getRequestorType()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRequestorType",
- args = {}
- )
- public void test_getRequestorType() throws Exception {
- MockAuthenticator mock = new MockAuthenticator();
- assertNull(mock.getRequestorType());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setDefault",
- args = {java.net.Authenticator.class}
- )
- public void test_setDefault() {
- StubAuthenticator stub = new StubAuthenticator();
- InetAddress addr;
- try {
- addr = InetAddress.getLocalHost();
- PasswordAuthentication pa = Authenticator.
- requestPasswordAuthentication(addr, 8080, "http", "promt", "HTTP");
- assertNull(pa);
-
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- }
-
- MockAuthenticator mock = new MockAuthenticator();
- Authenticator.setDefault(mock);
-
- try {
- addr = InetAddress.getLocalHost();
- PasswordAuthentication pa = Authenticator.
- requestPasswordAuthentication(addr, 80, "http", "promt", "HTTP");
- assertNull(pa);
-
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- }
- Authenticator.setDefault(null);
-
- SecurityManager sm = new SecurityManager() {
- final String permissionName = "setDefaultAuthenticator";
-
- public void checkPermission(Permission perm) {
- if (perm.getName().equals(permissionName)) {
- throw new SecurityException();
- }
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- Authenticator.setDefault(stub);
- fail("Should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(oldSm);
- Authenticator.setDefault(null);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "Authenticator",
- args = {}
- )
- public void test_Constructor() {
- MockAuthenticator ma = new MockAuthenticator();
- assertNull(ma.getRequestingURL());
- assertNull(ma.getRequestorType());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPasswordAuthentication",
- args = {}
- )
- public void test_getPasswordAuthentication() {
- MockAuthenticator ma = new MockAuthenticator();
- assertNull(ma.getPasswordAuthentication());
- }
-
- /*
- * Mock Authernticator for test
- */
- class MockAuthenticator extends java.net.Authenticator {
- public MockAuthenticator() {
- super();
- }
-
- public URL getRequestingURL() {
- return super.getRequestingURL();
- }
-
- public Authenticator.RequestorType getRequestorType() {
- return super.getRequestorType();
- }
-
- public PasswordAuthentication getPasswordAuthentication() {
- return super.getPasswordAuthentication();
- }
-
- public String getMockRequestingHost() {
- return super.getRequestingHost();
- }
-
- public int getMockRequestingPort() {
- return super.getRequestingPort();
- }
-
- public String getMockRequestingPrompt() {
- return super.getRequestingPrompt();
- }
-
- public String getMockRequestingProtocol() {
- return super.getRequestingProtocol();
- }
-
- public String getMockRequestingScheme() {
- return super.getRequestingScheme();
- }
-
- public InetAddress getMockRequestingSite() {
- return super.getRequestingSite();
- }
- }
-
- class StubAuthenticator extends java.net.Authenticator {
- public StubAuthenticator() {
- super();
- }
-
- public URL getRequestingURL() {
- return null;
- }
-
- public Authenticator.RequestorType getRequestorType() {
- return null;
- }
-
- public PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication("test",
- new char[] {'t', 'e', 's', 't'});
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/BindExceptionTest.java b/luni/src/test/java/tests/api/java/net/BindExceptionTest.java
deleted file mode 100644
index 5063c02..0000000
--- a/luni/src/test/java/tests/api/java/net/BindExceptionTest.java
+++ /dev/null
@@ -1,85 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.BindException;
-
-@TestTargetClass(BindException.class)
-public class BindExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.BindException#BindException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "BindException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.net.BindException()
- try {
- throw new BindException();
- } catch (BindException e) {
- return;
- } catch (Exception e) {
- fail("Exception during BindException test" + e.toString());
- }
- fail("Failed to generate exception");
- }
-
- /**
- * @tests java.net.BindException#BindException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "BindException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.BindException(java.lang.String)
- try {
- throw new BindException("Some error message");
- } catch (BindException e) {
- return;
- } catch (Exception e) {
- fail("Exception during BindException test : " + e.getMessage());
- }
- fail("Failed to generate exception");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/CacheRequestTest.java b/luni/src/test/java/tests/api/java/net/CacheRequestTest.java
deleted file mode 100644
index cb53ad1..0000000
--- a/luni/src/test/java/tests/api/java/net/CacheRequestTest.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.api.java.net;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.net.CacheRequest;
-
-@TestTargetClass(CacheRequest.class)
-public class CacheRequestTest extends TestCase {
-
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "abort",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "CacheRequest",
- args = {}
- )
- })
- public void test_abort() {
- MockCacheRequest mcr = new MockCacheRequest();
- mcr.abort();
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBody",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "CacheRequest",
- args = {}
- )
- })
- public void test_getBody() throws IOException {
- MockCacheRequest mcr = new MockCacheRequest();
- assertNull(mcr.getBody());
- }
-
- class MockCacheRequest extends CacheRequest {
-
- MockCacheRequest() {
- super();
- }
-
- @Override
- public void abort() {
- }
-
- @Override
- public OutputStream getBody() throws IOException {
- return null;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/CacheResponseTest.java b/luni/src/test/java/tests/api/java/net/CacheResponseTest.java
deleted file mode 100644
index fe7ddcc..0000000
--- a/luni/src/test/java/tests/api/java/net/CacheResponseTest.java
+++ /dev/null
@@ -1,83 +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.api.java.net;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.CacheRequest;
-import java.net.CacheResponse;
-import java.util.List;
-import java.util.Map;
-
-@TestTargetClass(CacheResponse.class)
-public class CacheResponseTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getBody",
- args = {}
- )
- public void test_getBody() throws IOException {
- MockCacheResponse mcr = new MockCacheResponse();
- assertNull(mcr.getBody());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHeaders",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "CacheResponse",
- args = {}
- )
- })
- public void test_getHeaders() throws IOException {
- MockCacheResponse mcr = new MockCacheResponse();
- assertNull(mcr.getHeaders());
- }
-
- class MockCacheResponse extends CacheResponse {
-
- MockCacheResponse() {
- super();
- }
-
- @Override
- public Map<String,List<String>> getHeaders() throws IOException {
- return null;
- }
-
- @Override
- public InputStream getBody() throws IOException {
- return null;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/ConnectExceptionTest.java b/luni/src/test/java/tests/api/java/net/ConnectExceptionTest.java
deleted file mode 100644
index c7d8577..0000000
--- a/luni/src/test/java/tests/api/java/net/ConnectExceptionTest.java
+++ /dev/null
@@ -1,56 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.ConnectException;
-import java.net.InetAddress;
-import java.net.Socket;
-
-import tests.support.Support_PortManager;
-
-@TestTargetClass(ConnectException.class)
-public class ConnectExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.ConnectException#ConnectException()
- * @tests java.net.ConnectException#ConnectException(java.lang.String)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ConnectException",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ConnectException",
- args = {java.lang.String.class}
- )
- })
- public void test_Constructor() {
- assertNull("Wrong message", new ConnectException().getMessage());
- assertEquals("Wrong message", "message", new ConnectException("message").getMessage());
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/CookieHandlerTest.java b/luni/src/test/java/tests/api/java/net/CookieHandlerTest.java
deleted file mode 100644
index fb9d907..0000000
--- a/luni/src/test/java/tests/api/java/net/CookieHandlerTest.java
+++ /dev/null
@@ -1,234 +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.KnownFailure;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.net.CookieHandler;
-import java.net.MalformedURLException;
-import java.net.NetPermission;
-import java.net.URI;
-import java.net.URL;
-import java.net.URLConnection;
-import java.security.Permission;
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-import tests.support.Support_Configuration;
-
-@TestTargetClass(CookieHandler.class)
-public class CookieHandlerTest extends TestCase {
-
- URI getURI, putURI;
- String link = "http://" + Support_Configuration.SpecialInetTestAddress + "/";
- boolean isGetCalled = false;
- boolean isPutCalled = false;
-
- /**
- * @tests java.net.CookieHandler#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for getDefault method.",
- method = "getDefault",
- args = {}
- )
- public void test_GetDefault() {
- assertNull(CookieHandler.getDefault());
- }
-
- /**
- * @tests java.net.CookieHandler#setDefault(CookieHandler)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for setDefault method.",
- method = "setDefault",
- args = {java.net.CookieHandler.class}
- )
- public void test_SetDefault_java_net_cookieHandler() {
- MockCookieHandler rc1 = new MockCookieHandler();
- MockCookieHandler rc2 = new MockCookieHandler();
- CookieHandler.setDefault(rc1);
- assertSame(CookieHandler.getDefault(), rc1);
- CookieHandler.setDefault(rc2);
- assertSame(CookieHandler.getDefault(), rc2);
- CookieHandler.setDefault(null);
- assertNull(CookieHandler.getDefault());
- }
-
- /**
- * @tests java.net.CookieHandler#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for getDefault method.",
- method = "getDefault",
- args = {}
- )
- public void testGetDefault_Security() {
- SecurityManager old = System.getSecurityManager();
- try {
- System.setSecurityManager(new MockSM());
- } catch (SecurityException e) {
- System.err.println("Unable to reset securityManager,test ignored");
- return;
- }
- try {
- CookieHandler.getDefault();
- fail("should throw SecurityException");
- } catch (SecurityException e) {
- // correct
- } finally {
- System.setSecurityManager(old);
- }
- }
-
- /**
- * @tests java.net.CookieHandler#setDefault(CookieHandler)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for setDefault method.",
- method = "setDefault",
- args = {java.net.CookieHandler.class}
- ) public void testSetDefault_Security() {
- CookieHandler rc = new MockCookieHandler();
- SecurityManager old = System.getSecurityManager();
- try {
- System.setSecurityManager(new MockSM());
- } catch (SecurityException e) {
- System.err.println("Unable to reset securityManager,test ignored");
- return;
- }
-
- try {
- CookieHandler.setDefault(rc);
- fail("should throw SecurityException");
- } catch (SecurityException e) {
- // correct
- } finally {
- System.setSecurityManager(old);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "CookieHandler",
- args = {}
- )
- public void test_CookieHandler() {
- MockCookieHandler mch = new MockCookieHandler();
- assertNull(mch.getDefault());
- }
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "get",
- args = {java.net.URI.class, java.util.Map.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "put",
- args = {java.net.URI.class, java.util.Map.class}
- )
- })
- public void test_get_put() {
- MockCookieHandler mch = new MockCookieHandler();
- CookieHandler defaultHandler = CookieHandler.getDefault();
- CookieHandler.setDefault(mch);
-
- class TestThread extends Thread {
- public void run() {
- try {
- URL url = new URL(link);
- URLConnection conn = url.openConnection();
- Object obj = conn.getContent();
- url = new URL(link);
- conn = url.openConnection();
- obj = conn.getContent();
- } catch (MalformedURLException e) {
- fail("MalformedURLException was thrown: " + e.toString());
- } catch (IOException e) {
- fail("IOException was thrown.");
- }
- }
- };
- try {
- TestThread thread = new TestThread();
-
- thread.start();
- try {
- thread.join();
- } catch (InterruptedException e) {
- fail("InterruptedException was thrown.");
- }
-
- assertTrue(isGetCalled);
- assertTrue(isPutCalled);
- } finally {
- CookieHandler.setDefault(defaultHandler);
- }
- }
-
- class MockCookieHandler extends CookieHandler {
-
- public Map get(URI uri, Map requestHeaders) throws IOException {
- getURI = uri;
- isGetCalled = true;
- return requestHeaders;
- }
-
- public void put(URI uri, Map responseHeaders) throws IOException {
- putURI = uri;
- isPutCalled = true;
- }
-
- }
-
- class MockSM extends SecurityManager {
- public void checkPermission(Permission permission) {
- if (permission instanceof NetPermission) {
- if ("setCookieHandler".equals(permission.getName())) {
- throw new SecurityException();
- }
- }
-
- if (permission instanceof NetPermission) {
- if ("getCookieHandler".equals(permission.getName())) {
- throw new SecurityException();
- }
- }
-
- if (permission instanceof RuntimePermission) {
- if ("setSecurityManager".equals(permission.getName())) {
- return;
- }
- }
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/DatagramPacketTest.java b/luni/src/test/java/tests/api/java/net/DatagramPacketTest.java
deleted file mode 100644
index 00af786..0000000
--- a/luni/src/test/java/tests/api/java/net/DatagramPacketTest.java
+++ /dev/null
@@ -1,440 +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 java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-
-import tests.support.Support_Configuration;
-import tests.support.Support_PortManager;
-
-public class DatagramPacketTest extends junit.framework.TestCase {
-
- DatagramPacket dp;
-
- volatile boolean started = false;
-
- public void test_Constructor$BI() {
- // Test for method java.net.DatagramPacket(byte [], int)
- try {
- dp = new DatagramPacket("Hello".getBytes(), 5);
- assertEquals("Created incorrect packet", "Hello", new String(dp.getData(), 0,
- dp.getData().length));
- assertEquals("Wrong length", 5, dp.getLength());
- } catch (Exception e) {
- fail("Exception during Constructor test: " + e.toString());
- }
- //regression for Harmony-890
- dp = new DatagramPacket(new byte[942],4);
- assertEquals(-1, dp.getPort());
- try{
- dp.getSocketAddress();
- fail("Should throw IllegalArgumentException");
- }catch(IllegalArgumentException e){
- //expected
- }
- }
-
- public void test_Constructor$BII() {
- try {
- dp = new DatagramPacket("Hello".getBytes(), 2, 3);
- assertEquals("Created incorrect packet", "Hello", new String(dp.getData(), 0,
- dp.getData().length));
- assertEquals("Wrong length", 3, dp.getLength());
- assertEquals("Wrong offset", 2, dp.getOffset());
- } catch (Exception e) {
- fail("Exception during Constructor test: " + e.toString());
- }
- }
-
- public void test_Constructor$BIILjava_net_InetAddressI() {
- try {
- dp = new DatagramPacket("Hello".getBytes(), 2, 3, InetAddress
- .getLocalHost(), 0);
- assertTrue("Created incorrect packet", dp.getAddress().equals(
- InetAddress.getLocalHost())
- && dp.getPort() == 0);
- assertEquals("Wrong length", 3, dp.getLength());
- assertEquals("Wrong offset", 2, dp.getOffset());
- } catch (Exception e) {
- fail("Exception during Constructor test: " + e.toString());
- }
- }
-
- public void test_Constructor$BILjava_net_InetAddressI() {
- // Test for method java.net.DatagramPacket(byte [], int,
- // java.net.InetAddress, int)
- try {
- dp = new DatagramPacket("Hello".getBytes(), 5, InetAddress
- .getLocalHost(), 0);
- assertTrue("Created incorrect packet", dp.getAddress().equals(
- InetAddress.getLocalHost())
- && dp.getPort() == 0);
- assertEquals("Wrong length", 5, dp.getLength());
- } catch (Exception e) {
- fail("Exception during Constructor test: " + e.toString());
- }
- }
-
- public void test_getAddress() {
- // Test for method java.net.InetAddress
- // java.net.DatagramPacket.getAddress()
- try {
- dp = new DatagramPacket("Hello".getBytes(), 5, InetAddress
- .getLocalHost(), 0);
- assertTrue("Incorrect address returned", dp.getAddress().equals(
- InetAddress.getLocalHost()));
- } catch (Exception e) {
- fail("Exception during getAddress test:" + e.toString());
- }
- }
-
- public void test_getData() {
- // Test for method byte [] java.net.DatagramPacket.getData()
-
- dp = new DatagramPacket("Hello".getBytes(), 5);
- assertEquals("Incorrect length returned", "Hello", new String(dp.getData(), 0, dp
- .getData().length));
- }
-
- public void test_getLength() {
- // Test for method int java.net.DatagramPacket.getLength()
-
- dp = new DatagramPacket("Hello".getBytes(), 5);
- assertEquals("Incorrect length returned", 5, dp.getLength());
- }
-
- public void test_getOffset() {
- dp = new DatagramPacket("Hello".getBytes(), 3, 2);
- assertEquals("Incorrect length returned", 3, dp.getOffset());
- }
-
- public void test_getPort() {
- // Test for method int java.net.DatagramPacket.getPort()
- try {
- dp = new DatagramPacket("Hello".getBytes(), 5, InetAddress
- .getLocalHost(), 1000);
- assertEquals("Incorrect port returned", 1000, dp.getPort());
- } catch (Exception e) {
- fail("Exception during getPort test : " + e.getMessage());
- }
-
- InetAddress localhost = null;
- try {
- localhost = InetAddress.getByName("localhost");
- } catch (UnknownHostException e) {
- fail("Unexpected UnknownHostException : " + e.getMessage());
- }
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int port = ports[0];
- final Object lock = new Object();
-
- Thread thread = new Thread(new Runnable() {
- public void run() {
- DatagramSocket socket = null;
- try {
- socket = new DatagramSocket(port);
- synchronized (lock) {
- started = true;
- lock.notifyAll();
- }
- socket.setSoTimeout(3000);
- DatagramPacket packet = new DatagramPacket(new byte[256],
- 256);
- socket.receive(packet);
- socket.send(packet);
- socket.close();
- } catch (IOException e) {
- System.out.println("thread exception: " + e);
- if (socket != null)
- socket.close();
- }
- }
- });
- thread.start();
-
- DatagramSocket socket = null;
- try {
- socket = new DatagramSocket(ports[1]);
- socket.setSoTimeout(3000);
- DatagramPacket packet = new DatagramPacket(new byte[] { 1, 2, 3, 4,
- 5, 6 }, 6, localhost, port);
- synchronized (lock) {
- try {
- if (!started)
- lock.wait();
- } catch (InterruptedException e) {
- fail(e.toString());
- }
- }
- socket.send(packet);
- socket.receive(packet);
- socket.close();
- assertTrue("datagram received wrong port: " + packet.getPort(),
- packet.getPort() == port);
- } catch (IOException e) {
- if (socket != null)
- socket.close();
- System.err.println("port: " + port + " datagram server error: ");
- e.printStackTrace();
- fail("port : " + port + " datagram server error : "
- + e.getMessage());
- }
- }
-
- public void test_setAddressLjava_net_InetAddress() {
- // Test for method void
- // java.net.DatagramPacket.setAddress(java.net.InetAddress)
- try {
- InetAddress ia = InetAddress
- .getByName(Support_Configuration.InetTestIP);
- dp = new DatagramPacket("Hello".getBytes(), 5, InetAddress
- .getLocalHost(), 0);
- dp.setAddress(ia);
- assertTrue("Incorrect address returned", dp.getAddress().equals(ia));
- } catch (Exception e) {
- fail("Exception during getAddress test:" + e.toString());
- }
- }
-
- public void test_setData$BII() {
- dp = new DatagramPacket("Hello".getBytes(), 5);
- dp.setData("Wagga Wagga".getBytes(), 2, 3);
- assertEquals("Incorrect data set", "Wagga Wagga", new String(dp.getData())
- );
- try {
- dp.setData(null, 2, 3);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- public void test_setData$B() {
- // Test for method void java.net.DatagramPacket.setData(byte [])
- dp = new DatagramPacket("Hello".getBytes(), 5);
- dp.setData("Ralph".getBytes());
- assertEquals("Incorrect data set", "Ralph", new String(dp.getData(), 0, dp
- .getData().length));
-
- try {
- dp.setData(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- public void test_setLengthI() {
- // Test for method void java.net.DatagramPacket.setLength(int)
- dp = new DatagramPacket("Hello".getBytes(), 5);
- dp.setLength(1);
- assertEquals("Failed to set packet length", 1, dp.getLength());
-
- try {
- new DatagramPacket("Hello".getBytes(), 6);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- new DatagramPacket("Hello".getBytes(), -1);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- public void test_setPortI() {
- // Test for method void java.net.DatagramPacket.setPort(int)
- try {
- dp = new DatagramPacket("Hello".getBytes(), 5, InetAddress
- .getLocalHost(), 1000);
- dp.setPort(2000);
- assertEquals("Port not set", 2000, dp.getPort());
- } catch (Exception e) {
- fail("Exception during setPort test : " + e.getMessage());
- }
- }
-
- public void test_Constructor$BILjava_net_SocketAddress() {
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- try {
- // unsupported SocketAddress subclass
- byte buf[] = new byte[1];
- try {
- DatagramPacket thePacket = new DatagramPacket(buf, 1,
- new mySocketAddress());
- fail("No exception when constructing using unsupported SocketAddress subclass");
- } catch (IllegalArgumentException ex) {
- }
-
- // case were we try to pass in null
- // unsupported SocketAddress subclass
-
- try {
- DatagramPacket thePacket = new DatagramPacket(buf, 1, null);
- fail("No exception when constructing address using null");
- } catch (IllegalArgumentException ex) {
- }
-
- // now validate we can construct
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP());
- DatagramPacket thePacket = new DatagramPacket(buf, 1, theAddress);
- assertTrue("Socket address not set correctly (1)", theAddress
- .equals(thePacket.getSocketAddress()));
- assertTrue("Socket address not set correctly (2)", theAddress
- .equals(new InetSocketAddress(thePacket.getAddress(),
- thePacket.getPort())));
- } catch (Exception e) {
- fail("Exception during constructor test(1):" + e.toString());
- }
- }
-
- public void test_Constructor$BIILjava_net_SocketAddress() {
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- try {
- // unsupported SocketAddress subclass
- byte buf[] = new byte[2];
- try {
- DatagramPacket thePacket = new DatagramPacket(buf, 1, 1,
- new mySocketAddress());
- fail("No exception when constructing using unsupported SocketAddress subclass");
- } catch (IllegalArgumentException ex) {
- }
-
- // case were we try to pass in null
- // unsupported SocketAddress subclass
-
- try {
- DatagramPacket thePacket = new DatagramPacket(buf, 1, 1, null);
- fail("No exception when constructing address using null");
- } catch (IllegalArgumentException ex) {
- }
-
- // now validate we can construct
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP());
- DatagramPacket thePacket = new DatagramPacket(buf, 1, 1, theAddress);
- assertTrue("Socket address not set correctly (1)", theAddress
- .equals(thePacket.getSocketAddress()));
- assertTrue("Socket address not set correctly (2)", theAddress
- .equals(new InetSocketAddress(thePacket.getAddress(),
- thePacket.getPort())));
- assertEquals("Offset not set correctly", 1, thePacket.getOffset());
- } catch (Exception e) {
- fail("Exception during constructor test(2):" + e.toString());
- }
- }
-
- public void test_getSocketAddress() {
- try {
- byte buf[] = new byte[1];
- DatagramPacket thePacket = new DatagramPacket(buf, 1);
-
- // validate get returns the value we set
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP());
- thePacket = new DatagramPacket(buf, 1);
- thePacket.setSocketAddress(theAddress);
- assertTrue("Socket address not set correctly (1)", theAddress
- .equals(thePacket.getSocketAddress()));
- } catch (Exception e) {
- fail(
- "Exception during getSocketAddress test:" + e.toString());
- }
- }
-
- public void test_setSocketAddressLjava_net_SocketAddress() {
-
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- try {
- // unsupported SocketAddress subclass
- byte buf[] = new byte[1];
- DatagramPacket thePacket = new DatagramPacket(buf, 1);
- try {
- thePacket.setSocketAddress(new mySocketAddress());
- fail("No exception when setting address using unsupported SocketAddress subclass");
- } catch (IllegalArgumentException ex) {
- }
-
- // case were we try to pass in null
- // unsupported SocketAddress subclass
- thePacket = new DatagramPacket(buf, 1);
- try {
- thePacket.setSocketAddress(null);
- fail("No exception when setting address using null");
- } catch (IllegalArgumentException ex) {
- }
-
- // now validate we can set it correctly
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP());
- thePacket = new DatagramPacket(buf, 1);
- thePacket.setSocketAddress(theAddress);
- assertTrue("Socket address not set correctly (1)", theAddress
- .equals(thePacket.getSocketAddress()));
- assertTrue("Socket address not set correctly (2)", theAddress
- .equals(new InetSocketAddress(thePacket.getAddress(),
- thePacket.getPort())));
- } catch (Exception e) {
- fail(
- "Exception during setSocketAddress test:" + e.toString());
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-
- protected void doneSuite() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/DatagramSocketImplTest.java b/luni/src/test/java/tests/api/java/net/DatagramSocketImplTest.java
deleted file mode 100644
index b251aa7..0000000
--- a/luni/src/test/java/tests/api/java/net/DatagramSocketImplTest.java
+++ /dev/null
@@ -1,349 +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.AndroidOnly;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocketImpl;
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.SocketAddress;
-import java.net.SocketException;
-
-/*
- * DatagramSocketImplFactory can be specified only once,
- * therefore we can't check DatagramSocketImpl functionality.
- */
-
-@TestTargetClass(value = DatagramSocketImpl.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "bind",
- args = {int.class, InetAddress.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "close",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "create",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTimeToLive",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getTTL",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "join",
- args = {InetAddress.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "joinGroup",
- args = { SocketAddress.class, NetworkInterface.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "leave",
- args = { InetAddress.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "leaveGroup",
- args = { SocketAddress.class, NetworkInterface.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "peek",
- args = { InetAddress.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "peekData",
- args = { DatagramPacket.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "receive",
- args = { DatagramPacket.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "send",
- args = { DatagramPacket.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTimeToLive",
- args = { int.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setTTL",
- args = { byte.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setOption",
- args = { int.class, Object.class }
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getOption",
- args = { int.class }
- )
- })
-public class DatagramSocketImplTest extends junit.framework.TestCase {
-
- MockDatagramSocketImpl ds;
-
- public void setUp() {
- ds = new MockDatagramSocketImpl();
- }
-
- public void tearDown() {
- ds.close();
- ds = null;
- }
- /**
- * @tests java.net.DatagramSocketImpl#DatagramSocketImpl()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "DatagramSocketImpl",
- args = {}
- )
- public void test_Constructor() throws Exception {
- // regression test for Harmony-1117
- MockDatagramSocketImpl impl = new MockDatagramSocketImpl();
- assertNull(impl.getFileDescriptor());
- }
-
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "SocketException is not checked.",
- method = "connect",
- args = {java.net.InetAddress.class, int.class}
- )
- public void test_connect() {
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- //int port = ds.getLocalPort();
- ds.connect(localHost, 0);
- DatagramPacket send = new DatagramPacket(new byte[10], 10,
- localHost, 0);
- ds.send(send);
- } catch (IOException e) {
- fail("Unexpected IOException : " + e.getMessage());
- } finally {
- ds.close();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "disconnect",
- args = {}
- )
- public void test_disconnect() {
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- //int port = ds.getLocalPort();
- ds.connect(localHost, 0);
- DatagramPacket send = new DatagramPacket(new byte[10], 10,
- localHost, 0);
- ds.send(send);
- ds.disconnect();
- } catch (IOException e) {
- fail("Unexpected IOException : " + e.getMessage());
- } finally {
- ds.close();
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFileDescriptor",
- args = {}
- )
- public void test_getFileDescriptor() {
- assertNull(ds.getFileDescriptor());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalPort",
- args = {}
- )
- @AndroidOnly("Bug in RI")
- public void test_getLocalPort() {
- // RI fails here. RI returns 0. the spec doesn't say what the value for
- // an unbound DatagramSocket should be. The same difference can be seen
- // for Socket.getLocalPort. But there the spec says that unbound
- // Sockets return -1. And for that method also the RI returns 0 which
- // goes against the spec.
- assertEquals(-1, ds.getLocalPort());
- }
-}
-
-class MockDatagramSocketImpl extends DatagramSocketImpl {
-
- @Override
- public FileDescriptor getFileDescriptor() {
- return super.getFileDescriptor();
- }
-
- @Override
- public void bind(int port, InetAddress addr) throws SocketException {
- // empty
- }
-
- @Override
- public void close() {
- // empty
- }
-
- @Override
- public void create() throws SocketException {
- // empty
- }
-
-
- @Override
- public byte getTTL() throws IOException {
- return 0;
- }
-
- @Override
- public int getTimeToLive() throws IOException {
- return 0;
- }
-
- @Override
- public void join(InetAddress addr) throws IOException {
- // empty
- }
-
- @Override
- public void joinGroup(SocketAddress addr, NetworkInterface netInterface)
- throws IOException {
- // empty
- }
-
- @Override
- public void leave(InetAddress addr) throws IOException {
- // empty
- }
-
- @Override
- public void leaveGroup(SocketAddress addr, NetworkInterface netInterface)
- throws IOException {
- // empty
- }
-
- @Override
- public int peek(InetAddress sender) throws IOException {
- return 0;
- }
-
- @Override
- public int peekData(DatagramPacket pack) throws IOException {
- return 0;
- }
-
- @Override
- public void receive(DatagramPacket pack) throws IOException {
- // empty
- }
-
- @Override
- public void send(DatagramPacket pack) throws IOException {
- // TODO Auto-generated method stub
-
- }
-
-
- @Override
- public void setTTL(byte ttl) throws IOException {
- // empty
- }
-
- @Override
- public void setTimeToLive(int ttl) throws IOException {
- // empty
- }
-
- public Object getOption(int optID) throws SocketException {
- // TODO Auto-generated method stub
- return null;
- }
-
- public void setOption(int optID, Object value) throws SocketException {
- // TODO Auto-generated method stub
-
- }
-
- public void connect(InetAddress address, int port) throws SocketException {
- super.connect(address, port);
- }
-
- public void disconnect() {
- super.disconnect();
- }
-
- public int getLocalPort() {
- return super.getLocalPort();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/IDNTest.java b/luni/src/test/java/tests/api/java/net/IDNTest.java
deleted file mode 100644
index 01b8784..0000000
--- a/luni/src/test/java/tests/api/java/net/IDNTest.java
+++ /dev/null
@@ -1,160 +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 java.net.IDN;
-
-import junit.framework.TestCase;
-
-public class IDNTest extends TestCase {
-
- /**
- * @tests {@link java.net.IDN#toASCII(String)}
- *
- * @since 1.6
- */
- public void test_ToASCII_LString() {
- try {
- IDN.toASCII(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- try {
- IDN.toASCII("www.m\uE400kitorppa.edu");
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- try {
- IDN.toASCII("www.\u672C\uFE73\uFFFF.jp");
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- assertEquals("www.xn--gwtq9nb2a.jp", IDN
- .toASCII("www.\u65E5\u672C\u5E73.jp"));
- assertEquals(
- "www.xn--vckk7bxa0eza9ezc9d.com",
- IDN
- .toASCII("www.\u30CF\u30F3\u30C9\u30DC\u30FC\u30EB\u30B5\u30E0\u30BA.com"));
- assertEquals("www.xn--frgbolaget-q5a.nu", IDN
- .toASCII("www.f\u00E4rgbolaget.nu"));
- assertEquals("www.xn--bcher-kva.de", IDN.toASCII("www.b\u00FCcher.de"));
- assertEquals("www.xn--brndendekrlighed-vobh.com", IDN
- .toASCII("www.br\u00E6ndendek\u00E6rlighed.com"));
- assertEquals("www.xn--rksmrgs-5wao1o.se", IDN
- .toASCII("www.r\u00E4ksm\u00F6rg\u00E5s.se"));
- assertEquals("www.xn--9d0bm53a3xbzui.com", IDN
- .toASCII("www.\uC608\uBE44\uAD50\uC0AC.com"));
- assertEquals("xn--lck1c3crb1723bpq4a.com", IDN
- .toASCII("\u7406\u5BB9\u30CA\u30AB\u30E0\u30E9.com"));
- assertEquals("xn--l8je6s7a45b.org", IDN
- .toASCII("\u3042\u30FC\u308B\u3044\u3093.org"));
- assertEquals("www.xn--frjestadsbk-l8a.net", IDN
- .toASCII("www.f\u00E4rjestadsbk.net"));
- assertEquals("www.xn--mkitorppa-v2a.edu", IDN
- .toASCII("www.m\u00E4kitorppa.edu"));
- }
-
- /**
- * @tests {@link java.net.IDN#toASCII(String, int)}
- *
- * @since 1.6
- */
- public void test_ToASCII_LString_I() {
- try {
- IDN.toASCII("www.br\u00E6ndendek\u00E6rlighed.com",
- IDN.USE_STD3_ASCII_RULES);
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- try {
- IDN.toASCII("www.r\u00E4ksm\u00F6rg\u00E5s.se",
- IDN.USE_STD3_ASCII_RULES);
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- try {
- IDN.toASCII("www.f\u00E4rjestadsbk.net", IDN.ALLOW_UNASSIGNED
- | IDN.USE_STD3_ASCII_RULES);
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- assertEquals("www.xn--gwtq9nb2a.jp", IDN.toASCII(
- "www.\u65E5\u672C\u5E73.jp", 0));
- assertEquals(
- "www.xn--vckk7bxa0eza9ezc9d.com",
- IDN
- .toASCII(
- "www.\u30CF\u30F3\u30C9\u30DC\u30FC\u30EB\u30B5\u30E0\u30BA.com",
- 0));
- assertEquals("www.xn--frgbolaget-q5a.nu", IDN.toASCII(
- "www.f\u00E4rgbolaget.nu", IDN.ALLOW_UNASSIGNED));
- assertEquals("www.xn--bcher-kva.de", IDN.toASCII("www.b\u00FCcher.de",
- IDN.ALLOW_UNASSIGNED));
- assertEquals("www.google.com", IDN.toASCII("www.google\u002Ecom",
- IDN.USE_STD3_ASCII_RULES));
- }
-
- /**
- * @tests {@link java.net.IDN#toUnicode(String)}
- *
- * @since 1.6
- */
- public void test_ToUnicode_LString() {
- try {
- IDN.toUnicode(null);
- fail("should throw NullPointerException");
- } catch (NullPointerException e) {
- // expected
- }
-
- assertEquals("", IDN.toUnicode(""));
- assertEquals("www.bcher.de", IDN.toUnicode("www.bcher.de"));
- assertEquals("www.b\u00FCcher.de", IDN.toUnicode("www.b\u00FCcher.de"));
- assertEquals("www.\u65E5\u672C\u5E73.jp", IDN
- .toUnicode("www.\u65E5\u672C\u5E73.jp"));
- assertEquals("www.\u65E5\u672C\u5E73.jp", IDN.toUnicode("www\uFF0Exn--gwtq9nb2a\uFF61jp"));
- assertEquals("www.\u65E5\u672C\u5E73.jp", IDN.toUnicode("www.xn--gwtq9nb2a.jp"));
- }
-
- /**
- * @tests {@link java.net.IDN#toUnicode(String, int)}
- *
- * @since 1.6
- */
- public void test_ToUnicode_LString_I() {
- assertEquals("", IDN.toUnicode("", IDN.ALLOW_UNASSIGNED));
- assertEquals("www.f\u00E4rgbolaget.nu", IDN.toUnicode(
- "www.f\u00E4rgbolaget.nu", IDN.USE_STD3_ASCII_RULES));
- assertEquals("www.r\u00E4ksm\u00F6rg\u00E5s.nu", IDN.toUnicode(
- "www.r\u00E4ksm\u00F6rg\u00E5s\u3002nu",
- IDN.USE_STD3_ASCII_RULES));
- // RI bug. It cannot parse "www.xn--gwtq9nb2a.jp" when
- // USE_STD3_ASCII_RULES is set.
- assertEquals("www.\u65E5\u672C\u5E73.jp", IDN.toUnicode(
- "www\uFF0Exn--gwtq9nb2a\uFF61jp", IDN.USE_STD3_ASCII_RULES));
-
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/MalformedURLExceptionTest.java b/luni/src/test/java/tests/api/java/net/MalformedURLExceptionTest.java
deleted file mode 100644
index 3929ac3..0000000
--- a/luni/src/test/java/tests/api/java/net/MalformedURLExceptionTest.java
+++ /dev/null
@@ -1,91 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-
-@TestTargetClass(MalformedURLException.class)
-public class MalformedURLExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.MalformedURLException#MalformedURLException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "MalformedURLException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.net.MalformedURLException()
- boolean passed;
- passed = false;
- try {
- new URL("notAProtocol://www.ibm.com");
- } catch (MalformedURLException e) {
- // correct
- passed = true;
- } catch (Exception e) {
- fail("Wrong exception thrown : " + e.getMessage());
- }
- assertTrue("Failed to throw correct exception", passed);
- }
-
- /**
- * @tests java.net.MalformedURLException#MalformedURLException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "MalformedURLException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.MalformedURLException(java.lang.String)
- final String myString = "Gawsh!";
- try {
- if (true)
- throw new MalformedURLException(myString);
- } catch (MalformedURLException e) {
- assertTrue("Incorrect exception text", e.toString().indexOf(
- myString) >= 0);
- return;
- }
- fail("Exception not thrown");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/MulticastSocketTest.java b/luni/src/test/java/tests/api/java/net/MulticastSocketTest.java
deleted file mode 100644
index 825c8b0..0000000
--- a/luni/src/test/java/tests/api/java/net/MulticastSocketTest.java
+++ /dev/null
@@ -1,1165 +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 java.io.IOException;
-import java.net.BindException;
-import java.net.DatagramPacket;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.MulticastSocket;
-import java.net.NetworkInterface;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Enumeration;
-
-import dalvik.annotation.KnownFailure;
-import tests.support.Support_NetworkInterface;
-import tests.support.Support_PortManager;
-
-public class MulticastSocketTest extends SocketTestCase {
-
- Thread t;
-
- MulticastSocket mss;
-
- MulticastServer server;
-
- // private member variables used for tests
- boolean atLeastOneInterface = false;
-
- boolean atLeastTwoInterfaces = false;
-
- private NetworkInterface networkInterface1 = null;
-
- private NetworkInterface networkInterface2 = null;
-
- private NetworkInterface IPV6networkInterface1 = null;
-
- static class MulticastServer extends Thread {
-
- public MulticastSocket ms;
-
- boolean running = true;
-
- volatile public byte[] rbuf = new byte[512];
-
- volatile DatagramPacket rdp = null;
-
- private InetAddress groupAddr = null;
- private SocketAddress groupSockAddr = null;
- private NetworkInterface groupNI = null;
-
- public void run() {
- try {
- byte[] tmpbuf = new byte[512];
- DatagramPacket tmpPack =
- new DatagramPacket(tmpbuf, tmpbuf.length);
-
- while (running) {
- try {
- ms.receive(tmpPack);
-
- System.arraycopy(tmpPack.getData(), 0, rdp.getData(),
- rdp.getOffset(), tmpPack.getLength());
- rdp.setLength(tmpPack.getLength());
- rdp.setAddress(tmpPack.getAddress());
- rdp.setPort(tmpPack.getPort());
- } catch (java.io.InterruptedIOException e) {
- Thread.yield();
- }
- }
- } catch (java.io.IOException e) {
- System.out.println("Multicast server failed: " + e);
- } finally {
- ms.close();
- }
- }
-
- public void stopServer() {
- running = false;
- try {
- if (groupAddr != null) {
- ms.leaveGroup(groupAddr);
- } else if (groupSockAddr != null) {
- ms.leaveGroup(groupSockAddr, groupNI);
- }
- } catch (IOException e) {}
- }
-
- public MulticastServer(InetAddress anAddress, int aPort)
- throws java.io.IOException {
- rbuf = new byte[512];
- rbuf[0] = -1;
- rdp = new DatagramPacket(rbuf, rbuf.length);
- ms = new MulticastSocket(aPort);
- ms.setSoTimeout(2000);
- groupAddr = anAddress;
- ms.joinGroup(groupAddr);
- }
-
-
- public MulticastServer(SocketAddress anAddress, int aPort,
- NetworkInterface netInterface) throws java.io.IOException {
- rbuf = new byte[512];
- rbuf[0] = -1;
- rdp = new DatagramPacket(rbuf, rbuf.length);
- ms = new MulticastSocket(aPort);
- ms.setSoTimeout(2000);
- groupSockAddr = anAddress;
- groupNI = netInterface;
- ms.joinGroup(groupSockAddr, groupNI);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#MulticastSocket()
- */
- public void test_Constructor() throws IOException {
- // regression test for 497
- MulticastSocket s = new MulticastSocket();
- // regression test for Harmony-1162
- assertTrue(s.getReuseAddress());
- }
-
- /**
- * @tests java.net.MulticastSocket#MulticastSocket(int)
- */
- public void test_ConstructorI() throws IOException {
- MulticastSocket orig = new MulticastSocket();
- int port = orig.getLocalPort();
- orig.close();
- MulticastSocket dup = null;
- try {
- dup = new MulticastSocket(port);
- // regression test for Harmony-1162
- assertTrue(dup.getReuseAddress());
- } catch (IOException e) {
- fail("duplicate binding not allowed: " + e);
- }
- if (dup != null)
- dup.close();
- }
-
- /**
- * @tests java.net.MulticastSocket#getInterface()
- */
- public void test_getInterface() throws Exception {
- // Test for method java.net.InetAddress
- // java.net.MulticastSocket.getInterface()
- assertTrue("Used for testing.", true);
-
- int groupPort = Support_PortManager.getNextPortForUDP();
-
- if (atLeastOneInterface) {
- // validate that we get the expected response when one was not
- // set
- mss = new MulticastSocket(groupPort);
- String preferIPv4StackValue = System
- .getProperty("java.net.preferIPv4Stack");
- String preferIPv6AddressesValue = System
- .getProperty("java.net.preferIPv6Addresses");
- if (((preferIPv4StackValue == null) || preferIPv4StackValue
- .equalsIgnoreCase("false"))
- && (preferIPv6AddressesValue != null)
- && (preferIPv6AddressesValue.equals("true"))) {
- // we expect an IPv6 ANY in this case
- assertEquals("inet Address returned when not set",
- InetAddress.getByName("::0"),
- mss.getInterface());
- } else {
- // we expect an IPv4 ANY in this case
- assertEquals("inet Address returned when not set",
- InetAddress.getByName("0.0.0.0"),
- mss.getInterface());
- }
-
- // validate that we get the expected response when we set via
- // setInterface
- Enumeration addresses = networkInterface1.getInetAddresses();
- if (addresses.hasMoreElements()) {
- InetAddress firstAddress = (InetAddress) addresses
- .nextElement();
- mss.setInterface(firstAddress);
- assertEquals("getNetworkInterface did not return interface set by setInterface",
- firstAddress, mss.getInterface());
-
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
- mss.setNetworkInterface(networkInterface1);
- assertEquals("getInterface did not return interface set by setNetworkInterface",
- networkInterface1,
- NetworkInterface.getByInetAddress(mss.getInterface()));
- }
-
- }
- }
-
- /**
- * @throws IOException
- * @tests java.net.MulticastSocket#getNetworkInterface()
- */
- public void test_getNetworkInterface() throws IOException {
- int groupPort = Support_PortManager.getNextPortForUDP();
- if (atLeastOneInterface) {
- // validate that we get the expected response when one was not
- // set
- mss = new MulticastSocket(groupPort);
- NetworkInterface theInterface = mss.getNetworkInterface();
- assertTrue(
- "network interface returned wrong network interface when not set:"
- + theInterface, theInterface.getInetAddresses()
- .hasMoreElements());
- InetAddress firstAddress = (InetAddress) theInterface
- .getInetAddresses().nextElement();
- // validate we the first address in the network interface is the
- // ANY address
- String preferIPv4StackValue = System
- .getProperty("java.net.preferIPv4Stack");
- String preferIPv6AddressesValue = System
- .getProperty("java.net.preferIPv6Addresses");
- if (((preferIPv4StackValue == null) || preferIPv4StackValue
- .equalsIgnoreCase("false"))
- && (preferIPv6AddressesValue != null)
- && (preferIPv6AddressesValue.equals("true"))) {
- assertEquals("network interface returned wrong network interface when not set:"
- + theInterface,
- firstAddress, InetAddress.getByName("::0"));
-
- } else {
- assertEquals("network interface returned wrong network interface when not set:"
- + theInterface,
- InetAddress.getByName("0.0.0.0"),
- firstAddress);
- }
-
- mss.setNetworkInterface(networkInterface1);
- assertEquals("getNetworkInterface did not return interface set by setNeworkInterface",
- networkInterface1, mss.getNetworkInterface());
-
- if (atLeastTwoInterfaces) {
- mss.setNetworkInterface(networkInterface2);
- assertEquals("getNetworkInterface did not return network interface set by second setNetworkInterface call",
- networkInterface2, mss.getNetworkInterface());
- }
-
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
- if (IPV6networkInterface1 != null) {
- mss.setNetworkInterface(IPV6networkInterface1);
- assertEquals("getNetworkInterface did not return interface set by setNeworkInterface",
- IPV6networkInterface1,
- mss.getNetworkInterface());
- }
-
- // validate that we get the expected response when we set via
- // setInterface
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
- Enumeration addresses = networkInterface1.getInetAddresses();
- if (addresses.hasMoreElements()) {
- firstAddress = (InetAddress) addresses.nextElement();
- mss.setInterface(firstAddress);
- assertEquals("getNetworkInterface did not return interface set by setInterface",
- networkInterface1,
- mss.getNetworkInterface());
- }
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#getTimeToLive()
- */
- public void test_getTimeToLive() {
- try {
- mss = new MulticastSocket();
- mss.setTimeToLive(120);
- assertEquals("Returned incorrect 1st TTL",
- 120, mss.getTimeToLive());
- mss.setTimeToLive(220);
- assertEquals("Returned incorrect 2nd TTL",
- 220, mss.getTimeToLive());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (Exception e) {
- handleException(e, SO_MULTICAST);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#getTTL()
- */
- public void test_getTTL() {
- // Test for method byte java.net.MulticastSocket.getTTL()
-
- try {
- mss = new MulticastSocket();
- mss.setTTL((byte) 120);
- assertEquals("Returned incorrect TTL",
- 120, mss.getTTL());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (Exception e) {
- handleException(e, SO_MULTICAST);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#joinGroup(java.net.InetAddress)
- */
- public void test_joinGroupLjava_net_InetAddress() throws Exception {
- // Test for method void
- // java.net.MulticastSocket.joinGroup(java.net.InetAddress)
- String msg = null;
- InetAddress group = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
- group = InetAddress.getByName("224.0.0.3");
- server = new MulticastServer(group, groupPort);
- server.start();
- Thread.sleep(1000);
- msg = "Hello World";
- mss = new MulticastSocket(ports[1]);
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
- .length(), group, groupPort);
- mss.send(sdp, (byte) 10);
- Thread.sleep(1000);
-
- assertEquals("Group member did not recv data",
- msg,
- new String(server.rdp.getData(), 0, server.rdp.getLength()));
- }
-
- /**
- * @throws IOException
- * @throws InterruptedException
- * @tests java.net.MulticastSocket#joinGroup(java.net.SocketAddress,java.net.NetworkInterface)
- */
- @KnownFailure("Fails in CTS but passes under run-core-tests")
- public void test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface() throws IOException, InterruptedException {
- // security manager that allows us to check that we only return the
- // addresses that we should
- class mySecurityManager extends SecurityManager {
-
- public void checkMulticast(InetAddress address) {
- throw new SecurityException("not allowed");
- }
- }
-
- String msg = null;
- InetAddress group = null;
- SocketAddress groupSockAddr = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
- int serverPort = ports[1];
-
- Enumeration<NetworkInterface> theInterfaces = NetworkInterface.getNetworkInterfaces();
-
- // first validate that we handle a null group ok
- mss = new MulticastSocket(groupPort);
- try {
- mss.joinGroup(null, null);
- fail("Did not get exception when group was null");
- } catch (IllegalArgumentException e) {
- }
-
- // now validate we get the expected error if the address specified
- // is not a multicast group
- try {
- groupSockAddr = new InetSocketAddress(InetAddress
- .getByName("255.255.255.255"), groupPort);
- mss.joinGroup(groupSockAddr, null);
- fail("Did not get exception when group is not a multicast address");
- } catch (IOException e) {
- }
-
- // now try to join a group if we are not authorized
- // set the security manager that will make the first address not
- // visible
- System.setSecurityManager(new mySecurityManager());
- try {
- group = InetAddress.getByName("224.0.0.3");
- groupSockAddr = new InetSocketAddress(group, groupPort);
- mss.joinGroup(groupSockAddr, null);
- fail("Did not get exception when joining group is not allowed");
- } catch (SecurityException e) {
- }
- System.setSecurityManager(null);
-
- if (atLeastOneInterface) {
- // now validate that we can properly join a group with a null
- // network interface
- ports = Support_PortManager.getNextPortsForUDP(2);
- groupPort = ports[0];
- serverPort = ports[1];
- mss = new MulticastSocket(groupPort);
- mss.joinGroup(groupSockAddr, null);
- mss.setTimeToLive(2);
- Thread.sleep(1000);
-
- // set up the server and join the group on networkInterface1
- group = InetAddress.getByName("224.0.0.3");
- groupSockAddr = new InetSocketAddress(group, groupPort);
- server = new MulticastServer(groupSockAddr, serverPort,
- networkInterface1);
- server.start();
- Thread.sleep(1000);
- msg = "Hello World";
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
- .length(), group, serverPort);
- mss.setTimeToLive(2);
- mss.send(sdp);
- Thread.sleep(1000);
- // now vaildate that we received the data as expected
- assertEquals("Group member did not recv data",
- msg,
- new String(server.rdp.getData(), 0, server.rdp.getLength()));
- server.stopServer();
-
- // now validate that we handled the case were we join a
- // different multicast address.
- // verify we do not receive the data
- ports = Support_PortManager.getNextPortsForUDP(2);
- serverPort = ports[0];
- server = new MulticastServer(groupSockAddr, serverPort,
- networkInterface1);
- server.start();
- Thread.sleep(1000);
-
- groupPort = ports[1];
- mss = new MulticastSocket(groupPort);
- InetAddress group2 = InetAddress.getByName("224.0.0.4");
- mss.setTimeToLive(10);
- msg = "Hello World - Different Group";
- sdp = new DatagramPacket(msg.getBytes(), msg.length(), group2,
- serverPort);
- mss.send(sdp);
- Thread.sleep(1000);
- assertFalse(
- "Group member received data when sent on different group: ",
- new String(server.rdp.getData(), 0, server.rdp.getLength())
- .equals(msg));
- server.stopServer();
-
- // if there is more than one network interface then check that
- // we can join on specific interfaces and that we only receive
- // if data is received on that interface
- if (atLeastTwoInterfaces) {
- // set up server on first interfaces
- NetworkInterface loopbackInterface = NetworkInterface
- .getByInetAddress(InetAddress.getByName("127.0.0.1"));
-
- boolean anyLoop = networkInterface1.equals(loopbackInterface) || networkInterface2.equals(loopbackInterface);
-
- ArrayList<NetworkInterface> realInterfaces = new ArrayList<NetworkInterface>();
- theInterfaces = NetworkInterface.getNetworkInterfaces();
- while (theInterfaces.hasMoreElements()) {
- NetworkInterface thisInterface = (NetworkInterface) theInterfaces.nextElement();
- if (thisInterface.getInetAddresses().hasMoreElements()
- && (Support_NetworkInterface
- .useInterface(thisInterface) == true)){
- realInterfaces.add(thisInterface);
- }
- }
-
- for (int i = 0; i < realInterfaces.size(); i++) {
- final int SECOND = 1;
- NetworkInterface thisInterface = realInterfaces.get(i);
-
- // get the first address on the interface
-
- // start server which is joined to the group and has
- // only asked for packets on this interface
- Enumeration<InetAddress> addresses = thisInterface.getInetAddresses();
-
- NetworkInterface sendingInterface = null;
- if (addresses.hasMoreElements()) {
- InetAddress firstAddress = (InetAddress) addresses.nextElement();
- if (firstAddress instanceof Inet4Address) {
- group = InetAddress.getByName("224.0.0.4");
- if (anyLoop) {
- if (networkInterface1.equals(loopbackInterface)) {
- sendingInterface = networkInterface2;
- } else {
- sendingInterface = networkInterface1;
- }
- } else {
- if(i == SECOND){
- sendingInterface = networkInterface2;
- } else {
- sendingInterface = networkInterface1;
- }
- }
- } else {
- // if this interface only seems to support
- // IPV6 addresses
- group = InetAddress
- .getByName("FF01:0:0:0:0:0:2:8001");
- sendingInterface = IPV6networkInterface1;
- }
- }
-
- ports = Support_PortManager.getNextPortsForUDP(2);
- serverPort = ports[0];
- groupPort = ports[1];
- groupSockAddr = new InetSocketAddress(group, serverPort);
- server = new MulticastServer(groupSockAddr, serverPort,
- thisInterface);
- server.start();
- Thread.sleep(1000);
-
- // Now send out a package on interface
- // networkInterface 1. We should
- // only see the packet if we send it on interface 1
- mss = new MulticastSocket(groupPort);
- mss.setNetworkInterface(sendingInterface);
- msg = "Hello World - Again" + thisInterface.getName();
- sdp = new DatagramPacket(msg.getBytes(), msg.length(),
- group, serverPort);
- mss.send(sdp);
- Thread.sleep(1000);
- if (thisInterface.equals(sendingInterface)) {
- assertEquals("Group member did not recv data when bound on specific interface",
- msg,
- new String(server.rdp.getData(), 0, server.rdp.getLength()));
- } else {
- assertFalse(
- "Group member received data on other interface when only asked for it on one interface: ",
- new String(server.rdp.getData(), 0,
- server.rdp.getLength()).equals(msg));
- }
-
- server.stopServer();
- }
-
-
- // validate that we can join the same address on two
- // different interfaces but not on the same interface
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
- mss.joinGroup(groupSockAddr, networkInterface1);
- mss.joinGroup(groupSockAddr, networkInterface2);
- try {
- mss.joinGroup(groupSockAddr, networkInterface1);
- fail("Did not get expected exception when joining for second time on same interface");
- } catch (IOException e) {
- }
- }
- }
- System.setSecurityManager(null);
- }
-
- /**
- * @tests java.net.MulticastSocket#leaveGroup(java.net.InetAddress)
- */
- public void test_leaveGroupLjava_net_InetAddress() {
- // Test for method void
- // java.net.MulticastSocket.leaveGroup(java.net.InetAddress)
- String msg = null;
- boolean except = false;
- InetAddress group = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
-
- try {
- group = InetAddress.getByName("224.0.0.3");
- msg = "Hello World";
- mss = new MulticastSocket(ports[1]);
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
- .length(), group, groupPort);
- mss.send(sdp, (byte) 10);
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (Exception e) {
- handleException(e, SO_MULTICAST);
- }
- try {
- // Try to leave s group that mss is not a member of
- mss.leaveGroup(group);
- } catch (java.io.IOException e) {
- // Correct
- except = true;
- }
- assertTrue("Failed to throw exception leaving non-member group", except);
- }
-
- /**
- * @tests java.net.MulticastSocket#leaveGroup(java.net.SocketAddress,java.net.NetworkInterface)
- */
- public void test_leaveGroupLjava_net_SocketAddressLjava_net_NetworkInterface() throws Exception {
- // security manager that allows us to check that we only return the
- // addresses that we should
- class mySecurityManager extends SecurityManager {
-
- public void checkMulticast(InetAddress address) {
- throw new SecurityException("not allowed");
- }
- }
-
- String msg = null;
- InetAddress group = null;
- int groupPort = Support_PortManager.getNextPortForUDP();
- SocketAddress groupSockAddr = null;
- SocketAddress groupSockAddr2 = null;
-
- Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
-
- // first validate that we handle a null group ok
- mss = new MulticastSocket(groupPort);
- try {
- mss.leaveGroup(null, null);
- fail("Did not get exception when group was null");
- } catch (IllegalArgumentException e) {
- }
-
- // now validate we get the expected error if the address specified
- // is not a multicast group
- try {
- group = InetAddress.getByName("255.255.255.255");
- groupSockAddr = new InetSocketAddress(group, groupPort);
- mss.leaveGroup(groupSockAddr, null);
- fail("Did not get exception when group is not a multicast address");
- } catch (IOException e) {
- }
-
- // now try to leave a group if we are not authorized
- // set the security manager that will make the first address not
- // visible
- System.setSecurityManager(new mySecurityManager());
- try {
- group = InetAddress.getByName("224.0.0.3");
- groupSockAddr = new InetSocketAddress(group, groupPort);
- mss.leaveGroup(groupSockAddr, null);
- fail("Did not get exception when joining group is not allowed");
- } catch (SecurityException e) {
- }
- System.setSecurityManager(null);
-
- if (atLeastOneInterface) {
-
- // now test that we can join and leave a group successfully
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
- groupSockAddr = new InetSocketAddress(group, groupPort);
- mss.joinGroup(groupSockAddr, null);
- mss.leaveGroup(groupSockAddr, null);
- try {
- mss.leaveGroup(groupSockAddr, null);
- fail(
- "Did not get exception when trying to leave group that was allready left");
- } catch (IOException e) {
- }
-
- InetAddress group2 = InetAddress.getByName("224.0.0.4");
- groupSockAddr2 = new InetSocketAddress(group2, groupPort);
- mss.joinGroup(groupSockAddr, networkInterface1);
- try {
- mss.leaveGroup(groupSockAddr2, networkInterface1);
- fail(
- "Did not get exception when trying to leave group that was never joined");
- } catch (IOException e) {
- }
-
- mss.leaveGroup(groupSockAddr, networkInterface1);
- if (atLeastTwoInterfaces) {
- mss.joinGroup(groupSockAddr, networkInterface1);
- try {
- mss.leaveGroup(groupSockAddr, networkInterface2);
- fail(
- "Did not get exception when trying to leave group on wrong interface joined on ["
- + networkInterface1
- + "] left on ["
- + networkInterface2 + "]");
- } catch (IOException e) {
- }
- }
- }
-
- System.setSecurityManager(null);
- }
-
- /**
- * @tests java.net.MulticastSocket#send(java.net.DatagramPacket, byte)
- */
- public void test_sendLjava_net_DatagramPacketB() {
- // Test for method void
- // java.net.MulticastSocket.send(java.net.DatagramPacket, byte)
-
- String msg = "Hello World";
- InetAddress group = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
-
- try {
- group = InetAddress.getByName("224.0.0.3");
- mss = new MulticastSocket(ports[1]);
- server = new MulticastServer(group, groupPort);
- server.start();
- Thread.sleep(200);
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg
- .length(), group, groupPort);
- mss.send(sdp, (byte) 10);
- Thread.sleep(1000);
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (Exception e) {
- handleException(e, SO_MULTICAST);
- try {
- mss.close();
- } catch (Exception ex) {
- }
- ;
- return;
- }
- mss.close();
- byte[] data = server.rdp.getData();
- int length = server.rdp.getLength();
- assertEquals("Failed to send data. Received " + length,
- msg, new String(data, 0, length));
- }
-
- /**
- * @tests java.net.MulticastSocket#setInterface(java.net.InetAddress)
- */
- public void test_setInterfaceLjava_net_InetAddress() throws UnknownHostException {
- // Test for method void
- // java.net.MulticastSocket.setInterface(java.net.InetAddress)
- // Note that the machine is not multi-homed
-
- try {
- mss = new MulticastSocket();
- mss.setInterface(InetAddress.getLocalHost());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST_INTERFACE);
- } catch (Exception e) {
- handleException(e, SO_MULTICAST_INTERFACE);
- return;
- }
- try {
- InetAddress theInterface = mss.getInterface();
- // under IPV6 we are not guarrenteed to get the same address back as
- // the address, all we should be guaranteed is that we get an
- // address on the same interface
- if (theInterface instanceof Inet6Address) {
- assertTrue(
- "Failed to return correct interface IPV6",
- NetworkInterface
- .getByInetAddress(mss.getInterface())
- .equals(
- NetworkInterface
- .getByInetAddress(theInterface)));
- } else {
- assertTrue("Failed to return correct interface IPV4 got:"
- + mss.getInterface() + " excpeted: "
- + InetAddress.getLocalHost(), mss.getInterface()
- .equals(InetAddress.getLocalHost()));
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (SocketException e) {
- handleException(e, SO_MULTICAST);
- }
-
- // Regression test for Harmony-2410
- try {
- mss = new MulticastSocket();
- mss.setInterface(InetAddress.getByName("224.0.0.5"));
- } catch (SocketException se) {
- // expected
- } catch (IOException ioe) {
- handleException(ioe, SO_MULTICAST_INTERFACE);
- return;
- }
- }
-
- /**
- * @throws IOException
- * @throws InterruptedException
- * @tests java.net.MulticastSocket#setNetworkInterface(java.net.NetworkInterface)
- */
- public void test_setNetworkInterfaceLjava_net_NetworkInterface() throws IOException, InterruptedException {
- String msg = null;
- InetAddress group = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
- int serverPort = ports[1];
- if (atLeastOneInterface) {
- // validate that null interface is handled ok
- mss = new MulticastSocket(groupPort);
-
- // this should through a socket exception to be compatible
- try {
- mss.setNetworkInterface(null);
- fail("No socket exception when we set then network interface with NULL");
- } catch (SocketException ex) {
- }
-
- // validate that we can get and set the interface
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
- mss.setNetworkInterface(networkInterface1);
- assertEquals("Interface did not seem to be set by setNeworkInterface",
- networkInterface1, mss.getNetworkInterface());
-
- // set up the server and join the group
- group = InetAddress.getByName("224.0.0.3");
-
- Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
- while (theInterfaces.hasMoreElements()) {
- NetworkInterface thisInterface = (NetworkInterface) theInterfaces
- .nextElement();
- if (thisInterface.getInetAddresses().hasMoreElements()) {
- if ((!((InetAddress) thisInterface.getInetAddresses()
- .nextElement()).isLoopbackAddress())
- &&
- // for windows we cannot use these pseudo
- // interfaces for the test as the packets still
- // come from the actual interface, not the
- // Pseudo interface that was set
- (Support_NetworkInterface
- .useInterface(thisInterface) == true)) {
- ports = Support_PortManager.getNextPortsForUDP(2);
- serverPort = ports[0];
- server = new MulticastServer(group, serverPort);
- server.start();
- // give the server some time to start up
- Thread.sleep(1000);
-
- // Send the packets on a particular interface. The
- // source address in the received packet
- // should be one of the addresses for the interface
- // set
- groupPort = ports[1];
- mss = new MulticastSocket(groupPort);
- mss.setNetworkInterface(thisInterface);
- msg = thisInterface.getName();
- byte theBytes[] = msg.getBytes();
- DatagramPacket sdp = new DatagramPacket(theBytes,
- theBytes.length, group, serverPort);
- mss.send(sdp);
- Thread.sleep(1000);
- String receivedMessage = new String(server.rdp
- .getData(), 0, server.rdp.getLength());
- assertEquals("Group member did not recv data sent on a specific interface",
- msg, receivedMessage);
- // stop the server
- server.stopServer();
- }
- }
- }
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#setTimeToLive(int)
- */
- public void test_setTimeToLiveI() {
- try {
- mss = new MulticastSocket();
- mss.setTimeToLive(120);
- assertEquals("Returned incorrect 1st TTL",
- 120, mss.getTimeToLive());
- mss.setTimeToLive(220);
- assertEquals("Returned incorrect 2nd TTL",
- 220, mss.getTimeToLive());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (Exception e) {
- handleException(e, SO_MULTICAST);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#setTTL(byte)
- */
- public void test_setTTLB() {
- // Test for method void java.net.MulticastSocket.setTTL(byte)
- try {
- mss = new MulticastSocket();
- mss.setTTL((byte) 120);
- assertEquals("Failed to set TTL", 120, mss.getTTL());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_MULTICAST);
- } catch (Exception e) {
- handleException(e, SO_MULTICAST);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#MulticastSocket(java.net.SocketAddress)
- */
- public void test_ConstructorLjava_net_SocketAddress() throws Exception {
- MulticastSocket ms = new MulticastSocket((SocketAddress) null);
- assertTrue("should not be bound", !ms.isBound() && !ms.isClosed()
- && !ms.isConnected());
- ms.bind(new InetSocketAddress(InetAddress.getLocalHost(),
- Support_PortManager.getNextPortForUDP()));
- assertTrue("should be bound", ms.isBound() && !ms.isClosed()
- && !ms.isConnected());
- ms.close();
- assertTrue("should be closed", ms.isClosed());
- ms = new MulticastSocket(new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP()));
- assertTrue("should be bound", ms.isBound() && !ms.isClosed()
- && !ms.isConnected());
- ms.close();
- assertTrue("should be closed", ms.isClosed());
- ms = new MulticastSocket(new InetSocketAddress("localhost",
- Support_PortManager.getNextPortForUDP()));
- assertTrue("should be bound", ms.isBound() && !ms.isClosed()
- && !ms.isConnected());
- ms.close();
- assertTrue("should be closed", ms.isClosed());
- boolean exception = false;
- try {
- ms = new MulticastSocket(new InetSocketAddress("unresolvedname",
- Support_PortManager.getNextPortForUDP()));
- } catch (IOException e) {
- exception = true;
- }
- assertTrue("Expected IOException", exception);
-
- // regression test for Harmony-1162
- InetSocketAddress addr = new InetSocketAddress("0.0.0.0", 0);
- MulticastSocket s = new MulticastSocket(addr);
- assertTrue(s.getReuseAddress());
- }
-
- /**
- * @tests java.net.MulticastSocket#getLoopbackMode()
- */
- public void test_getLoopbackMode() {
- try {
- MulticastSocket ms = new MulticastSocket((SocketAddress) null);
- assertTrue("should not be bound", !ms.isBound() && !ms.isClosed()
- && !ms.isConnected());
- ms.getLoopbackMode();
- assertTrue("should not be bound", !ms.isBound() && !ms.isClosed()
- && !ms.isConnected());
- ms.close();
- assertTrue("should be closed", ms.isClosed());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_USELOOPBACK);
- } catch (IOException e) {
- handleException(e, SO_USELOOPBACK);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#setLoopbackMode(boolean)
- */
- public void test_setLoopbackModeZ() {
- try {
- MulticastSocket ms = new MulticastSocket();
- ms.setLoopbackMode(true);
- assertTrue("loopback should be true", ms.getLoopbackMode());
- ms.setLoopbackMode(false);
- assertTrue("loopback should be false", !ms.getLoopbackMode());
- ms.close();
- assertTrue("should be closed", ms.isClosed());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_USELOOPBACK);
- } catch (IOException e) {
- handleException(e, SO_USELOOPBACK);
- }
- }
-
- /**
- * @tests java.net.MulticastSocket#setLoopbackMode(boolean)
- */
- public void test_setLoopbackModeSendReceive() throws IOException{
- final String ADDRESS = "224.1.2.3";
- final int PORT = Support_PortManager.getNextPortForUDP();
- final String message = "Hello, world!";
-
- // test send receive
- MulticastSocket socket = null;
- try {
- // open a multicast socket
- socket = new MulticastSocket(PORT);
- socket.setLoopbackMode(false); // false indecates doing loop back
- socket.joinGroup(InetAddress.getByName(ADDRESS));
-
- // send the datagram
- byte[] sendData = message.getBytes();
- DatagramPacket sendDatagram = new DatagramPacket(sendData, 0,
- sendData.length, new InetSocketAddress(InetAddress
- .getByName(ADDRESS), PORT));
- socket.send(sendDatagram);
-
- // receive the datagram
- byte[] recvData = new byte[100];
- DatagramPacket recvDatagram = new DatagramPacket(recvData,
- recvData.length);
- socket.setSoTimeout(5000); // prevent eternal block in
- // socket.receive()
- socket.receive(recvDatagram);
- String recvMessage = new String(recvData, 0, recvDatagram
- .getLength());
- assertEquals(message, recvMessage);
- }finally {
- if (socket != null)
- socket.close();
- }
- }
-
-
- /**
- * @tests java.net.MulticastSocket#setReuseAddress(boolean)
- */
- public void test_setReuseAddressZ() throws Exception {
- try {
- // test case were we set it to false
- MulticastSocket theSocket1 = null;
- MulticastSocket theSocket2 = null;
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new MulticastSocket(null);
- theSocket2 = new MulticastSocket(null);
- theSocket1.setReuseAddress(false);
- theSocket2.setReuseAddress(false);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- fail(
- "No exception when trying to connect to do duplicate socket bind with re-useaddr set to false");
- } catch (BindException e) {
-
- }
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
-
- // test case were we set it to true
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new MulticastSocket(null);
- theSocket2 = new MulticastSocket(null);
- theSocket1.setReuseAddress(true);
- theSocket2.setReuseAddress(true);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
-
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
-
- // test the default case which we expect to be
- // the same on all platforms
- theAddress =
- new InetSocketAddress(
- InetAddress.getLocalHost(),
- Support_PortManager.getNextPortForUDP());
- theSocket1 = new MulticastSocket(null);
- theSocket2 = new MulticastSocket(null);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
- } catch (Exception e) {
- handleException(e, SO_REUSEADDR);
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
-
- Enumeration theInterfaces = null;
- try {
- theInterfaces = NetworkInterface.getNetworkInterfaces();
- } catch (Exception e) {
- }
-
- // only consider interfaces that have addresses associated with them.
- // Otherwise tests don't work so well
- if (theInterfaces != null) {
-
- atLeastOneInterface = false;
- while (theInterfaces.hasMoreElements()
- && (atLeastOneInterface == false)) {
- networkInterface1 = (NetworkInterface) theInterfaces
- .nextElement();
- if (networkInterface1.getInetAddresses().hasMoreElements() &&
- // we only want real interfaces
- (Support_NetworkInterface
- .useInterface(networkInterface1) == true)) {
- atLeastOneInterface = true;
- }
- }
-
- atLeastTwoInterfaces = false;
- if (theInterfaces.hasMoreElements()) {
- while (theInterfaces.hasMoreElements()
- && (atLeastTwoInterfaces == false)) {
- networkInterface2 = (NetworkInterface) theInterfaces
- .nextElement();
- if (networkInterface2.getInetAddresses().hasMoreElements()
- &&
- // we only want real interfaces
- (Support_NetworkInterface
- .useInterface(networkInterface2) == true)) {
- atLeastTwoInterfaces = true;
- }
- }
- }
-
- Enumeration addresses;
-
- // first the first interface that supports IPV6 if one exists
- try {
- theInterfaces = NetworkInterface.getNetworkInterfaces();
- } catch (Exception e) {
- }
- boolean found = false;
- while (theInterfaces.hasMoreElements() && !found) {
- NetworkInterface nextInterface = (NetworkInterface) theInterfaces
- .nextElement();
- addresses = nextInterface.getInetAddresses();
- if (addresses.hasMoreElements()) {
- while (addresses.hasMoreElements()) {
- InetAddress nextAddress = (InetAddress) addresses
- .nextElement();
- if (nextAddress instanceof Inet6Address) {
- IPV6networkInterface1 = nextInterface;
- found = true;
- break;
- }
- }
- }
- }
- }
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
-
- if (t != null)
- t.interrupt();
- if (mss != null)
- mss.close();
- if (server != null)
- server.stopServer();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/NetPermissionTest.java b/luni/src/test/java/tests/api/java/net/NetPermissionTest.java
deleted file mode 100644
index 525871e..0000000
--- a/luni/src/test/java/tests/api/java/net/NetPermissionTest.java
+++ /dev/null
@@ -1,81 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.NetPermission;
-
-@TestTargetClass(NetPermission.class)
-public class NetPermissionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.NetPermission#NetPermission(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NetPermission",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.NetPermission(java.lang.String)
- NetPermission n = new NetPermission("requestPasswordAuthentication");
- assertEquals("Returned incorrect name",
- "requestPasswordAuthentication", n.getName());
- }
-
- /**
- * @tests java.net.NetPermission#NetPermission(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NetPermission",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.net.NetPermission(java.lang.String,
- // java.lang.String)
- NetPermission n = new NetPermission("requestPasswordAuthentication",
- null);
- assertEquals("Returned incorrect name",
- "requestPasswordAuthentication", n.getName());
- NetPermission n1 = new NetPermission("requestPasswordAuthentication",
- "");
- assertEquals("", n1.getActions());
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/NetworkInterfaceTest.java b/luni/src/test/java/tests/api/java/net/NetworkInterfaceTest.java
deleted file mode 100644
index 972b342..0000000
--- a/luni/src/test/java/tests/api/java/net/NetworkInterfaceTest.java
+++ /dev/null
@@ -1,561 +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 java.net.InetAddress;
-import java.net.InterfaceAddress;
-import java.net.NetworkInterface;
-import java.net.SocketException;
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.List;
-
-public class NetworkInterfaceTest extends junit.framework.TestCase {
-
- // private member variables used for tests
- Enumeration<NetworkInterface> theInterfaces = null;
-
- boolean atLeastOneInterface = false;
-
- boolean atLeastTwoInterfaces = false;
-
- private NetworkInterface networkInterface1 = null;
-
- private NetworkInterface sameAsNetworkInterface1 = null;
-
- private NetworkInterface networkInterface2 = null;
-
- /**
- * @tests java.net.NetworkInterface#getName()
- */
- public void test_getName() {
- if (atLeastOneInterface) {
- assertNotNull("validate that non null name is returned",
- networkInterface1.getName());
- assertFalse("validate that non-zero length name is generated",
- networkInterface1.getName().equals(""));
- }
- if (atLeastTwoInterfaces) {
- assertFalse(
- "Validate strings are different for different interfaces",
- networkInterface1.getName().equals(
- networkInterface2.getName()));
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#getInetAddresses()
- */
- public void test_getInetAddresses() throws Exception {
-
- // security manager that allows us to check that we only return the
- // addresses that we should
- class mySecurityManager extends SecurityManager {
-
- ArrayList disallowedNames = null;
-
- public mySecurityManager(ArrayList addresses) {
- disallowedNames = new ArrayList();
- for (int i = 0; i < addresses.size(); i++) {
- disallowedNames.add(((InetAddress) addresses.get(i))
- .getHostName());
- disallowedNames.add(((InetAddress) addresses.get(i))
- .getHostAddress());
- }
- }
-
- public void checkConnect(String host, int port) {
-
- if (host == null) {
- throw new NullPointerException("host was null)");
- }
-
- for (int i = 0; i < disallowedNames.size(); i++) {
- if (((String) disallowedNames.get(i)).equals(host)) {
- throw new SecurityException("not allowed");
- }
- }
- }
-
- }
-
- if (atLeastOneInterface) {
- Enumeration theAddresses = networkInterface1.getInetAddresses();
- while (theAddresses.hasMoreElements()) {
- InetAddress theAddress = (InetAddress) theAddresses
- .nextElement();
- assertNotNull("validate that address is not null", theAddress);
- }
- }
-
- if (atLeastTwoInterfaces) {
- Enumeration theAddresses = networkInterface2.getInetAddresses();
- while (theAddresses.hasMoreElements()) {
- InetAddress theAddress = (InetAddress) theAddresses
- .nextElement();
- assertNotNull("validate that address is not null", theAddress);
- }
- }
-
- // create the list of ok and not ok addresses to return
- if (atLeastOneInterface) {
- ArrayList okAddresses = new ArrayList();
- Enumeration addresses = networkInterface1.getInetAddresses();
- int index = 0;
- ArrayList notOkAddresses = new ArrayList();
- while (addresses.hasMoreElements()) {
- InetAddress theAddress = (InetAddress) addresses.nextElement();
- if (index != 0) {
- okAddresses.add(theAddress);
- } else {
- notOkAddresses.add(theAddress);
- }
- index++;
- }
-
- // do the same for network interface 2 if it exists
- if (atLeastTwoInterfaces) {
- addresses = networkInterface2.getInetAddresses();
- index = 0;
- while (addresses.hasMoreElements()) {
- InetAddress theAddress = (InetAddress) addresses
- .nextElement();
- if (index != 0) {
- okAddresses.add(theAddress);
- } else {
- notOkAddresses.add(theAddress);
- }
- index++;
- }
- }
-
- // set the security manager that will make the first address not
- // visible
- System.setSecurityManager(new mySecurityManager(notOkAddresses));
-
- // validate not ok addresses are not returned
- for (int i = 0; i < notOkAddresses.size(); i++) {
- Enumeration reducedAddresses = networkInterface1
- .getInetAddresses();
- while (reducedAddresses.hasMoreElements()) {
- InetAddress nextAddress = (InetAddress) reducedAddresses
- .nextElement();
- assertTrue(
- "validate that address without permission is not returned",
- !nextAddress.equals(notOkAddresses.get(i)));
- }
- if (atLeastTwoInterfaces) {
- reducedAddresses = networkInterface2.getInetAddresses();
- while (reducedAddresses.hasMoreElements()) {
- InetAddress nextAddress = (InetAddress) reducedAddresses
- .nextElement();
- assertTrue(
- "validate that address without permission is not returned",
- !nextAddress.equals(notOkAddresses.get(i)));
- }
- }
- }
-
- // validate that ok addresses are returned
- for (int i = 0; i < okAddresses.size(); i++) {
- boolean addressReturned = false;
- Enumeration reducedAddresses = networkInterface1
- .getInetAddresses();
- while (reducedAddresses.hasMoreElements()) {
- InetAddress nextAddress = (InetAddress) reducedAddresses
- .nextElement();
- if (nextAddress.equals(okAddresses.get(i))) {
- addressReturned = true;
- }
- }
- if (atLeastTwoInterfaces) {
- reducedAddresses = networkInterface2.getInetAddresses();
- while (reducedAddresses.hasMoreElements()) {
- InetAddress nextAddress = (InetAddress) reducedAddresses
- .nextElement();
- if (nextAddress.equals(okAddresses.get(i))) {
- addressReturned = true;
- }
- }
- }
- assertTrue("validate that address with permission is returned",
- addressReturned);
- }
-
- // validate that we can get the interface by specifying the address.
- // This is to be compatible
- for (int i = 0; i < notOkAddresses.size(); i++) {
- assertNotNull(
- "validate we cannot get the NetworkInterface with an address for which we have no privs",
- NetworkInterface
- .getByInetAddress((InetAddress) notOkAddresses
- .get(i)));
- }
-
- // validate that we can get the network interface for the good
- // addresses
- for (int i = 0; i < okAddresses.size(); i++) {
- assertNotNull(
- "validate we cannot get the NetworkInterface with an address fro which we have no privs",
- NetworkInterface
- .getByInetAddress((InetAddress) okAddresses
- .get(i)));
- }
-
- System.setSecurityManager(null);
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#getDisplayName()
- */
- public void test_getDisplayName() {
- if (atLeastOneInterface) {
- assertNotNull("validate that non null display name is returned",
- networkInterface1.getDisplayName());
- assertFalse(
- "validate that non-zero length display name is generated",
- networkInterface1.getDisplayName().equals(""));
- }
- if (atLeastTwoInterfaces) {
- assertFalse(
- "Validate strings are different for different interfaces",
- networkInterface1.getDisplayName().equals(
- networkInterface2.getDisplayName()));
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#getByName(java.lang.String)
- */
- public void test_getByNameLjava_lang_String() throws Exception {
- try {
- assertNull("validate null handled ok",
- NetworkInterface.getByName(null));
- fail("getByName did not throw NullPointerException for null argument");
- } catch (NullPointerException e) {
- }
-
- assertNull("validate handled ok if we ask for name not associated with any interface",
- NetworkInterface.getByName("8not a name4"));
-
- // for each address in an interface validate that we get the right
- // interface for that name
- if (atLeastOneInterface) {
- String theName = networkInterface1.getName();
- if (theName != null) {
- assertEquals(
- "validate that Interface can be obtained with its name",
- networkInterface1, NetworkInterface.getByName(theName));
- }
- }
-
- // validate that we get the right interface with the second interface as
- // well (ie we just don't always get the first interface
- if (atLeastTwoInterfaces) {
- String theName = networkInterface2.getName();
- if (theName != null) {
- assertEquals(
- "validate that Interface can be obtained with its name",
- networkInterface2, NetworkInterface.getByName(theName));
- }
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#getByInetAddress(java.net.InetAddress)
- */
- public void test_getByInetAddressLjava_net_InetAddress() throws Exception {
-
- byte addressBytes[] = new byte[4];
- addressBytes[0] = 0;
- addressBytes[1] = 0;
- addressBytes[2] = 0;
- addressBytes[3] = 0;
-
- try {
- assertNull("validate null handled ok",
- NetworkInterface.getByInetAddress(null));
- fail("should not get here if getByInetAddress throws "
- + "NullPointerException if null passed in");
- } catch (NullPointerException e) {
- }
-
- assertNull("validate handled ok if we ask for address not associated with any interface",
- NetworkInterface.getByInetAddress(InetAddress
- .getByAddress(addressBytes)));
-
- // for each address in an interface validate that we get the right
- // interface for that address
- if (atLeastOneInterface) {
- Enumeration addresses = networkInterface1.getInetAddresses();
- while (addresses.hasMoreElements()) {
- InetAddress theAddress = (InetAddress) addresses.nextElement();
- assertEquals(
- "validate that Interface can be obtained with any one of its addresses",
- networkInterface1, NetworkInterface
- .getByInetAddress(theAddress));
- }
- }
-
- // validate that we get the right interface with the second interface as
- // well (ie we just don't always get the first interface
- if (atLeastTwoInterfaces) {
- Enumeration addresses = networkInterface2.getInetAddresses();
- while (addresses.hasMoreElements()) {
- InetAddress theAddress = (InetAddress) addresses.nextElement();
- assertEquals(
- "validate that Interface can be obtained with any one of its addresses",
- networkInterface2, NetworkInterface
- .getByInetAddress(theAddress));
- }
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#getNetworkInterfaces()
- */
- public void test_getNetworkInterfaces() throws Exception {
-
- // really this is tested by all of the other calls but just make sure we
- // can call it and get a list of interfaces if they exist
- Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
- }
-
- /**
- * @tests java.net.NetworkInterface#equals(java.lang.Object)
- */
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean
- // java.net.SocketPermission.equals(java.lang.Object)
- if (atLeastOneInterface) {
- assertEquals("If objects are the same true is returned",
- sameAsNetworkInterface1, networkInterface1);
- assertNotNull("Validate Null handled ok", networkInterface1);
- }
- if (atLeastTwoInterfaces) {
- assertFalse("If objects are different false is returned",
- networkInterface1.equals(networkInterface2));
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#hashCode()
- */
- public void test_hashCode() {
-
- if (atLeastOneInterface) {
- assertTrue(
- "validate that hash codes are the same for two calls on the same object",
- networkInterface1.hashCode() == networkInterface1
- .hashCode());
- assertTrue(
- "validate that hash codes are the same for two objects for which equals is true",
- networkInterface1.hashCode() == sameAsNetworkInterface1
- .hashCode());
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#toString()
- */
- public void test_toString() {
- if (atLeastOneInterface) {
- assertNotNull("validate that non null string is generated",
- networkInterface1.toString());
- assertFalse("validate that non-zero length string is generated",
- networkInterface1.toString().equals(""));
- }
- if (atLeastTwoInterfaces) {
- assertFalse(
- "Validate strings are different for different interfaces",
- networkInterface1.toString().equals(
- networkInterface2.toString()));
- }
- }
-
- private class MockSecurityManager extends SecurityManager {
- @Override
- public void checkConnect(String host, int port) {
- throw new SecurityException();
- }
- }
-
- /**
- *
- * @tests java.net.NetworkInterface#getInterfaceAddresses()
- *
- * @since 1.6
- */
- public void test_getInterfaceAddresses() throws SocketException {
- if (theInterfaces != null) {
- SecurityManager oldSM = System.getSecurityManager();
- System.setSecurityManager(new MockSecurityManager());
-
- while (theInterfaces.hasMoreElements()) {
- NetworkInterface netif = theInterfaces.nextElement();
- assertEquals(netif.getName()
- + " getInterfaceAddresses should contain no element", 0,
- netif.getInterfaceAddresses().size());
- }
- System.setSecurityManager(oldSM);
-
- theInterfaces = NetworkInterface.getNetworkInterfaces();
- while (theInterfaces.hasMoreElements()) {
- NetworkInterface netif = theInterfaces.nextElement();
- List<InterfaceAddress> interfaceAddrs = netif.getInterfaceAddresses();
- assertTrue(interfaceAddrs instanceof ArrayList);
- for (InterfaceAddress addr : interfaceAddrs) {
- assertNotNull(addr);
- }
-
- List<InterfaceAddress> interfaceAddrs2 = netif.getInterfaceAddresses();
- // RI fails on this since it cannot tolerate null broadcast address.
- assertEquals(interfaceAddrs, interfaceAddrs2);
- }
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#isLoopback()
- *
- * @since 1.6
- */
- public void test_isLoopback() throws SocketException {
- if (theInterfaces != null) {
- while (theInterfaces.hasMoreElements()) {
- NetworkInterface netif = theInterfaces.nextElement();
- boolean loopback = false;
- Enumeration<InetAddress> addrs = netif.getInetAddresses();
- while(addrs != null && addrs.hasMoreElements()){
- if(addrs.nextElement().isLoopbackAddress()){
- loopback = true;
- break;
- }
- }
- assertEquals(loopback, netif.isLoopback());
- }
- }
- }
-
- /**
- * @tests java.net.NetworkInterface#getHardwareAddress()
- *
- * @since 1.6
- */
- public void test_getHardwareAddress() throws SocketException {
- if (theInterfaces != null) {
- while (theInterfaces.hasMoreElements()) {
- NetworkInterface netif = theInterfaces.nextElement();
- byte[] hwAddr = netif.getHardwareAddress();
- if (netif.isLoopback()) {
- assertTrue(hwAddr == null || hwAddr.length == 0);
- } else {
- assertTrue(hwAddr.length >= 0);
- }
- }
- }
- }
-
- /**
- *
- * @tests java.net.NetworkInterface#getHardwareAddress()
- *
- * @since 1.6
- */
- public void test_getMTU() throws SocketException {
- if (theInterfaces != null) {
- while (theInterfaces.hasMoreElements()) {
- NetworkInterface netif = theInterfaces.nextElement();
- assertTrue(netif.getName() + "has non-positive MTU", netif.getMTU() >= 0);
- }
- }
- }
-
- protected void setUp() throws SocketException {
-
- Enumeration theInterfaces = null;
- try {
- theInterfaces = NetworkInterface.getNetworkInterfaces();
- } catch (Exception e) {
- fail("Exception occurred getting network interfaces : " + e);
- }
-
- // Set up NetworkInterface instance members. Note that because the call
- // to NetworkInterface.getNetworkInterfaces() returns *all* of the
- // interfaces on the test machine it is possible that one or more of
- // them will not currently be bound to an InetAddress. e.g. a laptop
- // running connected by a wire to the local network may also have a
- // wireless interface that is not active and so has no InetAddress
- // bound to it. For these tests only work with NetworkInterface objects
- // that are bound to an InetAddress.
- if ((theInterfaces != null) && (theInterfaces.hasMoreElements())) {
- while ((theInterfaces.hasMoreElements())
- && (atLeastOneInterface == false)) {
- NetworkInterface theInterface = (NetworkInterface) theInterfaces
- .nextElement();
- if (theInterface.getInetAddresses().hasMoreElements()) {
- // Ensure that the current NetworkInterface has at least
- // one InetAddress bound to it.
- Enumeration addrs = theInterface.getInetAddresses();
- if ((addrs != null) && (addrs.hasMoreElements())) {
- atLeastOneInterface = true;
- networkInterface1 = theInterface;
- }// end if
- }
- }
-
- while ((theInterfaces.hasMoreElements())
- && (atLeastTwoInterfaces == false)) {
- NetworkInterface theInterface = (NetworkInterface) theInterfaces
- .nextElement();
- if (theInterface.getInetAddresses().hasMoreElements()) {
- // Ensure that the current NetworkInterface has at least
- // one InetAddress bound to it.
- Enumeration addrs = theInterface.getInetAddresses();
- if ((addrs != null) && (addrs.hasMoreElements())) {
- atLeastTwoInterfaces = true;
- networkInterface2 = theInterface;
- }// end if
- }
- }
-
- // Only set sameAsNetworkInterface1 if we succeeded in finding
- // at least one good NetworkInterface
- if (atLeastOneInterface) {
- Enumeration addresses = networkInterface1.getInetAddresses();
- if (addresses.hasMoreElements()) {
- try {
- if (addresses.hasMoreElements()) {
- sameAsNetworkInterface1 = NetworkInterface
- .getByInetAddress((InetAddress) addresses
- .nextElement());
- }
- } catch (SocketException e) {
- fail("SocketException occurred : " + e);
- }
- }
- }// end if atLeastOneInterface
- }
- theInterfaces = NetworkInterface.getNetworkInterfaces();
- }
-
- protected void tearDown() {
- System.setSecurityManager(null);
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/NoRouteToHostExceptionTest.java b/luni/src/test/java/tests/api/java/net/NoRouteToHostExceptionTest.java
deleted file mode 100644
index db6149a..0000000
--- a/luni/src/test/java/tests/api/java/net/NoRouteToHostExceptionTest.java
+++ /dev/null
@@ -1,88 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.NoRouteToHostException;
-
-@TestTargetClass(NoRouteToHostException.class)
-public class NoRouteToHostExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.NoRouteToHostException#NoRouteToHostException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoRouteToHostException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.net.NoRouteToHostException()
-
- try {
- if (true)
- throw new NoRouteToHostException();
- } catch (NoRouteToHostException e) {
- return;
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * @tests java.net.NoRouteToHostException#NoRouteToHostException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "NoRouteToHostException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.NoRouteToHostException(java.lang.String)
- // Cannot test correctly without changing some routing tables !!
-
- try {
- if (true)
- throw new NoRouteToHostException("test");
- } catch (NoRouteToHostException e) {
- assertEquals("Threw exception with incorrect message", "test", e.getMessage()
- );
- return;
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/PasswordAuthenticationTest.java b/luni/src/test/java/tests/api/java/net/PasswordAuthenticationTest.java
deleted file mode 100644
index 7eb7396..0000000
--- a/luni/src/test/java/tests/api/java/net/PasswordAuthenticationTest.java
+++ /dev/null
@@ -1,94 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.PasswordAuthentication;
-
-@TestTargetClass(PasswordAuthentication.class)
-public class PasswordAuthenticationTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.PasswordAuthentication#PasswordAuthentication(java.lang.String,
- * char[])
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PasswordAuthentication",
- args = {java.lang.String.class, char[].class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPassword",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getUserName",
- args = {}
- )
- })
- public void test_ConstructorLjava_lang_String$C() {
- // Test for method java.net.PasswordAuthentication(java.lang.String,
- // char [])
- char[] password = new char[] { 'd', 'r', 'o', 'w', 's', 's', 'a', 'p' };
- final String name = "Joe Blow";
- PasswordAuthentication pa = new PasswordAuthentication(name, password);
- char[] returnedPassword = pa.getPassword();
- assertTrue("Incorrect name", pa.getUserName().equals(name));
- assertTrue("Password was not cloned", returnedPassword != password);
- assertTrue("Passwords not equal length",
- returnedPassword.length == password.length);
- for (int counter = password.length - 1; counter >= 0; counter--)
- assertTrue("Passwords not equal",
- returnedPassword[counter] == password[counter]);
-
- try {
- new PasswordAuthentication(name, null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
-
- pa = new PasswordAuthentication(null, password);
- assertNull(pa.getUserName());
- assertEquals(password.length, pa.getPassword().length);
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/PortUnreachableExceptionTest.java b/luni/src/test/java/tests/api/java/net/PortUnreachableExceptionTest.java
deleted file mode 100644
index 75c769d..0000000
--- a/luni/src/test/java/tests/api/java/net/PortUnreachableExceptionTest.java
+++ /dev/null
@@ -1,56 +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.api.java.net;
-
-import junit.framework.TestCase;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import java.net.PasswordAuthentication;
-import java.net.PortUnreachableException;
-
-@TestTargetClass(PortUnreachableException.class)
-public class PortUnreachableExceptionTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PortUnreachableException",
- args = {}
- )
- public void test_Constructor() {
- PortUnreachableException pue = new PortUnreachableException();
- assertNull(pue.getMessage());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "PortUnreachableException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLString() {
- String [] messages = {"", null, "Test Message"};
- for(String str:messages) {
- PortUnreachableException pue = new PortUnreachableException(str);
- assertEquals(str, pue.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/ProtocolExceptionTest.java b/luni/src/test/java/tests/api/java/net/ProtocolExceptionTest.java
deleted file mode 100644
index 80bedc8..0000000
--- a/luni/src/test/java/tests/api/java/net/ProtocolExceptionTest.java
+++ /dev/null
@@ -1,85 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.ProtocolException;
-
-@TestTargetClass(ProtocolException.class)
-public class ProtocolExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.ProtocolException#ProtocolException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ProtocolException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.net.ProtocolException()
- try {
- throw new ProtocolException();
- } catch (ProtocolException e) {
- return;
- } catch (Exception e) {
- fail("Exception during ProtocolException test : " + e.getMessage());
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * @tests java.net.ProtocolException#ProtocolException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ProtocolException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.ProtocolException(java.lang.String)
- try {
- throw new ProtocolException("Some error message");
- } catch (ProtocolException e) {
- return;
- } catch (Exception e) {
- fail("Exception during ProtocolException test : " + e.getMessage());
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/ProxySelectorTest.java b/luni/src/test/java/tests/api/java/net/ProxySelectorTest.java
deleted file mode 100644
index 8dc0039..0000000
--- a/luni/src/test/java/tests/api/java/net/ProxySelectorTest.java
+++ /dev/null
@@ -1,727 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.NetPermission;
-import java.net.Proxy;
-import java.net.ProxySelector;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.security.Permission;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(ProxySelector.class)
-public class ProxySelectorTest extends TestCase {
-
- private static final String HTTP_PROXY_HOST = "127.0.0.1";
-
- private static final int HTTP_PROXY_PORT = 80;
-
- private static final String HTTPS_PROXY_HOST = "127.0.0.2";
-
- private static final int HTTPS_PROXY_PORT = 443;
-
- private static final String FTP_PROXY_HOST = "127.0.0.3";
-
- private static final int FTP_PROXY_PORT = 80;
-
- private static final String SOCKS_PROXY_HOST = "127.0.0.4";
-
- private static final int SOCKS_PROXY_PORT = 1080;
-
- private static URI httpUri;
-
- private static URI ftpUri;
-
- private static URI httpsUri;
-
- private static URI tcpUri;
-
- private List proxyList;
-
- private ProxySelector selector = ProxySelector.getDefault();
-
- static {
- try {
- httpUri = new URI("http://test.com");
- ftpUri = new URI("ftp://test.com");
- httpsUri = new URI("https://test.com");
- tcpUri = new URI("socket://host.com");
- } catch (URISyntaxException e) {
-
- }
- }
-
- /**
- * @tests java.net.ProxySelector#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for getDefault method.",
- method = "getDefault",
- args = {}
- )
- public void test_getDefault() {
- ProxySelector selector1 = ProxySelector.getDefault();
- assertNotNull(selector1);
-
- ProxySelector selector2 = ProxySelector.getDefault();
- assertSame(selector1, selector2);
- }
-
- /**
- * @tests java.net.ProxySelector#getDefault()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for getDefault method.",
- method = "getDefault",
- args = {}
- )
- public void test_getDefault_Security() {
- SecurityManager orignalSecurityManager = System.getSecurityManager();
- try {
- System.setSecurityManager(new MockSecurityManager());
- } catch (SecurityException e) {
- System.err.println("No setSecurityManager permission.");
- System.err.println("test_getDefault_Security is not tested");
- return;
- }
- try {
- ProxySelector.getDefault();
- fail("should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(orignalSecurityManager);
- }
- }
-
- /**
- * @tests java.net.ProxySelector#setDefault(ProxySelector)}
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for setDefault method.",
- method = "setDefault",
- args = {java.net.ProxySelector.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ProxySelector",
- args = {}
- )
- })
- public void test_setDefaultLjava_net_ProxySelector() {
- ProxySelector originalSelector = ProxySelector.getDefault();
- try {
- ProxySelector newSelector = new MockProxySelector();
- ProxySelector.setDefault(newSelector);
- assertSame(newSelector, ProxySelector.getDefault());
- // use null to unset
- ProxySelector.setDefault(null);
- assertSame(null, ProxySelector.getDefault());
- } finally {
- ProxySelector.setDefault(originalSelector);
- }
- }
-
- /**
- * @tests java.net.ProxySelector#setDefault(ProxySelector)}
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for setDefault method.",
- method = "setDefault",
- args = {java.net.ProxySelector.class}
- )
- public void test_setDefaultLjava_net_ProxySelector_Security() {
- ProxySelector originalSelector = ProxySelector.getDefault();
- SecurityManager orignalSecurityManager = System.getSecurityManager();
- try {
- System.setSecurityManager(new MockSecurityManager());
- } catch (SecurityException e) {
- System.err.println("No setSecurityManager permission.");
- System.err
- .println("test_setDefaultLjava_net_ProxySelector_Security is not tested");
- return;
- }
- try {
- ProxySelector.setDefault(new MockProxySelector());
- fail("should throw SecurityException");
- } catch (SecurityException e) {
- // expected
- } finally {
- System.setSecurityManager(orignalSecurityManager);
- ProxySelector.setDefault(originalSelector);
- }
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectExact()
- throws URISyntaxException {
- // no proxy, return a proxyList only contains NO_PROXY
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
-
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,HTTP_PROXY_HOST,HTTP_PROXY_PORT);
-
- proxyList = selector.select(httpsUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,HTTPS_PROXY_HOST,HTTPS_PROXY_PORT);
-
- proxyList = selector.select(ftpUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,FTP_PROXY_HOST,FTP_PROXY_PORT);
-
- proxyList = selector.select(tcpUri);
- assertProxyEquals(proxyList,Proxy.Type.SOCKS,SOCKS_PROXY_HOST,SOCKS_PROXY_PORT);
-
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectExact_NullHost()
- throws URISyntaxException {
- // regression test for Harmony-1063
- httpUri = new URI("http://a@");
- ftpUri = new URI("ftp://a@");
- httpsUri = new URI("https://a@");
- tcpUri = new URI("socket://a@");
- // no proxy, return a proxyList only contains NO_PROXY
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList, Proxy.NO_PROXY);
-
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList, Proxy.Type.HTTP, HTTP_PROXY_HOST,
- HTTP_PROXY_PORT);
-
- proxyList = selector.select(httpsUri);
- assertProxyEquals(proxyList, Proxy.Type.HTTP, HTTPS_PROXY_HOST,
- HTTPS_PROXY_PORT);
-
- proxyList = selector.select(ftpUri);
- assertProxyEquals(proxyList, Proxy.Type.HTTP, FTP_PROXY_HOST,
- FTP_PROXY_PORT);
-
- proxyList = selector.select(tcpUri);
- assertProxyEquals(proxyList, Proxy.Type.SOCKS, SOCKS_PROXY_HOST,
- SOCKS_PROXY_PORT);
-
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectExact_DefaultPort()
- throws URISyntaxException {
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
-
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
-
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,HTTP_PROXY_HOST,HTTP_PROXY_PORT);
-
- proxyList = selector.select(httpsUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,HTTPS_PROXY_HOST,HTTPS_PROXY_PORT);
-
- proxyList = selector.select(ftpUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,FTP_PROXY_HOST,FTP_PROXY_PORT);
-
- proxyList = selector.select(tcpUri);
- assertProxyEquals(proxyList,Proxy.Type.SOCKS,SOCKS_PROXY_HOST,SOCKS_PROXY_PORT);
-
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectExact_InvalidPort()
- throws URISyntaxException {
- final String INVALID_PORT = "abc";
-
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", INVALID_PORT);
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", INVALID_PORT);
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", INVALID_PORT);
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksproxyPort", INVALID_PORT);
-
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,HTTP_PROXY_HOST,HTTP_PROXY_PORT);
-
- proxyList = selector.select(httpsUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,HTTPS_PROXY_HOST,HTTPS_PROXY_PORT);
-
- proxyList = selector.select(ftpUri);
- assertProxyEquals(proxyList,Proxy.Type.HTTP,FTP_PROXY_HOST,FTP_PROXY_PORT);
-
- proxyList = selector.select(tcpUri);
- assertProxyEquals(proxyList,Proxy.Type.SOCKS,SOCKS_PROXY_HOST,SOCKS_PROXY_PORT);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- // RI may fail this test case.
- // Uncomment this test case when regex.jar is ready.
- /*
- public void test_selectLjava_net_URI_Select_NonProxyHosts()
- throws URISyntaxException {
- // RI's bug. Some RIs may fail this test case.
- URI[] httpUris = { new URI("http://test.com"),
- new URI("http://10.10.1.2"), new URI("http://a"),
- new URI("http://def.abc.com") };
- URI[] ftpUris = { new URI("ftp://test.com"),
- new URI("ftp://10.10.1.2"), new URI("ftp://a"),
- new URI("ftp://def.abc.com") };
-
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.nonProxyHosts", "a|b|tes*|10.10.*|*.abc.com");
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.nonProxyHosts", "a|b|tes*|10.10.*|*.abc.com");
-
- for (int i = 0; i < httpUris.length; i++) {
- proxyList = selector.select(httpUris[i]);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
- }
-
- for (int i = 0; i < ftpUris.length; i++) {
- proxyList = selector.select(ftpUris[i]);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
- }
- }*/
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectLikeHTTP()
- throws URISyntaxException {
- System.setProperty("http.proxyHost", "");
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList,Proxy.Type.SOCKS,SOCKS_PROXY_HOST,SOCKS_PROXY_PORT);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectNoHTTP()
- throws URISyntaxException {
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
-
- proxyList = selector.select(httpUri);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectLikeHTTPS()
- throws URISyntaxException {
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set https proxy host empty
- System.setProperty("http.proxyHost", "");
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-
- proxyList = selector.select(httpsUri);
- assertProxyEquals(proxyList,Proxy.Type.SOCKS,SOCKS_PROXY_HOST,SOCKS_PROXY_PORT);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectNoHTTPS()
- throws URISyntaxException {
- // set https proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
-
- proxyList = selector.select(httpsUri);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectLikeFTP()
- throws URISyntaxException {
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set ftp host empty
- System.setProperty("ftp.proxyHost", "");
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-
- proxyList = selector.select(ftpUri);
- assertProxyEquals(proxyList,Proxy.Type.SOCKS,SOCKS_PROXY_HOST,SOCKS_PROXY_PORT);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectNoFTP()
- throws URISyntaxException {
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
-
- proxyList = selector.select(ftpUri);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_SelectNoSOCKS()
- throws URISyntaxException {
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set socks proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
-
- proxyList = selector.select(tcpUri);
- assertProxyEquals(proxyList,Proxy.NO_PROXY);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for connectFailed method.",
- method = "connectFailed",
- args = {java.net.URI.class, java.net.SocketAddress.class, java.io.IOException.class}
- )
- public void test_connectionFailedLjava_net_URILjava_net_SocketAddressLjava_io_IOException()
- throws URISyntaxException {
- // set http proxy
- System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
- System.setProperty("http.proxyPort", String.valueOf(HTTP_PROXY_PORT));
- // set https proxy
- System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
- System.setProperty("https.proxyPort", String.valueOf(HTTPS_PROXY_PORT));
- // set ftp proxy
- System.setProperty("ftp.proxyHost", FTP_PROXY_HOST);
- System.setProperty("ftp.proxyPort", String.valueOf(FTP_PROXY_PORT));
- // set socks proxy
- System.setProperty("socksProxyHost", SOCKS_PROXY_HOST);
- System.setProperty("socksProxyPort", String.valueOf(SOCKS_PROXY_PORT));
-
- List proxyList1 = selector.select(httpUri);
- assertNotNull(proxyList1);
- assertEquals(1, proxyList1.size());
- Proxy proxy1 = (Proxy) proxyList1.get(0);
- selector
- .connectFailed(httpUri, proxy1.address(), new SocketException());
-
- List proxyList2 = selector.select(httpUri);
- assertNotNull(proxyList2);
- assertEquals(1, proxyList2.size());
- Proxy proxy2 = (Proxy) proxyList2.get(0);
- // Default implemention doesn't change the proxy list
- assertEquals(proxy1, proxy2);
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for connectFailed method.",
- method = "connectFailed",
- args = {java.net.URI.class, java.net.SocketAddress.class, java.io.IOException.class}
- )
- public void test_connectionFailedLjava_net_URILjava_net_SocketAddressLjava_io_IOException_IllegalArguement()
- throws URISyntaxException {
- SocketAddress sa = InetSocketAddress.createUnresolved("127.0.0.1", 0);
- try {
- selector.connectFailed(null, sa, new SocketException());
- fail("should throw IllegalArgumentException if any argument is null.");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- selector.connectFailed(httpUri, null, new SocketException());
- fail("should throw IllegalArgumentException if any argument is null.");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- selector.connectFailed(httpUri, sa, null);
- fail("should throw IllegalArgumentException if any argument is null.");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- }
-
- /**
- * @tests java.net.ProxySelector#select(URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for select method.",
- method = "select",
- args = {java.net.URI.class}
- )
- public void test_selectLjava_net_URI_IllegalArgument()
- throws URISyntaxException {
- URI[] illegalUris = { new URI("abc"), new URI("http"), null };
- for (int i = 0; i < illegalUris.length; i++) {
- try {
- selector.select(illegalUris[i]);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
- }
-
- /*
- * asserts whether selectedProxyList contains one and only one element,
- * and the element equals proxy.
- */
- private void assertProxyEquals(List selectedProxyList, Proxy proxy) {
- assertNotNull(selectedProxyList);
- assertEquals(1, selectedProxyList.size());
- assertEquals((Proxy) selectedProxyList.get(0), proxy);
- }
-
- /*
- * asserts whether selectedProxyList contains one and only one element,
- * and the element equals proxy which is represented by arguments "type",
- * "host","port".
- */
- private void assertProxyEquals(List selectedProxyList, Proxy.Type type,
- String host, int port) {
- SocketAddress sa = InetSocketAddress.createUnresolved(host, port);
- Proxy proxy = new Proxy(type, sa);
- assertProxyEquals(selectedProxyList, proxy);
- }
-
- /*
- * Mock selector for setDefault test
- */
- static class MockProxySelector extends ProxySelector {
-
- public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
-
- }
-
- public List <Proxy> select(URI uri) {
- return null;
- }
- }
-
- /*
- * MockSecurityMaanger. It denies NetPermission("getProxySelector") and
- * NetPermission("setProxySelector").
- */
- class MockSecurityManager extends SecurityManager {
- public void checkPermission(Permission permission) {
- if (permission instanceof NetPermission) {
- if ("getProxySelector".equals(permission.getName())) {
- throw new SecurityException();
- }
- }
-
- if (permission instanceof NetPermission) {
- if ("setProxySelector".equals(permission.getName())) {
- throw new SecurityException();
- }
- }
-
- if (permission instanceof RuntimePermission) {
- if ("setSecurityManager".equals(permission.getName())) {
- return;
- }
- }
- }
- }
-
- /*
- * @see junit.framework.TestCase#setUp()
- */
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- /*
- * @see junit.framework.TestCase#tearDown()
- */
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/ProxyTest.java b/luni/src/test/java/tests/api/java/net/ProxyTest.java
deleted file mode 100644
index 2c0843e..0000000
--- a/luni/src/test/java/tests/api/java/net/ProxyTest.java
+++ /dev/null
@@ -1,343 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.InetSocketAddress;
-import java.net.Proxy;
-import java.net.SocketAddress;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(Proxy.class)
-public class ProxyTest extends TestCase {
-
- private SocketAddress address = new InetSocketAddress("127.0.0.1", 1234);
-
- /**
- * @tests java.net.Proxy#Proxy(java.net.Proxy.Type, SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for Proxy constructor.",
- method = "Proxy",
- args = {java.net.Proxy.Type.class, java.net.SocketAddress.class}
- )
- public void test_ConstructorLjava_net_ProxyLjava_net_SocketAddress_Normal() {
- // test HTTP type proxy
- Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
- assertEquals(Proxy.Type.HTTP, proxy.type());
- assertEquals(address, proxy.address());
-
- // test SOCKS type proxy
- proxy = new Proxy(Proxy.Type.SOCKS, address);
- assertEquals(Proxy.Type.SOCKS, proxy.type());
- assertEquals(address, proxy.address());
-
- // test DIRECT type proxy
- proxy = Proxy.NO_PROXY;
- assertEquals(Proxy.Type.DIRECT, proxy.type());
- assertNull(proxy.address());
- }
-
- /**
- * @tests java.net.Proxy#Proxy(java.net.Proxy.Type, SocketAddress)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for Proxy constructor.",
- method = "Proxy",
- args = {java.net.Proxy.Type.class, java.net.SocketAddress.class}
- )
- public void test_ConstructorLjava_net_ProxyLjava_net_SocketAddress_IllegalAddress() {
- Proxy proxy = null;
- // test HTTP type proxy
- try {
- proxy = new Proxy(Proxy.Type.HTTP, null);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- // test SOCKS type proxy
- try {
- proxy = new Proxy(Proxy.Type.SOCKS, null);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- // test DIRECT type proxy
- try {
- proxy = new Proxy(Proxy.Type.DIRECT, null);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
- // test DIRECT type proxy, any address is illegal
- try {
- proxy = new Proxy(Proxy.Type.DIRECT, address);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- }
-
- /**
- * @tests java.net.Proxy#hashCode()
- * @see test_equalsLjava_lang_Object_Equals
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- SocketAddress address1 = new InetSocketAddress("127.0.0.1", 1234);
-
- Proxy proxy1 = new Proxy(Proxy.Type.HTTP, address1);
- Proxy proxy2 = new Proxy(Proxy.Type.HTTP, address1);
- assertTrue(proxy1.hashCode() == proxy2.hashCode());
-
- Proxy proxy3 = new Proxy(Proxy.Type.SOCKS, address1);
- Proxy proxy4 = new Proxy(Proxy.Type.SOCKS, address1);
- assertTrue(proxy1.hashCode() == proxy2.hashCode());
-
- assertTrue(proxy1.hashCode() != proxy4.hashCode());
-
- SocketAddress address2 = new InetSocketAddress("127.0.0.1", 1235);
-
- Proxy proxy5 = new Proxy(Proxy.Type.SOCKS, address1);
- Proxy proxy6 = new Proxy(Proxy.Type.SOCKS, address2);
- assertTrue(proxy5.hashCode() != proxy6.hashCode());
- }
-
- /**
- * @tests java.net.Proxy#type()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "type",
- args = {}
- )
- public void test_type() {
-
- Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
- assertEquals(Proxy.Type.HTTP, proxy.type());
-
- proxy = new Proxy(Proxy.Type.SOCKS, address);
- assertEquals(Proxy.Type.SOCKS, proxy.type());
-
- proxy = Proxy.NO_PROXY;
- assertEquals(Proxy.Type.DIRECT, proxy.type());
- }
-
- /**
- * @tests java.net.Proxy#address() This method has been tested in
- * Constructor test case.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "address",
- args = {}
- )
- public void test_address() {
- Proxy proxy = new Proxy(Proxy.Type.SOCKS, address);
- assertEquals(address, proxy.address());
-
- try {
- new Proxy(Proxy.Type.SOCKS, null);
- fail("IllegalArgumentException was thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- /**
- * @tests java.net.Proxy#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() {
- Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
- // include type String
- assertTrue(proxy.toString().indexOf(proxy.type().toString()) != -1);
- // include address String
- assertTrue(proxy.toString().indexOf(proxy.address().toString()) != -1);
-
- proxy = new Proxy(Proxy.Type.SOCKS, address);
- // include type String
- assertTrue(proxy.toString().indexOf(proxy.type().toString()) != -1);
- // include address String
- assertTrue(proxy.toString().indexOf(proxy.address().toString()) != -1);
-
- proxy = Proxy.NO_PROXY;
- // include type String
- assertTrue(proxy.toString().indexOf(proxy.type().toString()) != -1);
-
- proxy = new Proxy(null, address);
- // ensure no NPE is thrown
- proxy.toString();
-
- }
-
- /**
- * @tests java.net.Proxy#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for equals method.",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object_Equals() {
- SocketAddress address1 = new InetSocketAddress("127.0.0.1", 1234);
- SocketAddress address2 = new InetSocketAddress("127.0.0.1", 1234);
- // HTTP type
- Proxy proxy1 = new Proxy(Proxy.Type.HTTP, address1);
- Proxy proxy2 = new Proxy(Proxy.Type.HTTP, address2);
- assertTrue(proxy1.equals(proxy2));
- // assert hashCode
- assertTrue(proxy1.hashCode() == proxy2.hashCode());
-
- // SOCKS type
- Proxy proxy3 = new Proxy(Proxy.Type.SOCKS, address1);
- Proxy proxy4 = new Proxy(Proxy.Type.SOCKS, address2);
- assertTrue(proxy3.equals(proxy4));
- // assert hashCode
- assertTrue(proxy3.hashCode() == proxy4.hashCode());
-
- // null type
- Proxy proxy5 = new Proxy(null, address1);
- Proxy proxy6 = new Proxy(null, address2);
- assertTrue(proxy5.equals(proxy6));
- }
-
- /**
- * @tests java.net.Proxy#equals(Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "This is a complete subset of tests for equals method.",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object_NotEquals() {
- SocketAddress address1 = new InetSocketAddress("127.0.0.1", 1234);
- SocketAddress address2 = new InetSocketAddress("127.0.0.1", 1235);
- Proxy proxy[] = { new Proxy(Proxy.Type.HTTP, address1),
- new Proxy(Proxy.Type.HTTP, address2),
- new Proxy(Proxy.Type.SOCKS, address1),
- new Proxy(Proxy.Type.SOCKS, address2), Proxy.NO_PROXY,
- new Proxy(null, address1), new Proxy(null, address2) };
- // All of them are not equals
- for (int i = 0; i < proxy.length; i++) {
- for (int j = i + 1; j < proxy.length; j++) {
- assertFalse(proxy[i].equals(proxy[j]));
- }
- }
- // Not equals to an Object type instance. Ensure no exception is thrown.
- assertFalse(proxy[0].equals(new Object()));
- }
-
- /**
- * @tests java.net.Proxy.Type#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Proxy.Type.DIRECT, Proxy.Type.HTTP, Proxy.Type.SOCKS",
- method = "!Constants",
- args = {}
- )
- public void test_Type_valueOfLjava_lang_String_Normal() {
- assertEquals(Proxy.Type.DIRECT, Proxy.Type.valueOf("DIRECT"));
- assertEquals(Proxy.Type.HTTP, Proxy.Type.valueOf("HTTP"));
- assertEquals(Proxy.Type.SOCKS, Proxy.Type.valueOf("SOCKS"));
- }
-
- /**
- * @tests java.net.Proxy.Type#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!Constants",
- args = {}
- )
- public void test_Type_valueOfLjava_lang_String_IllegalName() {
- String[] illegalName = { "Direct", "direct", "http", "socks",
- "illegalName", "" };
- for (int i = 0; i < illegalName.length; i++) {
- try {
- Proxy.Type.valueOf(illegalName[i]);
- fail("should throw IllegalArgumentException, illegalName:"
- + illegalName);
- } catch (IllegalArgumentException e) {
- // expected
- }
- }
- }
-
- /**
- * @tests java.net.Proxy.Type#valueOf(String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!Constants",
- args = {}
- )
- public void test_Type_valueOfLjava_lang_String_NullPointerException() {
- // Some old RIs,which throw IllegalArgumentException.
- // Latest RIs throw NullPointerException.
- try {
- Proxy.Type.valueOf(null);
- fail("should throw an exception.");
- } catch (NullPointerException e) {
- // May be caused by some compilers' code
- } catch (IllegalArgumentException e) {
- // other compilers will throw this
- }
- }
-
- /**
- * @tests java.net.Proxy.Type#values()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "!Constants",
- args = {}
- )
- public void test_Type_values() {
- Proxy.Type types[] = Proxy.Type.values();
- assertEquals(3, types.length);
- assertEquals(Proxy.Type.DIRECT, types[0]);
- assertEquals(Proxy.Type.HTTP, types[1]);
- assertEquals(Proxy.Type.SOCKS, types[2]);
- }
-
-}
diff --git a/luni/src/test/java/tests/api/java/net/ProxyTypeTest.java b/luni/src/test/java/tests/api/java/net/ProxyTypeTest.java
deleted file mode 100644
index ca4abb2..0000000
--- a/luni/src/test/java/tests/api/java/net/ProxyTypeTest.java
+++ /dev/null
@@ -1,84 +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.api.java.net;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.net.Proxy;
-
-@TestTargetClass(Proxy.Type.class)
-public class ProxyTypeTest extends TestCase {
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "valueOf",
- args = {java.lang.String.class}
- )
- public void test_valueOf() {
- Proxy.Type [] types = {Proxy.Type.DIRECT, Proxy.Type.HTTP,
- Proxy.Type.SOCKS};
-
- String [] strTypes = {"DIRECT", "HTTP", "SOCKS"};
-
- for(int i = 0; i < strTypes.length; i++) {
- assertEquals(types[i], Proxy.Type.valueOf(strTypes[i]));
- }
-
- String [] incTypes = {"", "direct", "http", "socks", " HTTP"};
-
- for(String str:incTypes) {
- try {
- Proxy.Type.valueOf(str);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
- }
-
- try {
- Proxy.Type.valueOf(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "values",
- args = {}
- )
- public void test_values() {
- Proxy.Type [] types = { Proxy.Type.DIRECT, Proxy.Type.HTTP,
- Proxy.Type.SOCKS };
-
- Proxy.Type [] result = Proxy.Type.values();
-
- assertEquals(types.length, result.length);
-
- for(int i = 0; i < result.length; i++) {
- assertEquals(types[i], result[i]);
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/SecureCacheResponseTest.java b/luni/src/test/java/tests/api/java/net/SecureCacheResponseTest.java
deleted file mode 100644
index 6fb6792..0000000
--- a/luni/src/test/java/tests/api/java/net/SecureCacheResponseTest.java
+++ /dev/null
@@ -1,177 +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.api.java.net;
-
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestTargetClass;
-
-import junit.framework.TestCase;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.CacheRequest;
-import java.net.HttpURLConnection;
-import java.net.ResponseCache;
-import java.net.SecureCacheResponse;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.util.List;
-import java.util.Map;
-
-import javax.net.ssl.SSLPeerUnverifiedException;
-
-@TestTargetClass(SecureCacheResponse.class)
-public class SecureCacheResponseTest extends TestCase {
-
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SecureCacheResponse",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getCipherSuite",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalCertificateChain",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalPrincipal",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPeerPrincipal",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getServerCertificateChain",
- args = {}
- )
- })
- public void test_Constructor() throws Exception {
- TestSecureCacheResponse scr = new TestSecureCacheResponse();
- assertNull(scr.getCipherSuite());
- assertNull(scr.getLocalCertificateChain());
- assertNull(scr.getLocalPrincipal());
- assertNull(scr.getPeerPrincipal());
- assertNull(scr.getServerCertificateChain());
- assertNull(scr.getBody());
- assertNull(scr.getHeaders());
- }
-
- @TestTargetNew(
- level = TestLevel.ADDITIONAL,
- notes = "",
- method = "SecureCacheResponse",
- args = {}
- )
- public void test_additional() throws Exception {
-
- URL url = new URL("http://google.com");
- ResponseCache.setDefault(new TestResponseCache());
- HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
- httpCon.setUseCaches(true);
- httpCon.connect();
- try {
- Thread.sleep(5000);
- } catch(Exception e) {}
- httpCon.disconnect();
-
- }
-
- class TestSecureCacheResponse extends SecureCacheResponse {
-
- @Override
- public String getCipherSuite() {
- return null;
- }
-
- @Override
- public List<Certificate> getLocalCertificateChain() {
- return null;
- }
-
- @Override
- public Principal getLocalPrincipal() {
- return null;
- }
-
- @Override
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- return null;
- }
-
- @Override
- public List<Certificate> getServerCertificateChain() throws SSLPeerUnverifiedException {
- return null;
- }
-
- @Override
- public InputStream getBody() throws IOException {
- return null;
- }
-
- @Override
- public Map<String, List<String>> getHeaders() throws IOException {
- return null;
- }
-
- }
-
- class TestResponseCache extends ResponseCache {
-
- URI uri1 = null;
-
- public TestSecureCacheResponse get(URI uri, String rqstMethod, Map rqstHeaders)
- throws IOException {
-
-
- try {
- uri1 = new URI("http://google.com");
- } catch (URISyntaxException e) {
- }
- if (uri.equals(uri)) {
- return new TestSecureCacheResponse();
- }
- return null;
- }
-
- public CacheRequest put(URI uri, URLConnection conn)
- throws IOException {
- return null;
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/ServerSocketTest.java b/luni/src/test/java/tests/api/java/net/ServerSocketTest.java
deleted file mode 100644
index 43e9241..0000000
--- a/luni/src/test/java/tests/api/java/net/ServerSocketTest.java
+++ /dev/null
@@ -1,1495 +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.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-import dalvik.annotation.TestLevel;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InterruptedIOException;
-import java.io.OutputStream;
-import java.net.BindException;
-import java.net.ConnectException;
-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.net.SocketImpl;
-import java.net.SocketImplFactory;
-import java.net.SocketTimeoutException;
-import java.net.UnknownHostException;
-import java.nio.channels.IllegalBlockingModeException;
-import java.nio.channels.ServerSocketChannel;
-import java.security.Permission;
-import java.util.Date;
-import java.util.Properties;
-
-import tests.support.Support_Configuration;
-import tests.support.Support_PortManager;
-
-@TestTargetClass(value = ServerSocket.class)
-public class ServerSocketTest extends SocketTestCase {
-
- boolean interrupted;
- boolean isCreateCalled = false;
-
- ServerSocket s;
-
- Socket sconn;
-
- Thread t;
-
- static class SSClient implements Runnable {
- Socket cs;
-
- int port;
-
- public SSClient(int prt) {
- port = prt;
- }
-
- public void run() {
- try {
- // Go to sleep so the server can setup and wait for connection
- Thread.sleep(1000);
- cs = new Socket(InetAddress.getLocalHost().getHostName(), port);
- // Sleep again to allow server side processing. Thread is
- // stopped by server.
- Thread.sleep(10000);
- } catch (InterruptedException e) {
- return;
- } catch (Throwable e) {
- System.out
- .println("Error establishing client: " + e.toString());
- } finally {
- try {
- if (cs != null)
- cs.close();
- } catch (Exception e) {
- }
- }
- }
- }
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- /**
- * @tests java.net.ServerSocket#ServerSocket()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ServerSocket",
- args = {}
- )
- public void test_Constructor() {
- ServerSocket ss = null;
- try {
- ss = new ServerSocket();
- assertEquals(-1, ss.getLocalPort());
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- try {
- ss.close();
- } catch(IOException ioe) {}
- }
- }
-
- /**
- * @tests java.net.ServerSocket#ServerSocket(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "ServerSocket",
- args = {int.class}
- )
- public void test_ConstructorI() throws Exception {
- int portNumber = Support_PortManager.getNextPort();
- s = new ServerSocket(portNumber);
- try {
- new ServerSocket(portNumber);
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- try {
- startClient(s.getLocalPort());
- sconn = s.accept();
- assertNotNull("Was unable to accept connection", sconn);
- sconn.close();
- } finally {
- s.close();
- }
-
- s = new ServerSocket(0);
- try {
- startClient(s.getLocalPort());
- sconn = s.accept();
- assertNotNull("Was unable to accept connection", sconn);
- sconn.close();
- } finally {
- s.close();
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new ServerSocket(0);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- }
-
- /**
- * @tests java.net.ServerSocket#ServerSocket(int)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Regression test.",
- method = "ServerSocket",
- args = {int.class}
- )
- public void test_ConstructorI_SocksSet() throws IOException {
- // Harmony-623 regression test
- ServerSocket ss = null;
- Properties props = (Properties) System.getProperties().clone();
- try {
- System.setProperty("socksProxyHost", "127.0.0.1");
- System.setProperty("socksProxyPort", "12345");
- ss = new ServerSocket(0);
- } finally {
- System.setProperties(props);
- if (null != ss) {
- ss.close();
- }
- }
- }
-
- /**
- * @tests java.net.ServerSocket#ServerSocket(int, int)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Doesn't check backlog.",
- method = "ServerSocket",
- args = {int.class, int.class}
- )
- public void test_ConstructorII() throws IOException {
- int freePortNumber = Support_PortManager.getNextPort();
- try {
- s = new ServerSocket(freePortNumber, 1);
- s.setSoTimeout(2000);
- startClient(freePortNumber);
- sconn = s.accept();
-
- } catch (InterruptedIOException e) {
- fail("InterruptedIOException was thrown.");
- } finally {
- try {
- sconn.close();
- s.close();
- } catch(IOException ioe) {}
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new ServerSocket(0, 0);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- int portNumber = Support_PortManager.getNextPort();
- new ServerSocket(portNumber, 0);
- try {
- new ServerSocket(portNumber, 0);
- fail("IOExcepion was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- }
-
- /**
- * @tests java.net.ServerSocket#ServerSocket(int, int, java.net.InetAddress)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "Doesn't check backlog value.",
- method = "ServerSocket",
- args = {int.class, int.class, java.net.InetAddress.class}
- )
- public void test_ConstructorIILjava_net_InetAddress()
- throws UnknownHostException, IOException {
- s = new ServerSocket(0, 10, InetAddress.getLocalHost());
- try {
- s.setSoTimeout(5000);
- startClient(s.getLocalPort());
- sconn = s.accept();
- assertNotNull("Was unable to accept connection", sconn);
- sconn.close();
- } finally {
- s.close();
- }
-
- int freePortNumber = Support_PortManager.getNextPort();
- ServerSocket ss = new ServerSocket(freePortNumber, 10,
- InetAddress.getLocalHost());
-
- try {
- new ServerSocket(freePortNumber, 10,
- InetAddress.getLocalHost());
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
-
- try {
- new ServerSocket(65536, 10,
- InetAddress.getLocalHost());
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new ServerSocket(0, 10, InetAddress.getLocalHost());
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-
- int portNumber = Support_PortManager.getNextPort();
- new ServerSocket(portNumber, 0);
- try {
- new ServerSocket(portNumber, 0);
- fail("IOExcepion was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- }
-
- /**
- * @tests java.net.ServerSocket#accept()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException is not checked.",
- method = "accept",
- args = {}
- )
- public void test_accept() throws IOException {
- s = new ServerSocket(0);
- try {
- s.setSoTimeout(5000);
- startClient(s.getLocalPort());
- sconn = s.accept();
- int localPort1 = s.getLocalPort();
- int localPort2 = sconn.getLocalPort();
- sconn.close();
- assertEquals("Bad local port value", localPort1, localPort2);
- } finally {
- s.close();
- }
-
- try {
- interrupted = false;
- final ServerSocket ss = new ServerSocket(0);
- ss.setSoTimeout(12000);
- Runnable runnable = new Runnable() {
- public void run() {
- try {
- ss.accept();
- } catch (InterruptedIOException e) {
- interrupted = true;
- } catch (IOException e) {
- }
- }
- };
- Thread thread = new Thread(runnable, "ServerSocket.accept");
- thread.start();
- try {
- do {
- Thread.sleep(500);
- } while (!thread.isAlive());
- } catch (InterruptedException e) {
- }
- ss.close();
- int c = 0;
- do {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- }
- if (interrupted) {
- fail("accept interrupted");
- }
- if (++c > 4) {
- fail("accept call did not exit");
- }
- } while (thread.isAlive());
-
- interrupted = false;
- ServerSocket ss2 = new ServerSocket(0);
- ss2.setSoTimeout(500);
- Date start = new Date();
- try {
- ss2.accept();
- } catch (InterruptedIOException e) {
- interrupted = true;
- }
- assertTrue("accept not interrupted", interrupted);
- Date finish = new Date();
- int delay = (int) (finish.getTime() - start.getTime());
- assertTrue("timeout too soon: " + delay + " " + start.getTime()
- + " " + finish.getTime(), delay >= 490);
- ss2.close();
- } catch (IOException e) {
- fail("Unexpected IOException : " + e.getMessage());
- }
-
- int portNumber = Support_PortManager.getNextPort();
- ServerSocket serSocket = new ServerSocket(portNumber);
- startClient(portNumber);
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkAccept(String host,
- int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- serSocket.accept();
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- serSocket.close();
- }
-
- ServerSocket newSocket = new ServerSocket(portNumber);
- newSocket.setSoTimeout(500);
-
- try {
- newSocket.accept();
- fail("SocketTimeoutException was not thrown.");
- } catch(SocketTimeoutException ste) {
- //expected
- } finally {
- newSocket.close();
- }
-
- ServerSocketChannel ssc = ServerSocketChannel.open();
- ServerSocket ss = ssc.socket();
-
- try {
- ss.accept();
- fail("IllegalBlockingModeException was not thrown.");
- } catch(IllegalBlockingModeException ibme) {
- //expected
- } finally {
- ss.close();
- ssc.close();
- }
- }
-
- /**
- * @tests java.net.ServerSocket#close()
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "IOException checking missed.",
- method = "close",
- args = {}
- )
- public void test_close() throws IOException {
- try {
- s = new ServerSocket(0);
- try {
- s.close();
- s.accept();
- fail("Close test failed");
- } catch (SocketException e) {
- // expected;
- }
- } finally {
- s.close();
- }
- }
-
- /**
- * @tests java.net.ServerSocket#getInetAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInetAddress",
- args = {}
- )
- public void test_getInetAddress() throws IOException {
- InetAddress addr = InetAddress.getLocalHost();
- s = new ServerSocket(0, 10, addr);
- try {
- assertEquals("Returned incorrect InetAdrees", addr, s
- .getInetAddress());
- } finally {
- s.close();
- }
- }
-
- /**
- * @tests java.net.ServerSocket#getLocalPort()
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getLocalPort",
- args = {}
- )
- public void test_getLocalPort() throws IOException {
- // Try a specific port number, but don't complain if we don't get it
- int portNumber = 63024; // I made this up
- try {
- try {
- s = new ServerSocket(portNumber);
- } catch (BindException e) {
- // we could not get the port, give up
- return;
- }
- assertEquals("Returned incorrect port", portNumber, s
- .getLocalPort());
- } finally {
- s.close();
- }
- }
-
- /**
- * @tests java.net.ServerSocket#getSoTimeout()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSoTimeout",
- args = {}
- )
- public void test_getSoTimeout() throws IOException {
- s = new ServerSocket(0);
- try {
- s.setSoTimeout(100);
- assertEquals("Returned incorrect sotimeout", 100, s.getSoTimeout());
- } finally {
- s.close();
- }
- try {
- ServerSocket newSocket = new ServerSocket();
- newSocket.close();
- try {
- newSocket.setSoTimeout(100);
- fail("SocketException was not thrown.");
- } catch(SocketException e) {
- //expected
- }
- } catch(Exception e) {
- fail("Unexpected exception.");
- }
- }
-
- /**
- * @tests java.net.ServerSocket#setSoTimeout(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setSoTimeout",
- args = {int.class}
- )
- public void test_setSoTimeoutI() throws IOException {
- // Timeout should trigger and throw InterruptedIOException
- try {
- s = new ServerSocket(0);
- s.setSoTimeout(100);
- s.accept();
- } catch (InterruptedIOException e) {
- try {
- assertEquals("Set incorrect sotimeout", 100, s.getSoTimeout());
- return;
- } catch (Exception x) {
- fail("Exception during setSOTimeout: " + e.toString());
- }
- } catch (IOException iox) {
- fail("IOException during setSotimeout: " + iox.toString());
- }
-
- // Timeout should not trigger in this case
- s = new ServerSocket(0);
- startClient(s.getLocalPort());
- s.setSoTimeout(10000);
- sconn = s.accept();
-
- ServerSocket newSocket = new ServerSocket();
- newSocket.close();
- try {
- newSocket.setSoTimeout(100);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- /**
- * @tests java.net.ServerSocket#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() throws Exception {
- s = new ServerSocket(0);
- try {
- int portNumber = s.getLocalPort();
- assertTrue(s.toString().contains("" + portNumber));
- } finally {
- try {
- s.close();
- } catch(Exception e) {
-
- }
- }
- }
-
- /**
- * @tests java.net.ServerSocket#bind(java.net.SocketAddress)
- */
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "bind",
- args = {java.net.SocketAddress.class}
- )
- public void test_bindLjava_net_SocketAddress() throws IOException {
- class mySocketAddress extends SocketAddress {
- public mySocketAddress() {
- }
- }
- // create servers socket, bind it and then validate basic state
- ServerSocket theSocket = new ServerSocket();
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), 0);
- theSocket.bind(theAddress);
- int portNumber = theSocket.getLocalPort();
- assertTrue(
- "Returned incorrect InetSocketAddress(2):"
- + theSocket.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), theSocket
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber)));
- assertTrue("Server socket not bound when it should be:", theSocket
- .isBound());
-
- // now make sure that it is actually bound and listening on the
- // address we provided
- Socket clientSocket = new Socket();
- InetSocketAddress clAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber);
- clientSocket.connect(clAddress);
- Socket servSock = theSocket.accept();
-
- assertEquals(clAddress, clientSocket.getRemoteSocketAddress());
- theSocket.close();
- servSock.close();
- clientSocket.close();
-
- // validate we can specify null for the address in the bind and all
- // goes ok
- theSocket = new ServerSocket();
- theSocket.bind(null);
- theSocket.close();
-
- // Address that we have already bound to
- theSocket = new ServerSocket();
- ServerSocket theSocket2 = new ServerSocket();
- try {
- theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
- theSocket.bind(theAddress);
- SocketAddress localAddress = theSocket.getLocalSocketAddress();
- theSocket2.bind(localAddress);
- fail("No exception binding to address that is not available");
- } catch (IOException ex) {
- }
- theSocket.close();
- theSocket2.close();
-
- // validate we get io address when we try to bind to address we
- // cannot bind to
- theSocket = new ServerSocket();
- try {
- theSocket.bind(new InetSocketAddress(InetAddress
- .getByAddress(Support_Configuration.nonLocalAddressBytes),
- 0));
- fail("No exception was thrown when binding to bad address");
- } catch (IOException ex) {
- }
- theSocket.close();
-
- // now validate case where we pass in an unsupported subclass of
- // SocketAddress
- theSocket = new ServerSocket();
- try {
- theSocket.bind(new mySocketAddress());
- fail("No exception when binding using unsupported SocketAddress subclass");
- } catch (IllegalArgumentException ex) {
- }
- theSocket.close();
-
-
- ServerSocket serSocket = new ServerSocket();
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- serSocket.bind(theAddress);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- serSocket.close();
- }
- }
-
- /**
- * @tests java.net.ServerSocket#bind(java.net.SocketAddress,int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "bind",
- args = {java.net.SocketAddress.class, int.class}
- )
- public void test_bindLjava_net_SocketAddressI() throws IOException {
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- // create servers socket, bind it and then validate basic state
- ServerSocket theSocket = new ServerSocket();
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), 0);
- theSocket.bind(theAddress, 5);
- int portNumber = theSocket.getLocalPort();
- assertTrue(
- "Returned incorrect InetSocketAddress(2):"
- + theSocket.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), theSocket
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber)));
- assertTrue("Server socket not bound when it should be:", theSocket
- .isBound());
-
- // now make sure that it is actually bound and listening on the
- // address we provided
- SocketAddress localAddress = theSocket.getLocalSocketAddress();
- Socket clientSocket = new Socket();
- clientSocket.connect(localAddress);
- Socket servSock = theSocket.accept();
-
- assertTrue(clientSocket.getRemoteSocketAddress().equals(localAddress));
- theSocket.close();
- servSock.close();
- clientSocket.close();
-
- // validate we can specify null for the address in the bind and all
- // goes ok
- theSocket = new ServerSocket();
- theSocket.bind(null, 5);
- theSocket.close();
-
- // Address that we have already bound to
- theSocket = new ServerSocket();
- ServerSocket theSocket2 = new ServerSocket();
- try {
- theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
- theSocket.bind(theAddress, 5);
- SocketAddress inuseAddress = theSocket.getLocalSocketAddress();
- theSocket2.bind(inuseAddress, 5);
- fail("No exception binding to address that is not available");
- } catch (IOException ex) {
- // expected
- }
- theSocket.close();
- theSocket2.close();
-
- // validate we get ioException when we try to bind to address we
- // cannot bind to
- theSocket = new ServerSocket();
- try {
- theSocket.bind(new InetSocketAddress(InetAddress
- .getByAddress(Support_Configuration.nonLocalAddressBytes),
- 0), 5);
- fail("No exception was thrown when binding to bad address");
- } catch (IOException ex) {
- }
- theSocket.close();
-
- // now validate case where we pass in an unsupported subclass of
- // SocketAddress
- theSocket = new ServerSocket();
- try {
- theSocket.bind(new mySocketAddress(), 5);
- fail("Binding using unsupported SocketAddress subclass should have thrown exception");
- } catch (IllegalArgumentException ex) {
- }
- theSocket.close();
-
- // now validate that backlog is respected. We have to do a test that
- // checks if it is a least a certain number as some platforms make
- // it higher than we request. Unfortunately non-server versions of
- // windows artificially limit the backlog to 5 and 5 is the
- // historical default so it it not a great test.
- theSocket = new ServerSocket();
- theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
- theSocket.bind(theAddress, 4);
- localAddress = theSocket.getLocalSocketAddress();
- Socket theSockets[] = new Socket[4];
- int i = 0;
- try {
- for (i = 0; i < 4; i++) {
- theSockets[i] = new Socket();
- theSockets[i].connect(localAddress);
- }
- } catch (ConnectException ex) {
- fail("Backlog does not seem to be respected in bind:" + i + ":"
- + ex.toString());
- }
-
- for (i = 0; i < 4; i++) {
- theSockets[i].close();
- }
-
- theSocket.close();
- servSock.close();
-
- ServerSocket serSocket = new ServerSocket();
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- serSocket.bind(theAddress, 5);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- serSocket.close();
- }
- }
-
- /**
- * @tests java.net.ServerSocket#getLocalSocketAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getLocalSocketAddress",
- args = {}
- )
- public void test_getLocalSocketAddress() {
- // set up server connect and then validate that we get the right
- // response for the local address
- try {
- ServerSocket theSocket = new ServerSocket(0, 5, InetAddress
- .getLocalHost());
- int portNumber = theSocket.getLocalPort();
- assertTrue("Returned incorrect InetSocketAddress(1):"
- + theSocket.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), theSocket
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)));
- theSocket.close();
-
- // now create a socket that is not bound and validate we get the
- // right answer
- theSocket = new ServerSocket();
- assertNull(
- "Returned incorrect InetSocketAddress -unbound socket- Expected null",
- theSocket.getLocalSocketAddress());
-
- // now bind the socket and make sure we get the right answer
- theSocket
- .bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
- int localPort = theSocket.getLocalPort();
- assertEquals("Returned incorrect InetSocketAddress(2):", theSocket
- .getLocalSocketAddress(), new InetSocketAddress(InetAddress
- .getLocalHost(), localPort));
- theSocket.close();
- } catch (Exception e) {
- fail("Exception during getLocalSocketAddress test: " + e);
- }
- }
-
- /**
- * @tests java.net.ServerSocket#isBound()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isBound",
- args = {}
- )
- public void test_isBound() throws IOException {
- InetAddress addr = InetAddress.getLocalHost();
- ServerSocket serverSocket = new ServerSocket();
- assertFalse("Socket indicated bound when it should be (1)",
- serverSocket.isBound());
-
- // now bind and validate bound ok
- serverSocket.bind(new InetSocketAddress(addr, 0));
- assertTrue("Socket indicated not bound when it should be (1)",
- serverSocket.isBound());
- serverSocket.close();
-
- // now do with some of the other constructors
- serverSocket = new ServerSocket(0);
- assertTrue("Socket indicated not bound when it should be (2)",
- serverSocket.isBound());
- serverSocket.close();
-
- serverSocket = new ServerSocket(0, 5, addr);
- assertTrue("Socket indicated not bound when it should be (3)",
- serverSocket.isBound());
- serverSocket.close();
-
- serverSocket = new ServerSocket(0, 5);
- assertTrue("Socket indicated not bound when it should be (4)",
- serverSocket.isBound());
- serverSocket.close();
- }
-
- /**
- * @tests java.net.ServerSocket#isClosed()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isClosed",
- args = {}
- )
- public void test_isClosed() throws IOException {
- InetAddress addr = InetAddress.getLocalHost();
- ServerSocket serverSocket = new ServerSocket(0, 5, addr);
-
- // validate isClosed returns expected values
- assertFalse("Socket should indicate it is not closed(1):", serverSocket
- .isClosed());
- serverSocket.close();
- assertTrue("Socket should indicate it is closed(1):", serverSocket
- .isClosed());
-
- // now do with some of the other constructors
- serverSocket = new ServerSocket(0);
- assertFalse("Socket should indicate it is not closed(1):", serverSocket
- .isClosed());
- serverSocket.close();
- assertTrue("Socket should indicate it is closed(1):", serverSocket
- .isClosed());
-
- serverSocket = new ServerSocket(0, 5, addr);
- assertFalse("Socket should indicate it is not closed(1):", serverSocket
- .isClosed());
- serverSocket.close();
- assertTrue("Socket should indicate it is closed(1):", serverSocket
- .isClosed());
-
- serverSocket = new ServerSocket(0, 5);
- assertFalse("Socket should indicate it is not closed(1):", serverSocket
- .isClosed());
- serverSocket.close();
- assertTrue("Socket should indicate it is closed(1):", serverSocket
- .isClosed());
- }
-
- /**
- * @tests java.net.ServerSocket#setReuseAddress(boolean)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setReuseAddress",
- args = {boolean.class}
- )
- public void test_setReuseAddressZ() {
- try {
- // set up server and connect
- InetSocketAddress anyAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), 0);
- ServerSocket serverSocket = new ServerSocket();
- serverSocket.setReuseAddress(false);
- serverSocket.bind(anyAddress);
- SocketAddress theAddress = serverSocket.getLocalSocketAddress();
-
- // make a connection to the server, then close the server
- Socket theSocket = new Socket();
- theSocket.connect(theAddress);
- Socket stillActiveSocket = serverSocket.accept();
- serverSocket.close();
-
- // now try to rebind the server which should fail with
- // setReuseAddress to false. On windows platforms the bind is
- // allowed even then reUseAddress is false so our test uses
- // the platform to determine what the expected result is.
- String platform = System.getProperty("os.name");
- try {
- serverSocket = new ServerSocket();
- serverSocket.setReuseAddress(false);
- serverSocket.bind(theAddress);
- if ((!platform.startsWith("Windows"))) {
- fail("No exception when setReuseAddress is false and we bind:"
- + theAddress.toString());
- }
- } catch (IOException ex) {
- if (platform.startsWith("Windows")) {
- fail("Got unexpected exception when binding with setReuseAddress false on windows platform:"
- + theAddress.toString() + ":" + ex.toString());
- }
- }
- stillActiveSocket.close();
- theSocket.close();
-
- // now test case were we set it to true
- anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
- serverSocket = new ServerSocket();
- serverSocket.setReuseAddress(true);
- serverSocket.bind(anyAddress);
- theAddress = serverSocket.getLocalSocketAddress();
-
- // make a connection to the server, then close the server
- theSocket = new Socket();
- theSocket.connect(theAddress);
- stillActiveSocket = serverSocket.accept();
- serverSocket.close();
-
- // now try to rebind the server which should pass with
- // setReuseAddress to true
- try {
- serverSocket = new ServerSocket();
- serverSocket.setReuseAddress(true);
- serverSocket.bind(theAddress);
- } catch (IOException ex) {
- fail("Unexpected exception when setReuseAddress is true and we bind:"
- + theAddress.toString() + ":" + ex.toString());
- }
- stillActiveSocket.close();
- theSocket.close();
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
-
- // now test default case were we expect this to work regardless of
- // the value set
- anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
- serverSocket = new ServerSocket();
- serverSocket.bind(anyAddress);
- theAddress = serverSocket.getLocalSocketAddress();
-
- // make a connection to the server, then close the server
- theSocket = new Socket();
- theSocket.connect(theAddress);
- stillActiveSocket = serverSocket.accept();
- serverSocket.close();
-
- // now try to rebind the server which should pass
- try {
- serverSocket = new ServerSocket();
- serverSocket.bind(theAddress);
- } catch (IOException ex) {
- fail("Unexpected exception when setReuseAddress is the default case and we bind:"
- + theAddress.toString() + ":" + ex.toString());
- }
- stillActiveSocket.close();
- theSocket.close();
- try {
- theSocket.setReuseAddress(true);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
- } catch (Exception e) {
- handleException(e, SO_REUSEADDR);
- }
- }
-
- /**
- * @tests java.net.ServerSocket#getReuseAddress()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReuseAddress",
- args = {}
- )
- public void test_getReuseAddress() {
- try {
- ServerSocket theSocket = new ServerSocket();
- theSocket.setReuseAddress(true);
- assertTrue("getReuseAddress false when it should be true",
- theSocket.getReuseAddress());
- theSocket.setReuseAddress(false);
- assertFalse("getReuseAddress true when it should be False",
- theSocket.getReuseAddress());
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
- } catch (Exception e) {
- handleException(e, SO_REUSEADDR);
- }
-
- try {
- ServerSocket newSocket = new ServerSocket();
- newSocket.close();
- try {
- newSocket.getReuseAddress();
- fail("SocketException was not thrown.");
- } catch(SocketException e) {
- //expected
- }
- } catch(Exception e) {
- fail("Unexpected exception.");
- }
- }
-
- /**
- * @tests java.net.ServerSocket#setReceiveBufferSize(int)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setReceiveBufferSize",
- args = {int.class}
- )
- public void test_setReceiveBufferSizeI() {
- try {
- // now validate case where we try to set to 0
- ServerSocket theSocket = new ServerSocket();
- try {
- theSocket.setReceiveBufferSize(0);
- fail("No exception when receive buffer size set to 0");
- } catch (IllegalArgumentException ex) {
- }
- theSocket.close();
-
- // now validate case where we try to set to a negative value
- theSocket = new ServerSocket();
- try {
- theSocket.setReceiveBufferSize(-1000);
- fail("No exception when receive buffer size set to -1000");
- } catch (IllegalArgumentException ex) {
- }
- theSocket.close();
-
- // now just try to set a good value to make sure it is set and there
- // are not exceptions
- theSocket = new ServerSocket();
- theSocket.setReceiveBufferSize(1000);
- theSocket.close();
- try {
- theSocket.setReceiveBufferSize(10);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
- } catch (Exception e) {
- handleException(e, SO_RCVBUF);
- }
-
- }
-
- /*
- * @tests java.net.ServerSocket#getReceiveBufferSize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReceiveBufferSize",
- args = {}
- )
- public void test_getReceiveBufferSize() {
- try {
- ServerSocket theSocket = new ServerSocket();
-
- // since the value returned is not necessary what we set we are
- // limited in what we can test
- // just validate that it is not 0 or negative
- assertFalse("get Buffer size returns 0:", 0 == theSocket
- .getReceiveBufferSize());
- assertFalse("get Buffer size returns a negative value:",
- 0 > theSocket.getReceiveBufferSize());
-
- ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
- } catch (Exception e) {
- handleException(e, SO_RCVBUF);
- }
- try {
- ServerSocket newSocket = new ServerSocket();
- newSocket.close();
- try {
- newSocket.getReceiveBufferSize();
- fail("SocketException was not thrown.");
- } catch(SocketException e) {
- //expected
- }
- } catch(Exception e) {
- fail("Unexpected exception.");
- }
- }
-
- /**
- * @tests java.net.ServerSocket#getChannel()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getChannel",
- args = {}
- )
- public void test_getChannel() throws Exception {
- assertNull(new ServerSocket().getChannel());
- }
-
- /*
- * @tests java.net.ServerSocket#setPerformancePreference()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "setPerformancePreferences",
- args = {int.class, int.class, int.class}
- )
- public void test_setPerformancePreference_Int_Int_Int() throws Exception {
- performancePreferenceTest(1, 0, 0);
- performancePreferenceTest(1, 1, 1);
- performancePreferenceTest(0, 1, 2);
- performancePreferenceTest(Integer.MAX_VALUE, Integer.MAX_VALUE,
- Integer.MAX_VALUE);
- }
-
- void performancePreferenceTest(int connectionTime, int latency,
- int bandwidth) throws Exception {
- ServerSocket theSocket = new ServerSocket();
- theSocket.setPerformancePreferences(connectionTime, latency, bandwidth);
-
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), 0);
- theSocket.bind(theAddress);
- int portNumber = theSocket.getLocalPort();
- assertTrue(
- "Returned incorrect InetSocketAddress(2):"
- + theSocket.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), theSocket
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber)));
- assertTrue("Server socket not bound when it should be:", theSocket
- .isBound());
-
- // now make sure that it is actually bound and listening on the
- // address we provided
- Socket clientSocket = new Socket();
- InetSocketAddress clAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber);
- clientSocket.connect(clAddress);
- Socket servSock = theSocket.accept();
-
- assertEquals(clAddress, clientSocket.getRemoteSocketAddress());
- theSocket.close();
- servSock.close();
- clientSocket.close();
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- if (s != null)
- s.close();
- if (sconn != null)
- sconn.close();
- if (t != null)
- t.interrupt();
- } catch (Exception e) {
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void startClient(int port) {
- t = new Thread(new SSClient(port), "SSClient");
- t.start();
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- System.out.println("Exception during startClinet()" + e.toString());
- }
- }
-
- /**
- * @tests java.net.ServerSocket#implAccept
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Regression test.",
- method = "implAccept",
- args = {java.net.Socket.class}
- )
- public void test_implAcceptLjava_net_Socket() throws Exception {
- // regression test for Harmony-1235
- try {
- new MockServerSocket().mockImplAccept(new MockSocket(
- new MockSocketImpl()));
- } catch (SocketException e) {
- // expected
- }
- }
-
- class MockSocketImpl extends SocketImpl {
- public MockSocketImpl() {
- isCreateCalled = true;
- }
-
- protected void create(boolean arg0) throws IOException {
- //empty
- }
-
- protected void connect(String arg0, int arg1) throws IOException {
- // empty
- }
-
- protected void connect(InetAddress arg0, int arg1) throws IOException {
- // empty
- }
-
- protected void connect(SocketAddress arg0, int arg1) throws IOException {
- // empty
- }
-
- protected void bind(InetAddress arg0, int arg1) throws IOException {
- // empty
- }
-
- protected void listen(int arg0) throws IOException {
- // empty
- }
-
- protected void accept(SocketImpl arg0) throws IOException {
- // empty
- }
-
- protected InputStream getInputStream() throws IOException {
- return null;
- }
-
- protected OutputStream getOutputStream() throws IOException {
- return null;
- }
-
- protected int available() throws IOException {
- return 0;
- }
-
- protected void close() throws IOException {
- // empty
- }
-
- protected void sendUrgentData(int arg0) throws IOException {
- // empty
- }
-
- public void setOption(int arg0, Object arg1) throws SocketException {
- // empty
- }
-
- public Object getOption(int arg0) throws SocketException {
- return null;
- }
- }
-
- static class MockSocket extends Socket {
- public MockSocket(SocketImpl impl) throws SocketException {
- super(impl);
- }
- }
-
- static class MockServerSocket extends ServerSocket {
- public MockServerSocket() throws Exception {
- super();
- }
-
- public void mockImplAccept(Socket s) throws Exception {
- super.implAccept(s);
- }
- }
-
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "getLocalPort",
- args = {}
- )
- public void test_LocalPort() throws IOException {
- ServerSocket ss1 = new ServerSocket(4242);
- assertEquals(ss1.getLocalPort(), 4242);
- ss1.close();
-
- ServerSocket ss2 = new ServerSocket();
- ss2.bind(new InetSocketAddress("127.0.0.1", 4343));
- assertEquals(ss2.getLocalPort(), 4343);
- ss2.close();
-
- ServerSocket ss3 = new ServerSocket(0);
- assertTrue(ss3.getLocalPort() != 0);
- ss3.close();
- }
-
- /**
- * @tests java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
- */
- @TestTargetNew(
- level = TestLevel.SUFFICIENT,
- notes = "",
- method = "setSocketFactory",
- args = {java.net.SocketImplFactory.class}
- )
- public void test_setSocketFactoryLjava_net_SocketImplFactory() {
-
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkSetFactory() {
- throw new SecurityException();
- }
- };
-
- MockSocketFactory sf = new MockSocketFactory();
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- ServerSocket.setSocketFactory(sf);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (IOException e) {
- fail("IOException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
-/*
-* try {
-* ServerSocket.setSocketFactory(sf);
-* ServerSocket ss1 = new ServerSocket();
-* assertTrue(isCreateCalled);
-* isCreateCalled = false;
-* ServerSocket ss2 = new ServerSocket(0);
-* assertTrue(isCreateCalled);
-* } catch(IOException ioe) {
-* fail("IOException was thrown: " + ioe.toString());
-* }
-
-* try {
-* ServerSocket.setSocketFactory(null);
-* fail("IOException was not thrown.");
-* } catch(IOException ioe) {
-* //expected
-* }
-*/
- }
-
- class MockSocketFactory implements SocketImplFactory {
- public SocketImpl createSocketImpl() {
- return new MockSocketImpl();
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/SocketExceptionTest.java b/luni/src/test/java/tests/api/java/net/SocketExceptionTest.java
deleted file mode 100644
index bdaa6a7..0000000
--- a/luni/src/test/java/tests/api/java/net/SocketExceptionTest.java
+++ /dev/null
@@ -1,83 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.SocketException;
-
-@TestTargetClass(SocketException.class)
-public class SocketExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.SocketException#SocketException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SocketException",
- args = {}
- )
- public void test_Constructor() {
- try {
- throw new SocketException();
- } catch (SocketException e) {
- return;
- } catch (Exception e) {
- fail("Exception during SocketException test : " + e.getMessage());
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * @tests java.net.SocketException#SocketException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SocketException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- try {
- throw new SocketException("Some error message");
- } catch (SocketException e) {
- return;
- } catch (Exception e) {
- fail("Exception during SocketException test" + e.toString());
- }
- fail("Failed to generate expected exception");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/SocketImplTest.java b/luni/src/test/java/tests/api/java/net/SocketImplTest.java
deleted file mode 100644
index b44bb21..0000000
--- a/luni/src/test/java/tests/api/java/net/SocketImplTest.java
+++ /dev/null
@@ -1,265 +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.TestTargetClass;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.io.FileDescriptor;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.InetAddress;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.SocketImpl;
-/*
-* SocketImpl functionality is untestable because of
-* Socket.setSocketImplFactory method can be specified only once.
-*/
-
-@TestTargetClass(value = SocketImpl.class,
- untestedMethods = {
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "accept",
- args = {SocketImpl.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "available",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "bind",
- args = {InetAddress.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "close",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "connect",
- args = {String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "connect",
- args = {InetAddress.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "connect",
- args = {SocketAddress.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "create",
- args = {boolean.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getFileDescriptor",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getInetAddress",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getInputStream",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getLocalPort",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getOption",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getOutputStream",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "getPort",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "listen",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "sendUrgentData",
- args = {int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setOption",
- args = {int.class, Object.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "setPerformancePreferences",
- args = {int.class, int.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "shutdownInput",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "shutdownOutput",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "supportsUrgentData",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.NOT_FEASIBLE,
- notes = "",
- method = "toString",
- args = {}
- )
- })
-public class SocketImplTest extends junit.framework.TestCase {
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Regression test.",
- method = "SocketImpl",
- args = {}
- )
- public void test_Constructor_fd() throws Exception {
- // regression test for Harmony-1117
- MockSocketImpl mockSocketImpl = new MockSocketImpl();
- assertNull(mockSocketImpl.getFileDescriptor());
- }
-
- // the mock class for test, leave all method empty
- class MockSocketImpl extends SocketImpl{
-
- protected void accept(SocketImpl newSocket) throws IOException {
- }
-
- protected int available() throws IOException {
- return 0;
- }
-
- protected void bind(InetAddress address, int port) throws IOException {
- }
-
- protected void close() throws IOException {
- }
-
- protected void connect(String host, int port) throws IOException {
- }
-
- protected void connect(InetAddress address, int port) throws IOException {
- }
-
- protected void create(boolean isStreaming) throws IOException {
- }
-
- protected InputStream getInputStream() throws IOException {
- return null;
- }
-
- public Object getOption(int optID) throws SocketException {
- return null;
- }
-
- protected OutputStream getOutputStream() throws IOException {
- return null;
- }
-
- protected void listen(int backlog) throws IOException {
- }
-
- public void setOption(int optID, Object val) throws SocketException {
- }
-
- protected void connect(SocketAddress remoteAddr, int timeout) throws IOException {
- }
-
- protected void sendUrgentData(int value) throws IOException {
- }
-
- public void setPerformancePreference(int connectionTime,
- int latency,
- int bandwidth){
- super.setPerformancePreferences(connectionTime, latency, bandwidth);
- }
-
- public FileDescriptor getFileDescriptor() {
- return super.getFileDescriptor();
- }
-
- public void shutdownOutput() throws IOException {
- super.shutdownOutput();
- }
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-
- protected void doneSuite() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/SocketPermissionTest.java b/luni/src/test/java/tests/api/java/net/SocketPermissionTest.java
deleted file mode 100644
index fe99369..0000000
--- a/luni/src/test/java/tests/api/java/net/SocketPermissionTest.java
+++ /dev/null
@@ -1,340 +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 org.apache.harmony.testframework.serialization.SerializationTest;
-
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.InetAddress;
-import java.net.SocketPermission;
-import java.net.UnknownHostException;
-import java.security.PermissionCollection;
-
-import tests.support.Support_Configuration;
-
-@TestTargetClass(SocketPermission.class)
-public class SocketPermissionTest extends junit.framework.TestCase {
-
- String starName = "*." + Support_Configuration.DomainAddress;
-
- String wwwName = Support_Configuration.HomeAddress;
-
- SocketPermission star_Resolve = new SocketPermission(starName, "resolve");
-
- SocketPermission star_All = new SocketPermission(starName,
- "listen,accept,connect");
-
- SocketPermission www_All = new SocketPermission(wwwName,
- "connect,listen,accept");
-
- SocketPermission copyOfWww_All = new SocketPermission(wwwName,
- "connect,listen,accept");
-
- /**
- * @tests java.net.SocketPermission#SocketPermission(java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SocketPermission",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // Test for method java.net.SocketPermission(java.lang.String,
- // java.lang.String)
- assertTrue("Incorrect name", star_Resolve.getName().equals(starName));
- assertEquals("Incorrect actions",
- "resolve", star_Resolve.getActions());
-
- SocketPermission sp1 = new SocketPermission("", "connect");
- assertEquals("Wrong name1", "localhost", sp1.getName());
- SocketPermission sp2 = new SocketPermission(":80", "connect");
- assertEquals("Wrong name2", ":80", sp2.getName());
-
- // regression for HARMONY-1462
- SocketPermission sp3 = new SocketPermission("localhost:*", "listen");
- assertEquals("Wrong name3", "localhost:*", sp3.getName());
- // for all ports
- SocketPermission spAllPorts = new SocketPermission("localhost:0-65535",
- "listen");
- assertTrue("Port range error", sp3.implies(spAllPorts));
- assertTrue("Port range error", spAllPorts.implies(sp3));
- }
-
- /**
- * @tests java.net.SocketPermission#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- // Test for method boolean
- // java.net.SocketPermission.equals(java.lang.Object)
- assertTrue("Different names but returned equal", !star_All
- .equals(www_All));
- assertTrue("Different actions but returned equal", !star_Resolve
- .equals(star_All));
- assertTrue("Same but returned unequal", www_All.equals(copyOfWww_All));
- assertTrue("Returned true when compared to a String", !www_All
- .equals(www_All.toString()));
-
- SocketPermission sp1 = new SocketPermission("TEST1.com",
- "resolve,connect");
- SocketPermission sp2 = new SocketPermission("test1.com",
- "resolve,connect");
- assertTrue("Different cases should be equal", sp1.equals(sp2));
-
- // Regression for HARMONY-1524
- assertFalse(sp1.equals(null));
-
- // Regression for HARMONY-3333
- sp1 = new SocketPermission("TEST1.com:333", "resolve");
- sp2 = new SocketPermission("test1.com:444", "resolve");
- assertTrue("Different cases should be equal", sp1.equals(sp2));
- }
-
- /**
- * @tests java.net.SocketPermission#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object_subtest0() {
- SocketPermission sp1 = new SocketPermission(
- Support_Configuration.InetTestAddress, "resolve,connect");
- SocketPermission sp2 = new SocketPermission(
- Support_Configuration.InetTestIP, "resolve,connect");
- assertTrue("Same IP address should be equal", sp1.equals(sp2));
-
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() {
- SocketPermission sp1 = new SocketPermission(
- Support_Configuration.InetTestIP, "resolve,connect");
- SocketPermission sp2 = new SocketPermission(
- Support_Configuration.InetTestIP, "resolve,connect");
- assertTrue("Same IP address should have equal hash codes",
- sp1.hashCode() == sp2.hashCode());
-
- assertTrue("Different names but returned equal hash codes",
- star_All.hashCode() != www_All.hashCode());
- }
-
- /**
- * @tests java.net.SocketPermission#getActions()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getActions",
- args = {}
- )
- public void test_getActions() {
- // Test for method java.lang.String
- // java.net.SocketPermission.getActions()
- assertEquals("Incorrect actions",
- "resolve", star_Resolve.getActions());
- assertEquals("Incorrect actions/not in canonical form", "connect,listen,accept,resolve", star_All
- .getActions());
- }
-
- /**
- * @tests java.net.SocketPermission#implies(java.security.Permission)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "implies",
- args = {java.security.Permission.class}
- )
- public void test_impliesLjava_security_Permission() {
- // Test for method boolean
- // java.net.SocketPermission.implies(java.security.Permission)
- assertTrue("All should imply resolve", star_All.implies(star_Resolve));
-
- // regression for HARMONY-1200
- assertFalse("Null should not be implied", star_All.implies((SocketPermission)null));
-
- assertTrue("Equals should imply eachother", www_All
- .implies(copyOfWww_All));
- assertTrue("Wild should imply normal", star_All.implies(www_All));
- assertTrue("Normal shouldn't imply wildcard", !www_All
- .implies(star_Resolve));
- assertTrue("Resolve shouldn't imply all", !star_Resolve
- .implies(star_All));
- SocketPermission p1 = new SocketPermission(wwwName + ":80-81",
- "connect");
- SocketPermission p2 = new SocketPermission(wwwName + ":80", "connect");
- assertTrue("Port 80 is implied by 80-81", p1.implies(p2));
- p1 = new SocketPermission(wwwName + ":79-80", "connect");
- assertTrue("Port 80 is implied by 79-80", p1.implies(p2));
- p1 = new SocketPermission(wwwName + ":79-81", "connect");
- assertTrue("Port 80 is implied by 79-81", p1.implies(p2));
- p2 = new SocketPermission(wwwName + ":79-80", "connect");
- assertTrue("Port 79-80 is implied by 79-81", p1.implies(p2));
- p2 = new SocketPermission(wwwName, "resolve");
- assertTrue(
- "Any identical host should imply resolve regardless of the ports",
- p1.implies(p2));
-
- SocketPermission sp1 = new SocketPermission("www.Ibm.com", "resolve");
- SocketPermission sp2 = new SocketPermission("www.IBM.com", "resolve");
- assertTrue("SocketPermission is case sensitive", sp1.implies(sp2));
-
- SocketPermission sp3 = new SocketPermission("*.ibm.com", "resolve");
- assertTrue("SocketPermission wildcard is case sensitive", sp3
- .implies(sp2));
-
- InetAddress host = null;
- try {
- host = InetAddress.getByName(Support_Configuration.UnresolvedIP);
- } catch (UnknownHostException e) {
- }
-
- SocketPermission perm1 = new SocketPermission(
- Support_Configuration.UnresolvedIP, "connect");
- SocketPermission perm2 = new SocketPermission(
- Support_Configuration.UnresolvedIP + ":80", "connect");
- assertTrue("should imply port 80", perm1.implies(perm2));
- PermissionCollection col = perm1.newPermissionCollection();
- col.add(perm1);
- assertTrue("collection should imply port 80", col.implies(perm2));
-
- }
-
- /**
- * @tests java.net.SocketPermission#newPermissionCollection()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "newPermissionCollection",
- args = {}
- )
- public void test_newPermissionCollection() {
- // Test for method java.security.PermissionCollection
- // java.net.SocketPermission.newPermissionCollection()
- java.security.PermissionCollection pc = star_Resolve
- .newPermissionCollection();
- pc.add(star_Resolve);
- pc.add(www_All);
- assertTrue("Should imply all on " + wwwName, pc.implies(www_All));
- assertTrue("Should imply resolve on " + starName, pc
- .implies(star_Resolve));
- assertTrue("Should not imply all on " + starName, !pc.implies(star_All));
-
- // wipe out pc
- pc = star_Resolve.newPermissionCollection();
- pc.add(star_All);
- assertTrue("Should imply resolve on " + starName, pc
- .implies(star_Resolve));
- assertTrue("Should imply all on " + wwwName, pc.implies(www_All));
-
- pc = star_Resolve.newPermissionCollection();
- SocketPermission p1 = new SocketPermission(wwwName + ":79-80",
- "connect");
- pc.add(p1);
- SocketPermission p2 = new SocketPermission(wwwName, "resolve");
- assertTrue(
- "Any identical host should imply resolve regardless of the ports",
- pc.implies(p2));
- assertTrue("A different host should not imply resolve", !pc
- .implies(star_Resolve));
- }
-
- /**
- * @tests serialization/deserialization.
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "Verifies serialization/deserialization compatibility.",
- method = "!SerializationSelf",
- args = {}
- )
- public void testSerializationSelf() throws Exception {
- SocketPermission permission = new SocketPermission("harmony.apache.org", "connect");;
-
- SerializationTest.verifySelf(permission);
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SocketPermission",
- args = {java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_String_subtestIPv6() {
- String[] goodTestStrings = {
- "12334.0.0.01", "[fe80::1]",
- "[FE80:0000:0000:0000:0000:0000:0000:0001]:80",
- "[::ffff]:80-82", "[ffff::]:80-82", "[fe80::1]:80",
- "FE80:0000:0000:0000:0000:0000:0000:0001",
- "FE80:0000:0000:0000:0000:0000:0000:0001:80"
- };
- String[] badTestStrings = {"someName:withColonInit:80", "fg80::1", "[ffff:::80-82]",
- ":[:fff]:80", "FE80:0000:0000:0000:0000:0000:0000:0001:80:82", "FE80::1"
- };
-
- for (int i=0; i < goodTestStrings.length; i++) {
- try {
- SocketPermission sp = new SocketPermission(goodTestStrings[i], "connect");
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- fail("SocketPermission named: " + goodTestStrings[i] + " failed construction: " + e.getMessage());
- }
- }
-
- for (int i=0; i < badTestStrings.length; i++) {
- try {
- SocketPermission sp = new SocketPermission(badTestStrings[i], "connect");
- fail("SocketPermission named: " + badTestStrings[i] + " should have thrown an IllegalArgumentException on construction");
- } catch (IllegalArgumentException e) {}
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/SocketTimeoutExceptionTest.java b/luni/src/test/java/tests/api/java/net/SocketTimeoutExceptionTest.java
deleted file mode 100644
index c7e436b..0000000
--- a/luni/src/test/java/tests/api/java/net/SocketTimeoutExceptionTest.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package tests.api.java.net;
-
-import junit.framework.TestCase;
-
-import java.net.SocketTimeoutException;
-
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetClass;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(SocketTimeoutException.class)
-public class SocketTimeoutExceptionTest extends TestCase {
-
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SocketTimeoutException",
- args = {}
- )
- public void test_Constructor() {
- SocketTimeoutException ste = new SocketTimeoutException();
- assertNull(ste.getMessage());
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "SocketTimeoutException",
- args = {String.class}
- )
- public void test_ConstructorLString() {
-
- String [] strs = {"", null, "Test String"};
- for(String str:strs) {
- SocketTimeoutException ste = new SocketTimeoutException(str);
- assertEquals(str, ste.getMessage());
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/URISyntaxExceptionTest.java b/luni/src/test/java/tests/api/java/net/URISyntaxExceptionTest.java
deleted file mode 100644
index 89db629..0000000
--- a/luni/src/test/java/tests/api/java/net/URISyntaxExceptionTest.java
+++ /dev/null
@@ -1,166 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.URISyntaxException;
-import java.util.Locale;
-
-@TestTargetClass(URISyntaxException.class)
-public class URISyntaxExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.URISyntaxException#URISyntaxException(java.lang.String,
- * java.lang.String, int)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URISyntaxException",
- args = {java.lang.String.class, java.lang.String.class, int.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getIndex",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInput",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReason",
- args = {}
- )
- })
- public void test_ConstructorLjava_lang_StringLjava_lang_StringI() {
- // test for Constructor(String str, String problem, int index);
- try {
- new URISyntaxException(null, "problem", 2);
- fail("Expected NullPointerException");
- } catch (NullPointerException npe) {
- }
-
- try {
- new URISyntaxException("str", null, 2);
- fail("Expected NullPointerException");
- } catch (NullPointerException npe) {
- }
-
- try {
- new URISyntaxException("str", "problem", -2);
- fail("Expected IllegalArgumentException");
- } catch (IllegalArgumentException iae) {
- }
-
- URISyntaxException e = new URISyntaxException("str", "problem", 2);
- assertEquals("returned incorrect reason", "problem", e.getReason());
- assertEquals("returned incorrect input", "str", e.getInput());
- assertEquals("returned incorrect index", 2, e.getIndex());
- }
-
- /**
- * @tests java.net.URISyntaxException#URISyntaxException(java.lang.String,
- * java.lang.String)
- */
- @TestTargets({
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URISyntaxException",
- args = {java.lang.String.class, java.lang.String.class}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getIndex",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getInput",
- args = {}
- ),
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getReason",
- args = {}
- )
- })
- public void test_ConstructorLjava_lang_StringLjava_lang_String() {
- // test for Constructor(String str, String problem);
- try {
- new URISyntaxException(null, "problem");
- fail("Expected NullPointerException");
- } catch (NullPointerException npe) {
- }
-
- try {
- new URISyntaxException("str", null);
- fail("Expected NullPointerException");
- } catch (NullPointerException npe) {
- }
-
- URISyntaxException e = new URISyntaxException("str", "problem");
- assertEquals("returned incorrect reason", "problem", e.getReason());
- assertEquals("returned incorrect input", "str", e.getInput());
- assertEquals("returned incorrect index", -1, e.getIndex());
- }
-
- /**
- * @tests java.net.URISyntaxException#getMessage()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getMessage",
- args = {}
- )
- public void test_getMessage() {
-
- // tests for java.lang.String getMessage()
- Locale.setDefault(Locale.US);
- URISyntaxException e = new URISyntaxException("str", "problem", 3);
- assertEquals("Returned incorrect message", "problem at index 3: str", e
- .getMessage());
-
- e = new URISyntaxException("str", "problem");
- assertEquals("Returned incorrect message", "problem: str", e
- .getMessage());
- }
-
- protected void setUp() {
- }
-
- protected void tearDown() {
- }
-
- protected void doneSuite() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/URITest.java b/luni/src/test/java/tests/api/java/net/URITest.java
deleted file mode 100644
index b40b0c1..0000000
--- a/luni/src/test/java/tests/api/java/net/URITest.java
+++ /dev/null
@@ -1,2174 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URISyntaxException;
-
-import junit.framework.TestCase;
-
-@TestTargetClass(URI.class)
-public class URITest extends TestCase {
-
- private URI[] uris;
-
- String[] constructorTests = new String[] {
- "http://user@www.google.com:45/search?q=helpinfo#somefragment",
- // http with authority, query and fragment
- "ftp://ftp.is.co.za/rfc/rfc1808.txt", // ftp
- "gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles", // gopher
- "mailto:mduerst@ifi.unizh.ch", // mailto
- "news:comp.infosystems.www.servers.unix", // news
- "telnet://melvyl.ucop.edu/", // telnet
- "http://123.24.17.98/test", // IPv4 authority
- "http://www.google.com:80/test",// domain name authority
- "http://joe@[3ffe:2a00:100:7031::1]:80/test",
- // IPv6 authority, with userinfo and port
- "/relative", // relative starting with /
- "//relative", // relative starting with //
- "relative", // relative with no /
- "#fragment",// relative just with fragment
- "http://user@host:80", // UI, host,port
- "http://user@host", // ui, host
- "http://host", // host
- "http://host:80", // host,port
- "http://joe@:80", // ui, port (becomes registry-based)
- "file:///foo/bar", // empty authority, non empty path
- "ht?tp://hoe@host:80", // miscellaneous tests
- "mai/lto:hey?joe#man", "http://host/a%20path#frag",
- // path with an escaped octet for space char
- "http://host/a%E2%82%ACpath#frag",
- // path with escaped octet for unicode char, not USASCII
- "http://host/a\u20ACpath#frag",
- // path with unicode char, not USASCII equivalent to
- // = "http://host/a\u0080path#frag",
- "http://host%20name/", // escaped octets in host (becomes
- // registry based)
- "http://host\u00DFname/", // unicodechar in host (becomes
- // registry based)
- // equivalent to = "http://host\u00dfname/",
- "ht123-+tp://www.google.com:80/test", // legal chars in scheme
- };
-
- String[] constructorTestsInvalid = new String[] {
- "http:///a path#frag", // space char in path, not in escaped
- // octet form, with no host
- "http://host/a[path#frag", // an illegal char, not in escaped
- // octet form, should throw an
- // exception
- "http://host/a%path#frag", // invalid escape sequence in path
- "http://host/a%#frag", // incomplete escape sequence in path
-
- "http://host#a frag", // space char in fragment, not in
- // escaped octet form, no path
- "http://host/a#fr#ag", // illegal char in fragment
- "http:///path#fr%ag", // invalid escape sequence in fragment,
- // with no host
- "http://host/path#frag%", // incomplete escape sequence in
- // fragment
-
- "http://host/path?a query#frag", // space char in query, not
- // in escaped octet form
- "http://host?query%ag", // invalid escape sequence in query, no
- // path
- "http:///path?query%", // incomplete escape sequence in query,
- // with no host
-
- "mailto:user^name@fklkf.com" // invalid char in scheme
- // specific part
- };
-
- private URI[] getUris() throws URISyntaxException {
- if (uris != null) {
- return uris;
- }
-
- uris = new URI[] {
- // single arg constructor
- new URI(
- "http://user%60%20info@host/a%20path?qu%60%20ery#fr%5E%20ag"),
- // escaped octets for illegal chars
- new URI(
- "http://user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g"),
- // escaped octets for unicode chars
- new URI(
- "ascheme://user\u00DF\u00A3info@host:0/a\u20ACpath?qu\u00A9\u00AEery#fr\u00E4\u00E8g"),
- // unicode chars equivalent to = new
- // URI("ascheme://user\u00df\u00a3info@host:0/a\u0080path?qu\u00a9\u00aeery#fr\u00e4\u00e8g"),
-
- // multiple arg constructors
- new URI("http", "user%60%20info", "host", 80, "/a%20path",
- "qu%60%20ery", "fr%5E%20ag"),
- // escaped octets for illegal
- new URI("http", "user%C3%9F%C2%A3info", "host", -1,
- "/a%E2%82%ACpath", "qu%C2%A9%C2%AEery",
- "fr%C3%A4%C3%A8g"),
- // escaped octets for unicode
- new URI("ascheme", "user\u00DF\u00A3info", "host", 80,
- "/a\u20ACpath", "qu\u00A9\u00AEery", "fr\u00E4\u00E8g"),
- // unicode chars equivalent to = new
- // URI("ascheme", "user\u00df\u00a3info", "host", 80,
- // "/a\u0080path", "qu\u00a9\u00aeery", "fr\u00e4\u00e8g"),
- new URI("http", "user` info", "host", 81, "/a path", "qu` ery",
- "fr^ ag"), // illegal chars
- new URI("http", "user%info", "host", 0, "/a%path", "que%ry",
- "f%rag"),
- // % as illegal char, not escaped octet
-
- // urls with undefined components
- new URI("mailto", "user@domain.com", null),
- // no host, path, query or fragment
- new URI("../adirectory/file.html#"),
- // relative path with empty fragment;
- new URI("news", "comp.infosystems.www.servers.unix", null), //
- new URI(null, null, null, "fragment"), // only fragment
- new URI("telnet://server.org"), // only host
- new URI("http://reg:istry?query"),
- // malformed hostname, therefore registry-based,
- // with query
- new URI("file:///c:/temp/calculate.pl?"),
- // empty authority, non empty path, empty query
- };
- return uris;
- }
-
- /**
- * @tests java.net.URI#URI(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "URI",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // tests for public URI(String uri) throws URISyntaxException
-
- for (int i = 0; i < constructorTests.length; i++) {
- try {
- new URI(constructorTests[i]);
- } catch (URISyntaxException e) {
- fail("Failed to construct URI for: " + constructorTests[i]
- + " : " + e);
- }
- }
-
- int[] constructorTestsInvalidIndices = new int[] { 9, 13, 13, 13, 13,
- 16, 15, 21, 18, 17, 18, 11 };
-
- for (int i = 0; i < constructorTestsInvalid.length; i++) {
- try {
- new URI(constructorTestsInvalid[i]);
- fail("Failed to throw URISyntaxException for: "
- + constructorTestsInvalid[i]);
- } catch (URISyntaxException e) {
- assertTrue("Wrong index in URISytaxException for: "
- + constructorTestsInvalid[i] + " expected: "
- + constructorTestsInvalidIndices[i] + ", received: "
- + e.getIndex(),
- e.getIndex() == constructorTestsInvalidIndices[i]);
- }
- }
-
- String invalid2[] = {
- // authority validation
- "http://user@[3ffe:2x00:100:7031::1]:80/test", // malformed
- // IPv6 authority
- "http://[ipv6address]/apath#frag", // malformed ipv6 address
- "http://[ipv6address/apath#frag", // malformed ipv6 address
- "http://ipv6address]/apath#frag", // illegal char in host name
- "http://ipv6[address/apath#frag",
- "http://ipv6addr]ess/apath#frag",
- "http://ipv6address[]/apath#frag",
- // illegal char in username...
- "http://us[]er@host/path?query#frag", "http://host name/path", // illegal
- // char
- // in
- // authority
- "http://host^name#fragment", // illegal char in authority
- "telnet://us er@hostname/", // illegal char in authority
- // missing components
- "//", // Authority expected
- "ascheme://", // Authority expected
- "ascheme:", // Scheme-specific part expected
- // scheme validation
- "a scheme://reg/", // illegal char
- "1scheme://reg/", // non alpha char as 1st char
- "asche\u00dfme:ssp", // unicode char , not USASCII
- "asc%20heme:ssp" // escape octets
- };
-
- for (int i = 0; i < invalid2.length; i++) {
- try {
- new URI(invalid2[i]);
- fail("Failed to throw URISyntaxException for: " + invalid2[i]);
- } catch (URISyntaxException e) {
- }
- }
-
- try {
- new URI(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- } catch (URISyntaxException e) {
- fail("URISyntaxException was thrown.");
- }
- }
-
- /**
- * @tests java.net.URI#URI(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "URISyntaxException checked.",
- method = "URI",
- args = {java.lang.String.class}
- )
- public void test_URI_String() {
- try {
- URI myUri = new URI(":abc@mymail.com");
- fail("TestA, URISyntaxException expected, but not received.");
- } catch (URISyntaxException e) {
- assertEquals("TestA, Wrong URISyntaxException index, ", 0, e
- .getIndex());
- }
-
- try {
- URI uri = new URI("path[one");
- fail("TestB, URISyntaxException expected, but not received.");
- } catch (URISyntaxException e1) {
- assertEquals("TestB, Wrong URISyntaxException index, ", 4, e1
- .getIndex());
- }
-
- try {
- URI uri = new URI(" ");
- fail("TestC, URISyntaxException expected, but not received.");
- } catch (URISyntaxException e2) {
- assertEquals("TestC, Wrong URISyntaxException index, ", 0, e2
- .getIndex());
- }
- }
-
- /**
- * @tests java.net.URI#URI(java.lang.String, java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URI",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_String() {
- // tests for public URI(String scheme, String ssp, String frag) throws
- // URISyntaxException
-
- URI uri;
- try {
- uri = new URI("mailto", "mduerst@ifi.unizh.ch", null);
- assertNull("wrong userinfo", uri.getUserInfo());
- assertNull("wrong hostname", uri.getHost());
- assertNull("wrong authority", uri.getAuthority());
- assertEquals("wrong port number", -1, uri.getPort());
- assertNull("wrong path", uri.getPath());
- assertNull("wrong query", uri.getQuery());
- assertNull("wrong fragment", uri.getFragment());
- assertEquals("wrong SchemeSpecificPart", "mduerst@ifi.unizh.ch",
- uri.getSchemeSpecificPart());
- } catch (URISyntaxException e) {
- fail("Unexpected Exception: " + e);
- }
-
- // scheme specific part can not be null
- try {
- uri = new URI("mailto", null, null);
- fail("Expected URISyntaxException");
- } catch (URISyntaxException e) {
- }
-
- // scheme needs to start with an alpha char
- try {
- uri = new URI("3scheme", "//authority/path", "fragment");
- fail("Expected URISyntaxException");
- } catch (URISyntaxException e) {
- }
-
- // scheme can not be empty string
- try {
- uri = new URI("", "//authority/path", "fragment");
- fail("Expected URISyntaxException");
- } catch (URISyntaxException e) {
- }
- }
-
- /**
- * @tests java.net.URI#URI(java.lang.String, java.lang.String,
- * java.lang.String, int, java.lang.String, java.lang.String,
- * java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URI",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, int.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_StringILjava_lang_StringLjava_lang_StringLjava_lang_String() {
- // tests for public URI(String scheme, String userinfo, String host, int
- // port, String path,
- // String query, String fragment) throws URISyntaxException
-
- // check for URISyntaxException for invalid Server Authority
- construct1("http", "user", "host\u00DFname", -1, "/file", "query",
- "fragment"); // unicode chars in host name
- // equivalent to construct1("http", "user", "host\u00dfname", -1,
- // "/file",
- // "query", "fragment");
- construct1("http", "user", "host%20name", -1, "/file", "query",
- "fragment"); // escaped octets in host name
- construct1("http", "user", "host name", -1, "/file", "query",
- "fragment"); // illegal char in host name
- construct1("http", "user", "host]name", -1, "/file", "query",
- "fragment"); // illegal char in host name
-
- // missing host name
- construct1("http", "user", "", 80, "/file", "query", "fragment");
-
- // missing host name
- construct1("http", "user", "", -1, "/file", "query", "fragment");
-
- // malformed ipv4 address
- construct1("telnet", null, "256.197.221.200", -1, null, null, null);
-
- // malformed ipv4 address
- construct1("ftp", null, "198.256.221.200", -1, null, null, null);
-
- // These tests fail on other implementations...
- // construct1("http", "user", null, 80, "/file", "query", "fragment");
- // //missing host name
- // construct1("http", "user", null, -1, "/file", "query", "fragment");
- // //missing host name
-
- // check for URISyntaxException for invalid scheme
- construct1("ht\u00DFtp", "user", "hostname", -1, "/file", "query",
- "fragment"); // unicode chars in scheme
- // equivalent to construct1("ht\u00dftp", "user", "hostname", -1,
- // "/file",
- // "query", "fragment");
-
- construct1("ht%20tp", "user", "hostname", -1, "/file", "query",
- "fragment"); // escaped octets in scheme
- construct1("ht tp", "user", "hostname", -1, "/file", "query",
- "fragment"); // illegal char in scheme
- construct1("ht]tp", "user", "hostname", -1, "/file", "query",
- "fragment"); // illegal char in scheme
-
- // relative path with scheme
- construct1("http", "user", "hostname", -1, "relative", "query",
- "fragment"); // unicode chars in scheme
-
- // functional test
- URI uri;
- try {
- uri = new URI("http", "us:e@r", "hostname", 85, "/file/dir#/qu?e/",
- "qu?er#y", "frag#me?nt");
- assertEquals("wrong userinfo", "us:e@r", uri.getUserInfo());
- assertEquals("wrong hostname", "hostname", uri.getHost());
- assertEquals("wrong port number", 85, uri.getPort());
- assertEquals("wrong path", "/file/dir#/qu?e/", uri.getPath());
- assertEquals("wrong query", "qu?er#y", uri.getQuery());
- assertEquals("wrong fragment", "frag#me?nt", uri.getFragment());
- assertEquals("wrong SchemeSpecificPart",
- "//us:e@r@hostname:85/file/dir#/qu?e/?qu?er#y", uri
- .getSchemeSpecificPart());
- } catch (URISyntaxException e) {
- fail("Unexpected Exception: " + e);
- }
- }
-
- /*
- * helper method checking if the 7 arg constructor throws URISyntaxException
- * for a given set of parameters
- */
- private void construct1(String scheme, String userinfo, String host,
- int port, String path, String query, String fragment) {
- try {
- URI uri = new URI(scheme, userinfo, host, port, path, query,
- fragment);
- fail("Expected URISyntaxException not thrown for URI: "
- + uri.toString());
- } catch (URISyntaxException e) {
- // this constructor throws URISyntaxException for malformed server
- // based authorities
- }
- }
-
- /**
- * @throws URISyntaxException
- * @tests java.net.URI#URI(java.lang.String, java.lang.String,
- * java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URI",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String()
- throws URISyntaxException {
- // relative path
- try {
- URI myUri = new URI("http", "www.joe.com", "relative", "jimmy");
- fail("URISyntaxException expected but not received.");
- } catch (URISyntaxException e) {
- // Expected
- }
-
- // valid parameters for this constructor
- URI uri;
-
- uri = new URI("http", "www.joe.com", "/path", "jimmy");
-
- // illegal char in path
- uri = new URI("http", "www.host.com", "/path?q", "somefragment");
-
- // empty fragment
- uri = new URI("ftp", "ftp.is.co.za", "/rfc/rfc1808.txt", "");
-
- // path with escaped octet for unicode char, not USASCII
- uri = new URI("http", "host", "/a%E2%82%ACpath", "frag");
-
- // frag with unicode char, not USASCII
- // equivalent to = uri = new URI("http", "host", "/apath",
- // "\u0080frag");
- uri = new URI("http", "host", "/apath", "\u20ACfrag");
-
- // Regression test for Harmony-1693
- new URI(null, null, null, null);
-
- // regression for Harmony-1346
- try {
- uri = new URI("http", ":2:3:4:5:6:7:8", "/apath", "\u20ACfrag");
- fail("Should throw URISyntaxException");
- } catch (URISyntaxException e) {
- // Expected
- }
- }
-
- /**
- * @throws URISyntaxException
- * @tests java.net.URI#URI(java.lang.String, java.lang.String,
- * java.lang.String, java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URI",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String()
- throws URISyntaxException {
- // URISyntaxException on relative path
- try {
- URI myUri = new URI("http", "www.joe.com", "relative", "query",
- "jimmy");
- fail("URISyntaxException expected but not received.");
- } catch (URISyntaxException e) {
- // Expected
- }
-
- // test if empty authority is parsed into undefined host, userinfo and
- // port and if unicode chars and escaped octets in components are
- // preserved, illegal chars are quoted
- URI uri = new URI("ht12-3+tp", "", "/p#a%E2%82%ACth", "q^u%25ery",
- "f/r\u00DFag");
-
- assertEquals("wrong scheme", "ht12-3+tp", uri.getScheme());
- assertNull("wrong authority", uri.getUserInfo());
- assertNull("wrong userinfo", uri.getUserInfo());
- assertNull("wrong hostname", uri.getHost());
- assertEquals("wrong port number", -1, uri.getPort());
- assertEquals("wrong path", "/p#a%E2%82%ACth", uri.getPath());
- assertEquals("wrong query", "q^u%25ery", uri.getQuery());
- assertEquals("wrong fragment", "f/r\u00DFag", uri.getFragment());
- // equivalent to = assertTrue("wrong fragment",
- // uri.getFragment().equals("f/r\u00dfag"));
- assertEquals("wrong SchemeSpecificPart", "///p#a%E2%82%ACth?q^u%25ery",
- uri.getSchemeSpecificPart());
- assertEquals("wrong RawSchemeSpecificPart",
- "///p%23a%25E2%2582%25ACth?q%5Eu%2525ery", uri
- .getRawSchemeSpecificPart());
- assertEquals(
- "incorrect toString()",
- "ht12-3+tp:///p%23a%25E2%2582%25ACth?q%5Eu%2525ery#f/r\u00dfag",
- uri.toString());
- assertEquals("incorrect toASCIIString()",
-
- "ht12-3+tp:///p%23a%25E2%2582%25ACth?q%5Eu%2525ery#f/r%C3%9Fag", uri
- .toASCIIString());
- }
-
- /**
- * @throws URISyntaxException
- * @tests java.net.URI#URI(java.lang.String, java.lang.String,
- * java.lang.String, java.lang.String, java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "URI",
- args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
- )
- public void test_fiveArgConstructor() throws URISyntaxException {
- // accept [] as part of valid ipv6 host name
- URI uri = new URI("ftp", "[0001:1234::0001]", "/dir1/dir2", "query",
- "frag");
- assertEquals("Returned incorrect host", "[0001:1234::0001]", uri
- .getHost());
-
- // do not accept [] as part of invalid ipv6 address
- try {
- uri = new URI("ftp", "[www.abc.com]", "/dir1/dir2", "query", "frag");
- fail("Expected URISyntaxException for invalid ipv6 address");
- } catch (URISyntaxException e) {
- // Expected
- }
-
- // do not accept [] as part of user info
- try {
- uri = new URI("ftp", "[user]@host", "/dir1/dir2", "query", "frag");
- fail("Expected URISyntaxException invalid user info");
- } catch (URISyntaxException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.net.URI#compareTo(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "compareTo",
- args = {Object.class}
- )
- public void test_compareToLjava_lang_Object() {
- // compareTo tests
-
- String[][] compareToData = new String[][] {
- // scheme tests
- { "http:test", "" }, // scheme null, scheme not null
- { "", "http:test" }, // reverse
- { "http:test", "ftp:test" }, // schemes different
- { "/test", "/test" }, // schemes null
- { "http://joe", "http://joe" }, // schemes same
- { "http://joe", "hTTp://joe" }, // schemes same ignoring case
-
- // opacity : one opaque, the other not
- { "http:opaque", "http://nonopaque" },
- { "http://nonopaque", "http:opaque" },
- { "mailto:abc", "mailto:abc" }, // same ssp
- { "mailto:abC", "mailto:Abc" }, // different, by case
- { "mailto:abc", "mailto:def" }, // different by letter
- { "mailto:abc#ABC", "mailto:abc#DEF" },
- { "mailto:abc#ABC", "mailto:abc#ABC" },
- { "mailto:abc#DEF", "mailto:abc#ABC" },
-
- // hierarchical tests..
-
- // diffrent authorities
- { "//www.test.com/test", "//www.test2.com/test" },
-
- { "/nullauth", "//nonnullauth/test" }, // one null authority
- { "//nonnull", "/null" },
- { "/hello", "/hello" }, // both authorities null
- // different userinfo
- { "http://joe@test.com:80", "http://test.com" },
- { "http://jim@test.com", "http://james@test.com" },
- // different hostnames
- { "http://test.com", "http://toast.com" },
- { "http://test.com:80", "test.com:87" }, // different ports
- { "http://test.com", "http://test.com:80" },
- // different paths
- { "http://test.com:91/dir1", "http://test.com:91/dir2" },
- // one null host
- { "http:/hostless", "http://hostfilled.com/hostless" },
-
- // queries
- { "http://test.com/dir?query", "http://test.com/dir?koory" },
- { "/test?query", "/test" },
- { "/test", "/test?query" },
- { "/test", "/test" },
-
- // fragments
- { "ftp://test.com/path?query#frag", "ftp://test.com/path?query" },
- { "ftp://test.com/path?query", "ftp://test.com/path?query#frag" },
- { "#frag", "#frag" }, { "p", "" },
-
- { "http://www.google.com", "#test" } // miscellaneous
- };
-
- int[] compareToResults = { 1, -1, 2, 0, 0, 0, 1, -1, 0, 32, -3, -3, 0,
- 3, -4, -1, 1, 0, 1, 8, -10, -12, -81, -1, -1, 6, 1, -1, 0, 1,
- -1, 0, 1, 1, };
-
- // test compareTo functionality
- for (int i = 0; i < compareToResults.length; i++) {
- try {
- URI b = new URI(compareToData[i][0]);
- URI r = new URI(compareToData[i][1]);
- if (b.compareTo(r) != compareToResults[i]) {
- fail("Test " + i + ": " + compareToData[i][0]
- + " compared to " + compareToData[i][1] + " -> "
- + b.compareTo(r) + " rather than "
- + compareToResults[i]);
- }
- } catch (Exception e) {
- fail("Error in compareTo test of " + compareToData[i][0]
- + " compared to " + compareToData[i][1] + ": " + e);
- }
- }
- }
-
- /**
- * @throws URISyntaxException
- * @tests java.net.URI#compareTo(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "compareTo",
- args = {java.net.URI.class}
- )
- public void test_compareTo2() throws URISyntaxException {
- URI uri, uri2;
-
- // test URIs with host names with different casing
- uri = new URI("http://AbC.cOm/root/news");
- uri2 = new URI("http://aBc.CoM/root/news");
- assertEquals("TestA", 0, uri.compareTo(uri2));
- assertEquals("TestB", 0, uri.compareTo(uri2));
-
- // test URIs with one undefined component
- uri = new URI("http://abc.com:80/root/news");
- uri2 = new URI("http://abc.com/root/news");
- assertTrue("TestC", uri.compareTo(uri2) > 0);
- assertTrue("TestD", uri2.compareTo(uri) < 0);
-
- // test URIs with one undefined component
- uri = new URI("http://user@abc.com/root/news");
- uri2 = new URI("http://abc.com/root/news");
- assertTrue("TestE", uri.compareTo(uri2) > 0);
- assertTrue("TestF", uri2.compareTo(uri) < 0);
- }
-
- /**
- * @tests java.net.URI#create(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "create",
- args = {java.lang.String.class}
- )
- public void test_createLjava_lang_String() {
-
-
- for (int i = 0; i < constructorTests.length; i++) {
- try {
- new URI(constructorTests[i]);
- } catch (URISyntaxException e) {
- fail("Failed to construct URI for: " + constructorTests[i]
- + " : " + e);
- }
- }
-
- for(int i = 0; i < constructorTestsInvalid.length; i++) {
- try {
- URI myUri = URI.create(constructorTestsInvalid[i]);
- fail("IllegalArgumentException expected but not received.");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
- }
-
- /**
- * @tests java.net.URI#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equalsLjava_lang_Object() {
- String[][] equalsData = new String[][] {
- { "", "" }, // null frags
- { "/path", "/path#frag" },
- { "#frag", "#frag2" },
- { "#frag", "#FRag" },
-
- // case insensitive on hex escapes
- { "#fr%4F", "#fr%4f" },
-
- { "scheme:test", "scheme2:test" }, // scheme stuff
- { "test", "http:test" },
- { "http:test", "test" },
- { "SCheme:test", "schEMe:test" },
-
- // hierarchical/opaque mismatch
- { "mailto:jim", "mailto://jim" },
- { "mailto://test", "mailto:test" },
-
- // opaque
- { "mailto:name", "mailto:name" },
- { "mailtO:john", "mailto:jim" },
-
- // test hex case insensitivity on ssp
- { "mailto:te%4Fst", "mailto:te%4fst" },
-
- { "mailto:john#frag", "mailto:john#frag2" },
-
- // hierarchical
- { "/test", "/test" }, // paths
- { "/te%F4st", "/te%f4st" },
- { "/TEst", "/teSt" },
- { "", "/test" },
-
- // registry based because they don't resolve properly to
- // server-based add more tests here
- { "//host.com:80err", "//host.com:80e" },
- { "//host.com:81e%Abrr", "//host.com:81e%abrr" },
-
- { "/test", "//auth.com/test" },
- { "//test.com", "/test" },
-
- { "//test.com", "//test.com" }, // hosts
-
- // case insensitivity for hosts
- { "//HoSt.coM/", "//hOsT.cOm/" },
- { "//te%ae.com", "//te%aE.com" },
- { "//test.com:80", "//test.com:81" },
- { "//joe@test.com:80", "//test.com:80" },
- { "//jo%3E@test.com:82", "//jo%3E@test.com:82" },
- { "//test@test.com:85", "//test@test.com" }, };
-
- boolean[] equalsResults = new boolean[] { true, false, false, false,
- true, false, false, false, true, false, false, true, false,
- true, false, true, true, false, false, false, true, false,
- false, true, true, true, false, false, true, false, };
-
- // test equals functionality
- for (int i = 0; i < equalsResults.length; i++) {
- try {
- URI b = new URI(equalsData[i][0]);
- URI r = new URI(equalsData[i][1]);
- if (b.equals(r) != equalsResults[i]) {
- fail("Error: " + equalsData[i][0] + " == "
- + equalsData[i][1] + "? -> " + b.equals(r)
- + " expected " + equalsResults[i]);
- }
- } catch (Exception e) {
- fail("Exception during equals testing data " + equalsData[i][0]
- + " == " + equalsData[i][1] + "? " + e);
- }
- }
-
- }
-
- /**
- * @throws URISyntaxException
- * @tests java.net.URI#equals(java.lang.Object)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "equals",
- args = {java.lang.Object.class}
- )
- public void test_equals2() throws URISyntaxException {
- // test URIs with empty string authority
- URI uri = new URI("http:///~/dictionary");
- URI uri2 = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(),
- uri.getQuery(), uri.getFragment());
- assertTrue(uri2.equals(uri));
-
- // test URIs with port number
- uri = new URI("http://abc.com%E2%82%AC:88/root/news");
- uri2 = new URI("http://abc.com%E2%82%AC/root/news");
- assertFalse(uri.equals(uri2));
- assertFalse(uri2.equals(uri));
-
- // test URIs with host names with different casing
- uri = new URI("http://AbC.cOm/root/news");
- uri2 = new URI("http://aBc.CoM/root/news");
- assertTrue(uri.equals(uri2));
- assertTrue(uri2.equals(uri));
- }
-
- /**
- * @tests java.net.URI#getAuthority()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAuthority",
- args = {}
- )
- public void test_getAuthority() throws Exception {
- URI[] uris = getUris();
-
- String[] getAuthorityResults = {
- "user` info@host",
- "user\u00DF\u00A3info@host:80", // =
- // "user\u00df\u00a3info@host:80",
- "user\u00DF\u00A3info@host:0", // =
- // "user\u00df\u00a3info@host:0",
- "user%60%20info@host:80",
- "user%C3%9F%C2%A3info@host",
- "user\u00DF\u00A3info@host:80", // =
- // "user\u00df\u00a3info@host:80",
- "user` info@host:81", "user%info@host:0", null, null, null,
- null, "server.org", "reg:istry", null, };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getAuthority();
- if (getAuthorityResults[i] != result
- && !getAuthorityResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getAuthority() returned: " + result
- + ", expected: " + getAuthorityResults[i]);
- }
- }
- // regression test for HARMONY-1119
- assertNull(new URI(null, null, null, 127, null, null, null)
- .getAuthority());
- }
-
- /**
- * @tests java.net.URI#getAuthority()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getAuthority",
- args = {}
- )
- public void test_getAuthority2() throws Exception {
- // tests for URIs with empty string authority component
-
- URI uri = new URI("file:///tmp/");
- assertNull("Authority not null for URI: " + uri, uri.getAuthority());
- assertNull("Host not null for URI " + uri, uri.getHost());
- assertEquals("testA, toString() returned incorrect value",
- "file:///tmp/", uri.toString());
-
- uri = new URI("file", "", "/tmp", "frag");
- assertNull("Authority not null for URI: " + uri, uri.getAuthority());
- assertNull("Host not null for URI " + uri, uri.getHost());
- assertEquals("testB, toString() returned incorrect value",
- "file:///tmp#frag", uri.toString());
-
- uri = new URI("file", "", "/tmp", "query", "frag");
- assertNull("Authority not null for URI: " + uri, uri.getAuthority());
- assertNull("Host not null for URI " + uri, uri.getHost());
- assertEquals("test C, toString() returned incorrect value",
- "file:///tmp?query#frag", uri.toString());
-
- // after normalization the host string info may be lost since the
- // uri string is reconstructed
- uri = new URI("file", "", "/tmp/a/../b/c", "query", "frag");
- URI uri2 = uri.normalize();
- assertNull("Authority not null for URI: " + uri2, uri.getAuthority());
- assertNull("Host not null for URI " + uri2, uri.getHost());
- assertEquals("test D, toString() returned incorrect value",
- "file:///tmp/a/../b/c?query#frag", uri.toString());
- assertEquals("test E, toString() returned incorrect value",
- "file:/tmp/b/c?query#frag", uri2.toString());
-
- // the empty string host will give URISyntaxException
- // for the 7 arg constructor
- try {
- uri = new URI("file", "user", "", 80, "/path", "query", "frag");
- fail("Expected URISyntaxException");
- } catch (URISyntaxException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.net.URI#getFragment()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getFragment",
- args = {}
- )
- public void test_getFragment() throws Exception {
- URI[] uris = getUris();
-
- String[] getFragmentResults = { "fr^ ag", "fr\u00E4\u00E8g", // =
- // "fr\u00e4\u00e8g",
- "fr\u00E4\u00E8g", // = "fr\u00e4\u00e8g",
- "fr%5E%20ag", "fr%C3%A4%C3%A8g", "fr\u00E4\u00E8g", // =
- // "fr\u00e4\u00e8g",
- "fr^ ag", "f%rag", null, "", null, "fragment", null, null, null };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getFragment();
- if (getFragmentResults[i] != result
- && !getFragmentResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getFragment() returned: " + result
- + ", expected: " + getFragmentResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getHost()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getHost",
- args = {}
- )
- public void test_getHost() throws Exception {
- URI[] uris = getUris();
-
- String[] getHostResults = { "host", "host", "host", "host", "host",
- "host", "host", "host", null, null, null, null, "server.org",
- null, null };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getHost();
- if (getHostResults[i] != result
- && !getHostResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getHost() returned: " + result + ", expected: "
- + getHostResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getPath()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPath",
- args = {}
- )
- public void test_getPath() throws Exception {
- URI[] uris = getUris();
-
- String[] getPathResults = { "/a path",
- "/a\u20ACpath", // = "/a\u0080path",
- "/a\u20ACpath", // = "/a\u0080path",
- "/a%20path", "/a%E2%82%ACpath",
- "/a\u20ACpath", // = "/a\u0080path",
- "/a path", "/a%path", null, "../adirectory/file.html", null,
- "", "", "", "/c:/temp/calculate.pl" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getPath();
- if (getPathResults[i] != result
- && !getPathResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getPath() returned: " + result + ", expected: "
- + getPathResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getPort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPort",
- args = {}
- )
- public void test_getPort() throws Exception {
- URI[] uris = getUris();
-
- int[] getPortResults = { -1, 80, 0, 80, -1, 80, 81, 0, -1, -1, -1, -1,
- -1, -1, -1 };
-
- for (int i = 0; i < uris.length; i++) {
- int result = uris[i].getPort();
- assertTrue("Error: For URI \"" + uris[i].toString()
- + "\", getPort() returned: " + result + ", expected: "
- + getPortResults[i], result == getPortResults[i]);
- }
- }
-
- /**
- * @tests java.net.URI#getPort()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getPort",
- args = {}
- )
- public void test_getPort2() throws Exception {
- // if port value is negative, the authority should be
- // consider registry based.
-
- URI uri = new URI("http://myhost:-8096/site/index.html");
- assertEquals("TestA, returned wrong port value,", -1, uri.getPort());
- assertNull("TestA, returned wrong host value,", uri.getHost());
- try {
- uri.parseServerAuthority();
- fail("TestA, Expected URISyntaxException");
- } catch (URISyntaxException e) {
- // Expected
- }
-
- uri = new URI("http", "//myhost:-8096", null);
- assertEquals("TestB returned wrong port value,", -1, uri.getPort());
- assertNull("TestB returned wrong host value,", uri.getHost());
- try {
- uri.parseServerAuthority();
- fail("TestB, Expected URISyntaxException");
- } catch (URISyntaxException e) {
- // Expected
- }
- }
-
- /**
- * @tests java.net.URI#getQuery()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getQuery",
- args = {}
- )
- public void test_getQuery() throws Exception {
- URI[] uris = getUris();
-
- String[] getQueryResults = { "qu` ery", "qu\u00A9\u00AEery", // =
- // "qu\u00a9\u00aeery",
- "qu\u00A9\u00AEery", // = "qu\u00a9\u00aeery",
- "qu%60%20ery", "qu%C2%A9%C2%AEery", "qu\u00A9\u00AEery", // =
- // "qu\u00a9\u00aeery",
- "qu` ery", "que%ry", null, null, null, null, null, "query", "" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getQuery();
- if (getQueryResults[i] != result
- && !getQueryResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getQuery() returned: " + result + ", expected: "
- + getQueryResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getRawAuthority()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRawAuthority",
- args = {}
- )
- public void test_getRawAuthority() throws Exception {
- URI[] uris = getUris();
-
- String[] getRawAuthorityResults = {
- "user%60%20info@host",
- "user%C3%9F%C2%A3info@host:80",
- "user\u00DF\u00A3info@host:0", // =
- // "user\u00df\u00a3info@host:0",
- "user%2560%2520info@host:80",
- "user%25C3%259F%25C2%25A3info@host",
- "user\u00DF\u00A3info@host:80", // =
- // "user\u00df\u00a3info@host:80",
- "user%60%20info@host:81", "user%25info@host:0", null, null,
- null, null, "server.org", "reg:istry", null };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getRawAuthority();
- if (getRawAuthorityResults[i] != result
- && !getRawAuthorityResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getRawAuthority() returned: " + result
- + ", expected: " + getRawAuthorityResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getRawFragment()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRawFragment",
- args = {}
- )
- public void test_getRawFragment() throws Exception {
- URI[] uris = getUris();
-
- String[] getRawFragmentResults = { "fr%5E%20ag",
- "fr%C3%A4%C3%A8g",
- "fr\u00E4\u00E8g", // = "fr\u00e4\u00e8g",
- "fr%255E%2520ag", "fr%25C3%25A4%25C3%25A8g",
- "fr\u00E4\u00E8g", // =
- // "fr\u00e4\u00e8g",
- "fr%5E%20ag", "f%25rag", null, "", null, "fragment", null,
- null, null };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getRawFragment();
- if (getRawFragmentResults[i] != result
- && !getRawFragmentResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getRawFragment() returned: " + result
- + ", expected: " + getRawFragmentResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getRawPath()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRawPath",
- args = {}
- )
- public void test_getRawPath() throws Exception {
- URI[] uris = getUris();
-
- String[] getRawPathResults = { "/a%20path",
- "/a%E2%82%ACpath",
- "/a\u20ACpath", // = "/a\u0080path",
- "/a%2520path", "/a%25E2%2582%25ACpath",
- "/a\u20ACpath", // =
- // "/a\u0080path",
- "/a%20path", "/a%25path", null, "../adirectory/file.html",
- null, "", "", "", "/c:/temp/calculate.pl" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getRawPath();
- if (getRawPathResults[i] != result
- && !getRawPathResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getRawPath() returned: " + result
- + ", expected: " + getRawPathResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getRawQuery()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRawQuery",
- args = {}
- )
- public void test_getRawQuery() throws Exception {
- URI[] uris = getUris();
-
- String[] getRawQueryResults = {
- "qu%60%20ery",
- "qu%C2%A9%C2%AEery",
- "qu\u00A9\u00AEery", // = "qu\u00a9\u00aeery",
- "qu%2560%2520ery",
- "qu%25C2%25A9%25C2%25AEery",
- "qu\u00A9\u00AEery", // = "qu\u00a9\u00aeery",
- "qu%60%20ery", "que%25ry", null, null, null, null, null,
- "query", "" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getRawQuery();
- if (getRawQueryResults[i] != result
- && !getRawQueryResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getRawQuery() returned: " + result
- + ", expected: " + getRawQueryResults[i]);
- }
- }
-
- }
-
- /**
- * @tests java.net.URI#getRawSchemeSpecificPart()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRawSchemeSpecificPart",
- args = {}
- )
- public void test_getRawSchemeSpecificPart() throws Exception {
- URI[] uris = getUris();
-
- String[] getRawSspResults = {
- "//user%60%20info@host/a%20path?qu%60%20ery",
- "//user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery",
- "//user\u00DF\u00A3info@host:0/a\u20ACpath?qu\u00A9\u00AEery", // =
- // "//user\u00df\u00a3info@host:0/a\u0080path?qu\u00a9\u00aeery"
- "//user%2560%2520info@host:80/a%2520path?qu%2560%2520ery",
- "//user%25C3%259F%25C2%25A3info@host/a%25E2%2582%25ACpath?qu%25C2%25A9%25C2%25AEery",
- "//user\u00DF\u00A3info@host:80/a\u20ACpath?qu\u00A9\u00AEery", // =
- // "//user\u00df\u00a3info@host:80/a\u0080path?qu\u00a9\u00aeery"
- "//user%60%20info@host:81/a%20path?qu%60%20ery",
- "//user%25info@host:0/a%25path?que%25ry", "user@domain.com",
- "../adirectory/file.html", "comp.infosystems.www.servers.unix",
- "", "//server.org", "//reg:istry?query",
- "///c:/temp/calculate.pl?" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getRawSchemeSpecificPart();
- if (!getRawSspResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getRawSchemeSpecificPart() returned: " + result
- + ", expected: " + getRawSspResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getRawUserInfo()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getRawUserInfo",
- args = {}
- )
- public void test_getRawUserInfo() throws URISyntaxException {
- URI[] uris = getUris();
-
- String[] getRawUserInfoResults = {
- "user%60%20info",
- "user%C3%9F%C2%A3info",
- "user\u00DF\u00A3info", // = "user\u00df\u00a3info",
- "user%2560%2520info",
- "user%25C3%259F%25C2%25A3info",
- "user\u00DF\u00A3info", // = "user\u00df\u00a3info",
- "user%60%20info", "user%25info", null, null, null, null, null,
- null, null };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getRawUserInfo();
- if (getRawUserInfoResults[i] != result
- && !getRawUserInfoResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getRawUserInfo() returned: " + result
- + ", expected: " + getRawUserInfoResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getScheme()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getScheme",
- args = {}
- )
- public void test_getScheme() throws Exception {
- URI[] uris = getUris();
-
- String[] getSchemeResults = { "http", "http", "ascheme", "http",
- "http", "ascheme", "http", "http", "mailto", null, "news",
- null, "telnet", "http", "file" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getScheme();
- if (getSchemeResults[i] != result
- && !getSchemeResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getScheme() returned: " + result
- + ", expected: " + getSchemeResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#getSchemeSpecificPart()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getSchemeSpecificPart",
- args = {}
- )
- public void test_getSchemeSpecificPart() throws Exception {
- URI[] uris = getUris();
-
- String[] getSspResults = {
- "//user` info@host/a path?qu` ery",
- "//user\u00DF\u00A3info@host:80/a\u20ACpath?qu\u00A9\u00AEery", // =
- // "//user\u00df\u00a3info@host:80/a\u0080path?qu\u00a9\u00aeery",
- "//user\u00DF\u00A3info@host:0/a\u20ACpath?qu\u00A9\u00AEery", // =
- // "//user\u00df\u00a3info@host:0/a\u0080path?qu\u00a9\u00aeery",
- "//user%60%20info@host:80/a%20path?qu%60%20ery",
- "//user%C3%9F%C2%A3info@host/a%E2%82%ACpath?qu%C2%A9%C2%AEery",
- "//user\u00DF\u00A3info@host:80/a\u20ACpath?qu\u00A9\u00AEery", // =
- // "//user\u00df\u00a3info@host:80/a\u0080path?qu\u00a9\u00aeery",
- "//user` info@host:81/a path?qu` ery",
- "//user%info@host:0/a%path?que%ry", "user@domain.com",
- "../adirectory/file.html", "comp.infosystems.www.servers.unix",
- "", "//server.org", "//reg:istry?query",
- "///c:/temp/calculate.pl?" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getSchemeSpecificPart();
- if (!getSspResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getSchemeSpecificPart() returned: " + result
- + ", expected: " + getSspResults[i]);
- }
- }
-
- }
-
- /**
- * @tests java.net.URI#getUserInfo()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "getUserInfo",
- args = {}
- )
- public void test_getUserInfo() throws Exception {
- URI[] uris = getUris();
-
- String[] getUserInfoResults = {
- "user` info",
- "user\u00DF\u00A3info", // =
- // "user\u00df\u00a3info",
- "user\u00DF\u00A3info", // = "user\u00df\u00a3info",
- "user%60%20info",
- "user%C3%9F%C2%A3info",
- "user\u00DF\u00A3info", // = "user\u00df\u00a3info",
- "user` info", "user%info", null, null, null, null, null, null,
- null };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].getUserInfo();
- if (getUserInfoResults[i] != result
- && !getUserInfoResults[i].equals(result)) {
- fail("Error: For URI \"" + uris[i].toString()
- + "\", getUserInfo() returned: " + result
- + ", expected: " + getUserInfoResults[i]);
- }
- }
- }
-
- /**
- * @tests java.net.URI#hashCode()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "hashCode",
- args = {}
- )
- public void test_hashCode() throws Exception {
- String[][] hashCodeData = new String[][] {
- { "", "" }, // null frags
- { "/path", "/path#frag" },
- { "#frag", "#frag2" },
- { "#frag", "#FRag" },
-
- { "#fr%4F", "#fr%4F" }, // case insensitive on hex escapes
-
- { "scheme:test", "scheme2:test" }, // scheme
- { "test", "http:test" },
- { "http:test", "test" },
-
- // case insensitivity for scheme
- { "SCheme:test", "schEMe:test" },
-
- // hierarchical/opaque mismatch
- { "mailto:jim", "mailto://jim" },
- { "mailto://test", "mailto:test" },
-
- // opaque
- { "mailto:name", "mailto:name" },
- { "mailtO:john", "mailto:jim" },
- { "mailto:te%4Fst", "mailto:te%4Fst" },
- { "mailto:john#frag", "mailto:john#frag2" },
-
- // hierarchical
- { "/test/", "/test/" }, // paths
- { "/te%F4st", "/te%F4st" },
- { "/TEst", "/teSt" },
- { "", "/test" },
-
- // registry based because they don't resolve properly to
- // server-based
- // add more tests here
- { "//host.com:80err", "//host.com:80e" },
- { "//host.com:81e%Abrr", "//host.com:81e%Abrr" },
- { "//Host.com:80e", "//hoSt.com:80e" },
-
- { "/test", "//auth.com/test" },
- { "//test.com", "/test" },
-
- { "//test.com", "//test.com" }, // server based
-
- // case insensitivity for host
- { "//HoSt.coM/", "//hOsT.cOm/" },
- { "//te%aE.com", "//te%aE.com" },
- { "//test.com:80", "//test.com:81" },
- { "//joe@test.com:80", "//test.com:80" },
- { "//jo%3E@test.com:82", "//jo%3E@test.com:82" },
- { "//test@test.com:85", "//test@test.com" }, };
-
- boolean[] hashCodeResults = new boolean[] { true, false, false, false,
- true, false, false, false, true, false, false, true, false,
- true, false, true, true, false, false, false, true, false,
- false, false, true, true, true, false, false, true, false, };
-
- for (int i = 0; i < hashCodeResults.length; i++) {
- URI b = new URI(hashCodeData[i][0]);
- URI r = new URI(hashCodeData[i][1]);
- assertEquals("Error in hashcode equals results for" + b.toString()
- + " " + r.toString(), hashCodeResults[i], b.hashCode() == r
- .hashCode());
- }
-
- }
-
- /**
- * @tests java.net.URI#isAbsolute()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isAbsolute",
- args = {}
- )
- public void test_isAbsolute() throws URISyntaxException {
- String[] isAbsoluteData = new String[] { "mailto:user@ca.ibm.com",
- "urn:isbn:123498989h", "news:software.ibm.com",
- "http://www.amazon.ca", "file:///d:/temp/results.txt",
- "scheme:ssp", "calculate.pl?isbn=123498989h",
- "?isbn=123498989h", "//www.amazon.ca", "a.html", "#top",
- "//pc1/", "//user@host/path/file" };
-
- boolean results[] = new boolean[] { true, true, true, true, true, true,
- false, false, false, false, false, false, false };
-
- for (int i = 0; i < isAbsoluteData.length; i++) {
- boolean result = new URI(isAbsoluteData[i]).isAbsolute();
- assertEquals("new URI(" + isAbsoluteData[i] + ").isAbsolute()",
- results[i], result);
- }
- }
-
- /**
- * @tests java.net.URI#isOpaque()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "isOpaque",
- args = {}
- )
- public void test_isOpaque() throws URISyntaxException {
- String[] isOpaqueData = new String[] { "mailto:user@ca.ibm.com",
- "urn:isbn:123498989h", "news:software.ibm.com",
- "http://www.amazon.ca", "file:///d:/temp/results.txt",
- "scheme:ssp", "calculate.pl?isbn=123498989h",
- "?isbn=123498989h", "//www.amazon.ca", "a.html", "#top",
- "//pc1/", "//user@host/path/file" };
-
- boolean results[] = new boolean[] { true, true, true, false, false,
- true, false, false, false, false, false, false, false };
-
- for (int i = 0; i < isOpaqueData.length; i++) {
- boolean result = new URI(isOpaqueData[i]).isOpaque();
- assertEquals("new URI(" + isOpaqueData[i] + ").isOpaque()",
- results[i], result);
- }
- }
-
- /**
- * @tests java.net.URI#normalize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "normalize",
- args = {}
- )
- public void test_normalize() throws Exception {
-
- String[] normalizeData = new String[] {
- // normal
- "/",
- "/a",
- "/a/b",
- "/a/b/c",
- // single, '.'
- "/.", "/./", "/./.", "/././",
- "/./a",
- "/./a/",
- "/././a",
- "/././a/",
- "/a/.",
- "/a/./",
- "/a/./.",
- "/a/./b",
- // double, '..'
- "/a/..", "/a/../", "/a/../b", "/a/../b/..", "/a/../b/../",
- "/a/../b/../c", "/..", "/../", "/../..", "/../../", "/../a",
- "/../a/", "/../../a", "/../../a/", "/a/b/../../c",
- "/a/b/../..",
- "/a/b/../../",
- "/a/b/../../c",
- "/a/b/c/../../../d",
- "/a/b/..",
- "/a/b/../",
- "/a/b/../c",
- // miscellaneous
- "/a/b/.././../../c/./d/../e",
- "/a/../../.c././../././c/d/../g/..",
- // '.' in the middle of segments
- "/a./b", "/.a/b", "/a.b/c", "/a/b../c",
- "/a/..b/c",
- "/a/b..c/d",
- // no leading slash, miscellaneous
- "", "a", "a/b", "a/b/c", "../", ".", "..", "../g",
- "g/a/../../b/c/./g", "a/b/.././../../c/./d/../e",
- "a/../../.c././../././c/d/../g/..", };
-
- String[] normalizeResults = new String[] { "/", "/a", "/a/b", "/a/b/c",
- "/", "/", "/", "/", "/a", "/a/", "/a", "/a/", "/a/", "/a/",
- "/a/", "/a/b", "/", "/", "/b", "/", "/", "/c", "/..", "/../",
- "/../..", "/../../", "/../a", "/../a/", "/../../a",
- "/../../a/", "/c", "/", "/", "/c", "/d", "/a/", "/a/", "/a/c",
- "/../c/e", "/../c/", "/a./b", "/.a/b", "/a.b/c", "/a/b../c",
- "/a/..b/c", "/a/b..c/d", "", "a", "a/b", "a/b/c", "../", "",
- "..", "../g", "b/c/g", "../c/e", "../c/", };
-
- for (int i = 0; i < normalizeData.length; i++) {
- URI test = new URI(normalizeData[i]);
- String result = test.normalize().toString();
- assertEquals("Normalized incorrectly, ", normalizeResults[i],
- result.toString());
- }
- }
-
- /**
- * @tests java.net.URI#normalize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "normalize",
- args = {}
- )
- public void test_normalize2() throws URISyntaxException {
- URI uri1 = null, uri2 = null;
- uri1 = new URI("file:/D:/one/two/../../three");
- uri2 = uri1.normalize();
-
- assertEquals("Normalized to incorrect URI", "file:/D:/three", uri2
- .toString());
- assertTrue("Resolved URI is not absolute", uri2.isAbsolute());
- assertFalse("Resolved URI is opaque", uri2.isOpaque());
- assertEquals("Resolved URI has incorrect scheme specific part",
- "/D:/three", uri2.getRawSchemeSpecificPart());
- }
-
- /**
- * @tests java.net.URI#normalize()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "normalize",
- args = {}
- )
- public void test_normalize3() throws URISyntaxException {
- // return same URI if it has a normalized path already
- URI uri1 = null, uri2 = null;
- uri1 = new URI("http://host/D:/one/two/three");
- uri2 = uri1.normalize();
- assertSame("Failed to return same URI after normalization", uri1, uri2);
-
- // try with empty path
- uri1 = new URI("http", "host", null, "fragment");
- uri2 = uri1.normalize();
- assertSame("Failed to return same URI after normalization", uri1, uri2);
- }
-
- /**
- * @tests java.net.URI#parseServerAuthority()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "parseServerAuthority",
- args = {}
- )
- public void test_parseServerAuthority() throws URISyntaxException {
- // registry based uris
- URI[] uris = null;
- uris = new URI[] {
- // port number not digits
- new URI("http://foo:bar/file#fragment"),
- new URI("http", "//foo:bar/file", "fragment"),
-
- // unicode char in the hostname = new
- // URI("http://host\u00dfname/")
- new URI("http://host\u00DFname/"),
-
- new URI("http", "//host\u00DFname/", null),
- // = new URI("http://host\u00dfname/", null),
-
- // escaped octets in host name
- new URI("http://host%20name/"),
- new URI("http", "//host%20name/", null),
-
- // missing host name, port number
- new URI("http://joe@:80"),
-
- // missing host name, no port number
- new URI("http://user@/file?query#fragment"),
-
- new URI("//host.com:80err"), // malformed port number
- new URI("//host.com:81e%Abrr"),
-
- // malformed ipv4 address
- new URI("telnet", "//256.197.221.200", null),
-
- new URI("telnet://198.256.221.200"),
- new URI("//te%ae.com"), // misc ..
- new URI("//:port"), new URI("//:80"),
-
- // last label has to start with alpha char
- new URI("//fgj234fkgj.jhj.123."),
-
- new URI("//fgj234fkgj.jhj.123"),
-
- // '-' cannot be first or last charcter in a label
- new URI("//-domain.name"), new URI("//domain.name-"),
- new URI("//domain-"),
-
- // illegal char in host name
- new URI("//doma*in"),
-
- // host expected
- new URI("http://:80/"), new URI("http://user@/"),
-
- // ipv6 address not enclosed in "[]"
- new URI("http://3ffe:2a00:100:7031:22:1:80:89/"),
-
- // expected ipv6 addresses to be enclosed in "[]"
- new URI("http", "34::56:78", "/path", "query", "fragment"),
-
- // expected host
- new URI("http", "user@", "/path", "query", "fragment") };
- // these URIs do not have valid server based authorities,
- // but single arg, 3 and 5 arg constructors
- // parse them as valid registry based authorities
-
- // exception should occur when parseServerAuthority is
- // requested on these uris
- for (int i = 0; i < uris.length; i++) {
- try {
- URI uri = uris[i].parseServerAuthority();
- fail("URISyntaxException expected but not received for URI: "
- + uris[i].toString());
- } catch (URISyntaxException e) {
- // Expected
- }
- }
-
- // valid Server based authorities
- new URI("http", "3ffe:2a00:100:7031:2e:1:80:80", "/path", "fragment")
- .parseServerAuthority();
- new URI("http", "host:80", "/path", "query", "fragment")
- .parseServerAuthority();
- new URI("http://[::3abc:4abc]:80/").parseServerAuthority();
- new URI("http", "34::56:78", "/path", "fragment")
- .parseServerAuthority();
- new URI("http", "[34:56::78]:80", "/path", "fragment")
- .parseServerAuthority();
-
- // invalid authorities (neither server nor registry)
- try {
- URI uri = new URI("http://us[er@host:80/");
- fail("Expected URISyntaxException for URI " + uri.toString());
- } catch (URISyntaxException e) {
- // Expected
- }
-
- try {
- URI uri = new URI("http://[ddd::hgghh]/");
- fail("Expected URISyntaxException for URI " + uri.toString());
- } catch (URISyntaxException e) {
- // Expected
- }
-
- try {
- URI uri = new URI("http", "[3ffe:2a00:100:7031:2e:1:80:80]a:80",
- "/path", "fragment");
- fail("Expected URISyntaxException for URI " + uri.toString());
- } catch (URISyntaxException e) {
- // Expected
- }
-
- try {
- URI uri = new URI("http", "host:80", "/path", "fragment");
- fail("Expected URISyntaxException for URI " + uri.toString());
- } catch (URISyntaxException e) {
- // Expected
- }
-
- // regression test for HARMONY-1126
- assertNotNull(URI.create("file://C:/1.txt").parseServerAuthority());
- }
-
- /**
- * @tests java.net.URI#relativize(java.net.URI)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "relativize",
- args = {java.net.URI.class}
- )
- public void test_relativizeLjava_net_URI() {
- // relativization tests
- String[][] relativizeData = new String[][] {
- // first is base, second is the one to relativize
- { "http://www.google.com/dir1/dir2", "mailto:test" }, // rel =
- // opaque
- { "mailto:test", "http://www.google.com" }, // base = opaque
-
- // different authority
- { "http://www.eclipse.org/dir1",
- "http://www.google.com/dir1/dir2" },
-
- // different scheme
- { "http://www.google.com", "ftp://www.google.com" },
-
- { "http://www.google.com/dir1/dir2/",
- "http://www.google.com/dir3/dir4/file.txt" },
- { "http://www.google.com/dir1/",
- "http://www.google.com/dir1/dir2/file.txt" },
- { "./dir1/", "./dir1/hi" },
- { "/dir1/./dir2", "/dir1/./dir2/hi" },
- { "/dir1/dir2/..", "/dir1/dir2/../hi" },
- { "/dir1/dir2/..", "/dir1/dir2/hi" },
- { "/dir1/dir2/", "/dir1/dir3/../dir2/text" },
- { "//www.google.com", "//www.google.com/dir1/file" },
- { "/dir1", "/dir1/hi" }, { "/dir1/", "/dir1/hi" }, };
-
- // expected results
- String[] relativizeResults = new String[] { "mailto:test",
- "http://www.google.com", "http://www.google.com/dir1/dir2",
- "ftp://www.google.com",
- "http://www.google.com/dir3/dir4/file.txt", "dir2/file.txt",
- "hi", "hi", "hi", "dir2/hi", "text", "dir1/file", "hi", "hi", };
-
- for (int i = 0; i < relativizeData.length; i++) {
- try {
- URI b = new URI(relativizeData[i][0]);
- URI r = new URI(relativizeData[i][1]);
- if (!b.relativize(r).toString().equals(relativizeResults[i])) {
- fail("Error: relativize, " + relativizeData[i][0] + ", "
- + relativizeData[i][1] + " returned: "
- + b.relativize(r) + ", expected:"
- + relativizeResults[i]);
- }
- } catch (URISyntaxException e) {
- fail("Exception on relativize test on data "
- + relativizeData[i][0] + ", " + relativizeData[i][1]
- + ": " + e);
- }
- }
-
- try {
- URI b = new URI(relativizeData[0][0]);
- b.relativize(null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- } catch (URISyntaxException e) {
- fail("URISyntaxException was thrown.");
- }
- }
-
- /**
- * @tests java.net.URI#relativize(java.net.URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL,
- notes = "NullPointerException checking missed.",
- method = "relativize",
- args = {java.net.URI.class}
- )
- public void test_relativize2() throws Exception {
- URI a = new URI("http://host/dir");
- URI b = new URI("http://host/dir/file?query");
- assertEquals("relativized incorrectly,", new URI("file?query"), a
- .relativize(b));
-
- // one URI with empty host
- a = new URI("file:///~/dictionary");
- b = new URI("file://tools/~/dictionary");
- assertEquals("relativized incorrectly,", new URI(
- "file://tools/~/dictionary"), a.relativize(b));
- assertEquals("relativized incorrectly,",
- new URI("file:///~/dictionary"), b.relativize(a));
-
- // two URIs with empty hosts
- b = new URI("file:///~/therasus");
- assertEquals("relativized incorrectly,", new URI("file:///~/therasus"),
- a.relativize(b));
- assertEquals("relativized incorrectly,",
- new URI("file:///~/dictionary"), b.relativize(a));
- }
-
- /**
- * @tests java.net.URI#resolve(java.net.URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "NullPointerException checking missed.",
- method = "resolve",
- args = {java.net.URI.class}
- )
- public void test_resolve() throws URISyntaxException {
- URI uri1 = null, uri2 = null;
- uri1 = new URI("file:/D:/one/two/three");
- uri2 = uri1.resolve(new URI(".."));
-
- assertEquals("Resolved to incorrect URI", "file:/D:/one/", uri2
- .toString());
- assertTrue("Resolved URI is not absolute", uri2.isAbsolute());
- assertFalse("Resolved URI is opaque", uri2.isOpaque());
- assertEquals("Resolved URI has incorrect scheme specific part",
- "/D:/one/", uri2.getRawSchemeSpecificPart());
- }
-
- /**
- * @tests java.net.URI#resolve(java.net.URI)
- */
- @TestTargetNew(
- level = TestLevel.PARTIAL_COMPLETE,
- notes = "",
- method = "resolve",
- args = {java.net.URI.class}
- )
- public void test_resolveLjava_net_URI() {
- // resolution tests
- String[][] resolveData = new String[][] {
- // authority in given URI
- { "http://www.test.com/dir",
- "//www.test.com/hello?query#fragment" },
- // no authority, absolute path
- { "http://www.test.com/dir", "/abspath/file.txt" },
- // no authority, relative paths
- { "/", "dir1/file.txt" }, { "/dir1", "dir2/file.txt" },
- { "/dir1/", "dir2/file.txt" }, { "", "dir1/file.txt" },
- { "dir1", "dir2/file.txt" }, { "dir1/", "dir2/file.txt" },
- // normalization required
- { "/dir1/dir2/../dir3/./", "dir4/./file.txt" },
- // allow a standalone fragment to be resolved
- { "http://www.google.com/hey/joe?query#fragment", "#frag2" },
- // return given when base is opaque
- { "mailto:idontexist@uk.ibm.com", "dir1/dir2" },
- // return given when given is absolute
- { "http://www.google.com/hi/joe", "http://www.oogle.com" }, };
-
- // expected results
- String[] resolveResults = new String[] {
- "http://www.test.com/hello?query#fragment",
- "http://www.test.com/abspath/file.txt", "/dir1/file.txt",
- "/dir2/file.txt", "/dir1/dir2/file.txt", "dir1/file.txt",
- "dir2/file.txt", "dir1/dir2/file.txt",
- "/dir1/dir3/dir4/file.txt",
- "http://www.google.com/hey/joe?query#frag2", "dir1/dir2",
- "http://www.oogle.com", };
-
- for (int i = 0; i < resolveResults.length; i++) {
- try {
- URI b = new URI(resolveData[i][0]);
- URI r = new URI(resolveData[i][1]);
- URI result = b.resolve(r);
- if (!result.toString().equals(resolveResults[i])) {
- fail("Error: resolve, " + resolveData[i][0] + ", "
- + resolveData[i][1] + " returned: " + result
- + ", expected:" + resolveResults[i]);
- }
- if (!b.isOpaque()) {
- assertEquals(b + " and " + result
- + " incorrectly differ in absoluteness", b
- .isAbsolute(), result.isAbsolute());
- }
- } catch (URISyntaxException e) {
- fail("Exception on resolve test on data " + resolveData[i][0]
- + ", " + resolveData[i][1] + ": " + e);
- }
- }
-
- try {
- URI b = new URI(resolveData[0][0]);
- b.resolve((URI) null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- } catch (URISyntaxException e) {
- fail("URISyntaxException was thrown.");
- }
- }
-
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "resolve",
- args = {java.lang.String.class}
- )
- public void test_resolveLjava_lang_String() {
- // resolution tests
- String[][] resolveData = new String[][] {
- // authority in given URI
- { "http://www.test.com/dir",
- "//www.test.com/hello?query#fragment" },
- // no authority, absolute path
- { "http://www.test.com/dir", "/abspath/file.txt" },
- // no authority, relative paths
- { "/", "dir1/file.txt" }, { "/dir1", "dir2/file.txt" },
- { "/dir1/", "dir2/file.txt" }, { "", "dir1/file.txt" },
- { "dir1", "dir2/file.txt" }, { "dir1/", "dir2/file.txt" },
- // normalization required
- { "/dir1/dir2/../dir3/./", "dir4/./file.txt" },
- // allow a standalone fragment to be resolved
- { "http://www.google.com/hey/joe?query#fragment", "#frag2" },
- // return given when base is opaque
- { "mailto:idontexist@uk.ibm.com", "dir1/dir2" },
- // return given when given is absolute
- { "http://www.google.com/hi/joe", "http://www.oogle.com" }, };
-
- // expected results
- String[] resolveResults = new String[] {
- "http://www.test.com/hello?query#fragment",
- "http://www.test.com/abspath/file.txt", "/dir1/file.txt",
- "/dir2/file.txt", "/dir1/dir2/file.txt", "dir1/file.txt",
- "dir2/file.txt", "dir1/dir2/file.txt",
- "/dir1/dir3/dir4/file.txt",
- "http://www.google.com/hey/joe?query#frag2", "dir1/dir2",
- "http://www.oogle.com", };
-
- for (int i = 0; i < resolveResults.length; i++) {
- try {
- URI b = new URI(resolveData[i][0]);
- URI result = b.resolve(resolveData[i][1]);
- if (!result.toString().equals(resolveResults[i])) {
- fail("Error: resolve, " + resolveData[i][0] + ", "
- + resolveData[i][1] + " returned: " + result
- + ", expected:" + resolveResults[i]);
- }
- if (!b.isOpaque()) {
- assertEquals(b + " and " + result
- + " incorrectly differ in absoluteness", b
- .isAbsolute(), result.isAbsolute());
- }
- } catch (URISyntaxException e) {
- fail("Exception on resolve test on data " + resolveData[i][0]
- + ", " + resolveData[i][1] + ": " + e);
- }
- }
-
- try {
- URI b = new URI(resolveData[0][0]);
- b.resolve((String) null);
- fail("NullPointerException was not thrown.");
- } catch(NullPointerException npe) {
- //expected
- } catch (URISyntaxException e) {
- fail("URISyntaxException was thrown.");
- }
-
- try {
- URI b = new URI(resolveData[0][0]);
- b.resolve("http://a/b/c/g?y/./x\n");
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- } catch (URISyntaxException e) {
- fail("URISyntaxException was thrown.");
- }
- }
-
- /**
- * @tests java.net.URI#toASCIIString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toASCIIString",
- args = {}
- )
- public void test_toASCIIString() throws Exception {
- URI[] uris = getUris();
-
- String[] toASCIIStringResults0 = new String[] {
- "http://user%60%20info@host/a%20path?qu%60%20ery#fr%5E%20ag",
- "http://user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g",
- "ascheme://user%C3%9F%C2%A3info@host:0/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g",
- "http://user%2560%2520info@host:80/a%2520path?qu%2560%2520ery#fr%255E%2520ag",
- "http://user%25C3%259F%25C2%25A3info@host/a%25E2%2582%25ACpath?qu%25C2%25A9%25C2%25AEery#fr%25C3%25A4%25C3%25A8g",
- "ascheme://user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g",
- "http://user%60%20info@host:81/a%20path?qu%60%20ery#fr%5E%20ag",
- "http://user%25info@host:0/a%25path?que%25ry#f%25rag",
- "mailto:user@domain.com", "../adirectory/file.html#",
- "news:comp.infosystems.www.servers.unix", "#fragment",
- "telnet://server.org", "http://reg:istry?query",
- "file:///c:/temp/calculate.pl?" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].toASCIIString();
- assertTrue("Error: For URI \"" + uris[i].toString()
- + "\", toASCIIString() returned: " + result
- + ", expected: " + toASCIIStringResults0[i], result
- .equals(toASCIIStringResults0[i]));
- }
-
- String[] toASCIIStringData = new String[] {
- "http://www.test.com/\u00DF/dir/",
- "http://www.test.com/\u20AC/dir", "http://www.\u20AC.com/dir",
- "http://www.test.com/\u20AC/dir/file#fragment",
- "mailto://user@domain.com", "mailto://user\u00DF@domain.com", };
-
- String[] toASCIIStringResults = new String[] {
- "http://www.test.com/%C3%9F/dir/",
- "http://www.test.com/%E2%82%AC/dir",
- "http://www.%E2%82%AC.com/dir",
- "http://www.test.com/%E2%82%AC/dir/file#fragment",
- "mailto://user@domain.com", "mailto://user%C3%9F@domain.com", };
-
- for (int i = 0; i < toASCIIStringData.length; i++) {
- URI test = new URI(toASCIIStringData[i]);
- String result = test.toASCIIString();
- assertTrue("Error: new URI(\"" + toASCIIStringData[i]
- + "\").toASCIIString() returned: " + result
- + ", expected: " + toASCIIStringResults[i], result
- .equals(toASCIIStringResults[i]));
- }
- }
-
- /**
- * @tests java.net.URI#toString()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toString",
- args = {}
- )
- public void test_toString() throws Exception {
- URI[] uris = getUris();
-
- String[] toStringResults = {
- "http://user%60%20info@host/a%20path?qu%60%20ery#fr%5E%20ag",
- "http://user%C3%9F%C2%A3info@host:80/a%E2%82%ACpath?qu%C2%A9%C2%AEery#fr%C3%A4%C3%A8g",
- "ascheme://user\u00DF\u00A3info@host:0/a\u20ACpath?qu\u00A9\u00AEery#fr\u00E4\u00E8g",
- // =
- // "ascheme://user\u00df\u00a3info@host:0/a\u0080path?qu\u00a9\u00aeery#fr\u00e4\u00e8g",
- "http://user%2560%2520info@host:80/a%2520path?qu%2560%2520ery#fr%255E%2520ag",
- "http://user%25C3%259F%25C2%25A3info@host/a%25E2%2582%25ACpath?qu%25C2%25A9%25C2%25AEery#fr%25C3%25A4%25C3%25A8g",
- "ascheme://user\u00DF\u00A3info@host:80/a\u20ACpath?qu\u00A9\u00AEery#fr\u00E4\u00E8g",
- // =
- // "ascheme://user\u00df\u00a3info@host:80/a\u0080path?qu\u00a9\u00aeery#fr\u00e4\u00e8g",
- "http://user%60%20info@host:81/a%20path?qu%60%20ery#fr%5E%20ag",
- "http://user%25info@host:0/a%25path?que%25ry#f%25rag",
- "mailto:user@domain.com", "../adirectory/file.html#",
- "news:comp.infosystems.www.servers.unix", "#fragment",
- "telnet://server.org", "http://reg:istry?query",
- "file:///c:/temp/calculate.pl?" };
-
- for (int i = 0; i < uris.length; i++) {
- String result = uris[i].toString();
- assertTrue("Error: For URI \"" + uris[i].toString()
- + "\", toString() returned: " + result + ", expected: "
- + toStringResults[i], result.equals(toStringResults[i]));
- }
- }
-
- /**
- * @tests java.net.URI#toURL()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "toURL",
- args = {}
- )
- public void test_toURL() throws Exception {
- String absoluteuris[] = new String[] { "mailto:user@ca.ibm.com",
- "urn:isbn:123498989h", "news:software.ibm.com",
- "http://www.amazon.ca", "file:///d:/temp/results.txt",
- "scheme:ssp", };
-
- String relativeuris[] = new String[] { "calculate.pl?isbn=123498989h",
- "?isbn=123498989h", "//www.amazon.ca", "a.html", "#top",
- "//pc1/", "//user@host/path/file" };
-
- for (int i = 0; i < absoluteuris.length; i++) {
- try {
- new URI(absoluteuris[i]).toURL();
- } catch (MalformedURLException e) {
- // not all the URIs can be translated into valid URLs
- }
- }
-
- for (int i = 0; i < relativeuris.length; i++) {
- try {
- new URI(relativeuris[i]).toURL();
- fail("Expected IllegalArgumentException not thrown");
- } catch (IllegalArgumentException e) {
- // Expected
- }
- }
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/UnknownHostExceptionTest.java b/luni/src/test/java/tests/api/java/net/UnknownHostExceptionTest.java
deleted file mode 100644
index ee56050..0000000
--- a/luni/src/test/java/tests/api/java/net/UnknownHostExceptionTest.java
+++ /dev/null
@@ -1,87 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-@TestTargetClass(java.net.UnknownHostException.class)
-public class UnknownHostExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.UnknownHostException#UnknownHostException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnknownHostException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.net.UnknownHostException()
- try {
- try {
- java.net.InetAddress.getByName("a.b.c.x.y.z.com");
- } catch (java.net.UnknownHostException e) {
- return;
- }
- fail("Failed to generate Exception");
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * @tests java.net.UnknownHostException#UnknownHostException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnknownHostException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.UnknownHostException(java.lang.String)
- try {
- try {
- java.net.InetAddress.getByName("a.b.c.x.y.z.com");
- } catch (java.net.UnknownHostException e) {
- return;
- }
- fail("Failed to generate Exception");
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/api/java/net/UnknownServiceExceptionTest.java b/luni/src/test/java/tests/api/java/net/UnknownServiceExceptionTest.java
deleted file mode 100644
index 139e508..0000000
--- a/luni/src/test/java/tests/api/java/net/UnknownServiceExceptionTest.java
+++ /dev/null
@@ -1,88 +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.TestTargetClass;
-import dalvik.annotation.TestTargets;
-import dalvik.annotation.TestLevel;
-import dalvik.annotation.TestTargetNew;
-
-import java.net.URL;
-import java.net.UnknownServiceException;
-
-@TestTargetClass(UnknownServiceException.class)
-public class UnknownServiceExceptionTest extends junit.framework.TestCase {
-
- /**
- * @tests java.net.UnknownServiceException#UnknownServiceException()
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnknownServiceException",
- args = {}
- )
- public void test_Constructor() {
- // Test for method java.net.UnknownServiceException()
- try {
- new URL("file:///moo.txt").openConnection().getOutputStream();
- } catch (UnknownServiceException e) {
- // correct
- return;
- } catch (Exception e) {
- fail("Wrong exception during test : " + e.getMessage());
- }
- fail("Exception not thrown");
- }
-
- /**
- * @tests java.net.UnknownServiceException#UnknownServiceException(java.lang.String)
- */
- @TestTargetNew(
- level = TestLevel.COMPLETE,
- notes = "",
- method = "UnknownServiceException",
- args = {java.lang.String.class}
- )
- public void test_ConstructorLjava_lang_String() {
- // Test for method java.net.UnknownServiceException(java.lang.String)
- try {
- if (true)
- throw new UnknownServiceException("HelloWorld");
- } catch (UnknownServiceException e) {
- assertTrue("Wrong exception message: " + e.toString(), e
- .getMessage().equals("HelloWorld"));
- return;
- }
- fail("Constructor failed");
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- }
-}
diff --git a/luni/src/test/java/tests/luni/AllTestsNet.java b/luni/src/test/java/tests/luni/AllTestsNet.java
index dcfef9e..a71b976 100644
--- a/luni/src/test/java/tests/luni/AllTestsNet.java
+++ b/luni/src/test/java/tests/luni/AllTestsNet.java
@@ -34,9 +34,6 @@ public class AllTestsNet
TestSuite suite = new TestSuite("Tests for java.net");
suite.addTest(org.apache.harmony.luni.tests.java.net.AllTests.suite());
-
- suite.addTest(tests.api.java.net.AllTests.suite());
-
suite.addTest(org.apache.harmony.luni.tests.internal.net.www.protocol.http.AllTests.suite());
suite.addTest(org.apache.harmony.luni.tests.internal.net.www.protocol.https.AllTests.suite());