OldSocketTest.java revision 04e25f30524dc7b51f280912d6ca97d991ae84b0
1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package libcore.java.net;
19
20import java.io.IOException;
21import java.io.InputStream;
22import java.io.OutputStream;
23import java.net.BindException;
24import java.net.ConnectException;
25import java.net.Inet4Address;
26import java.net.Inet6Address;
27import java.net.InetAddress;
28import java.net.InetSocketAddress;
29import java.net.Proxy;
30import java.net.ServerSocket;
31import java.net.Socket;
32import java.net.SocketAddress;
33import java.net.SocketException;
34import java.net.SocketImpl;
35import java.net.SocketTimeoutException;
36import java.net.UnknownHostException;
37import java.nio.channels.IllegalBlockingModeException;
38import java.nio.channels.SocketChannel;
39import java.security.Permission;
40import tests.support.Support_Configuration;
41import tests.support.Support_PortManager;
42
43public class OldSocketTest extends OldSocketTestCase {
44
45    ServerSocket ss;
46
47    Socket s;
48
49    Thread t;
50
51    SecurityManager sm = new SecurityManager() {
52
53        public void checkPermission(Permission perm) {}
54
55        public void checkConnect(String host, int port) {
56            throw new SecurityException();
57        }
58    };
59
60    public void test_Constructor() {
61        // create the socket and then validate some basic state
62        s = new Socket();
63        assertFalse("new socket should not be connected", s.isConnected());
64        assertFalse("new socket should not be bound", s.isBound());
65        assertFalse("new socket should not be closed", s.isClosed());
66        assertFalse("new socket should not be in InputShutdown", s
67                .isInputShutdown());
68        assertFalse("new socket should not be in OutputShutdown", s
69                .isOutputShutdown());
70
71    }
72
73    public void test_ConstructorLjava_lang_StringI() throws IOException {
74        // Test for method java.net.Socket(java.lang.String, int)
75        int sport = startServer("Cons String,I");
76        s = new Socket(InetAddress.getLocalHost().getHostName(), sport);
77        assertTrue("Failed to create socket", s.getPort() == sport);
78
79        //regression for HARMONY-946
80        ServerSocket ss = null;
81        Socket s = null;
82        try {
83            ss = new ServerSocket(0);
84            s = new Socket("0.0.0.0", ss.getLocalPort());
85        } finally {
86            try {
87                ss.close();
88            } catch(Exception e) {
89                //ignore
90            }
91            try {
92                s.close();
93            } catch(Exception e) {
94                //ignore
95            }
96        }
97
98        try {
99            new Socket("unknown.host", 0);
100            fail("UnknownHostException was not thrown.");
101        } catch(UnknownHostException uhe) {
102            //expected
103        }
104        Socket socket = null;
105        try {
106            socket = new Socket(InetAddress.getByName(null), sport);
107            InetAddress address = socket.getLocalAddress();
108            assertTrue(address.isLoopbackAddress());
109        } finally {
110            try {
111                socket.close();
112            } catch(Exception e) {}
113        }
114    }
115
116    public void test_ConstructorLjava_lang_StringILjava_net_InetAddressI1() throws IOException {
117        int sport = startServer("Cons String,I,InetAddress,I");
118        int portNumber = Support_PortManager.getNextPort();
119        s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
120                InetAddress.getLocalHost(), portNumber);
121        assertTrue("Failed to create socket", s.getPort() == sport);
122    }
123
124    public void test_ConstructorLjava_lang_StringILjava_net_InetAddressI2() throws IOException {
125        int testPort = Support_PortManager.getNextPort();
126        Socket s1 = new Socket("www.google.com", 80, null, testPort);
127        try {
128            Socket s2 = new Socket("www.google.com", 80, null, testPort);
129            try {
130                s2.close();
131            } catch (IOException ignored) {
132            }
133            fail("second connect should have failed with EADDRINUSE");
134        } catch (BindException expected) {
135            // success!
136        } finally {
137            try {
138                s1.close();
139            } catch (IOException ignored) {
140            }
141        }
142    }
143
144    public void test_ConstructorLjava_lang_StringIZ() throws IOException {
145        // Test for method java.net.Socket(java.lang.String, int, boolean)
146        int sport = startServer("Cons String,I,Z");
147        s = new Socket(InetAddress.getLocalHost().getHostName(), sport, true);
148        assertTrue("Failed to create socket", s.getPort() == sport);
149
150        s = new Socket(InetAddress.getLocalHost().getHostName(), sport, false);
151    }
152
153    public void test_ConstructorLjava_net_InetAddressI() throws IOException {
154        // Test for method java.net.Socket(java.net.InetAddress, int)
155        int sport = startServer("Cons InetAddress,I");
156        s = new Socket(InetAddress.getLocalHost(), sport);
157        assertTrue("Failed to create socket", s.getPort() == sport);
158    }
159
160    public void test_ConstructorLjava_net_InetAddressILjava_net_InetAddressI()
161            throws IOException {
162        // Test for method java.net.Socket(java.net.InetAddress, int,
163        // java.net.InetAddress, int)
164        int sport = startServer("Cons InetAddress,I,InetAddress,I");
165        int portNumber = Support_PortManager.getNextPort();
166        s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
167                InetAddress.getLocalHost(), portNumber);
168        assertTrue("Failed to create socket", s.getLocalPort() == portNumber);
169    }
170
171    public void test_ConstructorLjava_net_InetAddressIZ() throws IOException {
172        // Test for method java.net.Socket(java.net.InetAddress, int, boolean)
173        int sport = startServer("Cons InetAddress,I,Z");
174        s = new Socket(InetAddress.getLocalHost(), sport, true);
175        assertTrue("Failed to create socket", s.getPort() == sport);
176
177        s = new Socket(InetAddress.getLocalHost(), sport, false);
178    }
179
180    public void test_close() throws IOException {
181        // Test for method void java.net.Socket.close()
182        int sport = startServer("SServer close");
183        int portNumber = Support_PortManager.getNextPort();
184        s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
185        try {
186            s.setSoLinger(false, 100);
187        } catch (IOException e) {
188            handleException(e, SO_LINGER);
189        }
190        s.close();
191        try {
192            s.getOutputStream();
193            fail("IOException was not thrown.");
194        } catch (java.io.IOException e) {
195            //expected
196        }
197    }
198
199    public void test_getInetAddress() throws IOException {
200        // Test for method java.net.InetAddress java.net.Socket.getInetAddress()
201        int sport = startServer("SServer getInetAddress");
202        int portNumber = Support_PortManager.getNextPort();
203        s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
204        assertTrue("Returned incorrect InetAddress", s.getInetAddress().equals(
205                InetAddress.getLocalHost()));
206
207    }
208
209    public void test_getInputStream() throws IOException {
210        // Simple fetch test
211        ServerSocket server = new ServerSocket(0);
212        Socket client = new Socket(InetAddress.getLocalHost(), server.getLocalPort());
213        InputStream is = client.getInputStream();
214        assertNotNull("Failed to get stream", is);
215        is.close();
216        client.close();
217        server.close();
218    }
219
220    public void test_getKeepAlive() {
221        try {
222            int sport = startServer("SServer getKeepAlive");
223            int portNumber = Support_PortManager.getNextPort();
224            Socket theSocket = new Socket(InetAddress.getLocalHost(), sport,
225                    null, portNumber);
226            theSocket.setKeepAlive(true);
227            assertTrue("getKeepAlive false when it should be true", theSocket
228                    .getKeepAlive());
229            theSocket.setKeepAlive(false);
230            assertFalse("getKeepAlive true when it should be False", theSocket
231                    .getKeepAlive());
232            theSocket.close();
233            try {
234                theSocket.setKeepAlive(false);
235                fail("IOException was not thrown after calling setKeepAlive " +
236                        "method.");
237            } catch(IOException ioe) {
238                //expected
239            }
240            try {
241                theSocket.getKeepAlive();
242                fail("IOException was not thrown after calling getKeepAlive +" +
243                        "method.");
244            } catch(IOException ioe) {
245                //expected
246            }
247            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_KEEPALIVE);
248        } catch (Exception e) {
249            handleException(e, SO_KEEPALIVE);
250        }
251    }
252
253    public void test_getLocalAddress() throws IOException {
254        // Test for method java.net.InetAddress
255        // java.net.Socket.getLocalAddress()
256        int sport = startServer("SServer getLocAddress");
257        int portNumber = Support_PortManager.getNextPort();
258        s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
259        assertEquals("Returned incorrect InetAddress",
260                InetAddress.getLocalHost(), s.getLocalAddress());
261
262        // now check behavior when the ANY address is returned
263        s = new Socket();
264        s.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
265
266        assertTrue("ANY address not IPv6: " + s.getLocalSocketAddress(),
267                    s.getLocalAddress() instanceof Inet6Address);
268        s.close();
269    }
270
271    public void test_getLocalPort() throws IOException {
272        // Test for method int java.net.Socket.getLocalPort()
273        int sport = startServer("SServer getLocalPort");
274        int portNumber = Support_PortManager.getNextPort();
275        s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
276                InetAddress.getLocalHost(), portNumber);
277        assertTrue("Returned incorrect port", s.getLocalPort() == portNumber);
278    }
279
280    @SuppressWarnings("deprecation")
281    public void test_getOutputStream() throws IOException {
282        // Test for method java.io.OutputStream
283        // java.net.Socket.getOutputStream()
284        int sport = startServer("SServer getOutputStream");
285        int portNumber = Support_PortManager.getNextPort();
286        s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
287        java.io.OutputStream os = s.getOutputStream();
288        assertNotNull("Failed to get stream", os);
289        os.write(1);
290        s.close();
291        // Regression test for harmony-2934
292        s = new Socket("127.0.0.1", Support_PortManager.getNextPort(),
293                false);
294        OutputStream o = s.getOutputStream();
295        o.write(1);
296        try {
297            Thread.sleep(1000);
298        } catch (InterruptedException e) {
299        }
300        o.close();
301        s.close();
302
303        // Regression test for harmony-2942
304        s = new Socket("0.0.0.0", Support_PortManager.getNextPort(),
305                false);
306        o = s.getOutputStream();
307        o.write(1);
308        try {
309            Thread.sleep(1000);
310        } catch (InterruptedException e) {
311        }
312        o.close();
313        s.close();
314    }
315
316    public void test_getPort() throws IOException {
317        // Test for method int java.net.Socket.getPort()
318        int sport = startServer("SServer getPort");
319        int portNumber = Support_PortManager.getNextPort();
320        s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
321        assertTrue("Returned incorrect port" + s.getPort(),
322                s.getPort() == sport);
323    }
324
325    public void test_getSoLinger() {
326        // Test for method int java.net.Socket.getSoLinger()
327        int sport = startServer("SServer getSoLinger");
328        try {
329            int portNumber = Support_PortManager.getNextPort();
330            s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
331            s.setSoLinger(true, 200);
332            assertEquals("Returned incorrect linger", 200, s.getSoLinger());
333            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_LINGER);
334            s.setSoLinger(false, 0);
335        } catch (Exception e) {
336            handleException(e, SO_LINGER);
337        }
338
339        try {
340            int portNumber = Support_PortManager.getNextPort();
341            s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
342            s.close();
343            try {
344                s.getSoLinger();
345                fail("SocketException was not thrown.");
346            } catch(SocketException ioe) {
347                //expected
348            }
349        } catch(Exception e) {
350            fail("Unexpected exception was thrown: " + e.toString());
351        }
352    }
353
354    public void test_getReceiveBufferSize() {
355        try {
356            int sport = startServer("SServer getReceiveBufferSize");
357            int portNumber = Support_PortManager.getNextPort();
358            s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
359                    null, portNumber);
360            s.setReceiveBufferSize(130);
361            assertTrue("Incorrect buffer size", s.getReceiveBufferSize() >= 130);
362            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
363        } catch (Exception e) {
364            handleException(e, SO_RCVBUF);
365        }
366
367        try {
368            Socket newSocket = new Socket();
369            newSocket.close();
370            try {
371                newSocket.getReceiveBufferSize();
372                fail("SocketException was not thrown.");
373            } catch(SocketException e) {
374                //expected
375            }
376        } catch(Exception e) {
377            fail("Unexpected exception.");
378        }
379    }
380
381    public void test_getSendBufferSize() {
382        int sport = startServer("SServer setSendBufferSize");
383        try {
384            int portNumber = Support_PortManager.getNextPort();
385            s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
386                    null, portNumber);
387            s.setSendBufferSize(134);
388            assertTrue("Incorrect buffer size", s.getSendBufferSize() >= 134);
389            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_SNDBUF);
390        } catch (Exception e) {
391            handleException(e, SO_SNDBUF);
392        }
393        try {
394            int portNumber = Support_PortManager.getNextPort();
395            s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
396            s.close();
397            try {
398                s.getSendBufferSize();
399                fail("IOException was not thrown.");
400            } catch(IOException ioe) {
401                //expected
402            }
403        } catch(Exception e) {
404            fail("Unexpected exception was thrown: " + e.toString());
405        }
406    }
407
408    public void test_getSoTimeout_setSoTimeout() throws Exception {
409        // TODO: a useful test would check that setSoTimeout actually causes timeouts!
410        Socket s = new Socket();
411        s.setSoTimeout(1500);
412        int ms = s.getSoTimeout();
413        if (ms < 1500-10 || ms > 1500+10) {
414            fail("suspicious timeout: " + ms);
415        }
416        s.close();
417        try {
418            s.getSoTimeout();
419            fail("SocketException was not thrown.");
420        } catch (SocketException expected) {
421        }
422        try {
423            s.setSoTimeout(1000);
424            fail("SocketException was not thrown.");
425        } catch (SocketException expected) {
426        }
427    }
428
429    public void test_getTcpNoDelay() {
430        // Test for method boolean java.net.Socket.getTcpNoDelay()
431        int sport = startServer("SServer getTcpNoDelay");
432        try {
433            int portNumber = Support_PortManager.getNextPort();
434            s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
435            boolean bool = !s.getTcpNoDelay();
436            s.setTcpNoDelay(bool);
437            assertTrue("Failed to get no delay setting: " + s.getTcpNoDelay(),
438                    s.getTcpNoDelay() == bool);
439            ensureExceptionThrownIfOptionIsUnsupportedOnOS(TCP_NODELAY);
440        } catch (Exception e) {
441            handleException(e, TCP_NODELAY);
442        }
443
444        try {
445            int portNumber = Support_PortManager.getNextPort();
446            s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
447            s.close();
448            try {
449                s.getTcpNoDelay();
450                fail("SocketException was not thrown.");
451            } catch(SocketException ioe) {
452                //expected
453            }
454        } catch(Exception e) {
455            fail("Unexpected exception was thrown: " + e.toString());
456        }
457    }
458
459    public void test_setKeepAliveZ() throws Exception {
460        // There is not really a good test for this as it is there to detect
461        // crashed machines. Just make sure we can set it
462        try {
463            int sport = startServer("SServer setKeepAlive");
464            int portNumber = Support_PortManager.getNextPort();
465            Socket theSocket = new Socket(InetAddress.getLocalHost(), sport,
466                    null, portNumber);
467            theSocket.setKeepAlive(true);
468            theSocket.setKeepAlive(false);
469            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_KEEPALIVE);
470        } catch (Exception e) {
471            handleException(e, SO_KEEPALIVE);
472        }
473        // regression test for HARMONY-1136
474        new TestSocket((SocketImpl) null).setKeepAlive(true);
475
476        try {
477            Socket theSocket = new Socket();
478            theSocket.close();
479            theSocket.setKeepAlive(true);
480            fail("SocketException was not thrown.");
481        } catch(SocketException ioe) {
482            //expected
483        }
484    }
485    class TestSocket extends Socket {
486        public TestSocket(SocketImpl impl) throws SocketException {
487            super(impl);
488        }
489    }
490
491    public void test_setSocketImplFactoryLjava_net_SocketImplFactory() {
492        // Test for method void
493        // java.net.Socket.setSocketImplFactory(java.net.SocketImplFactory)
494
495        // Cannot test as setting will cause the factory to be changed for
496        // all subsequent sockets
497
498        SecurityManager sm = new SecurityManager() {
499
500            public void checkPermission(Permission perm) {
501            }
502
503            public void checkSetFactory() {
504                throw new SecurityException();
505            }
506        };
507    }
508
509    public void test_setSendBufferSizeI() {
510        try {
511            int sport = startServer("SServer setSendBufferSizeI");
512            int portNumber = Support_PortManager.getNextPort();
513            s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
514            s.setSendBufferSize(134);
515            assertTrue("Incorrect buffer size", s.getSendBufferSize() >= 134);
516            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_SNDBUF);
517        } catch (Exception e) {
518            handleException(e, SO_SNDBUF);
519        }
520
521        try {
522            Socket theSocket = new Socket();
523            theSocket.close();
524            theSocket.setSendBufferSize(1);
525            fail("SocketException was not thrown.");
526        } catch(SocketException ioe) {
527            //expected
528        } catch(IOException ioe) {
529            fail("IOException was thrown.");
530        }
531    }
532
533    public void test_setReceiveBufferSizeI() {
534        try {
535            int sport = startServer("SServer setReceiveBufferSizeI");
536            int portNumber = Support_PortManager.getNextPort();
537            s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
538            s.setReceiveBufferSize(130);
539            assertTrue("Incorrect buffer size", s.getReceiveBufferSize() >= 130);
540            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
541        } catch (Exception e) {
542            handleException(e, SO_RCVBUF);
543        }
544
545        try {
546            Socket theSocket = new Socket();
547            theSocket.close();
548            theSocket.setReceiveBufferSize(1);
549            fail("SocketException was not thrown.");
550        } catch(SocketException ioe) {
551            //expected
552        } catch(IOException ioe) {
553            fail("IOException was thrown.");
554        }
555    }
556
557    public void test_setSoLingerZI() {
558        // Test for method void java.net.Socket.setSoLinger(boolean, int)
559        try {
560            int sport = startServer("SServer setSoLingerZI");
561            int portNumber = Support_PortManager.getNextPort();
562            s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
563            s.setSoLinger(true, 500);
564            assertEquals("Set incorrect linger", 500, s.getSoLinger());
565            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_LINGER);
566            s.setSoLinger(false, 0);
567        } catch (Exception e) {
568            handleException(e, SO_LINGER);
569        }
570
571        try {
572            Socket theSocket = new Socket();
573            theSocket.close();
574            theSocket.setSoLinger(true, 1);
575            fail("SocketException was not thrown.");
576        } catch(SocketException ioe) {
577            //expected
578        } catch(IOException ioe) {
579            fail("IOException was thrown.");
580        }
581    }
582
583    public void test_setTcpNoDelayZ() {
584        // Test for method void java.net.Socket.setTcpNoDelay(boolean)
585        try {
586            int sport = startServer("SServer setTcpNoDelayZ");
587            int portNumber = Support_PortManager.getNextPort();
588            s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
589            boolean bool;
590            s.setTcpNoDelay(bool = !s.getTcpNoDelay());
591            assertTrue("Failed to set no delay setting: " + s.getTcpNoDelay(),
592                    s.getTcpNoDelay() == bool);
593            ensureExceptionThrownIfOptionIsUnsupportedOnOS(TCP_NODELAY);
594        } catch (Exception e) {
595            handleException(e, TCP_NODELAY);
596        }
597
598        try {
599            Socket theSocket = new Socket();
600            theSocket.close();
601            theSocket.setTcpNoDelay(true);
602            fail("SocketException was not thrown.");
603        } catch(SocketException ioe) {
604            //expected
605        } catch(IOException ioe) {
606            fail("IOException was thrown.");
607        }
608    }
609
610    public void test_toString() throws IOException {
611        // Test for method java.lang.String java.net.Socket.toString()
612        int sport = startServer("SServer toString");
613        int portNumber = Support_PortManager.getNextPort();
614        s = new Socket(InetAddress.getLocalHost().getHostName(), sport,
615                InetAddress.getLocalHost(), portNumber);
616        assertEquals("Socket[address=" + InetAddress.getLocalHost() + ",port=" + s.getPort()
617                + ",localPort=" + s.getLocalPort() + "]", s.toString());
618    }
619
620    // AndroidOnly: RI returns wrong value for EOF
621    public void test_shutdownInput() throws Exception {
622        InetAddress addr = InetAddress.getLocalHost();
623        int port = Support_PortManager.getNextPort();
624        ServerSocket serverSocket = new ServerSocket(port, 5, addr);
625        Socket theSocket = new Socket(addr, port);
626        Socket servSock = serverSocket.accept();
627
628        InputStream theInput = theSocket.getInputStream();
629        OutputStream theOutput = servSock.getOutputStream();
630
631        // shutdown the input
632        theSocket.shutdownInput();
633
634        // send the regular data
635        String sendString = new String("Test");
636        theOutput.write(sendString.getBytes());
637        theOutput.flush();
638
639        // give things some time to settle
640        Thread.sleep(1000);
641
642        // RI fails here. It is a RI bug not to return 0 to indicate EOF
643        assertEquals(0, theInput.available());
644
645        theSocket.close();
646        serverSocket.close();
647
648        Socket socket = new Socket();
649        socket.close();
650        try {
651            socket.shutdownInput();
652            fail("IOException was not thrown.");
653        } catch(IOException ioe) {
654            //expected
655        }
656    }
657
658    public void test_shutdownOutput() throws IOException {
659        InetAddress addr = InetAddress.getLocalHost();
660        int port = Support_PortManager.getNextPort();
661        ServerSocket serverSocket = new ServerSocket(port, 5, addr);
662        Socket theSocket = new Socket(addr, port);
663        Socket servSock = serverSocket.accept();
664
665        InputStream theInput = theSocket.getInputStream();
666        OutputStream theOutput = servSock.getOutputStream();
667
668        // shutdown the output
669        servSock.shutdownOutput();
670
671        // send the regular data
672        String sendString = new String("Test");
673        try {
674            theOutput.write(sendString.getBytes());
675            theOutput.flush();
676            fail("No exception when writing on socket with output shutdown");
677        } catch (Exception e) {
678        }
679
680        theSocket.close();
681        serverSocket.close();
682
683        try {
684            theSocket.shutdownInput();
685            fail("IOException was not thrown.");
686        } catch(IOException ioe) {
687            //expected
688        }
689    }
690
691    public void test_getLocalSocketAddress() throws IOException {
692        // set up server connect and then validate that we get the right
693        // response for the local address
694        int sport = startServer("SServer getLocSocketAddress");
695        int portNumber = Support_PortManager.getNextPort();
696        s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
697        assertTrue(
698                "Returned incorrect InetSocketAddress(1):"
699                        + s.getLocalSocketAddress().toString()
700                        + "Expected: "
701                        + (new InetSocketAddress(InetAddress.getLocalHost(),
702                                portNumber)).toString(), s
703                        .getLocalSocketAddress().equals(
704                                new InetSocketAddress(InetAddress
705                                        .getLocalHost(), portNumber)));
706        s.close();
707
708        // now create a socket that is not bound and validate we get the
709        // right answer
710        Socket theSocket = new Socket();
711        assertNull(
712                "Returned incorrect InetSocketAddress -unbound socket- Expected null",
713                theSocket.getLocalSocketAddress());
714
715        // now bind the socket and make sure we get the right answer
716        portNumber = Support_PortManager.getNextPort();
717        theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
718                portNumber));
719        assertTrue(
720                "Returned incorrect InetSocketAddress(2):"
721                        + theSocket.getLocalSocketAddress().toString()
722                        + "Expected: "
723                        + (new InetSocketAddress(InetAddress.getLocalHost(),
724                                portNumber)).toString(), theSocket
725                        .getLocalSocketAddress().equals(
726                                new InetSocketAddress(InetAddress
727                                        .getLocalHost(), portNumber)));
728        theSocket.close();
729
730        // now validate that behaviour when the any address is returned
731        s = new Socket();
732        s.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
733
734        assertTrue("ANY address not IPv6: " + s.getLocalSocketAddress(),
735                ((InetSocketAddress) s.getLocalSocketAddress()).getAddress() instanceof Inet6Address);
736        s.close();
737
738        // now validate the same for getLocalAddress
739        s = new Socket();
740        s.bind(new InetSocketAddress(InetAddress.getByName("0.0.0.0"), 0));
741        assertTrue("ANY address not IPv6: " + s.getLocalSocketAddress(),
742                ((InetSocketAddress) s.getLocalSocketAddress()).getAddress() instanceof Inet6Address);
743        s.close();
744    }
745
746    public void test_getRemoteSocketAddress() throws IOException {
747        // set up server connect and then validate that we get the right
748        // response for the remote address
749        int sport = startServer("SServer getLocRemoteAddress");
750        int portNumber = Support_PortManager.getNextPort();
751        s = new Socket(InetAddress.getLocalHost(), sport, null, portNumber);
752        assertTrue("Returned incorrect InetSocketAddress(1):"
753                + s.getLocalSocketAddress().toString(),
754                s.getRemoteSocketAddress()
755                        .equals(
756                                new InetSocketAddress(InetAddress
757                                        .getLocalHost(), sport)));
758        s.close();
759
760        // now create one that is not connect and validate that we get the
761        // right answer
762        Socket theSocket = new Socket();
763        portNumber = Support_PortManager.getNextPort();
764        theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
765                portNumber));
766
767        assertNull("Returned incorrect InetSocketAddress -unconnected socket:"
768                + "Expected: NULL", theSocket.getRemoteSocketAddress());
769
770        // now connect and validate we get the right answer
771        theSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(),
772                sport));
773        assertTrue("Returned incorrect InetSocketAddress(2):"
774                + theSocket.getRemoteSocketAddress().toString(),
775                theSocket.getRemoteSocketAddress()
776                        .equals(
777                                new InetSocketAddress(InetAddress
778                                        .getLocalHost(), sport)));
779        theSocket.close();
780
781    }
782
783    public void test_isBound() throws IOException {
784        InetAddress addr = InetAddress.getLocalHost();
785        int port = Support_PortManager.getNextPort();
786        ServerSocket serverSocket = new ServerSocket(port, 5, addr);
787        Socket theSocket = new Socket(addr, port);
788        Socket servSock = serverSocket.accept();
789        assertTrue("Socket indicated  not bound when it should be (1)",
790                theSocket.isBound());
791        theSocket.close();
792        serverSocket.close();
793
794        // now do it with the new constructors and revalidate. Connect causes
795        // the socket to be bound
796        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
797                .getLocalHost(), Support_PortManager.getNextPort());
798        theSocket = new Socket();
799        assertFalse("Socket indicated bound when it was not (2)", theSocket
800                .isBound());
801        serverSocket = new ServerSocket();
802        serverSocket.bind(theAddress);
803        theSocket.connect(theAddress);
804        servSock = serverSocket.accept();
805        assertTrue("Socket indicated not bound when it should be (2)",
806                theSocket.isBound());
807        theSocket.close();
808        serverSocket.close();
809
810        // now test when we bind explicitly
811        InetSocketAddress theLocalAddress = new InetSocketAddress(InetAddress
812                .getLocalHost(), Support_PortManager.getNextPort());
813        theSocket = new Socket();
814        assertFalse("Socket indicated bound when it was not (3)", theSocket
815                .isBound());
816        theSocket.bind(theLocalAddress);
817        assertTrue("Socket indicated not bound when it should be (3a)",
818                theSocket.isBound());
819        theSocket.close();
820        assertTrue("Socket indicated not bound when it should be (3b)",
821                theSocket.isBound());
822    }
823
824    public void test_isConnected() throws IOException {
825        InetAddress addr = InetAddress.getLocalHost();
826        int port = Support_PortManager.getNextPort();
827        ServerSocket serverSocket = new ServerSocket(port, 5, addr);
828        Socket theSocket = new Socket(addr, port);
829        Socket servSock = serverSocket.accept();
830        assertTrue("Socket indicated  not connected when it should be",
831                theSocket.isConnected());
832        theSocket.close();
833        serverSocket.close();
834
835        // now do it with the new constructors and revalidate
836        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
837                .getLocalHost(), Support_PortManager.getNextPort());
838        theSocket = new Socket();
839        assertFalse("Socket indicated connected when it was not", theSocket
840                .isConnected());
841        serverSocket = new ServerSocket();
842        serverSocket.bind(theAddress);
843        theSocket.connect(theAddress);
844        servSock = serverSocket.accept();
845        assertTrue("Socket indicated  not connected when it should be",
846                theSocket.isConnected());
847        theSocket.close();
848        serverSocket.close();
849    }
850
851    public void test_isClosed() throws IOException {
852        InetAddress addr = InetAddress.getLocalHost();
853        int port = Support_PortManager.getNextPort();
854        ServerSocket serverSocket = new ServerSocket(port, 5, addr);
855        Socket theSocket = new Socket(addr, port);
856        Socket servSock = serverSocket.accept();
857
858        // validate isClosed returns expected values
859        assertFalse("Socket should indicate it is not closed(1):", theSocket
860                .isClosed());
861        theSocket.close();
862        assertTrue("Socket should indicate it is closed(1):", theSocket
863                .isClosed());
864
865        theSocket = new Socket(addr, port);
866        assertFalse("Socket should indicate it is not closed(2):", theSocket
867                .isClosed());
868        theSocket.close();
869        assertTrue("Socket should indicate it is closed(2):", theSocket
870                .isClosed());
871
872        // validate that isClosed works ok for sockets returned from
873        // ServerSocket.accept()
874        assertFalse("Server Socket should indicate it is not closed:", servSock
875                .isClosed());
876        servSock.close();
877        assertTrue("Server Socket should indicate it is closed:", servSock
878                .isClosed());
879    }
880
881    public void test_bindLjava_net_SocketAddress() throws IOException {
882
883        class mySocketAddress extends SocketAddress {
884
885            public mySocketAddress() {
886            }
887        }
888
889        // Address we cannot bind to
890        Socket theSocket = new Socket();
891        try {
892            theSocket.bind(new InetSocketAddress(InetAddress
893                    .getByAddress(Support_Configuration.nonLocalAddressBytes),
894                    Support_PortManager.getNextPort()));
895            fail("No exception when binding to bad address:"
896                   + theSocket.getLocalSocketAddress().toString());
897        } catch (IOException ex) {
898        }
899        theSocket.close();
900
901        // now create a socket that is not bound and then bind it
902        theSocket = new Socket();
903        int portNumber = Support_PortManager.getNextPort();
904        theSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(),
905                portNumber));
906
907        // validate that the localSocketAddress reflects the address we
908        // bound to
909        assertTrue(
910                "Local address not correct after bind:"
911                        + theSocket.getLocalSocketAddress().toString()
912                        + " Expected: "
913                        + (new InetSocketAddress(InetAddress.getLocalHost(),
914                                portNumber)).toString(), theSocket
915                        .getLocalSocketAddress().equals(
916                                new InetSocketAddress(InetAddress
917                                        .getLocalHost(), portNumber)));
918
919        // make sure we can now connect and that connections appear to come
920        // from the address we bound to.
921        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
922                .getLocalHost(), Support_PortManager.getNextPort());
923        ServerSocket serverSocket = new ServerSocket();
924        serverSocket.bind(theAddress);
925        theSocket.connect(theAddress);
926        Socket servSock = serverSocket.accept();
927        assertTrue(
928                "Returned Remote address from server connected to does not match expected local address:"
929                        + servSock.getRemoteSocketAddress().toString()
930                        + " Expected: "
931                        + (new InetSocketAddress(InetAddress.getLocalHost(),
932                                portNumber)).toString(), servSock
933                        .getRemoteSocketAddress().equals(
934                                new InetSocketAddress(InetAddress
935                                        .getLocalHost(), portNumber)));
936        theSocket.close();
937        servSock.close();
938        serverSocket.close();
939
940        // validate if we pass in null that it picks an address for us and
941        // all is ok
942        theSocket = new Socket();
943        theSocket.bind(null);
944        assertNotNull("Bind with null did not work", theSocket
945                .getLocalSocketAddress());
946        theSocket.close();
947
948        // now check the error conditions
949
950        // Address that we have already bound to
951        theSocket = new Socket();
952        Socket theSocket2 = new Socket();
953        try {
954            theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
955                    Support_PortManager.getNextPort());
956            theSocket.bind(theAddress);
957            theSocket2.bind(theAddress);
958            fail("No exception binding to address that is not available");
959        } catch (IOException ex) {
960        }
961        theSocket.close();
962        theSocket2.close();
963
964        // unsupported SocketAddress subclass
965        theSocket = new Socket();
966        try {
967            theSocket.bind(new mySocketAddress());
968            fail("No exception when binding using unsupported SocketAddress subclass");
969        } catch (IllegalArgumentException ex) {
970        }
971        theSocket.close();
972    }
973
974    public void test_bindLjava_net_SocketAddress_Proxy() throws IOException {
975        //The Proxy will not impact on the bind operation.It can be assigned with any address.
976        Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 0));
977        Socket socket = new Socket(proxy);
978
979        try {
980            InetAddress address = InetAddress.getByName("localhost");
981            int port = 0;
982            socket.bind(new InetSocketAddress(address, port));
983
984            assertEquals(address, socket.getLocalAddress());
985            assertTrue(port!=socket.getLocalPort());
986
987        } finally {
988            socket.close();
989        }
990    }
991
992    public void test_connectLjava_net_SocketAddress() throws Exception {
993        // needed for some tests
994        class mySocketAddress extends SocketAddress {
995
996            public mySocketAddress() {
997            }
998        }
999
1000        class SocketCloser extends Thread {
1001
1002            int timeout = 0;
1003
1004            Socket theSocket = null;
1005
1006            public void run() {
1007                try {
1008                    Thread.sleep(timeout);
1009                    theSocket.close();
1010                } catch (Exception e) {
1011                }
1012                ;
1013                return;
1014            }
1015
1016            public SocketCloser(int timeout, Socket theSocket) {
1017                this.timeout = timeout;
1018                this.theSocket = theSocket;
1019            }
1020        }
1021
1022        // start by validating the error checks
1023        int portNumber = Support_PortManager.getNextPort();
1024        Socket theSocket = null;
1025        ServerSocket serverSocket = null;
1026        SocketAddress theAddress = null;
1027        SocketAddress nonConnectableAddress = null;
1028        SocketAddress nonReachableAddress = null;
1029        SocketAddress invalidType = null;
1030        // byte[] theBytes = {-1,-1,-1,-1};
1031        byte[] theBytes = { 0, 0, 0, 0 };
1032        theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
1033                portNumber);
1034        nonConnectableAddress = new InetSocketAddress(InetAddress
1035                .getByAddress(theBytes), portNumber);
1036        nonReachableAddress = new InetSocketAddress(InetAddress
1037                .getByName(Support_Configuration.ResolvedNotExistingHost),
1038                portNumber);
1039
1040        invalidType = new mySocketAddress();
1041
1042        try {
1043            theSocket = new Socket();
1044            theSocket.connect(null);
1045            fail("No exception after null address passed in");
1046        } catch (Exception e) {
1047            assertTrue("Wrong exception null address passed in: "
1048                    + e.toString(), (e instanceof IllegalArgumentException));
1049        }
1050
1051        try {
1052            theSocket = new Socket();
1053            theSocket.connect(invalidType);
1054            fail("No exception when invalid socket address type passed in: ");
1055        } catch (Exception e) {
1056            assertTrue(
1057                    "Wrong exception when when invalid socket address type passed in: "
1058                            + e.toString(),
1059                    (e instanceof IllegalArgumentException));
1060        }
1061
1062        try {
1063            theSocket = new Socket();
1064            theSocket.connect(nonConnectableAddress);
1065            fail("No exception when non Connectable Address passed in: ");
1066        } catch (Exception e) {
1067            assertTrue(
1068                    "Wrong exception when non Connectable Address passed in: "
1069                            + e.toString(), (e instanceof ConnectException));
1070        }
1071
1072        // now validate that we get a connect exception if we try to connect to
1073        // an address on which nobody is listening
1074        try {
1075            theSocket = new Socket();
1076            theSocket.connect(theAddress);
1077            theSocket.close();
1078            fail("No exception when connecting to address nobody listening on: ");
1079        } catch (Exception e) {
1080            assertTrue(
1081                    "Wrong exception when connecting to address nobody listening on: "
1082                            + e.toString(), (e instanceof ConnectException));
1083        }
1084
1085        // now validate that we can actually connect when somebody is listening
1086        theSocket = new Socket();
1087        serverSocket = new ServerSocket();
1088        serverSocket.bind(theAddress);
1089        theSocket.connect(theAddress);
1090        theSocket.close();
1091        serverSocket.close();
1092
1093        // now validate that we can actually connect when somebody is listening
1094        theSocket = new Socket();
1095        serverSocket = new ServerSocket();
1096        serverSocket.bind(theAddress);
1097        theSocket.connect(theAddress);
1098
1099        // validate that when a socket is connected that it answers
1100        // correctly to related queries
1101        assertTrue("Socket did not returned connected when it is: ", theSocket
1102                .isConnected());
1103        assertFalse("Socket returned closed when it should be connected ",
1104                theSocket.isClosed());
1105        assertTrue("Socket returned not bound when it should be: ", theSocket
1106                .isBound());
1107        assertFalse(
1108                "Socket returned input Shutdown when it should be connected ",
1109                theSocket.isInputShutdown());
1110        assertFalse(
1111                "Socket returned output Shutdown when it should be connected ",
1112                theSocket.isOutputShutdown());
1113        assertTrue("Local port on connected socket was 0", theSocket
1114                .getLocalPort() != 0);
1115        theSocket.close();
1116        serverSocket.close();
1117
1118        // now validate that we get the right exception if we connect when we
1119        // are already connected
1120        try {
1121            theSocket = new Socket();
1122            serverSocket = new ServerSocket();
1123            serverSocket.bind(theAddress);
1124            theSocket.connect(theAddress);
1125            theSocket.connect(theAddress);
1126            theSocket.close();
1127            serverSocket.close();
1128            fail("No exception when we try to connect on a connected socket: ");
1129
1130        } catch (Exception e) {
1131            assertTrue(
1132                    "Wrong exception when connecting on socket that is allready connected"
1133                            + e.toString(), (e instanceof SocketException));
1134            assertFalse(
1135                    "Wrong exception when connecting on socket that is allready connected"
1136                            + e.toString(),
1137                    (e instanceof SocketTimeoutException));
1138            try {
1139                theSocket.close();
1140                serverSocket.close();
1141            } catch (Exception e2) {
1142            }
1143
1144        }
1145
1146        // now validate that connected socket can be used to read/write
1147        theSocket = new Socket();
1148        serverSocket = new ServerSocket();
1149        serverSocket.bind(theAddress);
1150        theSocket.connect(theAddress);
1151        Socket servSock = serverSocket.accept();
1152        InputStream theInput = theSocket.getInputStream();
1153        OutputStream theOutput = servSock.getOutputStream();
1154        InputStream theInput2 = servSock.getInputStream();
1155        OutputStream theOutput2 = theSocket.getOutputStream();
1156
1157        String sendString = new String("Test");
1158        theOutput.write(sendString.getBytes());
1159        theOutput.flush();
1160
1161        Thread.sleep(1000);
1162
1163        int totalBytesRead = 0;
1164        byte[] myBytes = new byte[100];
1165        while (theInput.available() > 0) {
1166            int bytesRead = theInput.read(myBytes, totalBytesRead,
1167                    myBytes.length - totalBytesRead);
1168            totalBytesRead = totalBytesRead + bytesRead;
1169        }
1170
1171        String receivedString = new String(myBytes, 0, totalBytesRead);
1172        assertTrue("Could not recv on socket connected with timeout:"
1173                + receivedString + ":" + sendString, receivedString
1174                .equals(sendString));
1175
1176        sendString = new String("SEND - Test");
1177        theOutput2.write(sendString.getBytes());
1178        theOutput2.flush();
1179        Thread.sleep(1000);
1180
1181        totalBytesRead = 0;
1182        myBytes = new byte[100];
1183        while (theInput2.available() > 0) {
1184            int bytesRead = theInput2.read(myBytes, totalBytesRead,
1185                    myBytes.length - totalBytesRead);
1186            totalBytesRead = totalBytesRead + bytesRead;
1187        }
1188
1189        receivedString = new String(myBytes, 0, totalBytesRead);
1190        assertTrue("Could not send on socket connected with timeout:"
1191                + receivedString + ":" + sendString, receivedString
1192                .equals(sendString));
1193
1194        theSocket.close();
1195        serverSocket.close();
1196
1197        SocketChannel channel = SocketChannel.open();
1198        channel.configureBlocking(false);
1199        Socket socket = channel.socket();
1200        int port = Support_PortManager.getNextPort();
1201        try {
1202            socket.connect( new InetSocketAddress(InetAddress.getLocalHost(),
1203                    Support_PortManager.getNextPort()));
1204            fail("IllegalBlockingModeException was not thrown.");
1205        } catch (IllegalBlockingModeException expected) {
1206        }
1207        socket.close();
1208    }
1209
1210    public void test_connectLjava_net_SocketAddressI() throws Exception {
1211
1212        // needed for some tests
1213        class mySocketAddress extends SocketAddress {
1214
1215            public mySocketAddress() {
1216            }
1217        }
1218
1219        class SocketCloser extends Thread {
1220
1221            int timeout = 0;
1222
1223            Socket theSocket = null;
1224
1225            public void run() {
1226                try {
1227                    Thread.sleep(timeout);
1228                    theSocket.close();
1229                } catch (Exception e) {
1230                }
1231                return;
1232            }
1233
1234            public SocketCloser(int timeout, Socket theSocket) {
1235                this.timeout = timeout;
1236                this.theSocket = theSocket;
1237            }
1238        }
1239
1240        class SocketConnector extends Thread {
1241
1242            int timeout = 0;
1243
1244            Socket theSocket = null;
1245
1246            SocketAddress address = null;
1247
1248            public void run() {
1249                try {
1250                    theSocket.connect(address, timeout);
1251                } catch (Exception e) {
1252                }
1253
1254                return;
1255            }
1256
1257            public SocketConnector(int timeout, Socket theSocket,
1258                    SocketAddress address) {
1259                this.timeout = timeout;
1260                this.theSocket = theSocket;
1261                this.address = address;
1262            }
1263        }
1264
1265        // start by validating the error checks
1266        int portNumber = Support_PortManager.getNextPort();
1267        Socket theSocket = null;
1268        ServerSocket serverSocket = null;
1269        SocketAddress theAddress = null;
1270        SocketAddress nonConnectableAddress = null;
1271        SocketAddress nonReachableAddress = null;
1272        SocketAddress nonListeningAddress = null;
1273        SocketAddress invalidType = null;
1274        byte[] theBytes = { 0, 0, 0, 0 };
1275
1276        theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
1277                portNumber);
1278        nonConnectableAddress = new InetSocketAddress(InetAddress
1279                .getByAddress(theBytes), portNumber);
1280        nonReachableAddress = new InetSocketAddress(InetAddress
1281                .getByName(Support_Configuration.ResolvedNotExistingHost),
1282                portNumber);
1283        // make sure we get another port
1284        Thread.sleep(7000);
1285        nonListeningAddress = new InetSocketAddress(InetAddress.getLocalHost(),
1286                Support_PortManager.getNextPort());
1287        invalidType = new mySocketAddress();
1288
1289        try {
1290            theSocket = new Socket();
1291            theSocket.connect(theAddress, -100);
1292            fail("No exception after negative timeout passed in");
1293        } catch (Exception e) {
1294            assertTrue("Wrong exception when negative timeout passed in: "
1295                    + e.toString(), (e instanceof IllegalArgumentException));
1296        }
1297
1298        try {
1299            theSocket = new Socket();
1300            theSocket.connect(null, 0);
1301            fail("No exception after null address passed in");
1302        } catch (Exception e) {
1303            assertTrue("Wrong exception null address passed in: "
1304                    + e.toString(), (e instanceof IllegalArgumentException));
1305        }
1306
1307        try {
1308            theSocket = new Socket();
1309            theSocket.connect(invalidType, 100000);
1310            fail("No exception when invalid socket address type passed in: ");
1311        } catch (Exception e) {
1312            assertTrue(
1313                    "Wrong exception when when invalid socket address type passed in: "
1314                            + e.toString(),
1315                    (e instanceof IllegalArgumentException));
1316        }
1317
1318        try {
1319            theSocket = new Socket();
1320            theSocket.connect(nonConnectableAddress, 100000);
1321            fail("No exception when non Connectable Address passed in: ");
1322        } catch (Exception e) {
1323            assertTrue(
1324                    "Wrong exception when non Connectable Address passed in: "
1325                            + e.toString(), (e instanceof SocketException));
1326        }
1327
1328        // now validate that we get a connect exception if we try to connect to
1329        // an address on which nobody is listening
1330        try {
1331            theSocket = new Socket();
1332            theSocket.connect(theAddress, 0);
1333            theSocket.close();
1334            fail("No timeout:No exception when connecting to address nobody listening on: ");
1335        } catch (Exception e) {
1336            assertTrue(
1337                    "No timeout:Wrong exception when connecting to address nobody listening on: "
1338                            + e.toString(), (e instanceof ConnectException));
1339        }
1340
1341        // now validate that we can actually connect when somebody is listening
1342        theSocket = new Socket();
1343        serverSocket = new ServerSocket();
1344        serverSocket.bind(theAddress);
1345        theSocket.connect(theAddress, 0);
1346        theSocket.close();
1347        serverSocket.close();
1348
1349        // now validate that we get a connect exception if we try to connect to
1350        // an address on which nobody is listening
1351        try {
1352            theSocket = new Socket();
1353            theSocket.connect(nonListeningAddress, 100000);
1354            theSocket.close();
1355            fail("No exception when connecting to address nobody listening on: ");
1356        } catch (Exception e) {
1357            assertTrue(
1358                    "Wrong exception when connecting to address nobody listening on: "
1359                            + e.toString(), (e instanceof ConnectException));
1360        }
1361
1362        // now validate that we get a interrupted exception if we try to connect
1363        // to an address on which nobody is accepting connections and the
1364        // timeout expired
1365        try {
1366            theSocket = new Socket();
1367            theSocket.connect(nonReachableAddress, 200);
1368            theSocket.close();
1369            fail("No interrupted exception when connecting to address nobody listening on with short timeout 200: ");
1370        } catch (Exception e) {
1371            assertTrue(
1372                    "Wrong exception when connecting to address nobody listening on with short timeout 200: "
1373                            + e.toString(),
1374                    (e instanceof SocketTimeoutException));
1375        }
1376
1377        // now validate that we get a interrupted exception if we try to connect
1378        // to an address on which nobody is accepting connections and the
1379        // timeout expired
1380        try {
1381            theSocket = new Socket();
1382            theSocket.connect(nonReachableAddress, 40);
1383            theSocket.close();
1384            fail("No interrupted exception when connecting to address nobody listening on with short timeout 40: ");
1385        } catch (Exception e) {
1386            assertTrue(
1387                    "Wrong exception when connecting to address nobody listening on with short timeout 40: "
1388                            + e.toString(),
1389                    (e instanceof SocketTimeoutException));
1390        }
1391
1392        // now validate that we can actually connect when somebody is listening
1393        new InetSocketAddress(InetAddress.getLocalHost(), Support_PortManager
1394                .getNextPort());
1395        theSocket = new Socket();
1396        serverSocket = new ServerSocket();
1397        serverSocket.bind(theAddress);
1398        theSocket.connect(theAddress, 100000);
1399
1400        // validate that when a socket is connected that it answers
1401        // correctly to related queries
1402        assertTrue("Socket did not returned connected when it is: ", theSocket
1403                .isConnected());
1404        assertFalse("Socket returned closed when it should be connected ",
1405                theSocket.isClosed());
1406        assertTrue("Socket returned not bound when it should be: ", theSocket
1407                .isBound());
1408        assertFalse(
1409                "Socket returned input Shutdown when it should be connected ",
1410                theSocket.isInputShutdown());
1411        assertFalse(
1412                "Socket returned output Shutdown when it should be connected ",
1413                theSocket.isOutputShutdown());
1414        assertTrue("Local port on connected socket was 0", theSocket
1415                .getLocalPort() != 0);
1416        theSocket.close();
1417        serverSocket.close();
1418
1419        // now validate that we get the right exception if we connect when we
1420        // are already connected
1421        try {
1422            new InetSocketAddress(InetAddress.getLocalHost(),
1423                    Support_PortManager.getNextPort());
1424            theSocket = new Socket();
1425            serverSocket = new ServerSocket();
1426            serverSocket.bind(theAddress);
1427            theSocket.connect(theAddress, 100000);
1428            theSocket.connect(theAddress, 100000);
1429            theSocket.close();
1430            serverSocket.close();
1431            fail("No exception when we try to connect on a connected socket: ");
1432
1433        } catch (Exception e) {
1434            assertTrue(
1435                    "Wrong exception when connecting on socket that is already connected"
1436                            + e.toString(), (e instanceof SocketException));
1437            assertFalse(
1438                    "Wrong exception when connecting on socket that is already connected"
1439                            + e.toString(),
1440                    (e instanceof SocketTimeoutException));
1441            try {
1442                theSocket.close();
1443                serverSocket.close();
1444            } catch (Exception e2) {
1445            }
1446
1447        }
1448
1449        // now validate that connected socket can be used to read/write
1450        new InetSocketAddress(InetAddress.getLocalHost(), Support_PortManager
1451                .getNextPort());
1452        theSocket = new Socket();
1453        serverSocket = new ServerSocket();
1454        serverSocket.bind(theAddress);
1455        theSocket.connect(theAddress, 100000);
1456        Socket servSock = serverSocket.accept();
1457        InputStream theInput = theSocket.getInputStream();
1458        OutputStream theOutput = servSock.getOutputStream();
1459        InputStream theInput2 = servSock.getInputStream();
1460        OutputStream theOutput2 = theSocket.getOutputStream();
1461
1462        String sendString = new String("Test");
1463        theOutput.write(sendString.getBytes());
1464        theOutput.flush();
1465
1466        Thread.sleep(1000);
1467
1468        int totalBytesRead = 0;
1469        byte[] myBytes = new byte[100];
1470        while (theInput.available() > 0) {
1471            int bytesRead = theInput.read(myBytes, totalBytesRead,
1472                    myBytes.length - totalBytesRead);
1473            totalBytesRead = totalBytesRead + bytesRead;
1474        }
1475
1476        String receivedString = new String(myBytes, 0, totalBytesRead);
1477        assertTrue("Could not recv on socket connected with timeout:"
1478                + receivedString + ":" + sendString, receivedString
1479                .equals(sendString));
1480
1481        sendString = new String("SEND - Test");
1482        theOutput2.write(sendString.getBytes());
1483        theOutput2.flush();
1484
1485        totalBytesRead = 0;
1486        myBytes = new byte[100];
1487        Thread.sleep(1000);
1488        while (theInput2.available() > 0) {
1489            int bytesRead = theInput2.read(myBytes, totalBytesRead,
1490                    myBytes.length - totalBytesRead);
1491            totalBytesRead = totalBytesRead + bytesRead;
1492        }
1493
1494        receivedString = new String(myBytes, 0, totalBytesRead);
1495        assertTrue("Could not send on socket connected with timeout:"
1496                + receivedString + ":" + sendString, receivedString
1497                .equals(sendString));
1498
1499        theSocket.close();
1500        serverSocket.close();
1501
1502        // now try to set options while we are connecting
1503        theSocket = new Socket();
1504        SocketConnector connector = new SocketConnector(5000, theSocket, nonReachableAddress);
1505        connector.start();
1506        theSocket.setSoTimeout(1000);
1507        Thread.sleep(10);
1508        assertEquals("Socket option not set during connect: 10 ", 1000, theSocket.getSoTimeout());
1509        Thread.sleep(50);
1510        theSocket.setSoTimeout(2000);
1511        assertEquals("Socket option not set during connect: 50 ", 2000, theSocket.getSoTimeout());
1512        Thread.sleep(5000);
1513        theSocket.close();
1514
1515        SocketChannel channel = SocketChannel.open();
1516        channel.configureBlocking(false);
1517        Socket socket = channel.socket();
1518        int port = Support_PortManager.getNextPort();
1519        try {
1520            socket.connect( new InetSocketAddress(InetAddress.getLocalHost(),
1521                    Support_PortManager.getNextPort()), port);
1522            fail("IllegalBlockingModeException was not thrown.");
1523        } catch (IllegalBlockingModeException expected) {
1524        }
1525        channel.close();
1526    }
1527
1528    public void test_isInputShutdown() throws IOException {
1529        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
1530                .getLocalHost(), Support_PortManager.getNextPort());
1531        Socket theSocket = new Socket();
1532        ServerSocket serverSocket = new ServerSocket();
1533        serverSocket.bind(theAddress);
1534        theSocket.connect(theAddress);
1535        Socket servSock = serverSocket.accept();
1536        InputStream theInput = theSocket.getInputStream();
1537        OutputStream theOutput = servSock.getOutputStream();
1538
1539        // make sure we get the right answer with newly connected socket
1540        assertFalse("Socket indicated input shutdown when it should not have",
1541                theSocket.isInputShutdown());
1542
1543        // shutdown the output
1544        theSocket.shutdownInput();
1545
1546        // make sure we get the right answer once it is shut down
1547        assertTrue(
1548                "Socket indicated input was NOT shutdown when it should have been",
1549                theSocket.isInputShutdown());
1550
1551        theSocket.close();
1552        serverSocket.close();
1553
1554        // make sure we get the right answer for closed sockets
1555        assertFalse(
1556                "Socket indicated input was shutdown when socket was closed",
1557                servSock.isInputShutdown());
1558
1559    }
1560
1561    public void test_isOutputShutdown() throws IOException {
1562        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
1563                .getLocalHost(), Support_PortManager.getNextPort());
1564        Socket theSocket = new Socket();
1565        ServerSocket serverSocket = new ServerSocket();
1566        serverSocket.bind(theAddress);
1567        theSocket.connect(theAddress);
1568        Socket servSock = serverSocket.accept();
1569        InputStream theInput = theSocket.getInputStream();
1570        OutputStream theOutput = servSock.getOutputStream();
1571
1572        // make sure we get the right answer with newly connected socket
1573        assertFalse("Socket indicated output shutdown when it should not have",
1574                servSock.isOutputShutdown());
1575
1576        // shutdown the output
1577        servSock.shutdownOutput();
1578
1579        // make sure we get the right answer once it is shut down
1580        assertTrue(
1581                "Socket indicated output was NOT shutdown when it should have been",
1582                servSock.isOutputShutdown());
1583
1584        theSocket.close();
1585        serverSocket.close();
1586
1587        // make sure we get the right answer for closed sockets
1588        assertFalse(
1589                "Socket indicated output was output shutdown when the socket was closed",
1590                theSocket.isOutputShutdown());
1591
1592    }
1593
1594    public void test_setReuseAddressZ() {
1595
1596        try {
1597            InetAddress allAddresses[] = InetAddress.getAllByName(InetAddress
1598                    .getLocalHost().getHostName());
1599            if (allAddresses.length > 1) {
1600
1601                InetSocketAddress theAddress = new InetSocketAddress(
1602                        InetAddress.getLocalHost(), Support_PortManager
1603                                .getNextPort());
1604                ServerSocket serverSocket = new ServerSocket();
1605                serverSocket.bind(theAddress);
1606
1607                // try to bind to port address that is already in use with
1608                // reuseAddress = false.
1609                // On windows platforms the bind is allowed even then
1610                // reUseAddress is false (ONLY IF BOTH SOCKETS
1611                // ARE IPV4 Sockets) so our test uses the platform to determine
1612                // what the expected result is. It seems that on linux
1613                // platforms we also don't get an exception.
1614                InetSocketAddress theLocalAddress = new InetSocketAddress(
1615                        (InetAddress) allAddresses[1], Support_PortManager
1616                                .getNextPort());
1617                InetSocketAddress theOtherLocalAddress = new InetSocketAddress(
1618                        (InetAddress) allAddresses[0], theLocalAddress
1619                                .getPort());
1620                Socket theSocket = new Socket();
1621                theSocket.setReuseAddress(false);
1622                theSocket.bind(theLocalAddress);
1623                Socket theSocket2 = null;
1624                String platform = System.getProperty("os.name");
1625                try {
1626                    theSocket2 = new Socket();
1627                    theSocket2.setReuseAddress(false);
1628                    theSocket2.bind(theOtherLocalAddress);
1629
1630                    if ((!platform.startsWith("Linux"))
1631                            && ((!platform.startsWith("Windows")) ||
1632                            // for windows we don't get an exception with
1633                            // setreuse set to false unless one of the
1634                            // addresses we bind to is an IPv6 address and we
1635                            // are therefore using the IPv6 stack.
1636                            !((((InetAddress) allAddresses[0]) instanceof Inet4Address) && (((InetAddress) allAddresses[1]) instanceof Inet4Address)))) {
1637                        fail("No exception when setReuseAddress is false and we bind:"
1638                                + theLocalAddress.toString()
1639                                + ":"
1640                                + theOtherLocalAddress.toString());
1641                    }
1642                } catch (IOException ex) {
1643                    if ((platform.startsWith("Linux"))
1644                            || ((platform.startsWith("Windows")) && ((((InetAddress) allAddresses[0]) instanceof Inet4Address) && (((InetAddress) allAddresses[1]) instanceof Inet4Address)))) {
1645                        fail("Got unexpected exception when binding with setReuseAddress false on windows platform:"
1646                                + theAddress.toString() + ":" + ex.toString());
1647                    }
1648                }
1649                theSocket.close();
1650                theSocket2.close();
1651
1652                // try to bind to port that is already in use with reuseAddress
1653                // = true
1654                theLocalAddress = new InetSocketAddress(
1655                        (InetAddress) allAddresses[0], Support_PortManager
1656                                .getNextPort());
1657                theOtherLocalAddress = new InetSocketAddress(
1658                        (InetAddress) allAddresses[1], theLocalAddress
1659                                .getPort());
1660
1661                theSocket = new Socket();
1662                theSocket.setReuseAddress(true);
1663                theSocket.bind(theLocalAddress);
1664                try {
1665                    theSocket2 = new Socket();
1666                    theSocket2.setReuseAddress(true);
1667                    theSocket2.bind(theOtherLocalAddress);
1668                    theSocket2.close();
1669                } catch (IOException ex) {
1670                    fail("IOException when setReuseAddress is true and we bind :"
1671                            + ex.toString());
1672                }
1673                theSocket.close();
1674                serverSocket.close();
1675
1676                // try with default behavior which should be the same on all
1677                // platforms
1678                theLocalAddress = new InetSocketAddress(
1679                        (InetAddress) allAddresses[0], Support_PortManager
1680                                .getNextPort());
1681                theOtherLocalAddress = new InetSocketAddress(
1682                        (InetAddress) allAddresses[1], theLocalAddress
1683                                .getPort());
1684
1685                theSocket = new Socket();
1686                theSocket.bind(theLocalAddress);
1687                try {
1688                    theSocket2 = new Socket();
1689                    theSocket2.bind(theOtherLocalAddress);
1690                    theSocket2.close();
1691                    if ((!platform.startsWith("Linux"))
1692                            && ((!platform.startsWith("Windows")) || !((((InetAddress) allAddresses[0]) instanceof Inet4Address) && (((InetAddress) allAddresses[1]) instanceof Inet4Address)))) {
1693                        fail("No exception when setReuseAddress is default and we bind:"
1694                                + theLocalAddress.toString()
1695                                + ":"
1696                                + theOtherLocalAddress.toString());
1697                    }
1698                } catch (IOException ex) {
1699                    if ((platform.startsWith("Linux"))
1700                            || ((platform.startsWith("Windows")) && ((((InetAddress) allAddresses[0]) instanceof Inet4Address) && (((InetAddress) allAddresses[1]) instanceof Inet4Address)))) {
1701                        fail("Got unexpected exception when binding with setReuseAddress default on windows platform:"
1702                                + theAddress.toString() + ":" + ex.toString());
1703                    }
1704                }
1705                theSocket.close();
1706                serverSocket.close();
1707
1708                ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
1709            }
1710        } catch (Exception e) {
1711            handleException(e, SO_REUSEADDR);
1712        }
1713
1714        try {
1715            Socket theSocket = new Socket();
1716            theSocket.close();
1717            theSocket.setReuseAddress(true);
1718            fail("SocketException was not thrown.");
1719        } catch(SocketException ioe) {
1720            //expected
1721        } catch(IOException ioe) {
1722            fail("IOException was thrown.");
1723        }
1724    }
1725
1726    public void test_getReuseAddress() {
1727        try {
1728            Socket theSocket = new Socket();
1729            theSocket.setReuseAddress(true);
1730            assertTrue("getReuseAddress false when it should be true",
1731                    theSocket.getReuseAddress());
1732            theSocket.setReuseAddress(false);
1733            assertFalse("getReuseAddress true when it should be False",
1734                    theSocket.getReuseAddress());
1735            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
1736        } catch (Exception e) {
1737            handleException(e, SO_REUSEADDR);
1738        }
1739
1740        try {
1741            Socket newSocket = new Socket();
1742            newSocket.close();
1743            try {
1744                newSocket.getReuseAddress();
1745                fail("SocketException was not thrown.");
1746            } catch(SocketException e) {
1747                //expected
1748            }
1749        } catch(Exception e) {
1750            fail("Unexpected exception.");
1751        }
1752    }
1753
1754    public void test_setOOBInlineZ() {
1755        // mostly tested in getOOBInline. Just set to make sure call works ok
1756        try {
1757            new InetSocketAddress(InetAddress.getLocalHost(),
1758                    Support_PortManager.getNextPort());
1759            Socket theSocket = new Socket();
1760            theSocket.setOOBInline(true);
1761            assertTrue("expected OOBIline to be true", theSocket.getOOBInline());
1762            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_OOBINLINE);
1763        } catch (Exception e) {
1764            handleException(e, SO_OOBINLINE);
1765        }
1766
1767        try {
1768            Socket theSocket = new Socket();
1769            theSocket.close();
1770            theSocket.setOOBInline(true);
1771            fail("SocketException was not thrown.");
1772        } catch(SocketException ioe) {
1773            //expected
1774        } catch(IOException ioe) {
1775            fail("IOException was thrown.");
1776        }
1777    }
1778
1779    public void test_getOOBInline() {
1780
1781        try {
1782            new InetSocketAddress(InetAddress.getLocalHost(),
1783                    Support_PortManager.getNextPort());
1784            Socket theSocket = new Socket();
1785
1786            // validate that value reflects what we set it to true after true,
1787            // false after false and false after false false
1788            theSocket.setOOBInline(true);
1789            assertTrue("expected OOBIline to be true", theSocket.getOOBInline());
1790            theSocket.setOOBInline(false);
1791            assertFalse("expected OOBIline to be true", theSocket
1792                    .getOOBInline());
1793            theSocket.setOOBInline(false);
1794            assertFalse("expected OOBIline to be true", theSocket
1795                    .getOOBInline());
1796            theSocket.close();
1797            try {
1798                theSocket.getOOBInline();
1799                fail("SocketException was not thrown.");
1800            } catch(SocketException se) {
1801                //expected
1802            }
1803            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_OOBINLINE);
1804
1805        } catch (Exception e) {
1806            handleException(e, SO_OOBINLINE);
1807        }
1808    }
1809
1810    public void test_setTrafficClassI() {
1811        try {
1812            int IPTOS_LOWCOST = 0x2;
1813            int IPTOS_THROUGHPUT = 0x8;
1814
1815            new InetSocketAddress(InetAddress.getLocalHost(),
1816                    Support_PortManager.getNextPort());
1817            Socket theSocket = new Socket();
1818
1819            // validate that value set must be between 0 and 255
1820            try {
1821                theSocket.setTrafficClass(256);
1822                fail("No exception was thrown when traffic class set to 256");
1823            } catch (IllegalArgumentException e) {
1824            }
1825
1826            try {
1827                theSocket.setTrafficClass(-1);
1828                fail("No exception was thrown when traffic class set to -1");
1829            } catch (IllegalArgumentException e) {
1830            }
1831
1832            // now validate that we can set it to some good values
1833            theSocket.setTrafficClass(IPTOS_LOWCOST);
1834            theSocket.setTrafficClass(IPTOS_THROUGHPUT);
1835            ensureExceptionThrownIfOptionIsUnsupportedOnOS(IP_TOS);
1836        } catch (Exception e) {
1837            handleException(e, IP_TOS);
1838        }
1839
1840        try {
1841            Socket theSocket = new Socket();
1842            theSocket.close();
1843            theSocket.setTrafficClass(0);
1844            fail("SocketException was not thrown.");
1845        } catch(SocketException ioe) {
1846            //expected
1847        } catch(IOException ioe) {
1848            fail("IOException was thrown.");
1849        }
1850    }
1851
1852    public void test_getTrafficClass() {
1853        try {
1854            new InetSocketAddress(InetAddress.getLocalHost(),
1855                    Support_PortManager.getNextPort());
1856            Socket theSocket = new Socket();
1857
1858            /*
1859             * we cannot actually check that the values are set as if a platform
1860             * does not support the option then it may come back unset even
1861             * though we set it so just get the value to make sure we can get it
1862             */
1863            int trafficClass = theSocket.getTrafficClass();
1864            ensureExceptionThrownIfOptionIsUnsupportedOnOS(IP_TOS);
1865        } catch (Exception e) {
1866            handleException(e, IP_TOS);
1867        }
1868    }
1869
1870    public void test_getChannel() throws Exception {
1871        assertNull(new Socket().getChannel());
1872
1873        SocketChannel channel = SocketChannel.open();
1874        Socket socket = channel.socket();
1875        assertEquals(channel, socket.getChannel());
1876        socket.close();
1877        channel.close();
1878    }
1879
1880    public void test_sendUrgentDataI() {
1881
1882        // Some platforms may not support urgent data in this case we will not
1883        // run these tests. For now run on all platforms until we find those
1884        // that do not support urgent data
1885        String platform = System.getProperty("os.name");
1886        if (!platform.equals("Dummy")) {
1887            // validate that when OOBInline is false that any urgent data
1888            // is silently ignored
1889            String urgentData = "U";
1890            try {
1891                InetSocketAddress theAddress = new InetSocketAddress(
1892                        InetAddress.getLocalHost(), Support_PortManager
1893                                .getNextPort());
1894                Socket theSocket = new Socket();
1895                ServerSocket serverSocket = new ServerSocket();
1896                serverSocket.bind(theAddress);
1897                theSocket.connect(theAddress);
1898                Socket servSock = serverSocket.accept();
1899                InputStream theInput = theSocket.getInputStream();
1900                OutputStream theOutput = servSock.getOutputStream();
1901
1902                // send the regular data
1903                String sendString = new String("Test");
1904                theOutput.write(sendString.getBytes());
1905                theOutput.flush();
1906
1907                // send the urgent data which should not be received
1908                theSocket.setOOBInline(false);
1909                servSock.sendUrgentData(urgentData.getBytes()[0]);
1910                theOutput.write(sendString.getBytes());
1911                theOutput.flush();
1912
1913                // give things some time to settle
1914                Thread.sleep(1000);
1915
1916                int totalBytesRead = 0;
1917                byte[] myBytes = new byte[100];
1918                while (theInput.available() > 0) {
1919                    int bytesRead = theInput.read(myBytes, totalBytesRead,
1920                            myBytes.length - totalBytesRead);
1921                    totalBytesRead = totalBytesRead + bytesRead;
1922                }
1923
1924                String receivedString = new String(myBytes, 0, totalBytesRead);
1925                //assertTrue("Urgent Data seems to have been received:"
1926                //        + receivedString + ":" + sendString, receivedString
1927                //        .equals(sendString + sendString));
1928
1929                theSocket.close();
1930                serverSocket.close();
1931
1932                // now validate that urgent data is received as expected. Expect
1933                // that it should be between the two writes.
1934                theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
1935                        Support_PortManager.getNextPort());
1936                theSocket = new Socket();
1937                serverSocket = new ServerSocket();
1938                serverSocket.bind(theAddress);
1939                theSocket.connect(theAddress);
1940                servSock = serverSocket.accept();
1941                theInput = theSocket.getInputStream();
1942                theOutput = servSock.getOutputStream();
1943
1944                // send the regular data
1945                sendString = new String("Test - Urgent Data");
1946                theOutput.write(sendString.getBytes());
1947                theOutput.flush();
1948
1949                // send the urgent data which should be received
1950                theSocket.setOOBInline(true);
1951                servSock.sendUrgentData(urgentData.getBytes()[0]);
1952
1953                theOutput.write(sendString.getBytes());
1954                theOutput.flush();
1955
1956                Thread.sleep(1000);
1957
1958                totalBytesRead = 0;
1959                myBytes = new byte[100];
1960                while (theInput.available() > 0) {
1961                    int bytesRead = theInput.read(myBytes, totalBytesRead,
1962                            myBytes.length - totalBytesRead);
1963                    totalBytesRead = totalBytesRead + bytesRead;
1964                }
1965
1966                receivedString = new String(myBytes, 0, totalBytesRead);
1967                assertTrue("Urgent Data was not received with one urgent byte:"
1968                        + receivedString + ":" + sendString + urgentData
1969                        + sendString, receivedString.equals(sendString
1970                        + urgentData + sendString));
1971
1972                theSocket.close();
1973                serverSocket.close();
1974
1975                // now test case where we try to send two urgent bytes.
1976                theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
1977                        Support_PortManager.getNextPort());
1978                theSocket = new Socket();
1979                serverSocket = new ServerSocket();
1980                serverSocket.bind(theAddress);
1981                theSocket.connect(theAddress);
1982                servSock = serverSocket.accept();
1983                theInput = theSocket.getInputStream();
1984                theOutput = servSock.getOutputStream();
1985
1986                // send the regular data
1987                sendString = new String("Test - Urgent Data");
1988                theOutput.write(sendString.getBytes());
1989                theOutput.flush();
1990
1991                // send the urgent data which should not be received
1992                theSocket.setOOBInline(true);
1993                servSock.sendUrgentData(urgentData.getBytes()[0]);
1994                servSock.sendUrgentData(urgentData.getBytes()[0]);
1995
1996                theOutput.write(sendString.getBytes());
1997                theOutput.flush();
1998
1999                Thread.sleep(1000);
2000
2001                totalBytesRead = 0;
2002                myBytes = new byte[100];
2003                while (theInput.available() > 0) {
2004                    int bytesRead = theInput.read(myBytes, totalBytesRead,
2005                            myBytes.length - totalBytesRead);
2006                    totalBytesRead = totalBytesRead + bytesRead;
2007                }
2008
2009                receivedString = new String(myBytes, 0, totalBytesRead);
2010                assertTrue(
2011                        "Did not get right byte of urgent data when two sent:"
2012                                + receivedString + ":" + sendString
2013                                + urgentData + urgentData + sendString,
2014                        receivedString.equals(sendString + urgentData
2015                                + urgentData + sendString));
2016
2017                theSocket.close();
2018                serverSocket.close();
2019
2020                /*
2021                 * TODO : These do not currently pass on XP SP2 and Server 2003
2022                 */
2023                if (!platform.startsWith("Windows")) {
2024                    // now test the case were we send turn the OOBInline on/off
2025                    theAddress = new InetSocketAddress(InetAddress
2026                            .getLocalHost(), Support_PortManager.getNextPort());
2027                    theSocket = new Socket();
2028                    serverSocket = new ServerSocket();
2029                    serverSocket.bind(theAddress);
2030                    theSocket.connect(theAddress);
2031                    servSock = serverSocket.accept();
2032                    theInput = theSocket.getInputStream();
2033                    theOutput = servSock.getOutputStream();
2034
2035                    // send the regular data
2036                    sendString = new String("Test - Urgent Data");
2037                    theOutput.write(sendString.getBytes());
2038                    theOutput.flush();
2039
2040                    // send the urgent data which should be received
2041                    theSocket.setOOBInline(true);
2042                    servSock.sendUrgentData(urgentData.getBytes()[0]);
2043
2044                    theOutput.write(sendString.getBytes());
2045                    theOutput.flush();
2046
2047                    Thread.sleep(1000);
2048
2049                    totalBytesRead = 0;
2050                    myBytes = new byte[100];
2051                    while (theInput.available() > 0) {
2052                        int bytesRead = theInput.read(myBytes, totalBytesRead,
2053                                myBytes.length - totalBytesRead);
2054                        totalBytesRead = totalBytesRead + bytesRead;
2055                    }
2056
2057                    receivedString = new String(myBytes, 0, totalBytesRead);
2058                    assertTrue(
2059                            "Did not get urgent data when turning on/off(1):"
2060                                    + receivedString + ":" + sendString
2061                                    + urgentData + sendString, receivedString
2062                                    .equals(sendString + urgentData
2063                                            + sendString));
2064
2065                    // send the regular data
2066                    sendString = new String("Test - Urgent Data");
2067                    theOutput.write(sendString.getBytes());
2068                    theOutput.flush();
2069
2070                    // send the urgent data which should not be received
2071                    theSocket.setOOBInline(false);
2072                    servSock.sendUrgentData(urgentData.getBytes()[0]);
2073
2074                    // send trailing data
2075                    theOutput.write(sendString.getBytes());
2076                    theOutput.flush();
2077
2078                    Thread.sleep(1000);
2079
2080                    totalBytesRead = 0;
2081                    myBytes = new byte[100];
2082                    while (theInput.available() > 0) {
2083                        int bytesRead = theInput.read(myBytes, totalBytesRead,
2084                                myBytes.length - totalBytesRead);
2085                        totalBytesRead = totalBytesRead + bytesRead;
2086                    }
2087
2088                    receivedString = new String(myBytes, 0, totalBytesRead);
2089                    //assertTrue(
2090                    //        "Got unexpected data data when turning on/off(2):"
2091                    //                + receivedString + ":" + sendString
2092                    //               + sendString, receivedString
2093                    //                .equals(sendString + sendString));
2094
2095                    // now turn back on and get data. Here we also
2096                    // get the previously sent byte of urgent data as it is
2097                    // still in the urgent buffer
2098
2099                    // send the regular data
2100                    sendString = new String("Test - Urgent Data");
2101                    theOutput.write(sendString.getBytes());
2102                    theOutput.flush();
2103
2104                    // send the urgent data which should be received again
2105                    theSocket.setOOBInline(true);
2106                    servSock.sendUrgentData(urgentData.getBytes()[0]);
2107
2108                    theOutput.write(sendString.getBytes());
2109                    theOutput.flush();
2110
2111                    Thread.sleep(1000);
2112
2113                    totalBytesRead = 0;
2114                    myBytes = new byte[100];
2115                    while (theInput.available() > 0) {
2116                        int bytesRead = theInput.read(myBytes, totalBytesRead,
2117                                myBytes.length - totalBytesRead);
2118                        totalBytesRead = totalBytesRead + bytesRead;
2119                    }
2120
2121                    receivedString = new String(myBytes, 0, totalBytesRead);
2122                    // depending on the platform we may get the previously sent
2123                    // urgent data or not (examples windows-yes, Linux-no).
2124                    // So accept either so long as we get the urgent data from
2125                    // when it was on.
2126                    //assertTrue(
2127                    //        "Did not get urgent data when turning on/off(3) GOT:"
2128                    //                + receivedString + ":Expected" + urgentData
2129                    //                + sendString + urgentData + sendString
2130                    //                + ":OR:" + sendString + urgentData
2131                    //                + sendString,
2132                    //        (receivedString.equals(urgentData + sendString
2133                    //                + urgentData + sendString) || receivedString
2134                    //                .equals(sendString + urgentData
2135                    //                        + sendString)));
2136
2137                    theSocket.close();
2138                    serverSocket.close();
2139                }
2140
2141                // now test the case where there is only urgent data
2142                theAddress = new InetSocketAddress(InetAddress.getLocalHost(),
2143                        Support_PortManager.getNextPort());
2144                theSocket = new Socket();
2145                serverSocket = new ServerSocket();
2146                serverSocket.bind(theAddress);
2147                theSocket.connect(theAddress);
2148                servSock = serverSocket.accept();
2149                theInput = theSocket.getInputStream();
2150                theOutput = servSock.getOutputStream();
2151
2152                // send the urgent data which should not be received.
2153                theSocket.setOOBInline(true);
2154                servSock.sendUrgentData(urgentData.getBytes()[0]);
2155
2156                Thread.sleep(1000);
2157
2158                totalBytesRead = 0;
2159                myBytes = new byte[100];
2160                while (theInput.available() > 0) {
2161                    int bytesRead = theInput.read(myBytes, totalBytesRead,
2162                            myBytes.length - totalBytesRead);
2163                    totalBytesRead = totalBytesRead + bytesRead;
2164                }
2165
2166                receivedString = new String(myBytes, 0, totalBytesRead);
2167                assertTrue("Did not get urgent data only urgent data sent:"
2168                        + receivedString + ":" + urgentData, receivedString
2169                        .equals(urgentData));
2170
2171            } catch (Exception e) {
2172                // for platforms that do not support urgent data we expect an
2173                // exception. For the others report an error.
2174                // TODO : Need to introduce a better test for the exception
2175                // so that the failure only occurs on platforms that support
2176                // urgent data
2177                fail("Platform:" + platform
2178                        + ": Got exception during sendUrgent data tests"
2179                        + e.toString());
2180            }
2181        }
2182
2183        try {
2184            Socket theSocket = new Socket();
2185            theSocket.close();
2186            theSocket.sendUrgentData(0);
2187            fail("IOException was not thrown.");
2188        } catch(IOException ioe) {
2189            //expected
2190        }
2191    }
2192
2193    public void test_setPerformancePreference_Int_Int_Int() throws Exception {
2194        Socket theSocket = new Socket();
2195        theSocket.setPerformancePreferences(1, 1, 1);
2196    }
2197
2198    public void test_ConstructorLjava_net_Proxy_Exception() {
2199
2200        SocketAddress addr1 = InetSocketAddress.createUnresolved("127.0.0.1",
2201                80);
2202        SocketAddress addr2 = new InetSocketAddress("localhost", 80);
2203
2204        Proxy proxy1 = new Proxy(Proxy.Type.HTTP, addr1);
2205        // IllegalArgumentException test
2206        try {
2207            new Socket(proxy1);
2208            fail("should throw IllegalArgumentException");
2209        } catch (IllegalArgumentException e) {
2210            // expected
2211        }
2212
2213        Proxy proxy2 = new Proxy(Proxy.Type.SOCKS, addr1);
2214        // should not throw any exception
2215        new Socket(proxy2);
2216        new Socket(Proxy.NO_PROXY);
2217
2218        try {
2219            new Socket((Proxy) null);
2220            fail("IllegalArgumentException was not thrown.");
2221        } catch(IllegalArgumentException iae) {
2222            //expected
2223        }
2224    }
2225
2226    public void test_ConstructorLSocketImpl() {
2227        MockSocketImpl msi = new MockSocketImpl();
2228        try {
2229            new TestSocket(msi);
2230        } catch (SocketException e) {
2231            fail("SocketException was thrown.");
2232        }
2233    }
2234
2235    public void test_connect_unknownhost() throws Exception {
2236        Socket socket = new Socket();
2237        InetSocketAddress socketAddress = new InetSocketAddress("unknownhost", 12345);
2238        try {
2239            socket.connect(socketAddress);
2240            fail("Should throw IOException");
2241        } catch (IOException e) {
2242            // expected
2243        }
2244    }
2245
2246    public void test_connect_unresolved_unknown() throws Exception {
2247        Socket socket = new Socket();
2248        InetSocketAddress unresolved = InetSocketAddress.createUnresolved("unknownhost", 12345);
2249        try {
2250            socket.connect(unresolved);
2251            fail("Should throw IOException");
2252        } catch (IOException e) {
2253            // expected
2254        }
2255    }
2256
2257    public void test_connect_unresolved() throws Exception {
2258        Socket socket = new Socket();
2259        InetSocketAddress unresolvedSocketAddress = InetSocketAddress.createUnresolved(
2260                Support_Configuration.SocksServerTestHost,
2261                Support_Configuration.SocksServerTestPort);
2262        try {
2263            socket.connect(unresolvedSocketAddress);
2264            fail("Should throw IOException");
2265        } catch (IOException e) {
2266            // expected
2267        }
2268    }
2269
2270    public void test_getOutputStream_shutdownOutput() throws Exception {
2271        // regression test for Harmony-873
2272        ServerSocket ss = new ServerSocket(0);
2273        Socket s = new Socket("127.0.0.1", ss.getLocalPort());
2274        ss.accept();
2275        s.shutdownOutput();
2276        try {
2277            s.getOutputStream();
2278            fail("should throw SocketException");
2279        } catch (IOException e) {
2280            // expected
2281        } finally {
2282            s.close();
2283        }
2284
2285        SocketChannel channel = SocketChannel.open(
2286                new InetSocketAddress(ss.getInetAddress(), ss.getLocalPort()));
2287        channel.configureBlocking(false);
2288        ss.accept();
2289        Socket socket = channel.socket();
2290
2291        OutputStream out = null;
2292
2293        try {
2294            out = socket.getOutputStream();
2295            out.write(1);
2296            fail("IllegalBlockingModeException was not thrown.");
2297        } catch(IllegalBlockingModeException ibme) {
2298            //expected
2299        } finally {
2300            if(out != null) out.close();
2301            socket.close();
2302            channel.close();
2303        }
2304    }
2305
2306    public void test_shutdownInputOutput_twice() throws Exception {
2307        // regression test for Harmony-2944
2308        Socket s = new Socket("0.0.0.0", 0, false);
2309        s.shutdownInput();
2310
2311        try {
2312            s.shutdownInput();
2313            fail("should throw SocketException");
2314        } catch (SocketException se) {
2315            // expected
2316        }
2317        s.shutdownOutput();
2318
2319        try {
2320            s.shutdownOutput();
2321            fail("should throw SocketException");
2322        } catch (SocketException se) {
2323            // expected
2324        }
2325    }
2326
2327    /**
2328     * Sets up the fixture, for example, open a network connection. This method
2329     * is called before a test is executed.
2330     *
2331     * @throws Exception
2332     */
2333    protected void setUp() throws Exception {
2334        super.setUp();
2335    }
2336
2337    /**
2338     * Tears down the fixture, for example, close a network connection. This
2339     * method is called after a test is executed.
2340     */
2341    protected void tearDown() {
2342        try {
2343            if (s != null)
2344                s.close();
2345        } catch (Exception e) {
2346        }
2347        try {
2348            if (ss != null)
2349                ss.close();
2350        } catch (Exception e) {
2351        }
2352        try {
2353            if (t != null)
2354                t.interrupt();
2355        } catch (Exception e) {
2356        }
2357    }
2358
2359    static class MockSecurityManager extends SecurityManager {
2360
2361        public void checkConnect(String host, int port) {
2362            if ("127.0.0.1".equals(host)) {
2363                throw new SecurityException("permission is not allowed");
2364            }
2365        }
2366
2367        public void checkPermission(Permission permission) {
2368            return;
2369        }
2370
2371    }
2372
2373    /**
2374     *
2375     */
2376    protected int startServer(String name) {
2377        int portNumber = Support_PortManager.getNextPort();
2378        try {
2379            ss = new ServerSocket(portNumber, 5);
2380        } catch (IOException e) {
2381            fail(name + ": " + e);
2382        }
2383        return ss.getLocalPort();
2384    }
2385
2386    class MockSocketImpl extends SocketImpl {
2387
2388        public MockSocketImpl() {
2389            super();
2390        }
2391
2392        @Override
2393        protected void accept(SocketImpl arg0) throws IOException {
2394        }
2395
2396        @Override
2397        protected int available() throws IOException {
2398            return 0;
2399        }
2400
2401        @Override
2402        protected void bind(InetAddress arg0, int arg1) throws IOException {
2403        }
2404
2405        @Override
2406        protected void close() throws IOException {
2407        }
2408
2409        @Override
2410        protected void connect(String arg0, int arg1) throws IOException {
2411        }
2412
2413        @Override
2414        protected void connect(InetAddress arg0, int arg1) throws IOException {
2415        }
2416
2417        @Override
2418        protected void connect(SocketAddress arg0, int arg1) throws IOException {
2419        }
2420
2421        @Override
2422        protected void create(boolean arg0) throws IOException {
2423        }
2424
2425        @Override
2426        protected InputStream getInputStream() throws IOException {
2427            return null;
2428        }
2429
2430        @Override
2431        protected OutputStream getOutputStream() throws IOException {
2432            return null;
2433        }
2434
2435        @Override
2436        protected void listen(int arg0) throws IOException {
2437        }
2438
2439        @Override
2440        protected void sendUrgentData(int arg0) throws IOException {
2441        }
2442
2443        public Object getOption(int arg0) throws SocketException {
2444            return null;
2445        }
2446
2447        public void setOption(int arg0, Object arg1) throws SocketException {
2448        }
2449    }
2450}
2451