summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--expectations/brokentests.txt4
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/AuthenticatorTest.java206
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ConnectExceptionTest.java4
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramSocketTest.java1524
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/net/MulticastSocketTest.java297
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ChannelsTest.java10
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/DatagramChannelTest.java667
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectionKeyTest.java7
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ServerSocketChannelTest.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SocketChannelTest.java48
-rw-r--r--luni/src/test/java/libcore/java/net/OldDatagramSocketTest.java2183
-rw-r--r--support/src/test/java/tests/support/Support_PortManager.java105
12 files changed, 865 insertions, 4245 deletions
diff --git a/expectations/brokentests.txt b/expectations/brokentests.txt
index 68331cd..93c9a5c 100644
--- a/expectations/brokentests.txt
+++ b/expectations/brokentests.txt
@@ -863,9 +863,7 @@
"org.apache.harmony.tests.java.net.Inet6AddressTest#test_getByNameLjava_lang_String",
"org.apache.harmony.tests.java.net.InetAddressTest#test_equalsLjava_lang_Object",
"org.apache.harmony.tests.java.net.InetAddressTest#test_getByNameLjava_lang_String",
- "org.apache.harmony.tests.java.net.InetAddressTest#test_isReachableLjava_net_NetworkInterfaceII_loopbackInterface",
- "org.apache.harmony.tests.java.net.MulticastSocketTest#test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface",
- "org.apache.harmony.tests.java.net.MulticastSocketTest#test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface_IPv4"
+ "org.apache.harmony.tests.java.net.InetAddressTest#test_isReachableLjava_net_NetworkInterfaceII_loopbackInterface"
]
},
{
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/AuthenticatorTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/AuthenticatorTest.java
deleted file mode 100644
index a0bd40f..0000000
--- a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/AuthenticatorTest.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/* Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.tests.java.net;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.Authenticator;
-import java.net.InetAddress;
-import java.net.MalformedURLException;
-import java.net.PasswordAuthentication;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.URL;
-import java.net.UnknownHostException;
-import java.net.Authenticator.RequestorType;
-
-import junit.framework.TestCase;
-import tests.support.Support_PortManager;
-
-public class AuthenticatorTest extends TestCase {
-
- /**
- * java.net.Authenticator.RequestorType#valueOf(String)
- */
- 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
- }
- }
-
- /**
- * java.net.Authenticator.RequestorType#values()
- */
- public void test_RequestorType_values() throws Exception {
- RequestorType[] rt = RequestorType.values();
- assertEquals(RequestorType.PROXY, rt[0]);
- assertEquals(RequestorType.SERVER, rt[1]);
- }
-
- /**
- * java.net.Authenticator#requestPasswordAuthentication(java.net.InetAddress, int, String, String, String)
- */
- 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);
- }
-
- /**
- * java.net.Authenticator#requestPasswordAuthentication(String, java.net.InetAddress, int, String, String, String)
- */
- 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);
- }
-
- /**
- * java.net.Authenticator#
- * requestPasswordAuthentication_String_InetAddress_int_String_String_String_URL_Authenticator_RequestorType()
- */
- 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());
- }
-
- /**
- * java.net.Authenticator#getRequestingURL()
- */
- public void test_getRequestingURL() throws Exception {
- MockAuthenticator mock = new MockAuthenticator();
- assertNull(mock.getRequestingURL());
- }
-
- /**
- * java.net.Authenticator#getRequestorType()
- */
- public void test_getRequestorType() throws Exception {
- MockAuthenticator mock = new MockAuthenticator();
- assertNull(mock.getRequestorType());
- }
-
- /**
- * java.net.Authenticator#setDefault(java.net.Authenticator)
- */
- public void test_setDefault() {
- final int port = Support_PortManager.getNextPort();
- final Object lock = new Object();
- final int[] result = new int[1];
- Thread t = new Thread(new Runnable() {
- public void run() {
- try {
- ServerSocket ss = null;
- synchronized (lock) {
- ss = new ServerSocket(port);
- lock.notifyAll();
- }
- Socket s = ss.accept();
- InputStream in = s.getInputStream();
- in.read(new byte[1024]);
- OutputStream out = s.getOutputStream();
- out
- .write("HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate:Basic realm=\"something\"\r\n\r\n"
- .getBytes("ISO8859_1"));
- Thread.sleep(500);
- out.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- synchronized (lock) {
- t.start();
- try {
- lock.wait();
- } catch (InterruptedException e) {
- // ignored
- }
- }
- Authenticator.setDefault(new Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- synchronized (lock) {
- result[0] = 1;
- }
- return null;
- }
- });
- Authenticator.setDefault(new Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- synchronized (lock) {
- result[0] = 2;
- }
- return null;
- }
- });
- try {
- new URL("http://localhost:" + port).openStream();
- } catch (IOException e) {
- // ignored
- }
- synchronized (lock) {
- assertEquals("wrong authenticator: " + result[0], 2, result[0]);
- }
- }
-
- /*
- * 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();
- }
- }
-}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ConnectExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ConnectExceptionTest.java
index 3c69890..d0290ec 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ConnectExceptionTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/ConnectExceptionTest.java
@@ -18,10 +18,6 @@
package org.apache.harmony.tests.java.net;
import java.net.ConnectException;
-import java.net.InetAddress;
-import java.net.Socket;
-
-import tests.support.Support_PortManager;
public class ConnectExceptionTest extends junit.framework.TestCase {
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramSocketTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramSocketTest.java
index 776b484..e585b14 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramSocketTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/DatagramSocketTest.java
@@ -23,76 +23,64 @@ import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.DatagramSocketImpl;
-import java.net.DatagramSocketImplFactory;
-import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
-import java.net.PortUnreachableException;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
-import java.util.Date;
-
-import tests.support.Support_Configuration;
-import tests.support.Support_PortManager;
+import java.nio.channels.DatagramChannel;
public class DatagramSocketTest extends junit.framework.TestCase {
- java.net.DatagramSocket ds;
-
- java.net.DatagramPacket dp;
-
- DatagramSocket sds = null;
-
- String retval;
-
- String testString = "Test String";
-
- boolean interrupted;
+ static final class DatagramServer extends Thread {
- class DatagramServer extends Thread {
+ volatile boolean running = true;
- public DatagramSocket ms;
+ private final boolean echo;
+ private final byte[] rbuf;
+ private final DatagramPacket rdp;
+ final DatagramSocket serverSocket;
- boolean running = true;
-
- public volatile byte[] rbuf = new byte[512];
+ public DatagramServer(InetAddress address, boolean echo)
+ throws IOException {
+ this.echo = echo;
+ rbuf = new byte[512];
+ rbuf[0] = -1;
+ rdp = new DatagramPacket(rbuf, rbuf.length);
+ serverSocket = new DatagramSocket(0, address);
+ serverSocket.setSoTimeout(2000);
+ }
- volatile DatagramPacket rdp = null;
+ public DatagramServer(InetAddress address) throws IOException {
+ this(address, true /* echo */);
+ }
public void run() {
try {
while (running) {
try {
- ms.receive(rdp);
- // echo the packet back
- ms.send(rdp);
- } catch (java.io.InterruptedIOException e) {
- Thread.yield();
+ serverSocket.receive(rdp);
+ if (echo) {
+ serverSocket.send(rdp);
+ }
+ } catch (InterruptedIOException e) {
}
- ;
}
- ;
- } catch (java.io.IOException e) {
- System.out.println("DatagramServer server failed: " + e);
+ } catch (IOException e) {
+ fail();
} finally {
- ms.close();
+ serverSocket.close();
}
}
- public void stopServer() {
- running = false;
+ public int getPort() {
+ return serverSocket.getLocalPort();
}
- public DatagramServer(int aPort, InetAddress address)
- throws IOException {
- rbuf = new byte[512];
- rbuf[0] = -1;
- rdp = new DatagramPacket(rbuf, rbuf.length);
- ms = new DatagramSocket(aPort, address);
- ms.setSoTimeout(2000);
+ public void stopServer() {
+ running = false;
}
}
@@ -147,289 +135,185 @@ public class DatagramSocketTest extends junit.framework.TestCase {
ds = new java.net.DatagramSocket();
inetAddress = InetAddress.getByName("FE80:0000:0000:0000:020D:60FF:FE0F:A776%4");
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- assertTrue("Incorrect InetAddress", ds.getInetAddress().equals(inetAddress));
- assertTrue("Incorrect Port", ds.getPort() == portNumber);
+ ds.connect(inetAddress, 0);
+ assertEquals(inetAddress, ds.getInetAddress());
ds.disconnect();
+ }
+ public void testConnect_connectToSelf() throws Exception {
// Create a connected datagram socket to test
// PlainDatagramSocketImpl.peek()
InetAddress localHost = InetAddress.getLocalHost();
- ds = new DatagramSocket();
- int port = ds.getLocalPort();
- ds.connect(localHost, port);
+ final DatagramSocket ds = new DatagramSocket(0);
+ ds.connect(localHost, ds.getLocalPort());
DatagramPacket send = new DatagramPacket(new byte[10], 10, localHost,
- port);
+ ds.getLocalPort());
ds.send(send);
+
DatagramPacket receive = new DatagramPacket(new byte[20], 20);
ds.setSoTimeout(2000);
ds.receive(receive);
ds.close();
- assertTrue("Wrong size: " + receive.getLength(),
- receive.getLength() == 10);
- assertTrue("Wrong receiver", receive.getAddress().equals(localHost));
-
- class DatagramServer extends Thread {
-
- public DatagramSocket ms;
- boolean running = true;
-
- public byte[] rbuf = new byte[512];
-
- DatagramPacket rdp = null;
-
- public void run() {
- try {
- while (running) {
- try {
- ms.receive(rdp);
- // echo the packet back
- ms.send(rdp);
- } catch (java.io.InterruptedIOException e) {
- Thread.yield();
- }
- ;
- }
- ;
- } catch (java.io.IOException e) {
- System.out.println("Multicast server failed: " + e);
- } finally {
- ms.close();
- }
- }
+ assertEquals(10, receive.getLength());
+ assertEquals(localHost, receive.getAddress());
+ }
- public void stopServer() {
- running = false;
- }
+ private static void assertPacketDataEquals(DatagramPacket p1, DatagramPacket p2)
+ throws Exception {
+ assertEquals(p1.getLength(), p2.getLength());
+ final byte[] p1Bytes = p1.getData();
+ final byte[] p2Bytes = p2.getData();
- public DatagramServer(int aPort, InetAddress address)
- throws java.io.IOException {
- rbuf = new byte[512];
- rbuf[0] = -1;
- rdp = new DatagramPacket(rbuf, rbuf.length);
- ms = new DatagramSocket(aPort, address);
- ms.setSoTimeout(2000);
+ for (int i = 0; i < p1.getLength(); ++i) {
+ if (p1Bytes[p1.getOffset() + i] != p2Bytes[p2.getOffset() + i]) {
+ String expected = new String(p1Bytes, p1.getOffset(), p1.getLength(),
+ "UTF-8");
+ String actual = new String(p2Bytes, p2.getOffset(), p2.getLength(),
+ "UTF-8");
+ fail("expected: " + expected + ", actual: " + actual);
}
}
+ }
- // validate that we get the PortUnreachable exception if we try to
- // send a dgram to a server that is not running and then do a recv
- try {
- ds = new java.net.DatagramSocket();
- inetAddress = InetAddress.getLocalHost();
- portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- send = new DatagramPacket(new byte[10], 10);
- ds.send(send);
- receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(10000);
- ds.receive(receive);
- ds.close();
- fail("No PortUnreachableException when connected at native level on recv ");
- } catch (PortUnreachableException e) {
- // Expected
- }
-
- // validate that we can send/receive with datagram sockets connected at
- // the native level
- DatagramServer server = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int serverPortNumber = ports[0];
-
- localHost = InetAddress.getLocalHost();
- ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
+ public void testConnect_echoServer() throws Exception {
+ final DatagramSocket ds = new DatagramSocket(0);
- server = new DatagramServer(serverPortNumber, localHost);
+ final DatagramServer server = new DatagramServer(Inet6Address.LOOPBACK);
server.start();
- Thread.sleep(1000);
- port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber);
+ ds.connect(Inet6Address.LOOPBACK, server.getPort());
final byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- send = new DatagramPacket(sendBytes, sendBytes.length);
+ final DatagramPacket send = new DatagramPacket(sendBytes, sendBytes.length);
+ final DatagramPacket receive = new DatagramPacket(new byte[20], 20);
+
ds.send(send);
- receive = new DatagramPacket(new byte[20], 20);
ds.setSoTimeout(2000);
ds.receive(receive);
ds.close();
- assertTrue("Wrong size data received: " + receive.getLength(), receive
- .getLength() == sendBytes.length);
- assertTrue("Wrong data received"
- + new String(receive.getData(), 0, receive.getLength()) + ":"
- + new String(sendBytes), new String(receive.getData(), 0,
- receive.getLength()).equals(new String(sendBytes)));
- assertTrue("Wrong receiver:" + receive.getAddress() + ":" + localHost,
- receive.getAddress().equals(localHost));
-
- if (server != null) {
- server.stopServer();
- }
- // validate that we can disconnect
- try {
- ds = new java.net.DatagramSocket();
- inetAddress = InetAddress.getLocalHost();
- portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- ds.disconnect();
- ds.close();
- } catch (PortUnreachableException e) {
- // Expected
- }
+ assertEquals(sendBytes.length, receive.getLength());
+ assertPacketDataEquals(send, receive);
+ assertEquals(Inet6Address.LOOPBACK, receive.getAddress());
+
+ server.stopServer();
+ }
+
+ // Validate that once connected we cannot send to another address.
+ public void testConnect_throwsOnAddressMismatch() throws Exception {
+ final DatagramSocket ds = new DatagramSocket(0);
- // validate that once connected we cannot send to another address
+ DatagramServer s1 = new DatagramServer(Inet6Address.LOOPBACK);
+ DatagramServer s2 = new DatagramServer(Inet6Address.LOOPBACK);
try {
- ds = new java.net.DatagramSocket();
- inetAddress = InetAddress.getLocalHost();
- portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- send = new DatagramPacket(new byte[10], 10, inetAddress,
- portNumber + 1);
- ds.send(send);
+ ds.connect(Inet6Address.LOOPBACK, s1.getPort());
+ ds.send(new DatagramPacket(new byte[10], 10, Inet6Address.LOOPBACK, s2.getPort()));
+ fail();
+ } catch (IllegalArgumentException expected) {
+ } finally {
ds.close();
- fail("No Exception when trying to send to a different address on a connected socket ");
- } catch (IllegalArgumentException e) {
- // Expected
+ s1.stopServer();
+ s2.stopServer();
}
+ }
- // validate that we can connect, then disconnect, then connect then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
-
- localHost = InetAddress.getLocalHost();
- ds = new DatagramSocket(ports[1]);
- ds2 = new DatagramSocket(ports[2]);
+ // Validate that we can connect, then disconnect, then connect then
+ // send/recv.
+ public void testConnect_connectDisconnectConnectThenSendRecv() throws Exception {
+ final DatagramSocket ds = new DatagramSocket(0);
- server = new DatagramServer(serverPortNumber, localHost);
+ final DatagramServer server = new DatagramServer(Inet6Address.LOOPBACK);
+ final DatagramServer broken = new DatagramServer(Inet6Address.LOOPBACK, false);
server.start();
- Thread.sleep(1000);
+ broken.start();
- port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber + 1);
+ final int serverPortNumber = server.getPort();
+ ds.connect(Inet6Address.LOOPBACK, broken.getPort());
ds.disconnect();
- ds.connect(localHost, serverPortNumber);
+ ds.connect(Inet6Address.LOOPBACK, serverPortNumber);
- send = new DatagramPacket(sendBytes, sendBytes.length);
+ final byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
+ final DatagramPacket send = new DatagramPacket(sendBytes, sendBytes.length);
+ final DatagramPacket receive = new DatagramPacket(new byte[20], 20);
ds.send(send);
- receive = new DatagramPacket(new byte[20], 20);
ds.setSoTimeout(2000);
ds.receive(receive);
ds.close();
- assertTrue("connect/disconnect/connect - Wrong size data received: "
- + receive.getLength(), receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength()) + ":"
- + new String(sendBytes), new String(receive.getData(), 0,
- receive.getLength()).equals(new String(sendBytes)));
- assertTrue("connect/disconnect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive.getAddress()
- .equals(localHost));
-
- if (server != null) {
- server.stopServer();
- }
- // validate that we can connect/disconnect then send/recv to any address
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
+ assertPacketDataEquals(send, receive);
+ assertEquals(Inet6Address.LOOPBACK, receive.getAddress());
- localHost = InetAddress.getLocalHost();
- ds = new DatagramSocket(ports[1]);
- ds2 = new DatagramSocket(ports[2]);
+ server.stopServer();
+ broken.stopServer();
+ }
+
+ // Validate that we can connect/disconnect then send/recv to any address
+ public void testConnect_connectDisconnectThenSendRecv() throws Exception {
+ final DatagramSocket ds = new DatagramSocket(0);
- server = new DatagramServer(serverPortNumber, localHost);
+ final DatagramServer server = new DatagramServer(Inet6Address.LOOPBACK);
server.start();
- Thread.sleep(1000);
- port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber + 1);
+ final int serverPortNumber = server.getPort();
+ ds.connect(Inet6Address.LOOPBACK, serverPortNumber);
ds.disconnect();
- send = new DatagramPacket(sendBytes, sendBytes.length, localHost,
- serverPortNumber);
+ final byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
+ final DatagramPacket send = new DatagramPacket(sendBytes, sendBytes.length,
+ Inet6Address.LOOPBACK, serverPortNumber);
+ final DatagramPacket receive = new DatagramPacket(new byte[20], 20);
ds.send(send);
- receive = new DatagramPacket(new byte[20], 20);
ds.setSoTimeout(2000);
ds.receive(receive);
ds.close();
- assertTrue("connect/disconnect - Wrong size data received: "
- + receive.getLength(), receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength()) + ":"
- + new String(sendBytes), new String(receive.getData(), 0,
- receive.getLength()).equals(new String(sendBytes)));
- assertTrue("connect/disconnect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive.getAddress()
- .equals(localHost));
-
- if (server != null) {
- server.stopServer();
- }
- // validate that we can connect on an allready connected socket and then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
+ assertPacketDataEquals(send, receive);
+ assertEquals(Inet6Address.LOOPBACK, receive.getAddress());
+
+ server.stopServer();
+ }
- localHost = InetAddress.getLocalHost();
- ds = new DatagramSocket(ports[1]);
- ds2 = new DatagramSocket(ports[2]);
+ public void testConnect_connectTwice() throws Exception {
+ final DatagramSocket ds = new DatagramSocket(0);
- server = new DatagramServer(serverPortNumber, localHost);
+ final DatagramServer server = new DatagramServer(Inet6Address.LOOPBACK);
+ final DatagramServer broken = new DatagramServer(Inet6Address.LOOPBACK);
server.start();
- Thread.sleep(1000);
+ broken.start();
- port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber + 1);
- ds.connect(localHost, serverPortNumber);
+ final int serverPortNumber = server.getPort();
+ ds.connect(Inet6Address.LOOPBACK, broken.getPort());
+ ds.connect(Inet6Address.LOOPBACK, serverPortNumber);
+ ds.disconnect();
- send = new DatagramPacket(sendBytes, sendBytes.length);
+ final byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
+ final DatagramPacket send = new DatagramPacket(sendBytes, sendBytes.length,
+ Inet6Address.LOOPBACK, serverPortNumber);
+ final DatagramPacket receive = new DatagramPacket(new byte[20], 20);
ds.send(send);
- receive = new DatagramPacket(new byte[20], 20);
ds.setSoTimeout(2000);
ds.receive(receive);
ds.close();
- assertTrue("connect/connect - Wrong size data received: "
- + receive.getLength(), receive.getLength() == sendBytes.length);
- assertTrue("connect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength()) + ":"
- + new String(sendBytes), new String(receive.getData(), 0,
- receive.getLength()).equals(new String(sendBytes)));
- assertTrue("connect/connect - Wrong receiver:" + receive.getAddress()
- + ":" + localHost, receive.getAddress().equals(localHost));
-
- if (server != null) {
- server.stopServer();
- }
- // test for when we fail to connect at the native level. Even though we
- // fail at the native level there is no way to return an exception so
- // there should be no exception
- ds = new java.net.DatagramSocket();
+ assertPacketDataEquals(send, receive);
+ assertEquals(Inet6Address.LOOPBACK, receive.getAddress());
+
+ server.stopServer();
+ broken.stopServer();
+ }
+
+ public void testConnect_zeroAddress() throws Exception {
+ DatagramSocket ds = new DatagramSocket();
byte[] addressBytes = { 0, 0, 0, 0 };
- inetAddress = InetAddress.getByAddress(addressBytes);
- portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
-
- if ("true".equals(System.getProperty("run.ipv6tests"))) {
- System.out
- .println("Running test_connectLjava_net_InetAddressI(DatagramSocketTest) with IPv6 address");
-
- ds = new java.net.DatagramSocket();
- byte[] addressTestBytes = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0 };
- inetAddress = InetAddress.getByAddress(addressTestBytes);
- portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- }
+ InetAddress inetAddress = InetAddress.getByAddress(addressBytes);
+ ds.connect(inetAddress, 0);
+
+ ds = new java.net.DatagramSocket();
+ byte[] addressTestBytes = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0 };
+ inetAddress = InetAddress.getByAddress(addressTestBytes);
+ ds.connect(inetAddress, 0);
}
public void test_disconnect() throws Exception {
@@ -448,19 +332,11 @@ public class DatagramSocketTest extends junit.framework.TestCase {
assertEquals("Incorrect Port", -1, ds.getPort());
}
- /**
- * java.net.DatagramSocket#getInetAddress()
- */
- public void test_getInetAddress() {
- assertTrue("Used to test", true);
- }
-
public void test_getLocalAddress() throws Exception {
// Test for method java.net.InetAddress
// java.net.DatagramSocket.getLocalAddress()
- int portNumber = Support_PortManager.getNextPortForUDP();
InetAddress local = InetAddress.getLocalHost();
- ds = new java.net.DatagramSocket(portNumber, local);
+ DatagramSocket ds = new java.net.DatagramSocket(0, local);
assertEquals(InetAddress.getByName(InetAddress.getLocalHost().getHostName()), ds.getLocalAddress());
// now check behavior when the ANY address is returned
@@ -469,17 +345,11 @@ public class DatagramSocketTest extends junit.framework.TestCase {
s.close();
}
- /**
- * java.net.DatagramSocket#getLocalPort()
- */
public void test_getLocalPort() throws SocketException {
DatagramSocket ds = new DatagramSocket();
assertTrue("Returned incorrect port", ds.getLocalPort() != 0);
}
- /**
- * java.net.DatagramSocket#getPort()
- */
public void test_getPort() throws IOException {
DatagramSocket theSocket = new DatagramSocket();
assertEquals("Expected -1 for remote port as not connected", -1,
@@ -496,13 +366,26 @@ public class DatagramSocketTest extends junit.framework.TestCase {
DatagramSocket ds = new DatagramSocket();
ds.setReceiveBufferSize(130);
assertTrue("Incorrect buffer size", ds.getReceiveBufferSize() >= 130);
+ ds.close();
+ try {
+ ds.getReceiveBufferSize();
+ fail("SocketException was not thrown.");
+ } catch(SocketException se) {
+ //expected
+ }
}
public void test_getSendBufferSize() throws Exception {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
+ final DatagramSocket ds = new java.net.DatagramSocket(0);
ds.setSendBufferSize(134);
assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134);
+ ds.close();
+ try {
+ ds.getSendBufferSize();
+ fail("SocketException was not thrown.");
+ } catch(SocketException se) {
+ //expected
+ }
}
public void test_getSoTimeout() throws Exception {
@@ -511,343 +394,109 @@ public class DatagramSocketTest extends junit.framework.TestCase {
assertEquals("Returned incorrect timeout", 100, ds.getSoTimeout());
}
- public void test_receiveLjava_net_DatagramPacket() throws IOException {
- // Test for method void
- // java.net.DatagramSocket.receive(java.net.DatagramPacket)
-
- receive_oversize_java_net_DatagramPacket();
- final int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int portNumber = ports[0];
-
- class TestDGRcv implements Runnable {
- public void run() {
- InetAddress localHost = null;
- try {
- localHost = InetAddress.getLocalHost();
- Thread.sleep(1000);
- DatagramSocket sds = new DatagramSocket(ports[1]);
- DatagramPacket rdp = new DatagramPacket("Test String"
- .getBytes(), 11, localHost, portNumber);
- sds.send(rdp);
- sds.close();
- } catch (Exception e) {
- System.err.println("host " + localHost + " port "
- + portNumber + " failed to send data: " + e);
- e.printStackTrace();
- }
- }
- }
-
- try {
- new Thread(new TestDGRcv(), "DGSender").start();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSoTimeout(6000);
- byte rbuf[] = new byte[1000];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
+ static final class TestDatagramSocketImpl extends DatagramSocketImpl {
+ // This field exists solely to force initialization of this class
+ // inside a test method.
+ public static final Object ACCESS = new Object();
- ds.receive(rdp);
- ds.close();
- assertTrue("Send/Receive failed to return correct data: "
- + new String(rbuf, 0, 11), new String(rbuf, 0, 11)
- .equals("Test String"));
- } finally {
- ds.close();
+ @Override
+ protected void create() throws SocketException {
}
- try {
- interrupted = false;
- final DatagramSocket ds = new DatagramSocket();
- ds.setSoTimeout(12000);
- Runnable runnable = new Runnable() {
- public void run() {
- try {
- ds.receive(new DatagramPacket(new byte[1], 1));
- } catch (InterruptedIOException e) {
- interrupted = true;
- } catch (IOException e) {
- }
- }
- };
- Thread thread = new Thread(runnable, "DatagramSocket.receive1");
- thread.start();
- try {
- do {
- Thread.sleep(500);
- } while (!thread.isAlive());
- } catch (InterruptedException e) {
- }
- ds.close();
- int c = 0;
- do {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- }
- if (interrupted) {
- fail("received interrupt");
- }
- if (++c > 4) {
- fail("read call did not exit");
- }
- } while (thread.isAlive());
-
- interrupted = false;
- int[] ports1 = Support_PortManager.getNextPortsForUDP(2);
- final int portNum = ports[0];
- final DatagramSocket ds2 = new DatagramSocket(ports[1]);
- ds2.setSoTimeout(12000);
- Runnable runnable2 = new Runnable() {
- public void run() {
- try {
- ds2.receive(new DatagramPacket(new byte[1], 1,
- InetAddress.getLocalHost(), portNum));
- } catch (InterruptedIOException e) {
- interrupted = true;
- } catch (IOException e) {
- }
- }
- };
- Thread thread2 = new Thread(runnable2, "DatagramSocket.receive2");
- thread2.start();
- try {
- do {
- Thread.sleep(500);
- } while (!thread2.isAlive());
- } catch (InterruptedException e) {
- }
- ds2.close();
- int c2 = 0;
- do {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- }
- if (interrupted) {
- fail("receive2 was interrupted");
- }
- if (++c2 > 4) {
- fail("read2 call did not exit");
- }
- } while (thread2.isAlive());
-
- interrupted = false;
- DatagramSocket ds3 = new DatagramSocket();
- ds3.setSoTimeout(500);
- Date start = new Date();
- try {
- ds3.receive(new DatagramPacket(new byte[1], 1));
- } catch (InterruptedIOException e) {
- interrupted = true;
- }
- ds3.close();
- assertTrue("receive not interrupted", interrupted);
- int delay = (int) (new Date().getTime() - start.getTime());
- assertTrue("timeout too soon: " + delay, delay >= 490);
- } catch (IOException e) {
- fail("Unexpected IOException : " + e.getMessage());
+ @Override
+ protected void bind(int arg0, InetAddress arg1)
+ throws SocketException {
}
- }
-
- /**
- * Tests receive() method in various combinations with
- * DatagramPacket#getLength() and DatagramPacket#getLength(). This is
- * regression test for HARMONY-2276.
- *
- * @throws IOException
- * if some I/O error occured
- */
- // public void test2276() throws IOException {
- // final String ADDRESS = "239.255.2.3";
- // final int PORT = Support_PortManager.getNextPortForUDP();
- // InetAddress group = InetAddress.getByName(ADDRESS);
- // MulticastSocket socket = new MulticastSocket(PORT);
- // byte[] recvData = new byte[100];
- // DatagramPacket recvDatagram = new DatagramPacket(recvData,
- // recvData.length);
- //
- // String message = "Hello, world!";
- // String longerMessage = message + " again.";
- // String veryLongMessage = longerMessage + " Forever!";
- //
- // socket.joinGroup(group);
- // socket.setSoTimeout(5000); // prevent eternal block in
- // // socket.receive()
- // // send & recieve packet
- // byte[] sendData = message.getBytes();
- // DatagramPacket sendDatagram = new DatagramPacket(sendData, 0,
- // sendData.length, group, PORT);
- // socket.send(sendDatagram);
- // socket.receive(recvDatagram);
- // String recvMessage = new String(recvData, 0, recvDatagram.getLength());
- // assertEquals(message, recvMessage);
- //
- // // send & receive longer packet
- // sendData = longerMessage.getBytes();
- // sendDatagram = new DatagramPacket(sendData, 0, sendData.length,
- // group, PORT);
- // socket.send(sendDatagram);
- // socket.receive(recvDatagram);
- // recvMessage = new String(recvData, 0, recvDatagram.getLength());
- // assertEquals(longerMessage, recvMessage);
- //
- // // tricky case, added to test compatibility with RI;
- // // depends on the previous test case
- // sendData = veryLongMessage.getBytes();
- // sendDatagram = new DatagramPacket(sendData, 0, sendData.length, group,
- // PORT);
- // socket.send(sendDatagram);
- // recvDatagram.setLength(recvDatagram.getLength()); // !!!
- // socket.receive(recvDatagram);
- // recvMessage = new String(recvData, 0, recvDatagram.getLength());
- // assertEquals(longerMessage, recvMessage);
- //
- // // tests if received packet is truncated after length was set to 1
- // sendData = message.getBytes();
- // sendDatagram = new DatagramPacket(sendData, 0, sendData.length,
- // group, PORT);
- // socket.send(sendDatagram);
- // recvDatagram.setLength(1);
- // socket.receive(recvDatagram);
- // assertEquals("Received message was not truncated", 1,
- // recvDatagram.getLength());
- // assertSame("Received message is invalid", sendData[0], recvData[0]);
- //
- // socket.leaveGroup(group);
- // socket.close();
- // }
-
- /**
- * java.net.DatagramSocket#send(java.net.DatagramPacket)
- */
- public void test_sendLjava_net_DatagramPacket() throws Exception {
- // Test for method void
- // java.net.DatagramSocket.send(java.net.DatagramPacket)
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int portNumber = ports[0];
-
- class TestDGSend implements Runnable {
- Thread pThread;
-
- public TestDGSend(Thread t) {
- pThread = t;
- }
+ @Override
+ protected void send(DatagramPacket arg0) throws IOException {
+ }
- public void run() {
- try {
- byte[] rbuf = new byte[1000];
-
- sds = new DatagramSocket(portNumber);
- DatagramPacket sdp = new DatagramPacket(rbuf, rbuf.length);
- sds.setSoTimeout(6000);
- sds.receive(sdp);
- retval = new String(rbuf, 0, testString.length());
- pThread.interrupt();
- } catch (java.io.InterruptedIOException e) {
- System.out.println("Recv operation timed out");
- pThread.interrupt();
- ds.close();
- return;
- } catch (Exception e) {
- System.out
- .println("Failed to establish Dgram server: " + e);
- }
- }
+ @Override
+ protected int peek(InetAddress arg0) throws IOException {
+ return 0;
}
- try {
- new Thread(new TestDGSend(Thread.currentThread()), "DGServer")
- .start();
- ds = new java.net.DatagramSocket(ports[1]);
- dp = new DatagramPacket(testString.getBytes(), testString.length(),
- InetAddress.getLocalHost(), portNumber);
- // Wait to allow send to occur
- try {
- Thread.sleep(500);
- ds.send(dp);
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- ds.close();
- assertTrue("Incorrect data sent: " + retval, retval
- .equals(testString));
- }
- } finally {
- ds.close();
+
+ @Override
+ protected int peekData(DatagramPacket arg0) throws IOException {
+ return 0;
}
- // Regression for HARMONY-1118
- class testDatagramSocket extends DatagramSocket {
- public testDatagramSocket(DatagramSocketImpl impl) {
- super(impl);
- }
+
+ @Override
+ protected void receive(DatagramPacket arg0) throws IOException {
}
- class testDatagramSocketImpl extends DatagramSocketImpl {
- protected void create() throws SocketException {
- }
- protected void bind(int arg0, InetAddress arg1)
- throws SocketException {
- }
+ @Override
+ protected void setTTL(byte arg0) throws IOException {
+ }
- protected void send(DatagramPacket arg0) throws IOException {
- }
+ @Override
+ protected byte getTTL() throws IOException {
+ return 0;
+ }
- protected int peek(InetAddress arg0) throws IOException {
- return 0;
- }
+ @Override
+ protected void setTimeToLive(int arg0) throws IOException {
+ }
- protected int peekData(DatagramPacket arg0) throws IOException {
- return 0;
- }
+ @Override
+ protected int getTimeToLive() throws IOException {
+ return 0;
+ }
- protected void receive(DatagramPacket arg0) throws IOException {
- }
+ @Override
+ protected void join(InetAddress arg0) throws IOException {
+ }
- protected void setTTL(byte arg0) throws IOException {
- }
+ @Override
+ protected void joinGroup(SocketAddress addr, NetworkInterface netInterface) throws IOException {
- protected byte getTTL() throws IOException {
- return 0;
- }
+ }
- protected void setTimeToLive(int arg0) throws IOException {
- }
+ @Override
+ protected void leave(InetAddress arg0) throws IOException {
+ }
- protected int getTimeToLive() throws IOException {
- return 0;
- }
+ @Override
+ protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1)
+ throws IOException {
+ }
- protected void join(InetAddress arg0) throws IOException {
- }
+ @Override
+ protected void close() {
+ }
- protected void leave(InetAddress arg0) throws IOException {
- }
+ public void setOption(int arg0, Object arg1) throws SocketException {
+ }
- protected void joinGroup(SocketAddress arg0, NetworkInterface arg1)
- throws IOException {
- }
+ public Object getOption(int arg0) throws SocketException {
+ return null;
+ }
+ }
- protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1)
- throws IOException {
- }
+ static final class TestDatagramSocket extends DatagramSocket {
+ // This field exists solely to force initialization of this class
+ // inside a test method.
+ public static final Object ACCESS = new Object();
- protected void close() {
- }
+ public TestDatagramSocket(DatagramSocketImpl impl) {
+ super(impl);
+ }
+ }
- public void setOption(int arg0, Object arg1) throws SocketException {
- }
- public Object getOption(int arg0) throws SocketException {
- return null;
- }
- }
+ public void testArchivedHarmonyRegressions() throws Exception {
+ // Regression for HARMONY-1118
+ assertNotNull(TestDatagramSocketImpl.ACCESS);
+ assertNotNull(TestDatagramSocket.ACCESS);
// Regression test for Harmony-2938
InetAddress i = InetAddress.getByName("127.0.0.1");
DatagramSocket d = new DatagramSocket(0, i);
try {
d.send(new DatagramPacket(new byte[] { 1 }, 1));
- fail("should throw NPE.");
- } catch (NullPointerException e) {
- // expected;
+ fail();
+ } catch (NullPointerException expected) {
} finally {
d.close();
}
@@ -856,56 +505,70 @@ public class DatagramSocketTest extends junit.framework.TestCase {
InetSocketAddress addr = InetSocketAddress.createUnresolved(
"localhost", 0);
try {
- DatagramPacket dp = new DatagramPacket(new byte[272], 3, addr);
- fail("should throw IllegalArgumentException");
- } catch (IllegalArgumentException e) {
- // expected
+ new DatagramPacket(new byte[272], 3, addr);
+ fail();
+ } catch (IllegalArgumentException expected) {
}
}
- /**
- * If the InetAddress of DatagramPacket is null, DatagramSocket.send(DatagramPacket)
- * should throw NullPointer Exception.
- *
- * java.net.DatagramSocket#send(java.net.DatagramPacket)
- */
- public void test_sendLjava_net_DatagramPacket2() throws IOException {
- int udp_port = 20000;
- int send_port = 23000;
- DatagramSocket udpSocket = new DatagramSocket(udp_port);
+ public void test_sendLjava_net_DatagramPacket_nullDestination() throws IOException {
+ DatagramSocket datagramSocket = new DatagramSocket(0);
byte[] data = { 65 };
- DatagramPacket sendPacket = new DatagramPacket(data, data.length, null, send_port);
+ DatagramPacket sendPacket = new DatagramPacket(data, data.length, null, 25000);
try {
- udpSocket.send(sendPacket);
- fail("Should throw SocketException");
- } catch (NullPointerException e) {
+ datagramSocket.send(sendPacket);
+ fail();
+ } catch (NullPointerException expected) {
// Expected
} finally {
- udpSocket.close();
+ datagramSocket.close();
}
}
public void test_setSendBufferSizeI() throws Exception {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
+ final DatagramSocket ds = new DatagramSocket(0);
ds.setSendBufferSize(134);
assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134);
+ ds.close();
+ try {
+ ds.setSendBufferSize(1);
+ fail("SocketException was not thrown.");
+ } catch(SocketException se) {
+ //expected
+ }
}
public void test_setReceiveBufferSizeI() throws Exception {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
+ final DatagramSocket ds = new DatagramSocket(0);
ds.setReceiveBufferSize(130);
assertTrue("Incorrect buffer size", ds.getReceiveBufferSize() >= 130);
- }
- public void test_setSoTimeoutI() throws Exception {
- DatagramSocket ds = new DatagramSocket();
- ds.setSoTimeout(100);
- assertTrue("Set incorrect timeout", ds.getSoTimeout() >= 100);
+ try {
+ ds.setReceiveBufferSize(0);
+ fail("IllegalArgumentException was not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ try {
+ ds.setReceiveBufferSize(-1);
+ fail("IllegalArgumentException was not thrown.");
+ } catch(IllegalArgumentException iae) {
+ //expected
+ }
+
+ ds.close();
+
+ try {
+ ds.setReceiveBufferSize(1);
+ fail("SocketException was not thrown.");
+ } catch (SocketException e) {
+ //expected
+ }
}
+
public void test_ConstructorLjava_net_DatagramSocketImpl() {
class SimpleTestDatagramSocket extends DatagramSocket {
public SimpleTestDatagramSocket(DatagramSocketImpl impl) {
@@ -914,19 +577,15 @@ public class DatagramSocketTest extends junit.framework.TestCase {
}
try {
- new SimpleTestDatagramSocket((DatagramSocketImpl) null);
+ new SimpleTestDatagramSocket(null);
fail("exception expected");
} catch (NullPointerException ex) {
// expected
}
}
- /**
- * java.net.DatagramSocket#DatagramSocket(java.net.SocketAddress)
- */
public void test_ConstructorLjava_net_SocketAddress() throws Exception {
class UnsupportedSocketAddress extends SocketAddress {
-
public UnsupportedSocketAddress() {
}
}
@@ -946,457 +605,118 @@ public class DatagramSocketTest extends junit.framework.TestCase {
}
// regression for HARMONY-894
- ds = new DatagramSocket((SocketAddress) null);
+ ds = new DatagramSocket(null);
assertTrue(ds.getBroadcast());
}
- /**
- * java.net.DatagramSocket#bind(java.net.SocketAddress)
- */
- public void test_bindLjava_net_SocketAddress() throws Exception {
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- DatagramServer server = null;
-
- // now create a socket that is not bound and then bind it
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int portNumber = ports[0];
- int serverPortNumber = ports[1];
- DatagramSocket theSocket = new DatagramSocket(new InetSocketAddress(
- InetAddress.getLocalHost(), portNumber));
-
- // validate that the localSocketAddress reflects the address we
- // bound to
- assertTrue(
- "Local address not correct after bind:"
- + theSocket.getLocalSocketAddress().toString()
- + "Expected: "
- + (new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber)).toString(), theSocket
- .getLocalSocketAddress().equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber)));
-
- // now make sure that datagrams sent from this socket appear to come
- // from the address we bound to
- InetAddress localHost = InetAddress.getLocalHost();
- portNumber = ports[2];
- DatagramSocket ds = new DatagramSocket(null);
- ds.bind(new InetSocketAddress(localHost, portNumber));
-
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes, sendBytes.length);
- ds.send(send);
- Thread.sleep(1000);
- ds.close();
- assertTrue("Address in packet sent does not match address bound to:"
- + server.rdp.getAddress() + ":" + server.rdp.getPort() + ":"
- + localHost + ":" + portNumber, (server.rdp.getAddress()
- .equals(localHost))
- && (server.rdp.getPort() == portNumber));
-
- // validate if we pass in null that it picks an address for us and
- // all is ok
- theSocket = new DatagramSocket(null);
+ public void test_bindLjava_net_SocketAddress_null() throws Exception {
+ // validate if we pass in null that it picks an address for us.
+ DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
theSocket.bind(null);
- assertNotNull("Bind with null did not work", theSocket
- .getLocalSocketAddress());
+ assertNotNull(theSocket.getLocalSocketAddress());
theSocket.close();
+ }
- // now check the error conditions
-
- // Address we cannot bind to
- theSocket = new DatagramSocket(null);
+ public void test_bindLjava_net_SocketAddress_address_in_use() throws Exception {
+ DatagramSocket socket1 = new DatagramSocket(0);
try {
- theSocket.bind(new InetSocketAddress(InetAddress
- .getByAddress(Support_Configuration.nonLocalAddressBytes),
- Support_PortManager.getNextPortForUDP()));
- fail("No exception when binding to bad address");
- } catch (SocketException ex) {
+ new DatagramSocket(socket1.getLocalPort());
+ fail();
+ } catch (SocketException expected) {
}
- theSocket.close();
+ socket1.close();
+ }
- // Address that we have allready bound to
- ports = Support_PortManager.getNextPortsForUDP(2);
- theSocket = new DatagramSocket(null);
- DatagramSocket theSocket2 = new DatagramSocket(ports[0]);
- try {
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), ports[1]);
- theSocket.bind(theAddress);
- theSocket2.bind(theAddress);
- fail("No exception binding to address that is not available");
- } catch (SocketException ex) {
+ public void test_bindLjava_net_SocketAddress_unsupported_address_type() throws Exception {
+ class mySocketAddress extends SocketAddress {
+ public mySocketAddress() {
+ }
}
- theSocket.close();
- theSocket2.close();
// unsupported SocketAddress subclass
- theSocket = new DatagramSocket(null);
+ DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
try {
theSocket.bind(new mySocketAddress());
fail("No exception when binding using unsupported SocketAddress subclass");
- } catch (IllegalArgumentException ex) {
+ } catch (IllegalArgumentException expected) {
}
theSocket.close();
-
- if (server != null) {
- server.stopServer();
- }
- }
-
- /**
- * java.net.DatagramSocket#connect(java.net.SocketAddress)
- */
- public void test_connectLjava_net_SocketAddress() throws Exception {
-
- // validate that we get the PortUnreachable exception if we try to
- // send a dgram to a server that is not running and then do a recv
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- DatagramPacket send = new DatagramPacket(new byte[10], 10);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(10000);
- ds.receive(receive);
- ds.close();
- fail("No PortUnreachableException when connected at native level on recv ");
- } catch (PortUnreachableException e) {
- // Expected
- }
-
- // validate that we can send/receive with datagram sockets connected at
- // the native level
- DatagramServer server = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int serverPortNumber = ports[0];
-
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
-
- int port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- final byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes, sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("Wrong size data received: " + receive.getLength(), receive
- .getLength() == sendBytes.length);
- assertTrue("Wrong data received"
- + new String(receive.getData(), 0, receive.getLength()) + ":"
- + new String(sendBytes), new String(receive.getData(), 0,
- receive.getLength()).equals(new String(sendBytes)));
- assertTrue("Wrong receiver:" + receive.getAddress() + ":" + localHost,
- receive.getAddress().equals(localHost));
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can disconnect
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- ds.disconnect();
- ds.close();
- } catch (PortUnreachableException e) {
- // Expected
- }
-
- // validate that once connected we cannot send to another address
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- DatagramPacket senddp = new DatagramPacket(new byte[10], 10,
- inetAddress, portNumber + 1);
- ds.send(senddp);
- ds.close();
- fail("No Exception when trying to send to a different address on a connected socket ");
- } catch (IllegalArgumentException e) {
- // Expected
- }
-
- // validate that we can connect, then disconnect, then connect then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
-
- localHost = InetAddress.getLocalHost();
- ds = new DatagramSocket(ports[1]);
- ds2 = new DatagramSocket(ports[2]);
-
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
-
- port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
- ds.disconnect();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- send = new DatagramPacket(sendBytes, sendBytes.length);
- ds.send(send);
- receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/disconnect/connect - Wrong size data received: "
- + receive.getLength(), receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength()) + ":"
- + new String(sendBytes), new String(receive.getData(), 0,
- receive.getLength()).equals(new String(sendBytes)));
- assertTrue("connect/disconnect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive.getAddress()
- .equals(localHost));
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect/disconnect then send/recv to any address
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
-
- localHost = InetAddress.getLocalHost();
- ds = new DatagramSocket(ports[1]);
- ds2 = new DatagramSocket(ports[2]);
-
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
-
- port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
- ds.disconnect();
-
- send = new DatagramPacket(sendBytes, sendBytes.length, localHost,
- serverPortNumber);
- ds.send(send);
- receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/disconnect - Wrong size data received: "
- + receive.getLength(), receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength()) + ":"
- + new String(sendBytes), new String(receive.getData(), 0,
- receive.getLength()).equals(new String(sendBytes)));
- assertTrue("connect/disconnect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive.getAddress()
- .equals(localHost));
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect on an allready connected socket and then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
-
- localHost = InetAddress.getLocalHost();
- ds = new DatagramSocket(ports[1]);
- ds2 = new DatagramSocket(ports[2]);
-
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
-
- port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendTestBytes = { 'T', 'e', 's', 't', 0 };
- send = new DatagramPacket(sendTestBytes, sendTestBytes.length);
- ds.send(send);
- DatagramPacket receivedp = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receivedp);
- ds.close();
- assertTrue("connect/connect - Wrong size data received: "
- + receivedp.getLength(),
- receivedp.getLength() == sendTestBytes.length);
- assertTrue("connect/connect - Wrong data received"
- + new String(receivedp.getData(), 0, receivedp.getLength())
- + ":" + new String(sendTestBytes), new String(receivedp
- .getData(), 0, receivedp.getLength()).equals(new String(
- sendTestBytes)));
- assertTrue("connect/connect - Wrong receiver:" + receivedp.getAddress()
- + ":" + localHost, receivedp.getAddress().equals(localHost));
-
- if (server != null) {
- server.stopServer();
- }
-
- // test for when we fail to connect at the native level. It seems to
- // fail for the any address so we use this. Now to be compatible we
- // don't throw the exception but eat it and then act as if we were
- // connected at the Java level.
- try {
- ds = new java.net.DatagramSocket();
- byte[] addressBytes = { 0, 0, 0, 0 };
- InetAddress inetAddress = InetAddress.getByAddress(addressBytes);
- int portNumber = Support_PortManager.getNextPortForUDP();
- InetAddress localHostIA = InetAddress.getLocalHost();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- assertTrue("Is not connected after connect to inaddr any", ds
- .isConnected());
- byte[] sendBytesArray = { 'T', 'e', 's', 't', 0 };
- DatagramPacket senddp = new DatagramPacket(sendBytesArray,
- sendBytesArray.length, localHostIA, portNumber);
- ds.send(senddp);
- fail("No exception when trying to connect at native level with bad address (exception from send) ");
- } catch (IllegalArgumentException e) {
- // Expected
- }
}
- /**
- * java.net.DatagramSocket#isBound()
- */
public void test_isBound() throws Exception {
- InetAddress addr = InetAddress.getLocalHost();
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int port = ports[0];
-
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
- assertTrue("Socket indicated not bound when it should be (1)",
- theSocket.isBound());
+ DatagramSocket theSocket = new DatagramSocket(0);
+ assertTrue(theSocket.isBound());
theSocket.close();
- theSocket = new DatagramSocket(new InetSocketAddress(addr, port));
- assertTrue("Socket indicated not bound when it should be (2)",
- theSocket.isBound());
+ theSocket = new DatagramSocket(new InetSocketAddress(Inet6Address.LOOPBACK, 0));
+ assertTrue(theSocket.isBound());
theSocket.close();
theSocket = new DatagramSocket(null);
- assertFalse("Socket indicated bound when it should not be (1)",
- theSocket.isBound());
+ assertFalse(theSocket.isBound());
theSocket.close();
// connect causes implicit bind
theSocket = new DatagramSocket(null);
- theSocket.connect(new InetSocketAddress(addr, port));
- assertTrue("Socket indicated not bound when it should be (3)",
- theSocket.isBound());
+ theSocket.connect(new InetSocketAddress(Inet6Address.LOOPBACK, 0));
+ assertTrue(theSocket.isBound());
theSocket.close();
// now test when we bind explicitely
- InetSocketAddress theLocalAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), ports[2]);
+ InetSocketAddress theLocalAddress = new InetSocketAddress(Inet6Address.LOOPBACK, 0);
theSocket = new DatagramSocket(null);
- assertFalse("Socket indicated bound when it should not be (2)",
- theSocket.isBound());
+ assertFalse(theSocket.isBound());
theSocket.bind(theLocalAddress);
- assertTrue("Socket indicated not bound when it should be (4)",
- theSocket.isBound());
+ assertTrue(theSocket.isBound());
theSocket.close();
- assertTrue("Socket indicated not bound when it should be (5)",
- theSocket.isBound());
+ assertTrue(theSocket.isBound());
}
- /**
- * java.net.DatagramSocket#isConnected()
- */
public void test_isConnected() throws Exception {
- InetAddress addr = InetAddress.getLocalHost();
- int[] ports = Support_PortManager.getNextPortsForUDP(4);
- int port = ports[0];
+ DatagramServer ds = new DatagramServer(Inet6Address.LOOPBACK);
// base test
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
- assertFalse("Socket indicated connected when it should not be",
- theSocket.isConnected());
- theSocket.connect(new InetSocketAddress(addr, port));
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
+ DatagramSocket theSocket = new DatagramSocket(0);
+ assertFalse(theSocket.isConnected());
+ theSocket.connect(new InetSocketAddress(Inet6Address.LOOPBACK, ds.getPort()));
+ assertTrue(theSocket.isConnected());
// reconnect the socket and make sure we get the right answer
- theSocket.connect(new InetSocketAddress(addr, ports[2]));
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
+ theSocket.connect(new InetSocketAddress(Inet6Address.LOOPBACK, ds.getPort()));
+ assertTrue(theSocket.isConnected());
// now disconnect the socket and make sure we get the right answer
theSocket.disconnect();
- assertFalse("Socket indicated connected when it should not be",
- theSocket.isConnected());
+ assertFalse(theSocket.isConnected());
theSocket.close();
// now check behavior when socket is closed when connected
- theSocket = new DatagramSocket(ports[3]);
- theSocket.connect(new InetSocketAddress(addr, port));
+ theSocket = new DatagramSocket(0);
+ theSocket.connect(new InetSocketAddress(Inet6Address.LOOPBACK, ds.getPort()));
theSocket.close();
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
+ assertTrue(theSocket.isConnected());
}
- /**
- * java.net.DatagramSocket#getRemoteSocketAddress()
- */
public void test_getRemoteSocketAddress() throws Exception {
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int sport = ports[0];
- int portNumber = ports[1];
- DatagramSocket s = new DatagramSocket(new InetSocketAddress(InetAddress
- .getLocalHost(), portNumber));
- s.connect(new InetSocketAddress(InetAddress.getLocalHost(), sport));
- assertTrue("Returned incorrect InetSocketAddress(1):"
- + s.getLocalSocketAddress().toString(),
- s.getRemoteSocketAddress()
- .equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), sport)));
+ DatagramServer server = new DatagramServer(Inet6Address.LOOPBACK);
+ DatagramSocket s = new DatagramSocket(0);
+ s.connect(new InetSocketAddress(Inet6Address.LOOPBACK, server.getPort()));
+
+ assertEquals(new InetSocketAddress(Inet6Address.LOOPBACK, server.getPort()),
+ s.getRemoteSocketAddress());
s.close();
// now create one that is not connected and validate that we get the
// right answer
DatagramSocket theSocket = new DatagramSocket(null);
- portNumber = ports[2];
- theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber));
- assertNull("Returned incorrect InetSocketAddress -unconnected socket:"
- + "Expected: NULL", theSocket.getRemoteSocketAddress());
+ theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ assertNull(theSocket.getRemoteSocketAddress());
// now connect and validate we get the right answer
- theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
- sport));
- assertTrue("Returned incorrect InetSocketAddress(2):"
- + theSocket.getRemoteSocketAddress().toString(),
- theSocket.getRemoteSocketAddress()
- .equals(
- new InetSocketAddress(InetAddress
- .getLocalHost(), sport)));
+ theSocket.connect(new InetSocketAddress(Inet6Address.LOOPBACK, server.getPort()));
+ assertEquals(new InetSocketAddress(Inet6Address.LOOPBACK, server.getPort()),
+ theSocket.getRemoteSocketAddress());
theSocket.close();
}
@@ -1406,18 +726,17 @@ public class DatagramSocketTest extends junit.framework.TestCase {
assertNull(theSocket.getLocalSocketAddress());
// now bind the socket and make sure we get the right answer
- int portNumber = Support_PortManager.getNextPortForUDP();
- InetSocketAddress localAddress = new InetSocketAddress(InetAddress.getLocalHost(), portNumber);
+ InetSocketAddress localAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
theSocket.bind(localAddress);
- assertEquals(localAddress, theSocket.getLocalSocketAddress());
+ assertEquals(localAddress.getAddress(), theSocket.getLocalAddress());
+ assertTrue(theSocket.getLocalPort() > 0);
theSocket.close();
}
public void test_getLocalSocketAddress_unbound() throws Exception {
- int portNumber = Support_PortManager.getNextPortForUDP();
- InetSocketAddress localAddress1 = new InetSocketAddress(InetAddress.getLocalHost(), portNumber);
+ InetSocketAddress localAddress1 = new InetSocketAddress(InetAddress.getLocalHost(), 0);
DatagramSocket s = new DatagramSocket(localAddress1);
- assertEquals(localAddress1, s.getLocalSocketAddress());
+ assertEquals(localAddress1.getAddress(), s.getLocalAddress());
s.close();
InetSocketAddress remoteAddress = (InetSocketAddress) s.getRemoteSocketAddress();
@@ -1439,14 +758,14 @@ public class DatagramSocketTest extends junit.framework.TestCase {
DatagramSocket theSocket1 = null;
DatagramSocket theSocket2 = null;
try {
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress.getLocalHost(), Support_PortManager.getNextPortForUDP());
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
theSocket1 = new DatagramSocket(null);
theSocket2 = new DatagramSocket(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");
+ theSocket2.bind(new InetSocketAddress(InetAddress.getLocalHost(), theSocket1.getLocalPort()));
+ fail();
} catch (BindException expected) {
}
if (theSocket1 != null) {
@@ -1457,13 +776,13 @@ public class DatagramSocketTest extends junit.framework.TestCase {
}
// test case were we set it to true
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress.getLocalHost(), Support_PortManager.getNextPortForUDP());
+ InetSocketAddress theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
theSocket1 = new DatagramSocket(null);
theSocket2 = new DatagramSocket(null);
theSocket1.setReuseAddress(true);
theSocket2.setReuseAddress(true);
theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
+ theSocket2.bind(new InetSocketAddress(InetAddress.getLocalHost(), theSocket1.getLocalPort()));
if (theSocket1 != null) {
theSocket1.close();
@@ -1475,11 +794,11 @@ public class DatagramSocketTest extends junit.framework.TestCase {
// test the default case which we expect to be the same on all
// platforms
try {
- theAddress = new InetSocketAddress(InetAddress.getLocalHost(), Support_PortManager.getNextPortForUDP());
+ theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
theSocket1 = new DatagramSocket(null);
theSocket2 = new DatagramSocket(null);
theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
+ theSocket2.bind(new InetSocketAddress(InetAddress.getLocalHost(), theSocket1.getLocalPort()));
fail("No exception when trying to connect to do duplicate socket bind with re-useaddr left as default");
} catch (BindException expected) {
}
@@ -1489,6 +808,13 @@ public class DatagramSocketTest extends junit.framework.TestCase {
if (theSocket2 != null) {
theSocket2.close();
}
+
+ try {
+ theSocket1.setReuseAddress(true);
+ fail("SocketException was not thrown.");
+ } catch(SocketException se) {
+ //expected
+ }
}
public void test_getReuseAddress() throws Exception {
@@ -1497,26 +823,40 @@ public class DatagramSocketTest extends junit.framework.TestCase {
assertTrue("getReuseAddress false when it should be true", theSocket.getReuseAddress());
theSocket.setReuseAddress(false);
assertFalse("getReuseAddress true when it should be False", theSocket.getReuseAddress());
+ theSocket.close();
+ try {
+ theSocket.getReuseAddress();
+ fail("SocketException was not thrown.");
+ } catch(SocketException se) {
+ //expected
+ }
}
public void test_setBroadcastZ() throws Exception {
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- DatagramSocket theSocket = new DatagramSocket(ports[0]);
+ DatagramSocket theSocket = new DatagramSocket(0);
theSocket.setBroadcast(false);
byte theBytes[] = { -1, -1, -1, -1 };
// validate we cannot connect to the broadcast address when
// setBroadcast is false
try {
- theSocket.connect(new InetSocketAddress(InetAddress.getByAddress(theBytes), ports[1]));
- assertFalse("No exception when connecting to broadcast address with setBroadcast(false)", theSocket.getBroadcast());
- } catch (Exception ex) {
+ theSocket.connect(new InetSocketAddress(InetAddress.getByAddress(theBytes), 0));
+ fail();
+ } catch (Exception expected) {
}
// now validate that we can connect to the broadcast address when
// setBroadcast is true
theSocket.setBroadcast(true);
- theSocket.connect(new InetSocketAddress(InetAddress.getByAddress(theBytes), ports[2]));
+ theSocket.connect(new InetSocketAddress(InetAddress.getByAddress(theBytes), 0));
+
+ theSocket.close();
+ try {
+ theSocket.setBroadcast(false);
+ fail();
+ } catch(SocketException se) {
+ //expected
+ }
}
public void test_getBroadcast() throws Exception {
@@ -1529,13 +869,8 @@ public class DatagramSocketTest extends junit.framework.TestCase {
public void test_setTrafficClassI() throws Exception {
int IPTOS_LOWCOST = 0x2;
- int IPTOS_RELIABILTY = 0x4;
int IPTOS_THROUGHPUT = 0x8;
- int IPTOS_LOWDELAY = 0x10;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
-
- new InetSocketAddress(InetAddress.getLocalHost(), ports[0]);
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
+ DatagramSocket theSocket = new DatagramSocket(0);
// validate that value set must be between 0 and 255
try {
@@ -1555,114 +890,51 @@ public class DatagramSocketTest extends junit.framework.TestCase {
theSocket.setTrafficClass(IPTOS_THROUGHPUT);
}
- public void test_getTrafficClass() throws Exception {
- int IPTOS_LOWCOST = 0x2;
- int IPTOS_RELIABILTY = 0x4;
- int IPTOS_THROUGHPUT = 0x8;
- int IPTOS_LOWDELAY = 0x10;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
-
- new InetSocketAddress(InetAddress.getLocalHost(), ports[0]);
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
-
- /*
- * we cannot actually check that the values are set as if a platform
- * does not support the option then it may come back unset even
- * though we set it so just get the value to make sure we can get it
- */
- int trafficClass = theSocket.getTrafficClass();
- }
public void test_isClosed() throws Exception {
DatagramSocket theSocket = new DatagramSocket();
-
// validate isClosed returns expected values
- assertFalse("Socket should indicate it is not closed(1):", theSocket
- .isClosed());
+ assertFalse(theSocket.isClosed());
theSocket.close();
- assertTrue("Socket should indicate it is not closed(1):", theSocket
- .isClosed());
+ assertTrue(theSocket.isClosed());
InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP());
+ .getLocalHost(), 0);
theSocket = new DatagramSocket(theAddress);
- assertFalse("Socket should indicate it is not closed(2):", theSocket
- .isClosed());
+ assertFalse(theSocket.isClosed());
theSocket.close();
- assertTrue("Socket should indicate it is not closed(2):", theSocket
- .isClosed());
+ assertTrue(theSocket.isClosed());
}
- /**
- * java.net.DatagramSocket#getChannel()
- */
- public void test_getChannel() throws SocketException {
+ public void test_getChannel() throws Exception {
assertNull(new DatagramSocket().getChannel());
- }
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- retval = "Bogus retval";
- }
+ DatagramServer server = new DatagramServer(Inet6Address.LOOPBACK);
+ DatagramSocket ds = new DatagramSocket(0);
+ assertNull(ds.getChannel());
+ ds.disconnect();
+ ds.close();
+ server.stopServer();
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- ds.close();
- sds.close();
- } catch (Exception e) {
- }
+ DatagramChannel channel = DatagramChannel.open();
+ DatagramSocket socket = channel.socket();
+ assertEquals(channel, socket.getChannel());
+ socket.close();
}
- protected void receive_oversize_java_net_DatagramPacket() {
- final int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int portNumber = ports[0];
-
- class TestDGRcvOver implements Runnable {
- public void run() {
- InetAddress localHost = null;
- try {
- localHost = InetAddress.getLocalHost();
- Thread.sleep(1000);
- DatagramSocket sds = new DatagramSocket(ports[1]);
- DatagramPacket rdp = new DatagramPacket("0123456789"
- .getBytes(), 10, localHost, portNumber);
- sds.send(rdp);
- sds.close();
- } catch (Exception e) {
- System.err.println("host " + localHost + " port "
- + portNumber + " failed to send oversize data: "
- + e);
- e.printStackTrace();
- }
- }
- }
+ public void testReceiveOversizePacket() throws Exception {
+ DatagramSocket ds = new DatagramSocket(0);
+ DatagramSocket sds = new DatagramSocket(0);
- try {
- new Thread(new TestDGRcvOver(), "DGSenderOver").start();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSoTimeout(6000);
- byte rbuf[] = new byte[5];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- ;
- ds.receive(rdp);
- ds.close();
- assertTrue("Send/Receive oversize failed to return correct data: "
- + new String(rbuf, 0, 5), new String(rbuf, 0, 5)
- .equals("01234"));
- } catch (Exception e) {
- System.err.println("Exception during send test: " + e);
- e.printStackTrace();
- fail("port " + portNumber + " Exception: " + e
- + " during oversize send test");
- } finally {
- ds.close();
- }
+ DatagramPacket rdp = new DatagramPacket("0123456789".getBytes("UTF-8"),
+ 5, Inet6Address.LOOPBACK, ds.getLocalPort());
+ sds.send(rdp);
+ sds.close();
+
+ byte[] recvBuffer = new byte[5];
+ DatagramPacket receive = new DatagramPacket(recvBuffer, recvBuffer.length);
+ ds.receive(receive);
+ ds.close();
+ assertEquals(new String("01234"), new String(recvBuffer, 0, recvBuffer.length, "UTF-8"));
}
}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/MulticastSocketTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/MulticastSocketTest.java
index b8444a4..96be9fd 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/MulticastSocketTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/net/MulticastSocketTest.java
@@ -18,6 +18,7 @@
package org.apache.harmony.tests.java.net;
import java.io.IOException;
+import java.io.InterruptedIOException;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.Inet4Address;
@@ -28,12 +29,9 @@ 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 tests.support.Support_PortManager;
-
public class MulticastSocketTest extends junit.framework.TestCase {
private boolean atLeastTwoInterfaces = false;
@@ -64,17 +62,38 @@ public class MulticastSocketTest extends junit.framework.TestCase {
static class MulticastServer extends Thread {
- public MulticastSocket ms;
+ public final MulticastSocket ms;
+ public final byte[] rbuf = new byte[512];
+ public final DatagramPacket rdp;
+ private final InetAddress groupAddr;
+ private final NetworkInterface groupNI;
- boolean running = true;
+ private volatile boolean running = true;
- volatile public byte[] rbuf = new byte[512];
+ public MulticastServer(InetAddress anAddress, int aPort) throws java.io.IOException {
+ rbuf[0] = -1;
+ rdp = new DatagramPacket(rbuf, rbuf.length);
+ ms = new MulticastSocket(aPort);
+ ms.setSoTimeout(2000);
+
+ groupAddr = anAddress;
+ groupNI = null;
- volatile DatagramPacket rdp = null;
+ ms.joinGroup(groupAddr);
+ }
+
+ public MulticastServer(InetAddress anAddress, int aPort,
+ NetworkInterface netInterface) throws java.io.IOException {
+ rbuf[0] = -1;
+ rdp = new DatagramPacket(rbuf, rbuf.length);
+ ms = new MulticastSocket(aPort);
+ ms.setSoTimeout(2000);
+
+ groupAddr = anAddress;
+ groupNI = netInterface;
- private InetAddress groupAddr = null;
- private SocketAddress groupSockAddr = null;
- private NetworkInterface groupNI = null;
+ ms.joinGroup(new InetSocketAddress(groupAddr, ms.getLocalPort()), groupNI);
+ }
public void run() {
try {
@@ -84,17 +103,16 @@ public class MulticastSocketTest extends junit.framework.TestCase {
while (running) {
try {
ms.receive(tmpPack);
-
- System.arraycopy(tmpPack.getData(), 0, rdp.getData(), rdp.getOffset(), tmpPack.getLength());
+ 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 (InterruptedIOException e) {
}
}
} catch (java.io.IOException e) {
- System.out.println("Multicast server failed: " + e);
+ fail();
} finally {
ms.close();
}
@@ -103,35 +121,10 @@ public class MulticastSocketTest extends junit.framework.TestCase {
public void stopServer() {
running = false;
try {
- if (groupAddr != null) {
- ms.leaveGroup(groupAddr);
- } else if (groupSockAddr != null) {
- ms.leaveGroup(groupSockAddr, groupNI);
- }
+ ms.leaveGroup(groupAddr);
} 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);
- }
}
public void test_Constructor() throws IOException {
@@ -159,10 +152,8 @@ public class MulticastSocketTest extends junit.framework.TestCase {
}
public void test_getInterface() throws Exception {
- int groupPort = Support_PortManager.getNextPortForUDP();
-
// validate that we get the expected response when one was not set
- MulticastSocket mss = new MulticastSocket(groupPort);
+ MulticastSocket mss = new MulticastSocket(0);
// we expect an ANY address in this case
assertTrue(mss.getInterface().isAnyLocalAddress());
@@ -174,8 +165,8 @@ public class MulticastSocketTest extends junit.framework.TestCase {
mss.setInterface(firstAddress);
assertEquals("getNetworkInterface did not return interface set by setInterface", firstAddress, mss.getInterface());
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
+ mss.close();
+ mss = new MulticastSocket(0);
mss.setNetworkInterface(networkInterface1);
assertEquals("getInterface did not return interface set by setNetworkInterface", networkInterface1, NetworkInterface.getByInetAddress(mss.getInterface()));
}
@@ -184,10 +175,8 @@ public class MulticastSocketTest extends junit.framework.TestCase {
}
public void test_getNetworkInterface() throws IOException {
- int groupPort = Support_PortManager.getNextPortForUDP();
-
// validate that we get the expected response when one was not set
- MulticastSocket mss = new MulticastSocket(groupPort);
+ MulticastSocket mss = new MulticastSocket(0);
NetworkInterface theInterface = mss.getNetworkInterface();
assertTrue("network interface returned wrong network interface when not set:" + theInterface,
theInterface.getInetAddresses().hasMoreElements());
@@ -206,8 +195,7 @@ public class MulticastSocketTest extends junit.framework.TestCase {
}
mss.close();
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
+ mss = new MulticastSocket(0);
if (IPV6networkInterface1 != null) {
mss.setNetworkInterface(IPV6networkInterface1);
assertEquals("getNetworkInterface did not return interface set by setNeworkInterface",
@@ -215,8 +203,7 @@ public class MulticastSocketTest extends junit.framework.TestCase {
}
// validate that we get the expected response when we set via setInterface
- groupPort = Support_PortManager.getNextPortForUDP();
- mss = new MulticastSocket(groupPort);
+ mss = new MulticastSocket(0);
Enumeration addresses = networkInterface1.getInetAddresses();
if (addresses.hasMoreElements()) {
firstAddress = (InetAddress) addresses.nextElement();
@@ -250,15 +237,13 @@ public class MulticastSocketTest extends junit.framework.TestCase {
}
private void test_joinGroupLjava_net_InetAddress(InetAddress group) throws Exception {
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
-
- MulticastServer server = new MulticastServer(group, groupPort);
+ MulticastServer server = new MulticastServer(group, 0);
server.start();
Thread.sleep(1000);
String msg = "Hello World";
- MulticastSocket mss = new MulticastSocket(ports[1]);
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg.length(), group, groupPort);
+ MulticastSocket mss = new MulticastSocket(server.ms.getLocalPort());
+ DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg.length(), group,
+ server.ms.getLocalPort());
mss.send(sdp, (byte) 10);
Thread.sleep(1000);
String receivedMessage = new String(server.rdp.getData(), 0, server.rdp.getLength());
@@ -306,24 +291,21 @@ public class MulticastSocketTest extends junit.framework.TestCase {
}
private void test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface(InetAddress group, InetAddress group2) throws Exception {
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
- int serverPort = ports[1];
-
- SocketAddress groupSockAddr = new InetSocketAddress(group, groupPort);
-
// Check that we can join a group using a null network interface.
- MulticastSocket mss = new MulticastSocket(groupPort);
+ MulticastSocket mss = new MulticastSocket(0);
+ SocketAddress groupSockAddr = new InetSocketAddress(group, mss.getLocalPort());
+
mss.joinGroup(groupSockAddr, null);
mss.setTimeToLive(2);
Thread.sleep(1000);
// set up the server and join the group on networkInterface1
- MulticastServer server = new MulticastServer(groupSockAddr, serverPort, networkInterface1);
+ MulticastServer server = new MulticastServer(group, 0, networkInterface1);
server.start();
Thread.sleep(1000);
String msg = "Hello World";
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg.length(), group, serverPort);
+ DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg.length(), group,
+ server.ms.getLocalPort());
mss.setTimeToLive(2);
mss.send(sdp);
Thread.sleep(1000);
@@ -332,20 +314,14 @@ public class MulticastSocketTest extends junit.framework.TestCase {
server.stopServer();
mss.close();
- // 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 = new MulticastServer(group, 0, networkInterface1);
server.start();
Thread.sleep(1000);
- groupPort = ports[1];
- mss = new MulticastSocket(groupPort);
+ mss = new MulticastSocket(0);
mss.setTimeToLive(10);
msg = "Hello World - Different Group";
- sdp = new DatagramPacket(msg.getBytes(), msg.length(), group2, serverPort);
+ sdp = new DatagramPacket(msg.getBytes(), msg.length(), group2, server.ms.getLocalPort());
mss.send(sdp);
Thread.sleep(1000);
assertFalse("Group member received data when sent on different group: ",
@@ -362,15 +338,16 @@ public class MulticastSocketTest extends junit.framework.TestCase {
return;
}
// set up server on first interfaces
- NetworkInterface loopbackInterface = NetworkInterface.getByInetAddress(InetAddress.getByName("127.0.0.1"));
+ NetworkInterface loopbackInterface = NetworkInterface.getByInetAddress(
+ InetAddress.getByName("127.0.0.1"));
- boolean anyLoop = networkInterface1.equals(loopbackInterface) || networkInterface2.equals(loopbackInterface);
- System.err.println("anyLoop=" + anyLoop);
+ boolean anyLoop = networkInterface1.equals(loopbackInterface) ||
+ networkInterface2.equals(loopbackInterface);
ArrayList<NetworkInterface> realInterfaces = new ArrayList<NetworkInterface>();
Enumeration<NetworkInterface> theInterfaces = NetworkInterface.getNetworkInterfaces();
while (theInterfaces.hasMoreElements()) {
- NetworkInterface thisInterface = (NetworkInterface) theInterfaces.nextElement();
+ NetworkInterface thisInterface = theInterfaces.nextElement();
if (thisInterface.getInetAddresses().hasMoreElements()) {
realInterfaces.add(thisInterface);
}
@@ -388,7 +365,7 @@ public class MulticastSocketTest extends junit.framework.TestCase {
NetworkInterface sendingInterface = null;
InetAddress group = null;
if (addresses.hasMoreElements()) {
- InetAddress firstAddress = (InetAddress) addresses.nextElement();
+ InetAddress firstAddress = addresses.nextElement();
if (firstAddress instanceof Inet4Address) {
group = InetAddress.getByName("224.0.0.4");
if (anyLoop) {
@@ -411,22 +388,19 @@ public class MulticastSocketTest extends junit.framework.TestCase {
}
}
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int serverPort = ports[0];
- int groupPort = ports[1];
- InetSocketAddress groupSockAddr = new InetSocketAddress(group, serverPort);
- MulticastServer server = new MulticastServer(groupSockAddr, serverPort, thisInterface);
+
+ MulticastServer server = new MulticastServer(group, 0, 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
- MulticastSocket mss = new MulticastSocket(groupPort);
+ MulticastSocket mss = new MulticastSocket(0);
mss.setNetworkInterface(sendingInterface);
String msg = "Hello World - Again" + thisInterface.getName();
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg.length(), group, serverPort);
- System.err.println(thisInterface + " " + group);
+ DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg.length(), group,
+ server.ms.getLocalPort());
mss.send(sdp);
Thread.sleep(1000);
if (thisInterface.equals(sendingInterface)) {
@@ -453,9 +427,8 @@ public class MulticastSocketTest extends junit.framework.TestCase {
private void test_joinGroupLjava_net_SocketAddressLjava_net_NetworkInterface_multiple_joins(InetAddress group) throws Exception {
// validate that we can join the same address on two
// different interfaces but not on the same interface
- int groupPort = Support_PortManager.getNextPortForUDP();
- MulticastSocket mss = new MulticastSocket(groupPort);
- SocketAddress groupSockAddr = new InetSocketAddress(group, groupPort);
+ MulticastSocket mss = new MulticastSocket(0);
+ SocketAddress groupSockAddr = new InetSocketAddress(group, mss.getLocalPort());
mss.joinGroup(groupSockAddr, networkInterface1);
mss.joinGroup(groupSockAddr, networkInterface2);
try {
@@ -475,12 +448,10 @@ public class MulticastSocketTest extends junit.framework.TestCase {
}
private void test_leaveGroupLjava_net_InetAddress(InetAddress group) throws Exception {
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
-
String msg = "Hello World";
- MulticastSocket mss = new MulticastSocket(ports[1]);
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg.length(), group, groupPort);
+ MulticastSocket mss = new MulticastSocket(0);
+ DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg.length(), group,
+ mss.getLocalPort());
mss.send(sdp, (byte) 10);
try {
// Try to leave a group we didn't join.
@@ -531,16 +502,11 @@ public class MulticastSocketTest extends junit.framework.TestCase {
private void test_leaveGroupLjava_net_SocketAddressLjava_net_NetworkInterface(InetAddress group, InetAddress group2) throws Exception {
String msg = null;
- int groupPort = Support_PortManager.getNextPortForUDP();
SocketAddress groupSockAddr = null;
SocketAddress groupSockAddr2 = null;
- groupSockAddr = new InetSocketAddress(group, groupPort);
-
- // now test that we can join and leave a group successfully
- groupPort = Support_PortManager.getNextPortForUDP();
- MulticastSocket mss = new MulticastSocket(groupPort);
- groupSockAddr = new InetSocketAddress(group, groupPort);
+ MulticastSocket mss = new MulticastSocket(0);
+ groupSockAddr = new InetSocketAddress(group, mss.getLocalPort());
mss.joinGroup(groupSockAddr, null);
mss.leaveGroup(groupSockAddr, null);
try {
@@ -549,7 +515,7 @@ public class MulticastSocketTest extends junit.framework.TestCase {
} catch (IOException expected) {
}
- groupSockAddr2 = new InetSocketAddress(group2, groupPort);
+ groupSockAddr2 = new InetSocketAddress(group2, mss.getLocalPort());
mss.joinGroup(groupSockAddr, networkInterface1);
try {
mss.leaveGroup(groupSockAddr2, networkInterface1);
@@ -562,7 +528,8 @@ public class MulticastSocketTest extends junit.framework.TestCase {
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 + "]");
+ fail("Did not get exception when trying to leave group on wrong interface " +
+ "joined on [" + networkInterface1 + "] left on [" + networkInterface2 + "]");
} catch (IOException expected) {
}
}
@@ -578,14 +545,11 @@ public class MulticastSocketTest extends junit.framework.TestCase {
private void test_sendLjava_net_DatagramPacketB(InetAddress group) throws Exception {
String msg = "Hello World";
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int groupPort = ports[0];
-
- MulticastSocket mss = new MulticastSocket(ports[1]);
- MulticastServer server = new MulticastServer(group, groupPort);
+ MulticastSocket mss = new MulticastSocket(0);
+ MulticastServer server = new MulticastServer(group, mss.getLocalPort());
server.start();
Thread.sleep(200);
- DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg.length(), group, groupPort);
+ DatagramPacket sdp = new DatagramPacket(msg.getBytes(), msg.length(), group, mss.getLocalPort());
mss.send(sdp, (byte) 10);
Thread.sleep(1000);
mss.close();
@@ -661,13 +625,9 @@ public class MulticastSocketTest extends junit.framework.TestCase {
Enumeration theInterfaces = NetworkInterface.getNetworkInterfaces();
while (theInterfaces.hasMoreElements()) {
NetworkInterface thisInterface = (NetworkInterface) theInterfaces.nextElement();
- if (thisInterface.getInetAddresses().hasMoreElements()) {
- if ((!((InetAddress) thisInterface.getInetAddresses().nextElement()).isLoopbackAddress())) {
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- int serverPort = ports[0];
- int groupPort = ports[1];
-
- MulticastServer server = new MulticastServer(group, serverPort);
+ if (thisInterface.getInetAddresses().hasMoreElements() && thisInterface.isUp()) {
+ if ((!(thisInterface.getInetAddresses().nextElement()).isLoopbackAddress())) {
+ MulticastServer server = new MulticastServer(group, 0);
server.start();
// give the server some time to start up
Thread.sleep(1000);
@@ -676,11 +636,12 @@ public class MulticastSocketTest extends junit.framework.TestCase {
// source address in the received packet
// should be one of the addresses for the interface
// set
- MulticastSocket mss = new MulticastSocket(groupPort);
+ MulticastSocket mss = new MulticastSocket(0);
mss.setNetworkInterface(thisInterface);
String msg = thisInterface.getName();
byte theBytes[] = msg.getBytes();
- DatagramPacket sdp = new DatagramPacket(theBytes, theBytes.length, group, serverPort);
+ DatagramPacket sdp = new DatagramPacket(theBytes, theBytes.length, group,
+ server.ms.getLocalPort());
mss.send(sdp);
Thread.sleep(1000);
String receivedMessage = new String(server.rdp.getData(), 0, server.rdp.getLength());
@@ -712,20 +673,20 @@ public class MulticastSocketTest extends junit.framework.TestCase {
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()));
+ ms.bind(null);
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()));
+ ms = new MulticastSocket(0);
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()));
+ ms = new MulticastSocket(0);
assertTrue("should be bound", ms.isBound() && !ms.isClosed() && !ms.isConnected());
ms.close();
assertTrue("should be closed", ms.isClosed());
try {
- ms = new MulticastSocket(new InetSocketAddress("unresolvedname", Support_PortManager.getNextPortForUDP()));
+ ms = new MulticastSocket(new InetSocketAddress("unresolvedname", 31415));
fail();
} catch (IOException expected) {
}
@@ -737,7 +698,7 @@ public class MulticastSocketTest extends junit.framework.TestCase {
}
public void test_getLoopbackMode() throws Exception {
- MulticastSocket ms = new MulticastSocket((SocketAddress) null);
+ MulticastSocket ms = new MulticastSocket(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());
@@ -764,17 +725,17 @@ public class MulticastSocketTest extends junit.framework.TestCase {
}
private void test_setLoopbackModeSendReceive(InetAddress group) throws IOException {
- final int PORT = Support_PortManager.getNextPortForUDP();
final String message = "Hello, world!";
// test send receive
- MulticastSocket socket = new MulticastSocket(PORT);
+ MulticastSocket socket = new MulticastSocket(0);
socket.setLoopbackMode(false); // false indicates doing loop back
socket.joinGroup(group);
// send the datagram
byte[] sendData = message.getBytes();
- DatagramPacket sendDatagram = new DatagramPacket(sendData, 0, sendData.length, new InetSocketAddress(group, PORT));
+ DatagramPacket sendDatagram = new DatagramPacket(sendData, 0, sendData.length,
+ new InetSocketAddress(group, socket.getLocalPort()));
socket.send(sendDatagram);
// receive the datagram
@@ -792,13 +753,14 @@ public class MulticastSocketTest extends junit.framework.TestCase {
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);
+ InetSocketAddress addr = new InetSocketAddress(Inet4Address.getLocalHost(), 0);
+ theSocket1.bind(addr);
+ addr = new InetSocketAddress(Inet4Address.getLocalHost(), theSocket1.getLocalPort());
+ theSocket2.bind(addr);
fail("No exception when trying to connect to do duplicate socket bind with re-useaddr set to false");
} catch (BindException expected) {
}
@@ -810,13 +772,14 @@ public class MulticastSocketTest extends junit.framework.TestCase {
}
// 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);
+ InetSocketAddress addr = new InetSocketAddress(Inet4Address.getLocalHost(), 0);
+ theSocket1.bind(addr);
+ addr = new InetSocketAddress(Inet4Address.getLocalHost(), theSocket1.getLocalPort());
+ theSocket2.bind(addr);
if (theSocket1 != null) {
theSocket1.close();
@@ -827,11 +790,12 @@ public class MulticastSocketTest extends junit.framework.TestCase {
// 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);
+ addr = new InetSocketAddress(Inet4Address.getLocalHost(), 0);
+ theSocket1.bind(addr);
+ addr = new InetSocketAddress(Inet4Address.getLocalHost(), theSocket1.getLocalPort());
+ theSocket2.bind(addr);
if (theSocket1 != null) {
theSocket1.close();
}
@@ -841,55 +805,52 @@ public class MulticastSocketTest extends junit.framework.TestCase {
}
@Override
- protected void setUp() {
- Enumeration theInterfaces = null;
- try {
- theInterfaces = NetworkInterface.getNetworkInterfaces();
- } catch (Exception e) {
- }
+ protected void setUp() throws Exception {
+ Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
// only consider interfaces that have addresses associated with them.
// Otherwise tests don't work so well
- if (theInterfaces != null) {
+ if ( interfaces != null) {
boolean atLeastOneInterface = false;
- while (theInterfaces.hasMoreElements() && (atLeastOneInterface == false)) {
- networkInterface1 = (NetworkInterface) theInterfaces.nextElement();
- if (networkInterface1.getInetAddresses().hasMoreElements()) {
+ while ( interfaces.hasMoreElements() && (atLeastOneInterface == false)) {
+ networkInterface1 = interfaces.nextElement();
+ if (isUpAndHasAddresses(networkInterface1)) {
atLeastOneInterface = true;
}
}
+
assertTrue(atLeastOneInterface);
atLeastTwoInterfaces = false;
- if (theInterfaces.hasMoreElements()) {
- while (theInterfaces.hasMoreElements() && (atLeastTwoInterfaces == false)) {
- networkInterface2 = (NetworkInterface) theInterfaces.nextElement();
- if (networkInterface2.getInetAddresses().hasMoreElements()) {
+ if ( interfaces.hasMoreElements()) {
+ while ( interfaces.hasMoreElements() && (atLeastTwoInterfaces == false)) {
+ networkInterface2 = interfaces.nextElement();
+ if (isUpAndHasAddresses(networkInterface2)) {
atLeastTwoInterfaces = true;
}
}
}
// first the first interface that supports IPV6 if one exists
- try {
- theInterfaces = NetworkInterface.getNetworkInterfaces();
- } catch (Exception e) {
- }
+ interfaces = NetworkInterface.getNetworkInterfaces();
+
boolean found = false;
- while (theInterfaces.hasMoreElements() && !found) {
- NetworkInterface nextInterface = (NetworkInterface) theInterfaces.nextElement();
- Enumeration addresses = nextInterface.getInetAddresses();
- if (addresses.hasMoreElements()) {
- while (addresses.hasMoreElements()) {
- InetAddress nextAddress = (InetAddress) addresses.nextElement();
- if (nextAddress instanceof Inet6Address) {
- IPV6networkInterface1 = nextInterface;
- found = true;
- break;
- }
+ while ( interfaces.hasMoreElements() && !found) {
+ NetworkInterface nextInterface = interfaces.nextElement();
+ Enumeration<InetAddress> addresses = nextInterface.getInetAddresses();
+ while (addresses.hasMoreElements()) {
+ final InetAddress nextAddress = addresses.nextElement();
+ if (nextAddress instanceof Inet6Address) {
+ IPV6networkInterface1 = nextInterface;
+ found = true;
+ break;
}
}
}
}
}
+
+ private static boolean isUpAndHasAddresses(NetworkInterface iface) throws IOException {
+ return iface.isUp() && iface.getInetAddresses().hasMoreElements();
+ }
}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ChannelsTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ChannelsTest.java
index e37fd0b..561d661 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ChannelsTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ChannelsTest.java
@@ -24,7 +24,6 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
-import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Channels;
@@ -36,9 +35,6 @@ import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
-
-import tests.support.Support_PortManager;
-
import junit.framework.TestCase;
/**
@@ -590,13 +586,11 @@ public class ChannelsTest extends TestCase {
*/
public void test_newReader_LReadableByteChannel_LString()
throws IOException {
- InetSocketAddress localAddr = new InetSocketAddress("127.0.0.1",
- Support_PortManager.getNextPort());
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr);
+ sc.connect(ssc.socket().getLocalSocketAddress());
sc.configureBlocking(false);
assertFalse(sc.isBlocking());
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/DatagramChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/DatagramChannelTest.java
index 0b94c39..0bdc3ff 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/DatagramChannelTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/DatagramChannelTest.java
@@ -20,7 +20,7 @@ package org.apache.harmony.tests.java.nio.channels;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
-import java.net.InetAddress;
+import java.net.Inet6Address;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
@@ -33,14 +33,11 @@ import java.nio.channels.NotYetConnectedException;
import java.nio.channels.UnresolvedAddressException;
import java.nio.channels.UnsupportedAddressTypeException;
import java.nio.channels.spi.SelectorProvider;
-import java.security.Permission;
-
import junit.framework.TestCase;
-import tests.support.Support_PortManager;
+import libcore.io.IoUtils;
/**
* Test for DatagramChannel
- *
*/
public class DatagramChannelTest extends TestCase {
@@ -56,64 +53,45 @@ public class DatagramChannelTest extends TestCase {
private static final int TIME_UNIT = 500;
- private InetSocketAddress localAddr1;
+ private InetSocketAddress datagramSocket1Address;
+ private InetSocketAddress datagramSocket2Address;
- private InetSocketAddress localAddr2;
+ private InetSocketAddress channel1Address;
+ private InetSocketAddress channel2Address;
private DatagramChannel channel1;
-
private DatagramChannel channel2;
private DatagramSocket datagramSocket1;
-
private DatagramSocket datagramSocket2;
- // The port to be used in test cases.
- private int testPort;
-
protected void setUp() throws Exception {
super.setUp();
- this.channel1 = DatagramChannel.open();
- this.channel2 = DatagramChannel.open();
- int[] ports = Support_PortManager.getNextPortsForUDP(5);
- this.localAddr1 = new InetSocketAddress("127.0.0.1", ports[0]);
- this.localAddr2 = new InetSocketAddress("127.0.0.1", ports[1]);
- this.datagramSocket1 = new DatagramSocket(ports[2]);
- this.datagramSocket2 = new DatagramSocket(ports[3]);
- testPort = ports[4];
+
+ channel1 = DatagramChannel.open();
+ channel2 = DatagramChannel.open();
+
+ channel1.socket().bind(new InetSocketAddress(Inet6Address.LOOPBACK, 0));
+ channel2.socket().bind(new InetSocketAddress(Inet6Address.LOOPBACK, 0));
+
+ channel1Address = (InetSocketAddress) channel1.socket().getLocalSocketAddress();
+ channel2Address = (InetSocketAddress) channel2.socket().getLocalSocketAddress();
+
+ this.datagramSocket1 = new DatagramSocket(0, Inet6Address.LOOPBACK);
+ this.datagramSocket2 = new DatagramSocket(0, Inet6Address.LOOPBACK);
+
+ datagramSocket1Address = (InetSocketAddress) datagramSocket1.getLocalSocketAddress();
+ datagramSocket2Address = (InetSocketAddress) datagramSocket2.getLocalSocketAddress();
}
protected void tearDown() throws Exception {
- if (null != this.channel1) {
- try {
- this.channel1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- if (null != this.channel2) {
- try {
- this.channel2.close();
- } catch (Exception e) {
- //ignore
- }
- }
- if (null != this.datagramSocket1) {
- try {
- this.datagramSocket1.close();
- } catch (Exception e) {
- //ignore
- }
- }
- if (null != this.datagramSocket2) {
- try {
- this.datagramSocket2.close();
- } catch (Exception e) {
- //ignore
- }
- }
- localAddr1 = null;
- localAddr2 = null;
+ IoUtils.closeQuietly(channel1);
+ IoUtils.closeQuietly(channel2);
+ IoUtils.closeQuietly(datagramSocket1);
+ IoUtils.closeQuietly(datagramSocket2);
+
+ datagramSocket1Address = null;
+ datagramSocket2Address = null;
super.tearDown();
}
@@ -151,7 +129,6 @@ public class DatagramChannelTest extends TestCase {
*/
public void testReadByteBufferArray() throws IOException {
final int testNum = 0;
- long readres = testNum;
MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider
.provider());
MockDatagramChannel testMocknull = new MockDatagramChannel(null);
@@ -163,6 +140,8 @@ public class DatagramChannelTest extends TestCase {
} catch (NullPointerException e) {
// correct
}
+
+ long readres;
try {
readres = testMock.read(readBuf);
fail("Should throw NPE");
@@ -173,9 +152,9 @@ public class DatagramChannelTest extends TestCase {
try {
readres = this.channel1.read(readBuf);
fail("Should throw NotYetConnectedException");
- } catch (NotYetConnectedException e) {
- // correct
+ } catch (NotYetConnectedException expected) {
}
+
readres = testMock.read(readBuf);
assertEquals(testNum, readres);
readres = testMocknull.read(readBuf);
@@ -194,20 +173,17 @@ public class DatagramChannelTest extends TestCase {
try {
this.channel1.read(readBuf);
fail("Should throw NPE");
- } catch (NullPointerException e) {
- // correct
+ } catch (NullPointerException expected) {
}
try {
testMock.read(readBuf);
fail("Should throw NPE");
- } catch (NullPointerException e) {
- // correct
+ } catch (NullPointerException expected) {
}
try {
testMocknull.read(readBuf);
fail("Should throw NPE");
- } catch (NullPointerException e) {
- // correct
+ } catch (NullPointerException expected) {
}
}
@@ -284,11 +260,13 @@ public class DatagramChannelTest extends TestCase {
*
* @throws SocketException
*/
- public void testSocket_BasicStatusBeforeConnect() throws SocketException {
- assertFalse(this.channel1.isConnected());// not connected
- DatagramSocket s1 = this.channel1.socket();
+ public void testSocket_BasicStatusBeforeConnect() throws Exception {
+ final DatagramChannel dc = DatagramChannel.open();
+
+ assertFalse(dc.isConnected());// not connected
+ DatagramSocket s1 = dc.socket();
assertSocketBeforeConnect(s1);
- DatagramSocket s2 = this.channel1.socket();
+ DatagramSocket s2 = dc.socket();
// same
assertSame(s1, s2);
}
@@ -299,21 +277,25 @@ public class DatagramChannelTest extends TestCase {
* @throws IOException
*/
public void testSocket_Block_BasicStatusAfterConnect() throws IOException {
- this.channel1.connect(localAddr1);
- DatagramSocket s1 = this.channel1.socket();
+ final DatagramChannel dc = DatagramChannel.open();
+
+ dc.connect(datagramSocket1Address);
+ DatagramSocket s1 = dc.socket();
assertSocketAfterConnect(s1);
- DatagramSocket s2 = this.channel1.socket();
+ DatagramSocket s2 = dc.socket();
// same
assertSame(s1, s2);
}
public void testSocket_NonBlock_BasicStatusAfterConnect()
throws IOException {
- this.channel1.connect(localAddr1);
- this.channel1.configureBlocking(false);
- DatagramSocket s1 = this.channel1.socket();
+ final DatagramChannel dc = DatagramChannel.open();
+ dc.connect(datagramSocket1Address);
+ dc.configureBlocking(false);
+
+ DatagramSocket s1 = dc.socket();
assertSocketAfterConnect(s1);
- DatagramSocket s2 = this.channel1.socket();
+ DatagramSocket s2 = dc.socket();
// same
assertSame(s1, s2);
}
@@ -336,13 +318,13 @@ public class DatagramChannelTest extends TestCase {
*/
public void testSocket_Block_ActionsAfterConnect() throws IOException {
assertFalse(this.channel1.isConnected());// not connected
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
DatagramSocket s = this.channel1.socket();
assertSocketActionAfterConnect(s);
}
public void testSocket_NonBlock_ActionsAfterConnect() throws IOException {
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
this.channel1.configureBlocking(false);
DatagramSocket s = this.channel1.socket();
assertSocketActionAfterConnect(s);
@@ -375,14 +357,12 @@ public class DatagramChannelTest extends TestCase {
assertTrue(s.isConnected());
assertFalse(s.getBroadcast());
assertFalse(s.getReuseAddress());
- assertSame(s.getInetAddress(), localAddr1.getAddress());
- assertEquals(s.getLocalAddress(), localAddr1.getAddress());
assertNotNull(s.getLocalSocketAddress());
- assertEquals(s.getPort(), localAddr1.getPort());
+ assertEquals(s.getPort(), datagramSocket1Address.getPort());
assertTrue(s.getReceiveBufferSize() >= 8192);
// not same , but equals
- assertNotSame(s.getRemoteSocketAddress(), (SocketAddress) localAddr1);
- assertEquals(s.getRemoteSocketAddress(), (SocketAddress) localAddr1);
+ assertNotSame(s.getRemoteSocketAddress(), datagramSocket1Address);
+ assertEquals(s.getRemoteSocketAddress(), datagramSocket1Address);
assertFalse(s.getReuseAddress());
assertTrue(s.getSendBufferSize() >= 8192);
assertEquals(s.getSoTimeout(), 0);
@@ -391,7 +371,7 @@ public class DatagramChannelTest extends TestCase {
private void assertSocketActionBeforeConnect(DatagramSocket s)
throws IOException {
- s.connect(localAddr2);
+ s.connect(datagramSocket2Address);
assertFalse(this.channel1.isConnected());
assertFalse(s.isConnected());
@@ -406,12 +386,12 @@ public class DatagramChannelTest extends TestCase {
private void assertSocketActionAfterConnect(DatagramSocket s)
throws IOException {
- assertEquals(s.getPort(), localAddr1.getPort());
- s.connect(localAddr2);
+ assertEquals(s.getPort(), datagramSocket1Address.getPort());
+ s.connect(datagramSocket2Address);
assertTrue(this.channel1.isConnected());
assertTrue(s.isConnected());
// not changed
- assertEquals(s.getPort(), localAddr1.getPort());
+ assertEquals(s.getPort(), datagramSocket1Address.getPort());
s.disconnect();
assertFalse(this.channel1.isConnected());
@@ -423,29 +403,6 @@ public class DatagramChannelTest extends TestCase {
}
// -------------------------------------------------------------------
- // Test for configureBlocking()
- // -------------------------------------------------------------------
-
- public void testConfigureBlocking_Read() throws Exception {
- assertTrue(this.channel1.isBlocking());
- ByteBuffer buf = ByteBuffer.allocate(CAPACITY_1KB);
- new Thread() {
- public void run() {
- try {
- sleep(TIME_UNIT * 5);
- channel1.configureBlocking(false);
- assertFalse(channel1.isBlocking());
- datagramSocket1.close();
- } catch (Exception e) {
- // do nothing
- }
- }
- }.start();
- SocketAddress addr = channel1.receive(buf);
- assertNull(addr);
- }
-
- // -------------------------------------------------------------------
// Test for isConnected()
// -------------------------------------------------------------------
@@ -572,7 +529,7 @@ public class DatagramChannelTest extends TestCase {
this.channel1.close();
assertFalse(this.channel1.isOpen());
try {
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
fail("Should throw ClosedChannelException."); //$NON-NLS-1$
} catch (ClosedChannelException e) {
// OK.
@@ -587,11 +544,11 @@ public class DatagramChannelTest extends TestCase {
*/
public void testConnect_IllegalStateException() throws IOException {
assertFalse(this.channel1.isConnected());
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
assertTrue(this.channel1.isConnected());
// connect after connected.
try {
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
fail("Should throw IllegalStateException."); //$NON-NLS-1$
} catch (IllegalStateException e) {
// OK.
@@ -606,14 +563,14 @@ public class DatagramChannelTest extends TestCase {
*/
public void testConnect_CheckOpenBeforeStatus() throws IOException {
assertFalse(this.channel1.isConnected());
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
assertTrue(this.channel1.isConnected());
// connect after connected.
this.channel1.close();
assertFalse(this.channel1.isOpen());
// checking open is before checking status.
try {
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
fail("Should throw ClosedChannelException."); //$NON-NLS-1$
} catch (ClosedChannelException e) {
// OK.
@@ -636,7 +593,7 @@ public class DatagramChannelTest extends TestCase {
private void connectLocalServer() throws IOException {
assertFalse(this.channel1.isConnected());
assertTrue(this.datagramSocket1.isBound());
- assertSame(this.channel1, this.channel1.connect(localAddr1));
+ assertSame(this.channel1, this.channel1.connect(datagramSocket1Address));
assertTrue(this.channel1.isConnected());
}
@@ -644,7 +601,7 @@ public class DatagramChannelTest extends TestCase {
assertFalse(this.channel1.isConnected());
this.datagramSocket1.close();
assertTrue(this.datagramSocket1.isClosed());
- assertSame(this.channel1, this.channel1.connect(localAddr1));
+ assertSame(this.channel1, this.channel1.connect(datagramSocket1Address));
assertTrue(this.channel1.isConnected());
}
@@ -785,43 +742,38 @@ public class DatagramChannelTest extends TestCase {
assertNull(this.channel1.receive(dst));
}
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- public void testReceive_UnconnectedBufZero() throws Exception {
- assertFalse(this.channel1.isConnected());
+ public void testReceive_UnboundBufZero() throws Exception {
+ DatagramChannel dc = DatagramChannel.open();
+
+ assertFalse(dc.isConnected());
+ assertFalse(dc.socket().isBound());
ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ZERO);
- assertNull(this.channel1.receive(dst));
+ assertNull(dc.receive(dst));
}
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- public void testReceive_UnconnectedBufNotEmpty() throws Exception {
- assertFalse(this.channel1.isConnected());
+ public void testReceive_UnboundBufNotEmpty() throws Exception {
+ DatagramChannel dc = DatagramChannel.open();
+ assertFalse(dc.isConnected());
+ assertFalse(dc.socket().isBound());
+
ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
// buf is not empty
dst.put((byte) 88);
assertEquals(dst.position() + CAPACITY_NORMAL - 1, dst.limit());
- assertNull(this.channel1.receive(dst));
+ assertNull(dc.receive(dst));
}
- /**
- * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
- *
- * @throws Exception
- */
- public void testReceive_UnconnectedBufFull() throws Exception {
- assertFalse(this.channel1.isConnected());
+ public void testReceive_UnboundBufFull() throws Exception {
+ DatagramChannel dc = DatagramChannel.open();
+
+ assertFalse(dc.isConnected());
+ assertFalse(dc.socket().isBound());
ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ONE);
+
// buf is full
dst.put((byte) 88);
assertEquals(dst.position(), dst.limit());
- assertNull(this.channel1.receive(dst));
+ assertNull(dc.receive(dst));
}
/**
@@ -1141,21 +1093,21 @@ public class DatagramChannelTest extends TestCase {
*/
public void testSend_NoServerBlockingCommon() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- sendDataBlocking(localAddr1, writeBuf);
+ sendDataBlocking(datagramSocket1Address, writeBuf);
}
public void testSend_NoServerNonblockingCommon() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- sendDataNonBlocking(localAddr1, writeBuf);
+ sendDataNonBlocking(datagramSocket1Address, writeBuf);
}
public void testSend_NoServerTwice() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- sendDataBlocking(localAddr1, writeBuf);
+ sendDataBlocking(datagramSocket1Address, writeBuf);
// can not buffer twice!
- assertEquals(0, this.channel1.send(writeBuf, localAddr1));
+ assertEquals(0, this.channel1.send(writeBuf, datagramSocket1Address));
try {
- channel1.send(writeBuf, localAddr2);
+ channel1.send(writeBuf, datagramSocket2Address);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// correct
@@ -1164,11 +1116,11 @@ public class DatagramChannelTest extends TestCase {
public void testSend_NoServerNonBlockingTwice() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- sendDataNonBlocking(localAddr1, writeBuf);
+ sendDataNonBlocking(datagramSocket1Address, writeBuf);
// can not buffer twice!
- assertEquals(0, this.channel1.send(writeBuf, localAddr1));
+ assertEquals(0, this.channel1.send(writeBuf, datagramSocket1Address));
try {
- channel1.send(writeBuf, localAddr2);
+ channel1.send(writeBuf, datagramSocket2Address);
fail("Should throw IllegalArgumentException");
} catch (IllegalArgumentException e) {
// correct
@@ -1177,7 +1129,7 @@ public class DatagramChannelTest extends TestCase {
public void testSend_NoServerBufNull() throws IOException {
try {
- sendDataBlocking(localAddr1, null);
+ sendDataBlocking(datagramSocket1Address, null);
fail("Should throw a NPE here.");
} catch (NullPointerException e) {
// correct
@@ -1187,14 +1139,14 @@ public class DatagramChannelTest extends TestCase {
public void testSend_NoServerBufNullTwice() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
try {
- sendDataBlocking(localAddr1, null);
+ sendDataBlocking(datagramSocket1Address, null);
fail("Should throw a NPE here.");
} catch (NullPointerException e) {
// correct
}
- sendDataBlocking(localAddr1, writeBuf);
+ sendDataBlocking(datagramSocket1Address, writeBuf);
try {
- channel1.send(null, localAddr2);
+ channel1.send(null, datagramSocket2Address);
fail("Should throw NPE");
} catch (NullPointerException e) {
// correct
@@ -1219,7 +1171,7 @@ public class DatagramChannelTest extends TestCase {
} catch (NullPointerException e) {
// correct
}
- sendDataBlocking(localAddr1, writeBuf);
+ sendDataBlocking(datagramSocket1Address, writeBuf);
try {
channel1.send(writeBuf, null);
fail("Should throw NPE");
@@ -1233,62 +1185,47 @@ public class DatagramChannelTest extends TestCase {
// -------------------------------------------------------------------
public void testReceiveSend_Block_Normal() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByChannel("some normal string in testReceiveSend_Normal",
- localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2,
+ sendOnChannel2("some normal string in testReceiveSend_Normal",
+ channel1Address);
+ receiveOnChannel1AndClose(CAPACITY_NORMAL, channel2Address,
"some normal string in testReceiveSend_Normal");
}
- public void testReceiveSend_Block_NotBound() throws Exception {
- // not bound
- sendByChannel("some normal string in testReceiveSend_Normal",
- localAddr2);
- ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
- assertNull(channel1.receive(buf));
- assertFalse(channel1.socket().isBound());
- }
-
public void testReceiveSend_NonBlock_NotBound() throws Exception {
// not bound
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- sendByChannel("some normal string in testReceiveSend_Normal",
- localAddr2);
+ sendOnChannel2("some normal string in testReceiveSend_Normal",
+ datagramSocket2Address);
ByteBuffer buf = ByteBuffer.wrap(new byte[CAPACITY_NORMAL]);
- assertNull((InetSocketAddress) this.channel1.receive(buf));
+ assertNull(this.channel1.receive(buf));
}
public void testReceiveSend_Block_Normal_S2C() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByDatagramSocket(
- "some normal string in testReceiveSend_Normal_S2C", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2,
+ sendOnDatagramSocket1(
+ "some normal string in testReceiveSend_Normal_S2C", channel1Address);
+ receiveOnChannel1AndClose(CAPACITY_NORMAL, datagramSocket1Address,
"some normal string in testReceiveSend_Normal_S2C");
}
public void testReceiveSend_Block_Normal_C2S() throws Exception {
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
String str1 = "some normal string in testReceiveSend_Normal_C2S";
- sendByChannel(str1, localAddr2);
- receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, str1);
+ sendOnChannel2(str1, datagramSocket1Address);
+ receiveOnDatagramSocket1(CAPACITY_NORMAL, str1);
}
public void testReceiveSend_NonBlock_Normal_C2S() throws Exception {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
String str1 = "some normal string in testReceiveSend_Normal_C2S";
- sendByChannel(str1, localAddr2);
- receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, str1);
+ sendOnChannel2(str1, datagramSocket1Address);
+ receiveOnDatagramSocket1(CAPACITY_NORMAL, str1);
}
public void testReceiveSend_Normal_S2S() throws Exception {
String msg = "normal string in testReceiveSend_Normal_S2S";
- this.datagramSocket1 = new DatagramSocket(testPort);
DatagramPacket rdp = new DatagramPacket(msg.getBytes(), msg.length(),
- localAddr2);
- datagramSocket2 = new DatagramSocket(localAddr2.getPort());
+ datagramSocket2Address);
this.datagramSocket1.send(rdp);
byte[] buf = new byte[CAPACITY_NORMAL];
this.datagramSocket2.setSoTimeout(TIME_UNIT);
@@ -1298,53 +1235,45 @@ public class DatagramChannelTest extends TestCase {
}
public void testReceiveSend_Block_Empty() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByChannel("", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
+ sendOnChannel2("", channel1Address);
+ receiveOnChannel1AndClose(CAPACITY_NORMAL, channel2Address, "");
}
public void testReceiveSend_NonBlock_Empty() throws Exception {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- this.channel1.socket().bind(localAddr2);
- sendByChannel("", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
+ sendOnChannel2("", channel1Address);
+ receiveOnChannel1AndClose(CAPACITY_NORMAL, channel2Address, "");
}
public void testReceiveSend_Block_Empty_S2C() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByDatagramSocket("", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
+ sendOnDatagramSocket1("", channel1Address);
+ receiveOnChannel1AndClose(CAPACITY_NORMAL, datagramSocket1Address, "");
}
public void testReceiveSend_NonBlock_Empty_S2C() throws Exception {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- this.channel1.socket().bind(localAddr2);
- sendByDatagramSocket("", localAddr2);
- receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
+ sendOnDatagramSocket1("", channel1Address);
+ receiveOnChannel1AndClose(CAPACITY_NORMAL, datagramSocket1Address, "");
}
public void testReceiveSend_Block_Empty_C2S() throws Exception {
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- sendByChannel("", localAddr2);
- receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, "");
+ sendOnChannel2("", datagramSocket1Address);
+ receiveOnDatagramSocket1(CAPACITY_NORMAL, "");
}
public void testReceiveSend_NonBlock_Empty_C2S() throws Exception {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- sendByChannel("", localAddr2);
- receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, "");
+ sendOnChannel2("", datagramSocket1Address);
+ receiveOnDatagramSocket1(CAPACITY_NORMAL, "");
}
public void testReceiveSend_Empty_S2S() throws Exception {
String msg = "";
- this.datagramSocket1 = new DatagramSocket(testPort);
DatagramPacket rdp = new DatagramPacket(msg.getBytes(), msg.length(),
- localAddr2);
- datagramSocket2 = new DatagramSocket(localAddr2.getPort());
+ datagramSocket2Address);
this.datagramSocket1.send(rdp);
byte[] buf = new byte[CAPACITY_NORMAL];
this.datagramSocket2.setSoTimeout(TIME_UNIT);
@@ -1354,29 +1283,25 @@ public class DatagramChannelTest extends TestCase {
}
public void testReceiveSend_Block_Oversize() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByChannel("0123456789", localAddr2);
- receiveByChannel(5, localAddr2, "01234");
+ sendOnChannel2("0123456789", channel1Address);
+ receiveOnChannel1AndClose(5, channel2Address, "01234");
}
public void testReceiveSend_Block_Oversize_C2S() throws Exception {
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- sendByChannel("0123456789", localAddr2);
- receiveByDatagramSocket(5, localAddr2, "01234");
+ sendOnChannel2("0123456789", datagramSocket1Address);
+ receiveOnDatagramSocket1(5, "01234");
}
public void testReceiveSend_NonBlock_Oversize_C2S() throws Exception {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
- sendByChannel("0123456789", localAddr2);
- receiveByDatagramSocket(5, localAddr2, "01234");
+ sendOnChannel2("0123456789", datagramSocket1Address);
+ receiveOnDatagramSocket1(5, "01234");
}
public void testReceiveSend_Block_Oversize_S2C() throws Exception {
- this.channel1.socket().bind(localAddr2);
- sendByDatagramSocket("0123456789", localAddr2);
- receiveByChannel(5, localAddr2, "01234");
+ sendOnDatagramSocket1("0123456789", channel1Address);
+ receiveOnChannel1AndClose(5, datagramSocket1Address, "01234");
}
public void testReceiveSend_8K() throws Exception {
@@ -1385,9 +1310,9 @@ public class DatagramChannelTest extends TestCase {
str8k.append('a');
}
String str = str8k.toString();
- this.channel1.socket().bind(localAddr2);
- sendByChannel(str, localAddr2);
- receiveByChannel(8 * CAPACITY_1KB, localAddr2, str);
+
+ sendOnChannel2(str, channel1Address);
+ receiveOnChannel1AndClose(8 * CAPACITY_1KB, channel2Address, str);
}
public void testReceiveSend_64K() throws Exception {
@@ -1398,56 +1323,44 @@ public class DatagramChannelTest extends TestCase {
String str = str64k.toString();
try {
Thread.sleep(TIME_UNIT);
- channel2.send(ByteBuffer.wrap(str.getBytes()), localAddr1);
+ channel2.send(ByteBuffer.wrap(str.getBytes()), datagramSocket1Address);
fail("Should throw SocketException!");
} catch (SocketException e) {
//expected
}
}
- private void sendByChannel(String data, InetSocketAddress address)
- throws Exception {
- try {
- assertEquals(data.length(), this.channel2.send(ByteBuffer.wrap(data
- .getBytes()), address));
- } finally {
- this.channel2.close();
- }
+ private void sendOnChannel2(String data, SocketAddress address)
+ throws IOException {
+ assertEquals(data.length(), channel2.send(ByteBuffer.wrap(data.getBytes()), address));
}
- private void sendByDatagramSocket(String data, InetSocketAddress address)
+ private void sendOnDatagramSocket1(String data, InetSocketAddress address)
throws Exception {
- this.datagramSocket1 = new DatagramSocket(testPort);
- DatagramPacket rdp = new DatagramPacket(data.getBytes(), data.length(),
- address);
+ DatagramPacket rdp = new DatagramPacket(data.getBytes(), data.length(), address);
this.datagramSocket1.send(rdp);
}
- private void receiveByChannel(int bufSize, InetSocketAddress address,
- String expectedString) throws IOException {
+ private void receiveOnChannel1AndClose(int bufSize,
+ InetSocketAddress expectedAddress, String expectedString) throws IOException {
try {
ByteBuffer buf = ByteBuffer.wrap(new byte[bufSize]);
- InetSocketAddress returnAddr = null;
+ InetSocketAddress senderAddr = null;
long startTime = System.currentTimeMillis();
do {
- returnAddr = (InetSocketAddress) this.channel1.receive(buf);
+ senderAddr = (InetSocketAddress) this.channel1.receive(buf);
// continue loop when channel1 is non-blocking and no data was
// received.
- if (channel1.isBlocking() || null != returnAddr) {
+ if (channel1.isBlocking() || senderAddr != null) {
break;
}
// avoid dead loop
assertTimeout(startTime, 10000);
} while (true);
- int length = returnAddr.getAddress().getAddress().length;
- for (int i = 0; i < length; i++) {
- assertEquals(returnAddr.getAddress().getAddress()[i],
- InetAddress.getByName("127.0.0.1").getAddress()[i]);
- }
- // port is NOT equal
- assertFalse(returnAddr.getPort() == address.getPort());
- assertEquals(new String(buf.array(), 0, bufSize).trim(),
- expectedString);
+
+ assertEquals(senderAddr.getAddress(), Inet6Address.LOOPBACK);
+ assertEquals(expectedAddress.getPort(), senderAddr.getPort());
+ assertEquals(new String(buf.array(), 0, buf.position()), expectedString);
} finally {
this.channel1.close();
}
@@ -1464,8 +1377,7 @@ public class DatagramChannelTest extends TestCase {
}
}
- private void receiveByDatagramSocket(int bufSize,
- InetSocketAddress address, String expectedString)
+ private void receiveOnDatagramSocket1(int bufSize, String expectedString)
throws IOException {
byte[] buf = new byte[bufSize];
this.datagramSocket1.setSoTimeout(6000);
@@ -1474,28 +1386,27 @@ public class DatagramChannelTest extends TestCase {
assertEquals(new String(buf, 0, bufSize).trim(), expectedString);
}
- public void testRead_NoSecurity() throws Exception {
+ public void testRead_fromSend() throws Exception {
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
String strHello = "hello";
- localAddr1 = new InetSocketAddress("127.0.0.1", testPort);
- this.channel1.socket().bind(localAddr1);
- this.channel2.socket().bind(localAddr2);
- this.channel1.connect(localAddr2);
- this.channel2.send(ByteBuffer.wrap(strHello.getBytes()), localAddr1);
+
+ this.channel1.connect(channel2Address);
+ this.channel2.send(ByteBuffer.wrap(strHello.getBytes()), channel1Address);
+
assertEquals(strHello.length(), this.channel1.read(buf));
assertAscii(buf, strHello);
}
public void testReceive_Peek_NoSecurity_Nonblocking() throws Exception {
String strHello = "hello";
- localAddr1 = new InetSocketAddress("127.0.0.1", testPort);
- this.channel1.socket().bind(localAddr1);
- sendByChannel(strHello, localAddr1);
+
+ sendOnChannel2(strHello, channel1Address);
this.channel1.configureBlocking(false);
// for accepted addr, no problem.
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
+
InetSocketAddress source = (InetSocketAddress) this.channel1.receive(buf);
- assertEquals(localAddr1.getAddress(), source.getAddress());
+ assertEquals(channel2Address, source);
assertAscii(buf, strHello);
}
@@ -1532,18 +1443,18 @@ public class DatagramChannelTest extends TestCase {
*/
public void testWriteByteBuffer_Block() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- connectWriteBuf(localAddr1, writeBuf);
+ connectWriteBuf(datagramSocket1Address, writeBuf);
}
public void testWriteByteBuffer_NonBlock() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
this.channel1.configureBlocking(false);
- connectWriteBuf(localAddr1, writeBuf);
+ connectWriteBuf(datagramSocket1Address, writeBuf);
}
public void testWriteByteBuffer_Block_closed() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
noconnectWrite(writeBuf);
this.channel1.connect(ipAddr);
assertTrue(this.channel1.isConnected());
@@ -1558,7 +1469,7 @@ public class DatagramChannelTest extends TestCase {
public void testWriteByteBuffer_NonBlock_closed() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
// non block mode
this.channel1.configureBlocking(false);
noconnectWrite(writeBuf);
@@ -1575,7 +1486,7 @@ public class DatagramChannelTest extends TestCase {
public void testWriteByteBuffer_Block_BufNull() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(0);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
try {
this.channel1.write((ByteBuffer) null);
fail("Should throw NPE.");
@@ -1602,7 +1513,7 @@ public class DatagramChannelTest extends TestCase {
public void testWriteByteBuffer_NonBlock_BufNull() throws IOException {
ByteBuffer writeBuf = ByteBuffer.allocateDirect(0);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
// non block mode
this.channel1.configureBlocking(false);
@@ -1638,7 +1549,7 @@ public class DatagramChannelTest extends TestCase {
ByteBuffer[] writeBuf = new ByteBuffer[2];
writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
try {
this.channel1.write(writeBuf, 0, 2);
fail("Should throw NotYetConnectedException.");
@@ -1657,7 +1568,7 @@ public class DatagramChannelTest extends TestCase {
ByteBuffer[] writeBuf = new ByteBuffer[2];
writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
// non-block mode
this.channel1.configureBlocking(false);
try {
@@ -1679,7 +1590,7 @@ public class DatagramChannelTest extends TestCase {
ByteBuffer[] writeBuf = new ByteBuffer[2];
writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
try {
this.channel1.write(writeBuf, -1, 2);
fail("should throw IndexOutOfBoundsException");
@@ -1704,7 +1615,7 @@ public class DatagramChannelTest extends TestCase {
ByteBuffer[] writeBuf = new ByteBuffer[2];
writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
this.channel1.connect(ipAddr);
assertTrue(this.channel1.isConnected());
try {
@@ -1746,7 +1657,7 @@ public class DatagramChannelTest extends TestCase {
throws IOException {
ByteBuffer[] writeBuf = new ByteBuffer[2];
writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
this.channel1.connect(ipAddr);
assertTrue(this.channel1.isConnected());
try {
@@ -1785,7 +1696,7 @@ public class DatagramChannelTest extends TestCase {
} catch (NotYetConnectedException e) {
// correct
}
- this.channel1.connect(localAddr1);
+ this.channel1.connect(datagramSocket1Address);
assertTrue(this.channel1.isConnected());
this.channel1.configureBlocking(false);
// note : blocking-mode will make the read process endless!
@@ -1801,7 +1712,7 @@ public class DatagramChannelTest extends TestCase {
public void testReadByteBuffer_bufNull() throws IOException {
ByteBuffer readBuf = ByteBuffer.allocateDirect(0);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
try {
this.channel1.read(readBuf);
fail("should throw NotYetConnectedException");
@@ -1829,7 +1740,7 @@ public class DatagramChannelTest extends TestCase {
ByteBuffer[] readBuf = new ByteBuffer[2];
readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
try {
this.channel1.read(readBuf, 0, 2);
fail("should throw NotYetConnectedException");
@@ -1867,7 +1778,7 @@ public class DatagramChannelTest extends TestCase {
public void testReadByteBufferArrayIntInt_BufNull() throws IOException {
ByteBuffer[] readBuf = new ByteBuffer[2];
readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
- InetSocketAddress ipAddr = localAddr1;
+ InetSocketAddress ipAddr = datagramSocket1Address;
try {
this.channel1.read(null, 0, 0);
fail("should throw NPE");
@@ -1904,26 +1815,37 @@ public class DatagramChannelTest extends TestCase {
// test read and write
// -------------------------------------------------------------------
- public void testReadWrite_configureBlock() throws Exception {
+ public static class A {
+ protected int z;
+ }
+
+ public static class B extends A {
+ protected int z;
+
+ void foo() {
+ super.z+=1;
+ }
+ }
+
+
+ public void testReadWrite_asyncClose() throws Exception {
byte[] targetArray = new byte[2];
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
+ channel2.connect(channel1Address);
+ channel1.connect(channel2Address);
+
new Thread() {
public void run() {
try {
Thread.sleep(TIME_UNIT);
- channel1.configureBlocking(false);
channel1.close();
} catch (Exception e) {
//ignore
}
}
}.start();
+
try {
this.channel1.read(targetBuf);
fail("should throw AsynchronousCloseException");
@@ -1935,11 +1857,9 @@ public class DatagramChannelTest extends TestCase {
public void testReadWrite_Block_Zero() throws Exception {
byte[] sourceArray = new byte[0];
byte[] targetArray = new byte[0];
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -1959,11 +1879,8 @@ public class DatagramChannelTest extends TestCase {
sourceArray[i] = (byte) i;
}
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
readWriteReadData(this.channel1, sourceArray, this.channel2,
targetArray, CAPACITY_NORMAL, "testReadWrite_Block_Normal");
@@ -1974,12 +1891,8 @@ public class DatagramChannelTest extends TestCase {
byte[] sourceArray = "".getBytes();
byte[] targetArray = new byte[CAPACITY_NORMAL];
- // bind and connect
-
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -1996,12 +1909,8 @@ public class DatagramChannelTest extends TestCase {
byte[] sourceArray = "".getBytes();
byte[] targetArray = new byte[CAPACITY_NORMAL];
- // bind and connect
-
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -2039,11 +1948,8 @@ public class DatagramChannelTest extends TestCase {
sourceArray[i] = (byte) i;
}
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
readWriteReadData(this.channel1, sourceArray, this.channel2,
targetArray, 8 * CAPACITY_1KB, "testReadWrite_Block_8KB");
@@ -2089,18 +1995,14 @@ public class DatagramChannelTest extends TestCase {
sourceArray[i] = (byte) i;
}
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
try {
channel1.write(sourceBuf);
fail("Should throw IOException");
- } catch (IOException e) {
+ } catch (IOException expected) {
// too big
}
}
@@ -2112,11 +2014,8 @@ public class DatagramChannelTest extends TestCase {
sourceArray[i] = (byte) i;
}
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr1);// the different addr
+ this.channel1.connect(channel1.socket().getLocalSocketAddress());
+ this.channel2.connect(datagramSocket1Address); // the different addr
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -2129,35 +2028,39 @@ public class DatagramChannelTest extends TestCase {
closeBlockedReaderChannel2(targetBuf);
}
- public void testReadWrite_Block_WriterNotBind() throws Exception {
+ public void testReadWrite_Block_WriterNotBound() throws Exception {
byte[] sourceArray = new byte[CAPACITY_NORMAL];
byte[] targetArray = new byte[CAPACITY_NORMAL];
for (int i = 0; i < sourceArray.length; i++) {
sourceArray[i] = (byte) i;
}
- // bind and connect
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ DatagramChannel dc = DatagramChannel.open();
+ // The writer isn't bound, but is connected.
+ dc.connect(channel1Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
+ assertEquals(CAPACITY_NORMAL, dc.write(sourceBuf));
+
+ // Connect channel2 after data has been written.
+ channel2.connect(dc.socket().getLocalSocketAddress());
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
closeBlockedReaderChannel2(targetBuf);
}
- public void testReadWrite_Block_WriterBindLater() throws Exception {
+ // NOTE: The original harmony test tested that things still work
+ // if there's no socket bound at the the address we're connecting to.
+ //
+ // It isn't really feasible to implement that in a non-racy way.
+ public void testReadWrite_Block_WriterConnectLater() throws Exception {
byte[] targetArray = new byte[CAPACITY_NORMAL];
- // bind and connect
- // writer channel1 is bound later
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ // The reader is bound & connected to channel1.
+ channel2.connect(channel1Address);
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
@@ -2170,8 +2073,8 @@ public class DatagramChannelTest extends TestCase {
for (int i = 0; i < sourceArray.length; i++) {
sourceArray[i] = (byte) i;
}
- channel1.socket().bind(localAddr2);
- channel1.connect(localAddr1);
+
+ channel1.connect(channel2Address);
// write later
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
assertEquals(CAPACITY_NORMAL, channel1.write(sourceBuf));
@@ -2184,6 +2087,7 @@ public class DatagramChannelTest extends TestCase {
int count = 0;
int total = 0;
long beginTime = System.currentTimeMillis();
+
while (total < CAPACITY_NORMAL && (count = channel2.read(targetBuf)) != -1) {
total = total + count;
// 3s timeout to avoid dead loop
@@ -2199,21 +2103,21 @@ public class DatagramChannelTest extends TestCase {
for (int i = 0; i < targetArray.length; i++) {
assertEquals(targetArray[i], (byte) i);
}
-
}
- public void testReadWrite_Block_ReaderNotBind() throws Exception {
+ // NOTE: The original harmony test tested that things still work
+ // if there's no socket bound at the the address we're connecting to.
+ //
+ // It isn't really feasible to implement that in a non-racy way.
+ public void testReadWrite_Block_ReaderNotConnected() throws Exception {
byte[] sourceArray = new byte[CAPACITY_NORMAL];
byte[] targetArray = new byte[CAPACITY_NORMAL];
for (int i = 0; i < sourceArray.length; i++) {
sourceArray[i] = (byte) i;
}
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- // reader channel2 is not bound
- this.channel2.connect(localAddr2);
+ // reader channel2 is not connected.
+ this.channel1.connect(channel2Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -2221,24 +2125,29 @@ public class DatagramChannelTest extends TestCase {
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- closeBlockedReaderChannel2(targetBuf);
-
+ try {
+ this.channel2.read(targetBuf);
+ fail();
+ } catch (NotYetConnectedException expected) {
+ }
}
private void closeBlockedReaderChannel2(ByteBuffer targetBuf)
throws IOException {
+ assertTrue(this.channel2.isBlocking());
+
new Thread() {
public void run() {
try {
Thread.sleep(TIME_UNIT);
- channel2.close();
- } catch (Exception e) {
- // do nothing
+ } catch (InterruptedException ie) {
+ fail();
}
+ IoUtils.closeQuietly(channel2);
}
}.start();
+
try {
- assertTrue(this.channel2.isBlocking());
this.channel2.read(targetBuf);
fail("Should throw AsynchronousCloseException");
} catch (AsynchronousCloseException e) {
@@ -2259,11 +2168,8 @@ public class DatagramChannelTest extends TestCase {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
readWriteReadData(this.channel1, sourceArray, this.channel2,
targetArray, CAPACITY_NORMAL, "testReadWrite_NonBlock_Normal");
@@ -2280,10 +2186,8 @@ public class DatagramChannelTest extends TestCase {
this.channel2.configureBlocking(false);
// bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
readWriteReadData(this.channel1, sourceArray, this.channel2,
targetArray, 8 * CAPACITY_1KB, "testReadWrite_NonBlock_8KB");
@@ -2299,11 +2203,8 @@ public class DatagramChannelTest extends TestCase {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr1);// the different addr
+ channel1.connect(channel2Address);
+ channel2.connect(datagramSocket1Address);// the different addr
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -2314,31 +2215,37 @@ public class DatagramChannelTest extends TestCase {
assertEquals(0, this.channel2.read(targetBuf));
}
- public void testReadWrite_NonBlock_WriterNotBind() throws Exception {
+
+ public void testReadWrite_NonBlock_WriterNotBound() throws Exception {
byte[] sourceArray = new byte[CAPACITY_NORMAL];
byte[] targetArray = new byte[CAPACITY_NORMAL];
for (int i = 0; i < sourceArray.length; i++) {
sourceArray[i] = (byte) i;
}
- this.channel1.configureBlocking(false);
- this.channel2.configureBlocking(false);
-
- // bind and connect
- this.channel1.connect(localAddr1);
- this.channel2.socket().bind(localAddr1);
- this.channel2.connect(localAddr2);
+ DatagramChannel dc = DatagramChannel.open();
+ // The writer isn't bound, but is connected.
+ dc.connect(channel1Address);
+ dc.configureBlocking(false);
+ channel2.configureBlocking(false);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
- assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
+ assertEquals(CAPACITY_NORMAL, dc.write(sourceBuf));
+
+ // Connect channel2 after data has been written.
+ channel2.connect(dc.socket().getLocalSocketAddress());
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
assertEquals(0, this.channel2.read(targetBuf));
}
- public void testReadWrite_NonBlock_ReaderNotBind() throws Exception {
+ // NOTE: The original harmony test tested that things still work
+ // if there's no socket bound at the the address we're connecting to.
+ //
+ // It isn't really feasible to implement that in a non-racy way.
+ public void testReadWrite_NonBlock_ReaderNotConnected() throws Exception {
byte[] sourceArray = new byte[CAPACITY_NORMAL];
byte[] targetArray = new byte[CAPACITY_NORMAL];
for (int i = 0; i < sourceArray.length; i++) {
@@ -2348,10 +2255,7 @@ public class DatagramChannelTest extends TestCase {
this.channel1.configureBlocking(false);
this.channel2.configureBlocking(false);
- // bind and connect
- this.channel1.socket().bind(localAddr2);
- this.channel1.connect(localAddr1);
- this.channel2.connect(localAddr2);
+ channel1.connect(channel2Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
@@ -2359,7 +2263,12 @@ public class DatagramChannelTest extends TestCase {
// read
ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
- assertEquals(0, this.channel2.read(targetBuf));
+
+ try {
+ assertEquals(0, this.channel2.read(targetBuf));
+ fail();
+ } catch (NotYetConnectedException expected) {
+ }
}
public void test_write_LBuffer_positioned() throws Exception {
@@ -2367,7 +2276,7 @@ public class DatagramChannelTest extends TestCase {
int position = 16;
DatagramChannel dc = DatagramChannel.open();
byte[] sourceArray = new byte[CAPACITY_NORMAL];
- dc.connect(localAddr1);
+ dc.connect(datagramSocket1Address);
// write
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
sourceBuf.position(position);
@@ -2384,7 +2293,7 @@ public class DatagramChannelTest extends TestCase {
// send ByteBuffer whose position is not zero
ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
sourceBuf.position(position);
- int ret = dc.send(sourceBuf, localAddr1);
+ int ret = dc.send(sourceBuf, datagramSocket1Address);
// assert send (256 - 16) bytes
assertEquals(CAPACITY_NORMAL - position, ret);
// assert the position of ByteBuffer has been set
@@ -2395,11 +2304,10 @@ public class DatagramChannelTest extends TestCase {
* @tests DatagramChannel#read(ByteBuffer[])
*/
public void test_read_$LByteBuffer() throws Exception {
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
+
// regression test for Harmony-754
- channel2.socket().bind(localAddr1);
- channel1.socket().bind(localAddr2);
- channel1.connect(localAddr1);
- channel2.connect(localAddr2);
channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL));
ByteBuffer[] readBuf = new ByteBuffer[2];
@@ -2414,11 +2322,10 @@ public class DatagramChannelTest extends TestCase {
* @tests DatagramChannel#read(ByteBuffer[],int,int)
*/
public void test_read_$LByteBufferII() throws Exception {
+ channel1.connect(channel2Address);
+ channel2.connect(channel1Address);
+
// regression test for Harmony-754
- channel2.socket().bind(localAddr1);
- channel1.socket().bind(localAddr2);
- channel1.connect(localAddr1);
- channel2.connect(localAddr2);
channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL));
ByteBuffer[] readBuf = new ByteBuffer[2];
@@ -2474,7 +2381,7 @@ public class DatagramChannelTest extends TestCase {
} catch (IllegalArgumentException e){
// expected
}
- channel.connect(localAddr1);
+ channel.connect(datagramSocket1Address);
try{
channel.read(c.asReadOnlyBuffer());
fail("Should throw IllegalArgumentException");
@@ -2491,13 +2398,13 @@ public class DatagramChannelTest extends TestCase {
channel1.close();
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
try {
- channel1.send(buf, localAddr1);
+ channel1.send(buf, datagramSocket1Address);
fail("Should throw ClosedChannelException");
} catch (ClosedChannelException e) {
//pass
}
try {
- channel1.send(null,localAddr1);
+ channel1.send(null, datagramSocket1Address);
fail("Should throw NullPointerException");
} catch (NullPointerException e) {
//pass
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectionKeyTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectionKeyTest.java
index eef10f5..150d11c 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectionKeyTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SelectionKeyTest.java
@@ -24,9 +24,7 @@ import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
-
import junit.framework.TestCase;
-import tests.support.Support_PortManager;
/*
* Tests for SelectionKey and its default implementation
@@ -295,10 +293,9 @@ public class SelectionKeyTest extends TestCase {
* @tests java.nio.channels.SelectionKey#readyOps()
*/
public void test_readyOps() throws IOException {
- int port = Support_PortManager.getNextPort();
- ServerSocket ss = new ServerSocket(port);
+ ServerSocket ss = new ServerSocket(0);
try {
- sc.connect(new InetSocketAddress(LOCAL_ADDR, port));
+ sc.connect(new InetSocketAddress(LOCAL_ADDR, ss.getLocalPort()));
assertEquals(0, selectionKey.readyOps());
assertFalse(selectionKey.isConnectable());
selector.select();
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ServerSocketChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ServerSocketChannelTest.java
index 83b838e..828ab30 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ServerSocketChannelTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/ServerSocketChannelTest.java
@@ -32,9 +32,7 @@ import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
-
import junit.framework.TestCase;
-import tests.support.Support_PortManager;
/*
* test for ServerSocketChannel
@@ -47,17 +45,12 @@ public class ServerSocketChannelTest extends TestCase {
private static final int TIME_UNIT = 200;
- private InetSocketAddress localAddr1;
-
private ServerSocketChannel serverChannel;
private SocketChannel clientChannel;
protected void setUp() throws Exception {
super.setUp();
- this.localAddr1 = new InetSocketAddress(
- "127.0.0.1", Support_PortManager
- .getNextPort());
this.serverChannel = ServerSocketChannel.open();
this.clientChannel = SocketChannel.open();
}
@@ -243,7 +236,7 @@ public class ServerSocketChannelTest extends TestCase {
public void testAccept_Block_NoConnect() throws IOException {
assertTrue(this.serverChannel.isBlocking());
ServerSocket gotSocket = this.serverChannel.socket();
- gotSocket.bind(localAddr1);
+ gotSocket.bind(null);
// blocking mode , will block and wait for ever...
// so must close the server channel with another thread.
new Thread() {
@@ -267,7 +260,7 @@ public class ServerSocketChannelTest extends TestCase {
public void testAccept_NonBlock_NoConnect() throws IOException {
ServerSocket gotSocket = this.serverChannel.socket();
- gotSocket.bind(localAddr1);
+ gotSocket.bind(null);
this.serverChannel.configureBlocking(false);
// non-blocking mode , will immediately return
assertNull(this.serverChannel.accept());
@@ -277,13 +270,13 @@ public class ServerSocketChannelTest extends TestCase {
* @tests ServerSocketChannel#accept().socket()
*/
public void test_read_Blocking_RealData() throws IOException {
- serverChannel.socket().bind(localAddr1);
+ serverChannel.socket().bind(null);
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
for (int i = 0; i < CAPACITY_NORMAL; i++) {
buf.put((byte) i);
}
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
Socket serverSocket = serverChannel.accept().socket();
InputStream in = serverSocket.getInputStream();
buf.flip();
@@ -316,13 +309,13 @@ public class ServerSocketChannelTest extends TestCase {
*/
public void test_read_NonBlocking_RealData() throws Exception {
serverChannel.configureBlocking(false);
- serverChannel.socket().bind(localAddr1);
+ serverChannel.socket().bind(null);
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
for (int i = 0; i < CAPACITY_NORMAL; i++) {
buf.put((byte) i);
}
buf.flip();
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
Socket serverSocket = serverChannel.accept().socket();
InputStream in = serverSocket.getInputStream();
clientChannel.write(buf);
@@ -336,13 +329,13 @@ public class ServerSocketChannelTest extends TestCase {
public void test_write_Blocking_RealData() throws IOException {
assertTrue(serverChannel.isBlocking());
ServerSocket serverSocket = serverChannel.socket();
- serverSocket.bind(localAddr1);
+ serverSocket.bind(null);
byte[] writeContent = new byte[CAPACITY_NORMAL];
for (int i = 0; i < writeContent.length; i++) {
writeContent[i] = (byte) i;
}
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
Socket socket = serverChannel.accept().socket();
OutputStream out = socket.getOutputStream();
out.write(writeContent);
@@ -358,13 +351,13 @@ public class ServerSocketChannelTest extends TestCase {
public void test_write_NonBlocking_RealData() throws Exception {
serverChannel.configureBlocking(false);
ServerSocket serverSocket = serverChannel.socket();
- serverSocket.bind(localAddr1);
+ serverSocket.bind(null);
byte[] writeContent = new byte[CAPACITY_NORMAL];
for (int i = 0; i < CAPACITY_NORMAL; i++) {
writeContent[i] = (byte) i;
}
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverSocket.getLocalSocketAddress());
Socket clientSocket = serverChannel.accept().socket();
OutputStream out = clientSocket.getOutputStream();
out.write(writeContent);
@@ -378,13 +371,13 @@ public class ServerSocketChannelTest extends TestCase {
*/
public void test_read_LByteBuffer_Blocking_ReadWriteRealLargeData()
throws IOException, InterruptedException {
- serverChannel.socket().bind(localAddr1);
+ serverChannel.socket().bind(null);
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_64KB);
for (int i = 0; i < CAPACITY_64KB; i++) {
buf.put((byte) i);
}
buf.flip();
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
WriteChannelThread writeThread = new WriteChannelThread(clientChannel, buf);
writeThread.start();
Socket socket = serverChannel.accept().socket();
@@ -423,13 +416,13 @@ public class ServerSocketChannelTest extends TestCase {
public void test_read_LByteBuffer_NonBlocking_ReadWriteRealLargeData()
throws Exception {
serverChannel.configureBlocking(false);
- serverChannel.socket().bind(localAddr1);
+ serverChannel.socket().bind(null);
ByteBuffer buf = ByteBuffer.allocate(CAPACITY_64KB);
for (int i = 0; i < CAPACITY_64KB; i++) {
buf.put((byte) i);
}
buf.flip();
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
WriteChannelThread writeThread = new WriteChannelThread(clientChannel, buf);
writeThread.start();
Socket socket = serverChannel.accept().socket();
@@ -448,12 +441,12 @@ public class ServerSocketChannelTest extends TestCase {
public void test_write_LByteBuffer_NonBlocking_ReadWriteRealLargeData()
throws Exception {
serverChannel.configureBlocking(false);
- serverChannel.socket().bind(localAddr1);
+ serverChannel.socket().bind(null);
byte[] writeContent = new byte[CAPACITY_64KB];
for (int i = 0; i < writeContent.length; i++) {
writeContent[i] = (byte) i;
}
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
Socket socket = serverChannel.accept().socket();
WriteSocketThread writeThread = new WriteSocketThread(socket, writeContent);
writeThread.start();
@@ -491,12 +484,12 @@ public class ServerSocketChannelTest extends TestCase {
*/
public void test_write_LByteBuffer_Blocking_ReadWriteRealLargeData()
throws Exception {
- serverChannel.socket().bind(localAddr1);
+ serverChannel.socket().bind(null);
byte[] writeContent = new byte[CAPACITY_64KB];
for (int i = 0; i < writeContent.length; i++) {
writeContent[i] = (byte) i;
}
- clientChannel.connect(localAddr1);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
Socket socket = serverChannel.accept().socket();
WriteSocketThread writeThread = new WriteSocketThread(socket, writeContent);
writeThread.start();
@@ -539,7 +532,7 @@ public class ServerSocketChannelTest extends TestCase {
ServerSocketChannel sc = ServerSocketChannel.open();
try {
ServerSocket ss = sc.socket();
- ss.bind(localAddr1);
+ ss.bind(null);
sc.configureBlocking(false);
ss.setSoTimeout(SO_TIMEOUT);
SocketChannel client = sc.accept();
@@ -604,7 +597,7 @@ public class ServerSocketChannelTest extends TestCase {
// regression test for Harmony-748
serverChannel.configureBlocking(false);
ServerSocket gotSocket = serverChannel.socket();
- gotSocket.bind(localAddr1);
+ gotSocket.bind(null);
try {
gotSocket.accept();
fail("Should throw an IllegalBlockingModeException");
@@ -627,7 +620,7 @@ public class ServerSocketChannelTest extends TestCase {
// regression test for Harmony-748
serverChannel.configureBlocking(true);
ServerSocket gotSocket = serverChannel.socket();
- gotSocket.bind(localAddr1);
+ gotSocket.bind(null);
serverChannel.close();
try {
gotSocket.accept();
@@ -640,11 +633,11 @@ public class ServerSocketChannelTest extends TestCase {
* Regression test for HARMONY-4961
*/
public void test_socket_getLocalPort() throws IOException {
- serverChannel.socket().bind(localAddr1);
- clientChannel.connect(localAddr1);
+ serverChannel.socket().bind(null);
+ clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
SocketChannel myChannel = serverChannel.accept();
int port = myChannel.socket().getLocalPort();
- assertEquals(localAddr1.getPort(), port);
+ assertEquals(serverChannel.socket().getLocalPort(), port);
myChannel.close();
clientChannel.close();
serverChannel.close();
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SocketChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SocketChannelTest.java
index 4b0cdaa..1151292 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SocketChannelTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/nio/channels/SocketChannelTest.java
@@ -41,9 +41,7 @@ import java.nio.channels.SocketChannel;
import java.nio.channels.UnresolvedAddressException;
import java.nio.channels.UnsupportedAddressTypeException;
import java.nio.channels.spi.SelectorProvider;
-
import junit.framework.TestCase;
-import tests.support.Support_PortManager;
/**
* Tests for SocketChannel and its default implementation.
@@ -53,7 +51,6 @@ public class SocketChannelTest extends TestCase {
private static final int CAPACITY_NORMAL = 200;
private InetSocketAddress localAddr1;
-
private InetSocketAddress localAddr2;
private SocketChannel channel1;
@@ -70,13 +67,13 @@ public class SocketChannelTest extends TestCase {
protected void setUp() throws Exception {
super.setUp();
- this.localAddr1 = new InetSocketAddress("127.0.0.1",
- Support_PortManager.getNextPort());
- this.localAddr2 = new InetSocketAddress("127.0.0.1",
- Support_PortManager.getNextPort());
this.channel1 = SocketChannel.open();
this.channel2 = SocketChannel.open();
- this.server1 = new ServerSocket(localAddr1.getPort());
+ this.server1 = new ServerSocket(0);
+ this.localAddr1 = new InetSocketAddress("127.0.0.1", server1.getLocalPort());
+
+ this.server2 = new ServerSocket(0);
+ this.localAddr2 = new InetSocketAddress("127.0.0.1", server2.getLocalPort());
}
protected void tearDown() throws Exception {
@@ -166,8 +163,7 @@ public class SocketChannelTest extends TestCase {
MockSocketChannel testMSChannelnull = new MockSocketChannel(null);
MockSocketChannel testMSChannel = new MockSocketChannel(
SelectorProvider.provider());
- ServerSocket testServer = new ServerSocket(Support_PortManager
- .getNextPort());
+ ServerSocket testServer = new ServerSocket(0);
try {
try {
this.channel1.read(byteBuf);
@@ -508,7 +504,6 @@ public class SocketChannelTest extends TestCase {
private void assertSocketAction_Block_BeforeConnect(Socket s)
throws IOException {
assertFalse(this.channel1.isConnected());
- this.server2 = new ServerSocket(localAddr2.getPort());
s.connect(localAddr2);
assertTrue(this.channel1.isConnected());
assertTrue(s.isConnected());
@@ -530,7 +525,6 @@ public class SocketChannelTest extends TestCase {
private void assertSocketAction_NonBlock_BeforeConnect(Socket s)
throws IOException {
assertFalse(this.channel1.isConnected());
- this.server2 = new ServerSocket(localAddr2.getPort());
try {
s.connect(localAddr2);
fail("Should throw IllegalBlockingModeException");
@@ -1419,8 +1413,10 @@ public class SocketChannelTest extends TestCase {
private void ensureServerOpen() throws IOException {
ensureServerClosed();
- this.server1 = new ServerSocket(localAddr1.getPort());
- this.server2 = new ServerSocket(localAddr2.getPort());
+ this.server1 = new ServerSocket(0);
+ this.localAddr1 = new InetSocketAddress("127.0.0.1", server1.getLocalPort());
+ this.server2 = new ServerSocket(0);
+ this.localAddr2 = new InetSocketAddress("127.0.0.1", server2.getLocalPort());
assertTrue(this.server1.isBound());
assertTrue(this.server2.isBound());
}
@@ -2734,9 +2730,9 @@ public class SocketChannelTest extends TestCase {
*/
public void test_writev() throws Exception {
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr2);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr2);
+ sc.connect(ssc.socket().getLocalSocketAddress());
SocketChannel sock = ssc.accept();
ByteBuffer[] buf = { ByteBuffer.allocate(10), ByteBuffer.allocateDirect(20) };
@@ -3059,9 +3055,9 @@ public class SocketChannelTest extends TestCase {
throws Exception {
// regression 1 for HARMONY-549
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr2);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr2);
+ sc.connect(ssc.socket().getLocalSocketAddress());
ssc.accept().close();
ByteBuffer[] buf = { ByteBuffer.allocate(10) };
assertEquals(-1, sc.read(buf, 0, 1));
@@ -3075,9 +3071,9 @@ public class SocketChannelTest extends TestCase {
public void test_socketChannel_write_ByteBufferII() throws Exception {
// regression 2 for HARMONY-549
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr2);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr2);
+ sc.connect(ssc.socket().getLocalSocketAddress());
SocketChannel sock = ssc.accept();
ByteBuffer[] buf = { ByteBuffer.allocate(10), null };
try {
@@ -3098,9 +3094,9 @@ public class SocketChannelTest extends TestCase {
public void test_socketChannel_read_ByteBufferII_bufNULL() throws Exception {
// regression 3 for HARMONY-549
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr2);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr2);
+ sc.connect(ssc.socket().getLocalSocketAddress());
ssc.accept();
ByteBuffer[] buf = new ByteBuffer[2];
buf[0] = ByteBuffer.allocate(1);
@@ -3121,9 +3117,9 @@ public class SocketChannelTest extends TestCase {
public void test_socketChannel_write_close() throws Exception {
// regression 4 for HARMONY-549
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr2);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr2);
+ sc.connect(ssc.socket().getLocalSocketAddress());
SocketChannel sock = ssc.accept();
ByteBuffer buf = null;
ssc.close();
@@ -3147,9 +3143,9 @@ public class SocketChannelTest extends TestCase {
ByteBuffer readBuf = ByteBuffer.allocate(11);
ByteBuffer buf = ByteBuffer.wrap(testStr.getBytes());
ServerSocketChannel ssc = ServerSocketChannel.open();
- ssc.socket().bind(localAddr2);
+ ssc.socket().bind(null);
SocketChannel sc = SocketChannel.open();
- sc.connect(localAddr2);
+ sc.connect(ssc.socket().getLocalSocketAddress());
buf.position(2);
ssc.accept().write(buf);
assertEquals(9, sc.read(readBuf));
diff --git a/luni/src/test/java/libcore/java/net/OldDatagramSocketTest.java b/luni/src/test/java/libcore/java/net/OldDatagramSocketTest.java
deleted file mode 100644
index d51d461..0000000
--- a/luni/src/test/java/libcore/java/net/OldDatagramSocketTest.java
+++ /dev/null
@@ -1,2183 +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 libcore.java.net;
-
-import java.io.IOException;
-import java.io.InterruptedIOException;
-import java.net.BindException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.DatagramSocketImpl;
-import java.net.DatagramSocketImplFactory;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.NetworkInterface;
-import java.net.PortUnreachableException;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.net.SocketTimeoutException;
-import java.net.UnknownHostException;
-import java.nio.channels.DatagramChannel;
-import java.nio.channels.IllegalBlockingModeException;
-import java.util.Date;
-import java.util.Vector;
-import tests.support.Support_Configuration;
-import tests.support.Support_PortManager;
-
-public class OldDatagramSocketTest extends junit.framework./*Socket*/TestCase {
-
- java.net.DatagramSocket ds;
-
- java.net.DatagramPacket dp;
-
- DatagramSocket sds = null;
-
- String retval;
-
- String testString = "Test String";
-
- boolean interrupted;
-
- class DatagramServer extends Thread {
-
- public DatagramSocket ms;
-
- boolean running = true;
-
- public volatile byte[] rbuf = new byte[512];
-
- volatile DatagramPacket rdp = null;
-
- public void run() {
- try {
- while (running) {
- try {
- ms.receive(rdp);
- // echo the packet back
- ms.send(rdp);
- } catch (java.io.InterruptedIOException e) {
- Thread.yield();
- }
- ;
- }
- ;
- } catch (java.io.IOException e) {
- System.out.println("DatagramServer server failed: " + e);
- } finally {
- ms.close();
- }
- }
-
- public void stopServer() {
- running = false;
- }
-
- public DatagramServer(int aPort, InetAddress address)
- throws java.io.IOException {
- rbuf = new byte[512];
- rbuf[0] = -1;
- rdp = new DatagramPacket(rbuf, rbuf.length);
- ms = new DatagramSocket(aPort, address);
- ms.setSoTimeout(2000);
- }
- }
-
- public void test_Constructor() {
- // Test for method java.net.DatagramSocket()
- try {
- ds = new java.net.DatagramSocket();
- } catch (Exception e) {
- fail("Could not create DatagramSocket : " + e.getMessage());
- }
-
- /*
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new DatagramSocket();
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- */
- }
-
- public void test_ConstructorI() {
- // Test for method java.net.DatagramSocket(int)
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- assertTrue("Created socket with incorrect port",
- ds.getLocalPort() == portNumber);
- } catch (Exception e) {
- fail("Could not create DatagramSocket : " + e.getMessage());
- }
-
- /*
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new DatagramSocket(8080);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- */
-
- try {
- DatagramSocket ds = new java.net.DatagramSocket(1);
- if (!("root".equals(System.getProperty("user.name")))) {
- fail("SocketException was not thrown.");
- }
- } catch (SocketException e) {
- //expected
- }
-
- }
-
- public void test_ConstructorILjava_net_InetAddress() {
- // Test for method java.net.DatagramSocket(int, java.net.InetAddress)
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber, InetAddress
- .getLocalHost());
- assertTrue("Created socket with incorrect port",
- ds.getLocalPort() == portNumber);
- assertTrue("Created socket with incorrect address", ds
- .getLocalAddress().equals(InetAddress.getLocalHost()));
- } catch (Exception e) {
- fail("Could not create DatagramSocket : " + e.getMessage());
- }
-
- /*
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new java.net.DatagramSocket(8080, InetAddress
- .getLocalHost());
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- */
-
- try {
- new java.net.DatagramSocket(1, InetAddress
- .getLocalHost());
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- }
- }
-
- public void test_close() {
- // Test for method void java.net.DatagramSocket.close()
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- dp = new DatagramPacket("Test String".getBytes(), 11, InetAddress
- .getLocalHost(), 0);
- ds.close();
- try {
- ds.send(dp);
- fail("IOException was not thrown.");
- } catch(IOException ioe) {
- //expected
- }
- } catch (Exception e) {
- fail("Unexpected exception: " + e.getMessage());
- }
- }
-
- public void test_connectLjava_net_InetAddressI() throws
- UnknownHostException, SocketException {
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- assertTrue("Incorrect InetAddress", ds.getInetAddress().equals(
- inetAddress));
- assertTrue("Incorrect Port", ds.getPort() == portNumber);
- ds.disconnect();
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- System.out
- .println("Running test_connectLjava_net_InetAddressI" +
- "(DatagramSocketTest) with IPv6GlobalAddressJcl4: "
- + Support_Configuration.IPv6GlobalAddressJcl4);
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress
- .getByName(Support_Configuration.IPv6GlobalAddressJcl4);
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- assertTrue("Incorrect InetAddress", ds.getInetAddress().equals(
- inetAddress));
- assertTrue("Incorrect Port", ds.getPort() == portNumber);
- ds.disconnect();
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- try {
- // Create a connected datagram socket to test
- // PlainDatagramSocketImpl.peek()
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket();
- int port = ds.getLocalPort();
- ds.connect(localHost, port);
- DatagramPacket send = new DatagramPacket(new byte[10], 10,
- localHost, port);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("Wrong size: " + receive.getLength(), receive
- .getLength() == 10);
- assertTrue("Wrong receiver", receive.getAddress().equals(localHost));
- } catch (IOException e) {
- fail("Unexpected IOException : " + e.getMessage());
- }
-
- class DatagramServer extends Thread {
-
- public DatagramSocket ms;
-
- boolean running = true;
-
- public byte[] rbuf = new byte[512];
-
- DatagramPacket rdp = null;
-
- public void run() {
- try {
- while (running) {
- try {
- ms.receive(rdp);
- // echo the packet back
- ms.send(rdp);
- } 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;
- }
-
- public DatagramServer(int aPort, InetAddress address)
- throws java.io.IOException {
- rbuf = new byte[512];
- rbuf[0] = -1;
- rdp = new DatagramPacket(rbuf, rbuf.length);
- ms = new DatagramSocket(aPort, address);
- ms.setSoTimeout(2000);
- }
- }
-
- // validate that we get the PortUnreachable exception if we try to
- // send a dgram to a server that is not running and then do a recv
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- DatagramPacket send = new DatagramPacket(new byte[10], 10);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(10000);
- ds.receive(receive);
- ds.close();
- fail(
- "No PortUnreachableException when connected at native level on recv ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to connect at native level on recv: "
- + e.toString(),
- (e instanceof PortUnreachableException));
- }
-
- // validate that we can send/receive with datagram sockets connected at
- // the native level
- DatagramServer server = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber);
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("Wrong size data received: " + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("Wrong receiver:" + receive.getAddress() + ":"
- + localHost, receive.getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can disconnect
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- ds.disconnect();
- ds.close();
- } catch (Exception e) {
- assertTrue("Unexpected exception when trying to connect at native"
- + e.toString(), (e instanceof PortUnreachableException));
- }
-
- // validate that once connected we cannot send to another address
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- DatagramPacket send = new DatagramPacket(new byte[10], 10,
- inetAddress, portNumber + 1);
- ds.send(send);
- ds.close();
- fail(
- "No Exception when trying to send to a different address on a connected socket ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to send to a different address on a connected socket: "
- + e.toString(),
- (e instanceof IllegalArgumentException));
- }
-
- // validate that we can connect, then disconnect, then connect then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber + 1);
- ds.disconnect();
- ds.connect(localHost, serverPortNumber);
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue(
- "connect/disconnect/connect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/disconnect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/disconnect/connect:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect/disconnect then send/recv to any address
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber + 1);
- ds.disconnect();
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length, localHost, serverPortNumber);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/disconnect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/disconnect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/disconnect:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect on an allready connected socket and then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(localHost, serverPortNumber + 1);
- ds.connect(localHost, serverPortNumber);
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/connect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/connect: "
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // test for when we fail to connect at the native level. Even though we
- // fail at the native level there is no way to return an exception so
- // there should be no exception
- try {
- ds = new java.net.DatagramSocket();
- byte[] addressBytes = { 0, 0, 0, 0 };
- InetAddress inetAddress = InetAddress.getByAddress(addressBytes);
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- } catch (Exception e) {
- fail(
- "Unexcpected exception when trying to connect at native level with bad address for signature with no exception to be returned: "
- + e.toString());
- }
-
- System.out
- .println("Running test_connectLjava_net_InetAddressI(DatagramSocketTest) with IPv6 address");
- try {
- ds = new java.net.DatagramSocket();
- byte[] addressBytes = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0 };
- InetAddress inetAddress = InetAddress
- .getByAddress(addressBytes);
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- } catch (Exception e) {
- fail(
- "Unexcpected exception when trying to connect at native level with bad IPv6 address for signature with no exception to be returned: "
- + e.toString());
- }
- }
-
- public void test_disconnect() {
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- ds.disconnect();
- assertNull("Incorrect InetAddress", ds.getInetAddress());
- assertEquals("Incorrect Port", -1, ds.getPort());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
-
- System.out
- .println("Running test_disconnect(DatagramSocketTest) with IPv6GlobalAddressJcl4: "
- + Support_Configuration.IPv6GlobalAddressJcl4);
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress
- .getByName(Support_Configuration.IPv6GlobalAddressJcl4);
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(inetAddress, portNumber);
- ds.disconnect();
- assertNull("Incorrect InetAddress", ds.getInetAddress());
- assertEquals("Incorrect Port", -1, ds.getPort());
- } catch (Exception e) {
- fail("Exception during test : " + e.getMessage());
- }
- }
-
- public void test_getInetAddress() {
- Vector<InetAddress> ias = new Vector<InetAddress>();
- try {
- ias.add(InetAddress.getLocalHost());
- ias.add(InetAddress
- .getByName(Support_Configuration.IPv6GlobalAddressJcl4));
- ias.add(InetAddress
- .getByName(Support_Configuration.InetTestAddress2));
- ias.add(InetAddress
- .getByName(Support_Configuration.InetTestAddress2));
- ias.add(InetAddress
- .getByName(Support_Configuration.InetTestIP));
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.toString());
- }
-
- for(InetAddress ia:ias) {
- int portNumber = Support_PortManager.getNextPortForUDP();
- DatagramSocket ds = null;
- try {
- ds = new DatagramSocket();
- ds.connect(ia, portNumber);
- assertEquals(ia, ds.getInetAddress());
- assertEquals("" + ia, ia, ds.getInetAddress());
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- ds.disconnect();
- ds.close();
- }
- }
-
- try {
- assertNull(new DatagramSocket().getInetAddress());
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- }
-
- }
-
- public void test_getLocalPort() {
- // Test for method int java.net.DatagramSocket.getLocalPort()
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- assertTrue("Returned incorrect port",
- ds.getLocalPort() == portNumber);
- } catch (Exception e) {
- fail("Exception during getLocalAddress : " + e.getMessage());
- }
- }
-
- public void test_getPort() {
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- DatagramSocket theSocket = new DatagramSocket(portNumber);
- assertEquals("Expected -1 for remote port as not connected",
- -1, theSocket.getPort());
-
- // now connect the socket and validate that we get the right port
- theSocket.connect(InetAddress.getLocalHost(), portNumber);
- assertTrue("getPort returned wrong value:" + theSocket.getPort()
- + ":Expected:" + portNumber,
- theSocket.getPort() == portNumber);
- } catch (Exception e) {
- fail("unexpected exception during getPort test : " + e.getMessage());
- }
- }
-
- public void test_getReceiveBufferSize() throws Exception {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setReceiveBufferSize(130);
- assertTrue("Incorrect buffer size", ds.getReceiveBufferSize() >= 130);
- ds.close();
- try {
- ds.getReceiveBufferSize();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_getSendBufferSize() throws Exception {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSendBufferSize(134);
- assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134);
- ds.close();
- try {
- ds.getSendBufferSize();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_getSoTimeout_setSoTimeout() throws Exception {
- // TODO: a useful test would check that setSoTimeout actually causes timeouts!
- DatagramSocket s = new DatagramSocket();
- s.setSoTimeout(1500);
- int ms = s.getSoTimeout();
- if (ms < 1500-10 || ms > 1500+10) {
- fail("suspicious timeout: " + ms);
- }
- s.close();
- try {
- s.getSoTimeout();
- fail("SocketException was not thrown.");
- } catch (SocketException expected) {
- }
- try {
- s.setSoTimeout(1000);
- fail("SocketException was not thrown.");
- } catch (SocketException expected) {
- }
- }
-
- public void test_receiveLjava_net_DatagramPacket() throws Exception {
- // Test for method void
- // java.net.DatagramSocket.receive(java.net.DatagramPacket)
-
- receive_oversize_java_net_DatagramPacket();
- final int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int portNumber = ports[0];
-
- class TestDGRcv implements Runnable {
- public void run() {
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- Thread.sleep(1000);
- DatagramSocket sds = new DatagramSocket(ports[1]);
- sds.send(new DatagramPacket("Test".getBytes("UTF-8"), "Test".length(), localHost, portNumber));
- sds.send(new DatagramPacket("Longer test".getBytes("UTF-8"), "Longer test".length(), localHost, portNumber));
- sds.send(new DatagramPacket("3 Test".getBytes("UTF-8"), "3 Test".length(), localHost, portNumber));
- sds.send(new DatagramPacket("4 Test".getBytes("UTF-8"), "4 Test".length(), localHost, portNumber));
- sds.send(new DatagramPacket("5".getBytes("UTF-8"), "5".length(), localHost, portNumber));
- sds.close();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- try {
- new Thread(new TestDGRcv(), "datagram receiver").start();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSoTimeout(6000);
- byte[] rbuf = new byte[1000];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
-
- // Receive the first packet.
- ds.receive(rdp);
- assertEquals("Test", new String(rbuf, 0, rdp.getLength()));
- // Check that we can still receive a longer packet (http://code.google.com/p/android/issues/detail?id=24748).
- ds.receive(rdp);
- assertEquals("Longer test", new String(rbuf, 0, rdp.getLength()));
- // See what happens if we manually call DatagramPacket.setLength.
- rdp.setLength(4);
- ds.receive(rdp);
- assertEquals("3 Te", new String(rbuf, 0, rdp.getLength()));
- // And then another.
- ds.receive(rdp);
- assertEquals("4 Te", new String(rbuf, 0, rdp.getLength()));
- // And then a packet shorter than the user-supplied length.
- ds.receive(rdp);
- assertEquals("5", new String(rbuf, 0, rdp.getLength()));
-
- ds.close();
- } finally {
- ds.close();
- }
- DatagramSocket socket = null;
- try {
- byte rbuf[] = new byte[1000];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- DatagramChannel channel = DatagramChannel.open();
- channel.configureBlocking(false);
- socket = channel.socket();
- socket.receive(rdp);
- fail("IllegalBlockingModeException was not thrown.");
- } catch(IllegalBlockingModeException expected) {
- } finally {
- socket.close();
- }
-
- try {
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSoTimeout(1000);
- byte rbuf[] = new byte[1000];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- ds.receive(rdp);
- fail("SocketTimeoutException was not thrown.");
- } catch(SocketTimeoutException expected) {
- } finally {
- ds.close();
- }
-
- interrupted = false;
- final DatagramSocket ds = new DatagramSocket();
- ds.setSoTimeout(12000);
- Runnable runnable = new Runnable() {
- public void run() {
- try {
- ds.receive(new DatagramPacket(new byte[1], 1));
- } catch (InterruptedIOException e) {
- interrupted = true;
- } catch (IOException ignored) {
- }
- }
- };
- Thread thread = new Thread(runnable, "DatagramSocket.receive1");
- thread.start();
- do {
- Thread.sleep(500);
- } while (!thread.isAlive());
- ds.close();
- int c = 0;
- do {
- Thread.sleep(500);
- if (interrupted) {
- fail("received interrupt");
- }
- if (++c > 4) {
- fail("read call did not exit");
- }
- } while (thread.isAlive());
-
- interrupted = false;
- final int portNum = ports[0];
- final DatagramSocket ds2 = new DatagramSocket(ports[1]);
- ds2.setSoTimeout(12000);
- Runnable runnable2 = new Runnable() {
- public void run() {
- try {
- ds2.receive(new DatagramPacket(new byte[1], 1,
- InetAddress.getLocalHost(), portNum));
- } catch (InterruptedIOException e) {
- interrupted = true;
- } catch (IOException ignored) {
- }
- }
- };
- Thread thread2 = new Thread(runnable2, "DatagramSocket.receive2");
- thread2.start();
- try {
- do {
- Thread.sleep(500);
- } while (!thread2.isAlive());
- } catch (InterruptedException ignored) {
- }
- ds2.close();
- int c2 = 0;
- do {
- Thread.sleep(500);
- if (interrupted) {
- fail("receive2 was interrupted");
- }
- if (++c2 > 4) {
- fail("read2 call did not exit");
- }
- } while (thread2.isAlive());
-
- interrupted = false;
- DatagramSocket ds3 = new DatagramSocket();
- ds3.setSoTimeout(500);
- Date start = new Date();
- try {
- ds3.receive(new DatagramPacket(new byte[1], 1));
- } catch (InterruptedIOException e) {
- interrupted = true;
- }
- ds3.close();
- assertTrue("receive not interrupted", interrupted);
- int delay = (int) (new Date().getTime() - start.getTime());
- assertTrue("timeout too soon: " + delay, delay >= 490);
- }
-
- public void test_sendLjava_net_DatagramPacket() throws Exception {
- // Test for method void
- // java.net.DatagramSocket.send(java.net.DatagramPacket)
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int portNumber = ports[0];
-
- class TestDGSend implements Runnable {
- Thread pThread;
-
- public TestDGSend(Thread t) {
- pThread = t;
- }
-
- public void run() {
- try {
- byte[] rbuf = new byte[1000];
-
- sds = new DatagramSocket(portNumber);
- DatagramPacket sdp = new DatagramPacket(rbuf, rbuf.length);
- sds.setSoTimeout(6000);
- sds.receive(sdp);
- retval = new String(rbuf, 0, testString.length());
- pThread.interrupt();
- } catch (java.io.InterruptedIOException e) {
- System.out.println("Recv operation timed out");
- pThread.interrupt();
- ds.close();
- } catch (Exception e) {
- System.out.println("Failed to establish Dgram server: " + e);
- }
- }
- }
- try {
- new Thread(new TestDGSend(Thread.currentThread()), "DGServer")
- .start();
- ds = new java.net.DatagramSocket(ports[1]);
- dp = new DatagramPacket(testString.getBytes(), testString.length(),
- InetAddress.getLocalHost(), portNumber);
- // Wait to allow send to occur
- try {
- Thread.sleep(500);
- ds.send(dp);
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- ds.close();
- assertTrue("Incorrect data sent: " + retval, retval
- .equals(testString));
- }
- } catch (Exception e) {
- fail("Exception during send test : " + e.getMessage());
- } finally {
- ds.close();
- }
-
- /*
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkMulticast(InetAddress maddr) {
- throw new SecurityException();
- }
-
- public void checkConnect(String host,
- int port) {
- throw new SecurityException();
- }
- };
- try {
-
- ds = new java.net.DatagramSocket(ports[1]);
- dp = new DatagramPacket(testString.getBytes(), testString.length(),
- InetAddress.getLocalHost(), portNumber);
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- ds.send(dp);
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- } catch(Exception e) {
- fail("Unexpected exception was thrown: " + e.getMessage());
- }
- */
-
- DatagramSocket socket = null;
- try {
- byte rbuf[] = new byte[1000];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- SocketAddress address = new InetSocketAddress(portNumber);
- DatagramChannel channel = DatagramChannel.open();
- channel.configureBlocking(false);
- socket = channel.socket();
- socket.send(rdp);
- fail("IllegalBlockingModeException was not thrown.");
- } catch(IllegalBlockingModeException ibme) {
- //expected
- } catch(IOException ioe) {
- fail("IOException was thrown: " + ioe.getMessage());
- } finally {
- socket.close();
- }
-
- //Regression for HARMONY-1118
- class testDatagramSocket extends DatagramSocket {
- public testDatagramSocket(DatagramSocketImpl impl){
- super(impl);
- }
- }
- class testDatagramSocketImpl extends DatagramSocketImpl {
- protected void create() throws SocketException {}
- protected void bind(int arg0, InetAddress arg1) throws SocketException {}
- protected void send(DatagramPacket arg0) throws IOException {}
- protected int peek(InetAddress arg0) throws IOException {
- return 0;
- }
- protected int peekData(DatagramPacket arg0) throws IOException {
- return 0;
- }
- protected void receive(DatagramPacket arg0) throws IOException {}
- protected void setTTL(byte arg0) throws IOException {}
- protected byte getTTL() throws IOException {
- return 0;
- }
- protected void setTimeToLive(int arg0) throws IOException {}
- protected int getTimeToLive() throws IOException {
- return 0;
- }
- protected void join(InetAddress arg0) throws IOException {}
- protected void leave(InetAddress arg0) throws IOException {}
- protected void joinGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {}
- protected void leaveGroup(SocketAddress arg0, NetworkInterface arg1) throws IOException {}
- protected void close() {}
- public void setOption(int arg0, Object arg1) throws SocketException {}
- public Object getOption(int arg0) throws SocketException {
- return null;
- }
- }
- InetSocketAddress sa = new InetSocketAddress(InetAddress.getLocalHost(), 0);
- //no exception expected for next line
- new testDatagramSocket(new testDatagramSocketImpl()).send(new DatagramPacket(new byte[272], 3, sa));
-
- // Regression test for Harmony-2938
- InetAddress i = InetAddress.getByName("127.0.0.1");
- DatagramSocket d = new DatagramSocket(0, i);
- try {
- d.send(new DatagramPacket(new byte[] { 1 }, 1));
- fail("should throw NPE.");
- } catch (NullPointerException e) {
- // expected;
- } finally {
- d.close();
- }
- }
-
- public void test_setSendBufferSizeI() throws Exception {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSendBufferSize(134);
- assertTrue("Incorrect buffer size", ds.getSendBufferSize() >= 134);
- ds.close();
- try {
- ds.setSendBufferSize(1);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_setReceiveBufferSizeI() throws Exception {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setReceiveBufferSize(130);
- assertTrue("Incorrect buffer size", ds.getReceiveBufferSize() >= 130);
-
- try {
- ds.setReceiveBufferSize(0);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- try {
- ds.setReceiveBufferSize(-1);
- fail("IllegalArgumentException was not thrown.");
- } catch(IllegalArgumentException iae) {
- //expected
- }
-
- ds.close();
-
- try {
- ds.setReceiveBufferSize(1);
- fail("SocketException was not thrown.");
- } catch (SocketException e) {
- //expected
- }
- }
-
- public void test_ConstructorLjava_net_DatagramSocketImpl() {
- class testDatagramSocket extends DatagramSocket {
- public testDatagramSocket(DatagramSocketImpl impl){
- super(impl);
- }
- }
-
- try {
- new testDatagramSocket((DatagramSocketImpl) null);
- fail("exception expected");
- } catch (NullPointerException ex) {
- //expected
- }
- }
-
- public void test_ConstructorLjava_net_SocketAddress() {
- class mySocketAddress extends SocketAddress {
-
- public mySocketAddress() {
- }
- }
-
- try {
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(new InetSocketAddress(
- InetAddress.getLocalHost(), portNumber));
- assertTrue(ds.getBroadcast());
- assertTrue("Created socket with incorrect port", ds
- .getLocalPort() == portNumber);
- assertTrue("Created socket with incorrect address", ds
- .getLocalAddress().equals(InetAddress.getLocalHost()));
- } catch (Exception e) {
- fail("Could not create DatagramSocket : " + e.getMessage());
- }
-
- try {
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds = new java.net.DatagramSocket(new mySocketAddress());
- fail(
- "No exception when constucting datagramSocket with unsupported SocketAddress type");
- } catch (IllegalArgumentException e) {
-
- }
- //regression for Harmony-894
- ds = new DatagramSocket((SocketAddress)null);
- assertTrue(ds.getBroadcast());
- } catch (Exception ex) {
- fail(
- "unexpected exception when datagramSocket SocketAddress constructor test");
- }
-
- /*
- SecurityManager sm = new SecurityManager() {
-
- public void checkPermission(Permission perm) {
- }
-
- public void checkListen(int port) {
- throw new SecurityException();
- }
- };
-
- SecurityManager oldSm = System.getSecurityManager();
- System.setSecurityManager(sm);
- try {
- new DatagramSocket(new InetSocketAddress(
- InetAddress.getLocalHost(), 1));
- fail("SecurityException should be thrown.");
- } catch (SecurityException e) {
- // expected
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- } finally {
- System.setSecurityManager(oldSm);
- }
- */
-
- InetSocketAddress isa = null;
- try {
- isa = new InetSocketAddress(
- InetAddress.getLocalHost(), 1);
- } catch (UnknownHostException e) {
- fail("UnknownHostException was thrown.");
- }
- }
-
- public void test_bindLjava_net_SocketAddress() throws Exception {
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int serverPortNumber = ports[1];
-
- // now create a socket that is not bound and then bind it
- InetAddress localHost = InetAddress.getLocalHost();
- InetSocketAddress localAddress1 = new InetSocketAddress(localHost, ports[0]);
- DatagramSocket theSocket = new DatagramSocket(localAddress1);
-
- // validate that the localSocketAddress reflects the address we bound to
- assertEquals(localAddress1, theSocket.getLocalSocketAddress());
-
- // now make sure that datagrams sent from this socket appear to come
- // from the address we bound to
- InetSocketAddress localAddress2 = new InetSocketAddress(localHost, ports[2]);
- DatagramSocket ds = new DatagramSocket((SocketAddress) null);
- ds.bind(localAddress2);
-
- DatagramServer server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
-
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes, sendBytes.length);
- ds.send(send);
- Thread.sleep(1000);
- ds.close();
- // Check that the address in the packet matches the bound address.
- assertEquals(localAddress2, server.rdp.getSocketAddress());
-
- if (server != null) {
- server.stopServer();
- }
- }
-
- public void test_bindLjava_net_SocketAddress_null() throws Exception {
- // validate if we pass in null that it picks an address for us.
- DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
- theSocket.bind(null);
- assertNotNull(theSocket.getLocalSocketAddress());
- theSocket.close();
- }
-
- public void test_bindLjava_net_SocketAddress_bad_address() throws Exception {
- // Address we cannot bind to
- DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
- try {
- InetAddress badAddress = InetAddress.getByAddress(Support_Configuration.nonLocalAddressBytes);
- theSocket.bind(new InetSocketAddress(badAddress, Support_PortManager.getNextPortForUDP()));
- fail("No exception when binding to bad address");
- } catch (SocketException expected) {
- }
- theSocket.close();
- }
-
- public void test_bindLjava_net_SocketAddress_address_in_use() throws Exception {
- // Address that we have already bound to
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
- DatagramSocket theSocket1 = new DatagramSocket((SocketAddress) null);
- DatagramSocket theSocket2 = new DatagramSocket(ports[0]);
- try {
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress.getLocalHost(), ports[1]);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- fail("No exception binding to address that is not available");
- } catch (SocketException expected) {
- }
- theSocket1.close();
- theSocket2.close();
- }
-
- public void test_bindLjava_net_SocketAddress_unsupported_address_type() throws Exception {
- class mySocketAddress extends SocketAddress {
- public mySocketAddress() {
- }
- }
-
- // unsupported SocketAddress subclass
- DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
- try {
- theSocket.bind(new mySocketAddress());
- fail("No exception when binding using unsupported SocketAddress subclass");
- } catch (IllegalArgumentException expected) {
- }
- theSocket.close();
- }
-
- public void test_connectLjava_net_SocketAddress() {
-
- // validate that we get the PortUnreachable exception if we try to
- // send a dgram to a server that is not running and then do a recv
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- DatagramPacket send = new DatagramPacket(new byte[10], 10);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(10000);
- ds.receive(receive);
- ds.close();
- fail(
- "No PortUnreachableException when connected at native level on recv ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to connect at native level on recv: "
- + e.toString(),
- (e instanceof PortUnreachableException));
- }
-
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
-
- ds.connect(new InetSocketAddress("asdfasdf", 1));
- ds.close();
- fail("SocketException was not thrown.");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to connect to unknown host: "
- + e.toString(),
- (e instanceof SocketException));
- }
-
- // validate that we can send/receive with datagram sockets connected at
- // the native level
- DatagramServer server = null;
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("Wrong size data received: " + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("Wrong receiver:" + receive.getAddress() + ":"
- + localHost, receive.getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can disconnect
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- ds.disconnect();
- ds.close();
- } catch (Exception e) {
- assertTrue("Unexpected exception when trying to connect at native"
- + e.toString(), (e instanceof PortUnreachableException));
- }
-
- // validate that once connected we cannot send to another address
- try {
- ds = new java.net.DatagramSocket();
- InetAddress inetAddress = InetAddress.getLocalHost();
- int portNumber = Support_PortManager.getNextPortForUDP();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- DatagramPacket send = new DatagramPacket(new byte[10], 10,
- inetAddress, portNumber + 1);
- ds.send(send);
- ds.close();
- fail(
- "No Exception when trying to send to a different address on a connected socket ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to send to a different address on a connected socket: "
- + e.toString(),
- (e instanceof IllegalArgumentException));
- }
-
- // validate that we can connect, then disconnect, then connect then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
- ds.disconnect();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue(
- "connect/disconnect/connect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/disconnect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/disconnect/connect:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect/disconnect then send/recv to any address
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
- ds.disconnect();
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length, localHost, serverPortNumber);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/disconnect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/disconnect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/disconnect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/disconnect:"
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // validate that we can connect on an allready connected socket and then
- // send/recv
- server = null;
- ports = Support_PortManager.getNextPortsForUDP(3);
- serverPortNumber = ports[0];
- try {
- InetAddress localHost = InetAddress.getLocalHost();
- DatagramSocket ds = new DatagramSocket(ports[1]);
- DatagramSocket ds2 = new DatagramSocket(ports[2]);
-
- try {
- server = new DatagramServer(serverPortNumber, localHost);
- server.start();
- Thread.sleep(1000);
- } catch (Exception e) {
- fail(
- "Failed to set up datagram server for native connected Dgram socket test ");
- }
-
- int port = ds.getLocalPort();
- ds.connect(new InetSocketAddress(localHost, serverPortNumber + 1));
- ds.connect(new InetSocketAddress(localHost, serverPortNumber));
-
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length);
- ds.send(send);
- DatagramPacket receive = new DatagramPacket(new byte[20], 20);
- ds.setSoTimeout(2000);
- ds.receive(receive);
- ds.close();
- assertTrue("connect/connect - Wrong size data received: "
- + receive.getLength(),
- receive.getLength() == sendBytes.length);
- assertTrue("connect/connect - Wrong data received"
- + new String(receive.getData(), 0, receive.getLength())
- + ":" + new String(sendBytes), new String(
- receive.getData(), 0, receive.getLength())
- .equals(new String(sendBytes)));
- assertTrue("connect/connect - Wrong receiver:"
- + receive.getAddress() + ":" + localHost, receive
- .getAddress().equals(localHost));
- } catch (Exception e) {
- fail(
- "Unexpected exception when sending data on dgram connected at native level after connect/connect: "
- + e.toString());
- }
-
- if (server != null) {
- server.stopServer();
- }
-
- // test for when we fail to connect at the native level. It seems to
- // fail for the any address so we use this. Now to be compatible we
- // don't throw the exception but eat it and then act as if we were
- // connected at the Java level.
- try {
- ds = new java.net.DatagramSocket();
- byte[] addressBytes = { 0, 0, 0, 0 };
- InetAddress inetAddress = InetAddress.getByAddress(addressBytes);
- int portNumber = Support_PortManager.getNextPortForUDP();
- InetAddress localHost = InetAddress.getLocalHost();
- ds.connect(new InetSocketAddress(inetAddress, portNumber));
- assertTrue("Is not connected after connect to inaddr any", ds
- .isConnected());
- byte[] sendBytes = { 'T', 'e', 's', 't', 0 };
- DatagramPacket send = new DatagramPacket(sendBytes,
- sendBytes.length, localHost, portNumber);
- ds.send(send);
- fail(
- "No exception when trying to connect at native level with bad address (exception from send) ");
- } catch (Exception e) {
- assertTrue(
- "Wrong exception when trying to connect at native level with bad address (exception from send): "
- + e.toString(),
- (e instanceof IllegalArgumentException));
- }
- }
-
- public void test_isBound() {
- try {
- InetAddress addr = InetAddress.getLocalHost();
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int port = ports[0];
-
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
- assertTrue("Socket indicated not bound when it should be (1)",
- theSocket.isBound());
- theSocket.close();
-
- theSocket = new DatagramSocket(new InetSocketAddress(addr, port));
- assertTrue("Socket indicated not bound when it should be (2)",
- theSocket.isBound());
- theSocket.close();
-
- theSocket = new DatagramSocket((SocketAddress) null);
- assertFalse("Socket indicated bound when it should not be (1)",
- theSocket.isBound());
- theSocket.close();
-
- // connect causes implicit bind
- theSocket = new DatagramSocket((SocketAddress) null);
- theSocket.connect(new InetSocketAddress(addr, port));
- assertTrue("Socket indicated not bound when it should be (3)",
- theSocket.isBound());
- theSocket.close();
-
- // now test when we bind explicitely
- InetSocketAddress theLocalAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), ports[2]);
- theSocket = new DatagramSocket((SocketAddress) null);
- assertFalse("Socket indicated bound when it should not be (2)",
- theSocket.isBound());
- theSocket.bind(theLocalAddress);
- assertTrue("Socket indicated not bound when it should be (4)",
- theSocket.isBound());
- theSocket.close();
- assertTrue("Socket indicated not bound when it should be (5)",
- theSocket.isBound());
- } catch (Exception e) {
- fail("Got exception during isBound tests" + e.toString());
- }
- }
-
- public void test_isConnected() {
- try {
- InetAddress addr = InetAddress.getLocalHost();
- int[] ports = Support_PortManager.getNextPortsForUDP(4);
- int port = ports[0];
-
- // base test
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
- assertFalse("Socket indicated connected when it should not be",
- theSocket.isConnected());
- theSocket.connect(new InetSocketAddress(addr, port));
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
-
- // reconnect the socket and make sure we get the right answer
- theSocket.connect(new InetSocketAddress(addr, ports[2]));
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
-
- // now disconnect the socket and make sure we get the right answer
- theSocket.disconnect();
- assertFalse("Socket indicated connected when it should not be",
- theSocket.isConnected());
- theSocket.close();
-
- // now check behavior when socket is closed when connected
- theSocket = new DatagramSocket(ports[3]);
- theSocket.connect(new InetSocketAddress(addr, port));
- theSocket.close();
- assertTrue("Socket indicated not connected when it should be",
- theSocket.isConnected());
- } catch (Exception e) {
- fail("Got exception during isConnected tests" + e.toString());
- }
- }
-
- public void test_getRemoteSocketAddress() {
- try {
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- int sport = ports[0];
- int portNumber = ports[1];
- DatagramSocket s = new DatagramSocket(new InetSocketAddress(
- InetAddress.getLocalHost(), portNumber));
- s.connect(new InetSocketAddress(InetAddress.getLocalHost(), sport));
- assertTrue("Returned incorrect InetSocketAddress(1):"
- + s.getLocalSocketAddress().toString(), s
- .getRemoteSocketAddress().equals(
- new InetSocketAddress(InetAddress.getLocalHost(),
- sport)));
- s.close();
-
- // now create one that is not connected and validate that we get the
- // right answer
- DatagramSocket theSocket = new DatagramSocket((SocketAddress) null);
- portNumber = ports[2];
- theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
- portNumber));
- assertNull(
- "Returned incorrect InetSocketAddress -unconnected socket:"
- + "Expected: NULL", theSocket
- .getRemoteSocketAddress());
-
- // now connect and validate we get the right answer
- theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
- sport));
- assertTrue("Returned incorrect InetSocketAddress(2):"
- + theSocket.getRemoteSocketAddress().toString(), theSocket
- .getRemoteSocketAddress().equals(
- new InetSocketAddress(InetAddress.getLocalHost(),
- sport)));
- theSocket.close();
-
- } catch (Exception e) {
- fail("Exception during getRemoteSocketAddress test: " + e);
- }
- }
-
- public void test_setReuseAddressZ() throws Exception {
- // test case were we set it to false
- DatagramSocket theSocket1 = null;
- DatagramSocket theSocket2 = null;
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new DatagramSocket((SocketAddress) null);
- theSocket2 = new DatagramSocket((SocketAddress) 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
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new DatagramSocket((SocketAddress) null);
- theSocket2 = new DatagramSocket((SocketAddress) null);
- theSocket1.setReuseAddress(true);
- theSocket2.setReuseAddress(true);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- } catch (Exception e) {
- fail(
- "unexpected exception when trying to connect to do duplicate socket bind with re-useaddr set to true");
- }
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
-
- // test the default case which we expect to be the same on all
- // platforms
- try {
- InetSocketAddress theAddress = new InetSocketAddress(
- InetAddress.getLocalHost(), Support_PortManager
- .getNextPortForUDP());
- theSocket1 = new DatagramSocket((SocketAddress) null);
- theSocket2 = new DatagramSocket((SocketAddress) null);
- theSocket1.bind(theAddress);
- theSocket2.bind(theAddress);
- fail(
- "No exception when trying to connect to do duplicate socket bind with re-useaddr left as default");
- } catch (BindException e) {
-
- }
- if (theSocket1 != null)
- theSocket1.close();
- if (theSocket2 != null)
- theSocket2.close();
-
- try {
- theSocket1.setReuseAddress(true);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_getReuseAddress() throws Exception {
- DatagramSocket theSocket = new DatagramSocket();
- 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());
- theSocket.close();
- try {
- theSocket.getReuseAddress();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_setBroadcastZ() throws Exception {
- int[] ports = Support_PortManager.getNextPortsForUDP(3);
- DatagramSocket theSocket = new DatagramSocket(ports[0]);
- theSocket.setBroadcast(false);
- byte theBytes[] = { -1, -1, -1, -1 };
-
- // validate we cannot connect to the broadcast address when
- // setBroadcast is false
- try {
- theSocket.connect(new InetSocketAddress(InetAddress
- .getByAddress(theBytes), ports[1]));
- assertFalse(
- "No exception when connecting to broadcast address with setBroadcast(false)",
- theSocket.getBroadcast());
- } catch (SocketException ex) {
- //expected
- }
-
- // now validate that we can connect to the broadcast address when
- // setBroadcast is true
- theSocket.setBroadcast(true);
- theSocket.connect(new InetSocketAddress(InetAddress
- .getByAddress(theBytes), ports[2]));
-
- theSocket.close();
- try {
- theSocket.setBroadcast(false);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_getBroadcast() throws Exception {
- DatagramSocket theSocket = new DatagramSocket();
- theSocket.setBroadcast(true);
- assertTrue("getBroadcast false when it should be true", theSocket
- .getBroadcast());
- theSocket.setBroadcast(false);
- assertFalse("getBroadcast true when it should be False", theSocket
- .getBroadcast());
- theSocket.close();
- try {
- theSocket.getBroadcast();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_setTrafficClassI() throws Exception {
- int IPTOS_LOWCOST = 0x2;
- int IPTOS_RELIABILTY = 0x4;
- int IPTOS_THROUGHPUT = 0x8;
- int IPTOS_LOWDELAY = 0x10;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
-
- new InetSocketAddress(InetAddress.getLocalHost(),
- ports[0]);
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
-
- // validate that value set must be between 0 and 255
- try {
- theSocket.setTrafficClass(256);
- fail("No exception when traffic class set to 256");
- } catch (IllegalArgumentException e) {
- }
-
- try {
- theSocket.setTrafficClass(-1);
- fail("No exception when traffic class set to -1");
- } catch (IllegalArgumentException e) {
- }
-
- // now validate that we can set it to some good values
- theSocket.setTrafficClass(IPTOS_LOWCOST);
- theSocket.setTrafficClass(IPTOS_THROUGHPUT);
-
- theSocket.close();
- try {
- theSocket.setTrafficClass(1);
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_getTrafficClass() throws Exception {
- int IPTOS_LOWCOST = 0x2;
- int IPTOS_RELIABILTY = 0x4;
- int IPTOS_THROUGHPUT = 0x8;
- int IPTOS_LOWDELAY = 0x10;
- int[] ports = Support_PortManager.getNextPortsForUDP(2);
-
- new InetSocketAddress(InetAddress.getLocalHost(),
- ports[0]);
- DatagramSocket theSocket = new DatagramSocket(ports[1]);
-
- /*
- * we cannot actually check that the values are set as if a platform
- * does not support the option then it may come back unset even
- * though we set it so just get the value to make sure we can get it
- */
- int trafficClass = theSocket.getTrafficClass();
-
- theSocket.close();
- try {
- theSocket.getTrafficClass();
- fail("SocketException was not thrown.");
- } catch(SocketException se) {
- //expected
- }
- }
-
- public void test_isClosed() {
- try {
- DatagramSocket theSocket = new DatagramSocket();
-
- // validate isClosed returns expected values
- assertFalse("Socket should indicate it is not closed(1):",
- theSocket.isClosed());
- theSocket.close();
- assertTrue("Socket should indicate it is not closed(1):", theSocket
- .isClosed());
-
- InetSocketAddress theAddress = new InetSocketAddress(InetAddress
- .getLocalHost(), Support_PortManager.getNextPortForUDP());
- theSocket = new DatagramSocket(theAddress);
- assertFalse("Socket should indicate it is not closed(2):",
- theSocket.isClosed());
- theSocket.close();
- assertTrue("Socket should indicate it is not closed(2):", theSocket
- .isClosed());
- } catch (Exception e) {
- fail("Got exception during isClosed tests" + e.toString());
- }
- }
-
- public void test_getChannel() throws Exception {
- assertNull(new DatagramSocket().getChannel());
-
- int portNumber = Support_PortManager.getNextPortForUDP();
- DatagramSocket ds = null;
- try {
- InetAddress ia = InetAddress
- .getByName(Support_Configuration.IPv6GlobalAddressJcl4);
- ds = new DatagramSocket();
- assertNull(ds.getChannel());
- ds.connect(ia, portNumber);
- assertNull(ds.getChannel());
- } catch (SocketException e) {
- fail("SocketException was thrown.");
- } finally {
- ds.disconnect();
- ds.close();
- }
- portNumber = Support_PortManager.getNextPortForUDP();
- SocketAddress address = new InetSocketAddress(portNumber);
- DatagramChannel channel = DatagramChannel.open();
- DatagramSocket socket = channel.socket();
- assertEquals(channel, socket.getChannel());
- socket.close();
- }
-
- class TestDatagramSocketImplFactory implements DatagramSocketImplFactory {
- public DatagramSocketImpl createDatagramSocketImpl() {
- return new TestDatagramSocketImpl();
- }
- }
-
- class TestDatagramSocketImpl extends DatagramSocketImpl {
-
- @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
- protected void create() throws SocketException {
- // TODO Auto-generated method stub
-
- }
-
- @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
- protected int peek(InetAddress arg0) throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @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
-
- }
-
- }
-
- /**
- * Sets up the fixture, for example, open a network connection. This method
- * is called before a test is executed.
- */
- protected void setUp() {
- retval = "Bogus retval";
- }
-
- /**
- * Tears down the fixture, for example, close a network connection. This
- * method is called after a test is executed.
- */
- protected void tearDown() {
- try {
- ds.close();
- sds.close();
- } catch (Exception e) {
- }
- }
-
- protected void receive_oversize_java_net_DatagramPacket() throws Exception {
- final int[] ports = Support_PortManager.getNextPortsForUDP(2);
- final int portNumber = ports[0];
-
- class TestDGRcvOver implements Runnable {
- public void run() {
- InetAddress localHost = null;
- try {
- localHost = InetAddress.getLocalHost();
- Thread.sleep(1000);
- DatagramSocket sds = new DatagramSocket(ports[1]);
- DatagramPacket rdp = new DatagramPacket("0123456789"
- .getBytes(), 10, localHost, portNumber);
- sds.send(rdp);
- sds.close();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- try {
- new Thread(new TestDGRcvOver(), "DGSenderOver").start();
- ds = new java.net.DatagramSocket(portNumber);
- ds.setSoTimeout(6000);
- byte rbuf[] = new byte[5];
- DatagramPacket rdp = new DatagramPacket(rbuf, rbuf.length);
- ;
- ds.receive(rdp);
- ds.close();
- assertTrue("Send/Receive oversize failed to return correct data: "
- + new String(rbuf, 0, 5), new String(rbuf, 0, 5)
- .equals("01234"));
- } finally {
- ds.close();
- }
- }
-}
diff --git a/support/src/test/java/tests/support/Support_PortManager.java b/support/src/test/java/tests/support/Support_PortManager.java
deleted file mode 100644
index b68a445..0000000
--- a/support/src/test/java/tests/support/Support_PortManager.java
+++ /dev/null
@@ -1,105 +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.support;
-
-import java.net.DatagramSocket;
-import java.net.ServerSocket;
-import java.util.Calendar;
-import java.util.TimeZone;
-
-/**
- * The port manager is supposed to help finding a free
- * network port on the machine; however, it uses strange
- * logic, so leave it to the OS.
- *
- * @deprecated Use the OS to find free ports.
- */
-public class Support_PortManager {
-
- private static int lastAssignedPort = somewhatRandomPort();
- private static boolean failedOnce = false;
-
- public static synchronized int getNextPort() {
- if (!failedOnce) {
- try {
- ServerSocket ss = new ServerSocket(0);
- int port = ss.getLocalPort();
-
- ss.close();
- return port;
- } catch (Exception ex) {
- failedOnce = true;
- }
- }
- return getNextPort_unsafe();
- }
-
- /**
- * Returns 1 free ports to be used.
- */
- public static synchronized int getNextPortForUDP() {
- return getNextPortsForUDP(1)[0];
- }
-
- /**
- * Returns the specified number of free ports to be used.
- */
- public static synchronized int[] getNextPortsForUDP(int num) {
- if (num <= 0) {
- throw new IllegalArgumentException("Invalid ports number: " + num);
- }
- DatagramSocket[] dss = new DatagramSocket[num];
- int[] ports = new int[num];
-
- try {
- for (int i = 0; i < num; ++i) {
- dss[i] = new DatagramSocket(0);
- ports[i] = dss[i].getLocalPort();
- }
- } catch (Exception ex) {
- throw new Error("Unable to get " + num + " ports for UDP: " + ex);
- } finally {
- for (int i = 0; i < num; ++i) {
- if (dss[i] != null) {
- dss[i].close();
- }
- }
- }
- return ports;
- }
-
- public static synchronized int getNextPort_unsafe() {
- if (++lastAssignedPort > 65534) {
- lastAssignedPort = 6000;
- }
- return lastAssignedPort;
- }
-
- /*
- * Returns a different port number every 6 seconds or so. The port number
- * should be about += 100 at each 6 second interval
- */
- private static int somewhatRandomPort() {
- Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
- int minutes = c.get(Calendar.MINUTE);
- int seconds = c.get(Calendar.SECOND);
-
- return 6000 + (1000 * minutes) + ((seconds / 6) * 100);
- }
-
-}