ServerSocketTest.java revision f6c387128427e121477c1b32ad35cdcaa5101ba3
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 tests.api.java.net;
19
20import dalvik.annotation.TestTargetClass;
21import dalvik.annotation.TestTargetNew;
22import dalvik.annotation.TestLevel;
23
24import java.io.IOException;
25import java.io.InputStream;
26import java.io.InterruptedIOException;
27import java.io.OutputStream;
28import java.net.BindException;
29import java.net.ConnectException;
30import java.net.InetAddress;
31import java.net.InetSocketAddress;
32import java.net.ServerSocket;
33import java.net.Socket;
34import java.net.SocketAddress;
35import java.net.SocketException;
36import java.net.SocketImpl;
37import java.net.SocketImplFactory;
38import java.net.SocketTimeoutException;
39import java.net.UnknownHostException;
40import java.nio.channels.IllegalBlockingModeException;
41import java.nio.channels.ServerSocketChannel;
42import java.security.Permission;
43import java.util.Date;
44import java.util.Properties;
45
46import tests.support.Support_Configuration;
47import tests.support.Support_PortManager;
48
49@TestTargetClass(value = ServerSocket.class,
50                 untestedMethods = {
51                    @TestTargetNew(
52                        level = TestLevel.NOT_NECESSARY,
53                        notes = "Protected constructor.",
54                        method = "ServerSocket",
55                        args = {SocketImpl.class}
56                    )}
57                )
58public class ServerSocketTest extends SocketTestCase {
59
60    boolean interrupted;
61    boolean isCreateCalled = false;
62
63    ServerSocket s;
64
65    Socket sconn;
66
67    Thread t;
68
69    static class SSClient implements Runnable {
70        Socket cs;
71
72        int port;
73
74        public SSClient(int prt) {
75            port = prt;
76        }
77
78        public void run() {
79            try {
80                // Go to sleep so the server can setup and wait for connection
81                Thread.sleep(1000);
82                cs = new Socket(InetAddress.getLocalHost().getHostName(), port);
83                // Sleep again to allow server side processing. Thread is
84                // stopped by server.
85                Thread.sleep(10000);
86            } catch (InterruptedException e) {
87                return;
88            } catch (Throwable e) {
89                System.out
90                        .println("Error establishing client: " + e.toString());
91            } finally {
92                try {
93                    if (cs != null)
94                        cs.close();
95                } catch (Exception e) {
96                }
97            }
98        }
99    }
100
101    SecurityManager sm = new SecurityManager() {
102
103        public void checkPermission(Permission perm) {
104        }
105
106        public void checkListen(int port) {
107            throw new SecurityException();
108        }
109    };
110
111    /**
112     * @tests java.net.ServerSocket#ServerSocket()
113     */
114    @TestTargetNew(
115      level = TestLevel.COMPLETE,
116      notes = "",
117      method = "ServerSocket",
118      args = {}
119    )
120    public void test_Constructor() {
121        ServerSocket ss = null;
122        try {
123            ss = new ServerSocket();
124            assertEquals(-1, ss.getLocalPort());
125        } catch (IOException e) {
126            fail("IOException was thrown.");
127        } finally {
128            try {
129                ss.close();
130            } catch(IOException ioe) {}
131        }
132    }
133
134    /**
135     * @tests java.net.ServerSocket#ServerSocket(int)
136     */
137    @TestTargetNew(
138      level = TestLevel.COMPLETE,
139      notes = "",
140      method = "ServerSocket",
141      args = {int.class}
142    )
143    public void test_ConstructorI() throws Exception {
144        int portNumber = Support_PortManager.getNextPort();
145        s = new ServerSocket(portNumber);
146        try {
147            new ServerSocket(portNumber);
148            fail("IOException was not thrown.");
149        } catch(IOException ioe) {
150            //expected
151        }
152        try {
153            startClient(s.getLocalPort());
154            sconn = s.accept();
155            assertNotNull("Was unable to accept connection", sconn);
156            sconn.close();
157        } finally {
158            s.close();
159        }
160
161        s = new ServerSocket(0);
162        try {
163            startClient(s.getLocalPort());
164            sconn = s.accept();
165            assertNotNull("Was unable to accept connection", sconn);
166            sconn.close();
167        } finally {
168            s.close();
169        }
170
171        SecurityManager oldSm = System.getSecurityManager();
172        System.setSecurityManager(sm);
173        try {
174            new ServerSocket(0);
175            fail("SecurityException should be thrown.");
176        } catch (SecurityException e) {
177            // expected
178        } catch (SocketException e) {
179            fail("SocketException was thrown.");
180        } finally {
181            System.setSecurityManager(oldSm);
182        }
183    }
184
185    /**
186     * @tests java.net.ServerSocket#ServerSocket(int)
187     */
188    @TestTargetNew(
189      level = TestLevel.SUFFICIENT,
190      notes = "Regression test.",
191      method = "ServerSocket",
192      args = {int.class}
193    )
194    public void test_ConstructorI_SocksSet() throws IOException {
195        // Harmony-623 regression test
196        ServerSocket ss = null;
197        Properties props = (Properties) System.getProperties().clone();
198        try {
199            System.setProperty("socksProxyHost", "127.0.0.1");
200            System.setProperty("socksProxyPort", "12345");
201            ss = new ServerSocket(0);
202        } finally {
203            System.setProperties(props);
204            if (null != ss) {
205                ss.close();
206            }
207        }
208    }
209
210    /**
211     * @tests java.net.ServerSocket#ServerSocket(int, int)
212     */
213    @TestTargetNew(
214      level = TestLevel.SUFFICIENT,
215      notes = "Doesn't check backlog.",
216      method = "ServerSocket",
217      args = {int.class, int.class}
218    )
219    public void test_ConstructorII() throws IOException {
220        int freePortNumber = Support_PortManager.getNextPort();
221        try {
222            s = new ServerSocket(freePortNumber, 1);
223            s.setSoTimeout(2000);
224            startClient(freePortNumber);
225            sconn = s.accept();
226
227        } catch (InterruptedIOException e) {
228            fail("InterruptedIOException was thrown.");
229        } finally {
230            try {
231                sconn.close();
232                s.close();
233            } catch(IOException ioe) {}
234        }
235
236        SecurityManager oldSm = System.getSecurityManager();
237        System.setSecurityManager(sm);
238        try {
239            new ServerSocket(0, 0);
240            fail("SecurityException should be thrown.");
241        } catch (SecurityException e) {
242            // expected
243        } catch (SocketException e) {
244            fail("SocketException was thrown.");
245        } finally {
246            System.setSecurityManager(oldSm);
247        }
248
249        int portNumber = Support_PortManager.getNextPort();
250        new ServerSocket(portNumber, 0);
251        try {
252            new ServerSocket(portNumber, 0);
253            fail("IOExcepion was not thrown.");
254        } catch(IOException ioe) {
255            //expected
256        }
257    }
258
259    /**
260     * @tests java.net.ServerSocket#ServerSocket(int, int, java.net.InetAddress)
261     */
262    @TestTargetNew(
263      level = TestLevel.SUFFICIENT,
264      notes = "Doesn't check backlog value.",
265      method = "ServerSocket",
266      args = {int.class, int.class, java.net.InetAddress.class}
267    )
268    public void test_ConstructorIILjava_net_InetAddress()
269                                    throws UnknownHostException, IOException {
270        s = new ServerSocket(0, 10, InetAddress.getLocalHost());
271        try {
272            s.setSoTimeout(5000);
273            startClient(s.getLocalPort());
274            sconn = s.accept();
275            assertNotNull("Was unable to accept connection", sconn);
276            sconn.close();
277        } finally {
278            s.close();
279        }
280
281        int freePortNumber = Support_PortManager.getNextPort();
282        ServerSocket ss = new ServerSocket(freePortNumber, 10,
283                InetAddress.getLocalHost());
284
285        try {
286            new ServerSocket(freePortNumber, 10,
287                    InetAddress.getLocalHost());
288            fail("IOException was not thrown.");
289        } catch(IOException ioe) {
290            //expected
291        }
292
293        try {
294            new ServerSocket(65536, 10,
295                    InetAddress.getLocalHost());
296            fail("IllegalArgumentException was not thrown.");
297        } catch(IllegalArgumentException iae) {
298            //expected
299        }
300
301        SecurityManager oldSm = System.getSecurityManager();
302        System.setSecurityManager(sm);
303        try {
304            new ServerSocket(0, 10, InetAddress.getLocalHost());
305            fail("SecurityException should be thrown.");
306        } catch (SecurityException e) {
307            // expected
308        } catch (SocketException e) {
309            fail("SocketException was thrown.");
310        } finally {
311            System.setSecurityManager(oldSm);
312        }
313
314        int portNumber = Support_PortManager.getNextPort();
315        new ServerSocket(portNumber, 0);
316        try {
317            new ServerSocket(portNumber, 0);
318            fail("IOExcepion was not thrown.");
319        } catch(IOException ioe) {
320            //expected
321        }
322    }
323
324    /**
325     * @tests java.net.ServerSocket#accept()
326     */
327    @TestTargetNew(
328      level = TestLevel.SUFFICIENT,
329      notes = "IOException is not checked.",
330      method = "accept",
331      args = {}
332    )
333    public void test_accept() throws IOException {
334        s = new ServerSocket(0);
335        try {
336            s.setSoTimeout(5000);
337            startClient(s.getLocalPort());
338            sconn = s.accept();
339            int localPort1 = s.getLocalPort();
340            int localPort2 = sconn.getLocalPort();
341            sconn.close();
342            assertEquals("Bad local port value", localPort1, localPort2);
343        } finally {
344            s.close();
345        }
346
347        try {
348            interrupted = false;
349            final ServerSocket ss = new ServerSocket(0);
350            ss.setSoTimeout(12000);
351            Runnable runnable = new Runnable() {
352                public void run() {
353                    try {
354                        ss.accept();
355                    } catch (InterruptedIOException e) {
356                        interrupted = true;
357                    } catch (IOException e) {
358                    }
359                }
360            };
361            Thread thread = new Thread(runnable, "ServerSocket.accept");
362            thread.start();
363            try {
364                do {
365                    Thread.sleep(500);
366                } while (!thread.isAlive());
367            } catch (InterruptedException e) {
368            }
369            ss.close();
370            int c = 0;
371            do {
372                try {
373                    Thread.sleep(500);
374                } catch (InterruptedException e) {
375                }
376                if (interrupted) {
377                    fail("accept interrupted");
378                }
379                if (++c > 4) {
380                    fail("accept call did not exit");
381                }
382            } while (thread.isAlive());
383
384            interrupted = false;
385            ServerSocket ss2 = new ServerSocket(0);
386            ss2.setSoTimeout(500);
387            Date start = new Date();
388            try {
389                ss2.accept();
390            } catch (InterruptedIOException e) {
391                interrupted = true;
392            }
393            assertTrue("accept not interrupted", interrupted);
394            Date finish = new Date();
395            int delay = (int) (finish.getTime() - start.getTime());
396            assertTrue("timeout too soon: " + delay + " " + start.getTime()
397                    + " " + finish.getTime(), delay >= 490);
398            ss2.close();
399        } catch (IOException e) {
400            fail("Unexpected IOException : " + e.getMessage());
401        }
402
403        int portNumber = Support_PortManager.getNextPort();
404        ServerSocket serSocket = new ServerSocket(portNumber);
405        startClient(portNumber);
406
407        SecurityManager sm = new SecurityManager() {
408
409            public void checkPermission(Permission perm) {
410            }
411
412            public void checkAccept(String host,
413                    int port) {
414               throw new SecurityException();
415            }
416        };
417
418        SecurityManager oldSm = System.getSecurityManager();
419        System.setSecurityManager(sm);
420        try {
421            serSocket.accept();
422            fail("SecurityException should be thrown.");
423        } catch (SecurityException e) {
424            // expected
425        } catch (SocketException e) {
426            fail("SocketException was thrown.");
427        } finally {
428            System.setSecurityManager(oldSm);
429            serSocket.close();
430        }
431
432        ServerSocket newSocket = new ServerSocket(portNumber);
433        newSocket.setSoTimeout(500);
434
435        try {
436            newSocket.accept();
437            fail("SocketTimeoutException was not thrown.");
438        } catch(SocketTimeoutException ste) {
439            //expected
440        } finally {
441            newSocket.close();
442        }
443
444        ServerSocketChannel ssc = ServerSocketChannel.open();
445        ServerSocket ss = ssc.socket();
446
447        try {
448            ss.accept();
449            fail("IllegalBlockingModeException was not thrown.");
450        } catch(IllegalBlockingModeException ibme) {
451            //expected
452        } finally {
453            ss.close();
454            ssc.close();
455        }
456    }
457
458    /**
459     * @tests java.net.ServerSocket#close()
460     */
461    @TestTargetNew(
462      level = TestLevel.SUFFICIENT,
463      notes = "IOException checking missed.",
464      method = "close",
465      args = {}
466    )
467    public void test_close() throws IOException {
468        try {
469            s = new ServerSocket(0);
470            try {
471                s.close();
472                s.accept();
473                fail("Close test failed");
474            } catch (SocketException e) {
475                // expected;
476            }
477        } finally {
478            s.close();
479        }
480    }
481
482    /**
483     * @tests java.net.ServerSocket#getInetAddress()
484     */
485    @TestTargetNew(
486      level = TestLevel.COMPLETE,
487      notes = "",
488      method = "getInetAddress",
489      args = {}
490    )
491    public void test_getInetAddress() throws IOException {
492        InetAddress addr = InetAddress.getLocalHost();
493        s = new ServerSocket(0, 10, addr);
494        try {
495            assertEquals("Returned incorrect InetAdrees", addr, s
496                    .getInetAddress());
497        } finally {
498            s.close();
499        }
500    }
501
502    /**
503     * @tests java.net.ServerSocket#getLocalPort()
504     */
505    @TestTargetNew(
506      level = TestLevel.PARTIAL_COMPLETE,
507      notes = "",
508      method = "getLocalPort",
509      args = {}
510    )
511    public void test_getLocalPort() throws IOException {
512        // Try a specific port number, but don't complain if we don't get it
513        int portNumber = 63024; // I made this up
514        try {
515            try {
516                s = new ServerSocket(portNumber);
517            } catch (BindException e) {
518                // we could not get the port, give up
519                return;
520            }
521            assertEquals("Returned incorrect port", portNumber, s
522                    .getLocalPort());
523        } finally {
524            s.close();
525        }
526    }
527
528    /**
529     * @tests java.net.ServerSocket#getSoTimeout()
530     */
531    @TestTargetNew(
532      level = TestLevel.COMPLETE,
533      notes = "",
534      method = "getSoTimeout",
535      args = {}
536    )
537    public void test_getSoTimeout() throws IOException {
538        s = new ServerSocket(0);
539        try {
540            s.setSoTimeout(100);
541            assertEquals("Returned incorrect sotimeout", 100, s.getSoTimeout());
542        } finally {
543            s.close();
544        }
545        try {
546            ServerSocket newSocket = new ServerSocket();
547            newSocket.close();
548            try {
549                newSocket.setSoTimeout(100);
550                fail("SocketException was not thrown.");
551            } catch(SocketException e) {
552                //expected
553            }
554        } catch(Exception e) {
555            fail("Unexpected exception.");
556        }
557    }
558
559    /**
560     * @tests java.net.ServerSocket#setSoTimeout(int)
561     */
562    @TestTargetNew(
563      level = TestLevel.COMPLETE,
564      notes = "",
565      method = "setSoTimeout",
566      args = {int.class}
567    )
568    public void test_setSoTimeoutI() throws IOException {
569        // Timeout should trigger and throw InterruptedIOException
570        try {
571            s = new ServerSocket(0);
572            s.setSoTimeout(100);
573            s.accept();
574        } catch (InterruptedIOException e) {
575            try {
576                assertEquals("Set incorrect sotimeout", 100, s.getSoTimeout());
577                return;
578            } catch (Exception x) {
579                fail("Exception during setSOTimeout: " + e.toString());
580            }
581        } catch (IOException iox) {
582            fail("IOException during setSotimeout: " + iox.toString());
583        }
584
585        // Timeout should not trigger in this case
586        s = new ServerSocket(0);
587        startClient(s.getLocalPort());
588        s.setSoTimeout(10000);
589        sconn = s.accept();
590
591        ServerSocket newSocket = new ServerSocket();
592        newSocket.close();
593        try {
594            newSocket.setSoTimeout(100);
595            fail("SocketException was not thrown.");
596        } catch(SocketException se) {
597            //expected
598        }
599    }
600
601    /**
602     * @tests java.net.ServerSocket#toString()
603     */
604    @TestTargetNew(
605      level = TestLevel.COMPLETE,
606      notes = "",
607      method = "toString",
608      args = {}
609    )
610    public void test_toString() throws Exception {
611        s = new ServerSocket(0);
612        try {
613            int portNumber = s.getLocalPort();
614            assertTrue(s.toString().contains("" + portNumber));
615        } finally {
616            try {
617                s.close();
618            } catch(Exception e) {
619
620            }
621        }
622    }
623
624    /**
625     * @tests java.net.ServerSocket#bind(java.net.SocketAddress)
626     */
627
628    @TestTargetNew(
629      level = TestLevel.COMPLETE,
630      notes = "",
631      method = "bind",
632      args = {java.net.SocketAddress.class}
633    )
634    public void test_bindLjava_net_SocketAddress() throws IOException {
635        class mySocketAddress extends SocketAddress {
636            public mySocketAddress() {
637            }
638        }
639        // create servers socket, bind it and then validate basic state
640        ServerSocket theSocket = new ServerSocket();
641        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
642                .getLocalHost(), 0);
643        theSocket.bind(theAddress);
644        int portNumber = theSocket.getLocalPort();
645        assertTrue(
646                "Returned incorrect InetSocketAddress(2):"
647                        + theSocket.getLocalSocketAddress().toString()
648                        + "Expected: "
649                        + (new InetSocketAddress(InetAddress.getLocalHost(),
650                                portNumber)).toString(), theSocket
651                        .getLocalSocketAddress().equals(
652                                new InetSocketAddress(InetAddress
653                                        .getLocalHost(), portNumber)));
654        assertTrue("Server socket not bound when it should be:", theSocket
655                .isBound());
656
657        // now make sure that it is actually bound and listening on the
658        // address we provided
659        Socket clientSocket = new Socket();
660        InetSocketAddress clAddress = new InetSocketAddress(InetAddress
661                .getLocalHost(), portNumber);
662        clientSocket.connect(clAddress);
663        Socket servSock = theSocket.accept();
664
665        assertEquals(clAddress, clientSocket.getRemoteSocketAddress());
666        theSocket.close();
667        servSock.close();
668        clientSocket.close();
669
670        // validate we can specify null for the address in the bind and all
671        // goes ok
672        theSocket = new ServerSocket();
673        theSocket.bind(null);
674        theSocket.close();
675
676        // Address that we have already bound to
677        theSocket = new ServerSocket();
678        ServerSocket theSocket2 = new ServerSocket();
679        try {
680            theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
681            theSocket.bind(theAddress);
682            SocketAddress localAddress = theSocket.getLocalSocketAddress();
683            theSocket2.bind(localAddress);
684            fail("No exception binding to address that is not available");
685        } catch (IOException ex) {
686        }
687        theSocket.close();
688        theSocket2.close();
689
690        // validate we get io address when we try to bind to address we
691        // cannot bind to
692        theSocket = new ServerSocket();
693        try {
694            theSocket.bind(new InetSocketAddress(InetAddress
695                    .getByAddress(Support_Configuration.nonLocalAddressBytes),
696                    0));
697            fail("No exception was thrown when binding to bad address");
698        } catch (IOException ex) {
699        }
700        theSocket.close();
701
702        // now validate case where we pass in an unsupported subclass of
703        // SocketAddress
704        theSocket = new ServerSocket();
705        try {
706            theSocket.bind(new mySocketAddress());
707            fail("No exception when binding using unsupported SocketAddress subclass");
708        } catch (IllegalArgumentException ex) {
709        }
710        theSocket.close();
711
712
713        ServerSocket serSocket = new ServerSocket();
714
715        SecurityManager oldSm = System.getSecurityManager();
716        System.setSecurityManager(sm);
717        try {
718            serSocket.bind(theAddress);
719            fail("SecurityException should be thrown.");
720        } catch (SecurityException e) {
721            // expected
722        } catch (SocketException e) {
723            fail("SocketException was thrown.");
724        } finally {
725            System.setSecurityManager(oldSm);
726            serSocket.close();
727        }
728    }
729
730    /**
731     * @tests java.net.ServerSocket#bind(java.net.SocketAddress,int)
732     */
733    @TestTargetNew(
734      level = TestLevel.COMPLETE,
735      notes = "",
736      method = "bind",
737      args = {java.net.SocketAddress.class, int.class}
738    )
739    public void test_bindLjava_net_SocketAddressI() throws IOException {
740        class mySocketAddress extends SocketAddress {
741
742            public mySocketAddress() {
743            }
744        }
745
746        // create servers socket, bind it and then validate basic state
747        ServerSocket theSocket = new ServerSocket();
748        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
749                .getLocalHost(), 0);
750        theSocket.bind(theAddress, 5);
751        int portNumber = theSocket.getLocalPort();
752        assertTrue(
753                "Returned incorrect InetSocketAddress(2):"
754                        + theSocket.getLocalSocketAddress().toString()
755                        + "Expected: "
756                        + (new InetSocketAddress(InetAddress.getLocalHost(),
757                                portNumber)).toString(), theSocket
758                        .getLocalSocketAddress().equals(
759                                new InetSocketAddress(InetAddress
760                                        .getLocalHost(), portNumber)));
761        assertTrue("Server socket not bound when it should be:", theSocket
762                .isBound());
763
764        // now make sure that it is actually bound and listening on the
765        // address we provided
766        SocketAddress localAddress = theSocket.getLocalSocketAddress();
767        Socket clientSocket = new Socket();
768        clientSocket.connect(localAddress);
769        Socket servSock = theSocket.accept();
770
771        assertTrue(clientSocket.getRemoteSocketAddress().equals(localAddress));
772        theSocket.close();
773        servSock.close();
774        clientSocket.close();
775
776        // validate we can specify null for the address in the bind and all
777        // goes ok
778        theSocket = new ServerSocket();
779        theSocket.bind(null, 5);
780        theSocket.close();
781
782        // Address that we have already bound to
783        theSocket = new ServerSocket();
784        ServerSocket theSocket2 = new ServerSocket();
785        try {
786            theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
787            theSocket.bind(theAddress, 5);
788            SocketAddress inuseAddress = theSocket.getLocalSocketAddress();
789            theSocket2.bind(inuseAddress, 5);
790            fail("No exception binding to address that is not available");
791        } catch (IOException ex) {
792            // expected
793        }
794        theSocket.close();
795        theSocket2.close();
796
797        // validate we get ioException when we try to bind to address we
798        // cannot bind to
799        theSocket = new ServerSocket();
800        try {
801            theSocket.bind(new InetSocketAddress(InetAddress
802                    .getByAddress(Support_Configuration.nonLocalAddressBytes),
803                    0), 5);
804            fail("No exception was thrown when binding to bad address");
805        } catch (IOException ex) {
806        }
807        theSocket.close();
808
809        // now validate case where we pass in an unsupported subclass of
810        // SocketAddress
811        theSocket = new ServerSocket();
812        try {
813            theSocket.bind(new mySocketAddress(), 5);
814            fail("Binding using unsupported SocketAddress subclass should have thrown exception");
815        } catch (IllegalArgumentException ex) {
816        }
817        theSocket.close();
818
819        // now validate that backlog is respected. We have to do a test that
820        // checks if it is a least a certain number as some platforms make
821        // it higher than we request. Unfortunately non-server versions of
822        // windows artificially limit the backlog to 5 and 5 is the
823        // historical default so it it not a great test.
824        theSocket = new ServerSocket();
825        theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
826        theSocket.bind(theAddress, 4);
827        localAddress = theSocket.getLocalSocketAddress();
828        Socket theSockets[] = new Socket[4];
829        int i = 0;
830        try {
831            for (i = 0; i < 4; i++) {
832                theSockets[i] = new Socket();
833                theSockets[i].connect(localAddress);
834            }
835        } catch (ConnectException ex) {
836            fail("Backlog does not seem to be respected in bind:" + i + ":"
837                    + ex.toString());
838        }
839
840        for (i = 0; i < 4; i++) {
841            theSockets[i].close();
842        }
843
844        theSocket.close();
845        servSock.close();
846
847        ServerSocket serSocket = new ServerSocket();
848
849        SecurityManager oldSm = System.getSecurityManager();
850        System.setSecurityManager(sm);
851        try {
852            serSocket.bind(theAddress, 5);
853            fail("SecurityException should be thrown.");
854        } catch (SecurityException e) {
855            // expected
856        } catch (SocketException e) {
857            fail("SocketException was thrown.");
858        } finally {
859            System.setSecurityManager(oldSm);
860            serSocket.close();
861        }
862    }
863
864    /**
865     * @tests java.net.ServerSocket#getLocalSocketAddress()
866     */
867    @TestTargetNew(
868      level = TestLevel.COMPLETE,
869      notes = "",
870      method = "getLocalSocketAddress",
871      args = {}
872    )
873    public void test_getLocalSocketAddress() {
874        // set up server connect and then validate that we get the right
875        // response for the local address
876        try {
877            ServerSocket theSocket = new ServerSocket(0, 5, InetAddress
878                    .getLocalHost());
879            int portNumber = theSocket.getLocalPort();
880            assertTrue("Returned incorrect InetSocketAddress(1):"
881                    + theSocket.getLocalSocketAddress().toString()
882                    + "Expected: "
883                    + (new InetSocketAddress(InetAddress.getLocalHost(),
884                            portNumber)).toString(), theSocket
885                    .getLocalSocketAddress().equals(
886                            new InetSocketAddress(InetAddress.getLocalHost(),
887                                    portNumber)));
888            theSocket.close();
889
890            // now create a socket that is not bound and validate we get the
891            // right answer
892            theSocket = new ServerSocket();
893            assertNull(
894                    "Returned incorrect InetSocketAddress -unbound socket- Expected null",
895                    theSocket.getLocalSocketAddress());
896
897            // now bind the socket and make sure we get the right answer
898            theSocket
899                    .bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
900            int localPort = theSocket.getLocalPort();
901            assertEquals("Returned incorrect InetSocketAddress(2):", theSocket
902                    .getLocalSocketAddress(), new InetSocketAddress(InetAddress
903                    .getLocalHost(), localPort));
904            theSocket.close();
905        } catch (Exception e) {
906            fail("Exception during getLocalSocketAddress test: " + e);
907        }
908    }
909
910    /**
911     * @tests java.net.ServerSocket#isBound()
912     */
913    @TestTargetNew(
914      level = TestLevel.COMPLETE,
915      notes = "",
916      method = "isBound",
917      args = {}
918    )
919    public void test_isBound() throws IOException {
920        InetAddress addr = InetAddress.getLocalHost();
921        ServerSocket serverSocket = new ServerSocket();
922        assertFalse("Socket indicated bound when it should be (1)",
923                serverSocket.isBound());
924
925        // now bind and validate bound ok
926        serverSocket.bind(new InetSocketAddress(addr, 0));
927        assertTrue("Socket indicated  not bound when it should be (1)",
928                serverSocket.isBound());
929        serverSocket.close();
930
931        // now do with some of the other constructors
932        serverSocket = new ServerSocket(0);
933        assertTrue("Socket indicated  not bound when it should be (2)",
934                serverSocket.isBound());
935        serverSocket.close();
936
937        serverSocket = new ServerSocket(0, 5, addr);
938        assertTrue("Socket indicated  not bound when it should be (3)",
939                serverSocket.isBound());
940        serverSocket.close();
941
942        serverSocket = new ServerSocket(0, 5);
943        assertTrue("Socket indicated  not bound when it should be (4)",
944                serverSocket.isBound());
945        serverSocket.close();
946    }
947
948    /**
949     * @tests java.net.ServerSocket#isClosed()
950     */
951    @TestTargetNew(
952      level = TestLevel.COMPLETE,
953      notes = "",
954      method = "isClosed",
955      args = {}
956    )
957    public void test_isClosed() throws IOException {
958        InetAddress addr = InetAddress.getLocalHost();
959        ServerSocket serverSocket = new ServerSocket(0, 5, addr);
960
961        // validate isClosed returns expected values
962        assertFalse("Socket should indicate it is not closed(1):", serverSocket
963                .isClosed());
964        serverSocket.close();
965        assertTrue("Socket should indicate it is closed(1):", serverSocket
966                .isClosed());
967
968        // now do with some of the other constructors
969        serverSocket = new ServerSocket(0);
970        assertFalse("Socket should indicate it is not closed(1):", serverSocket
971                .isClosed());
972        serverSocket.close();
973        assertTrue("Socket should indicate it is closed(1):", serverSocket
974                .isClosed());
975
976        serverSocket = new ServerSocket(0, 5, addr);
977        assertFalse("Socket should indicate it is not closed(1):", serverSocket
978                .isClosed());
979        serverSocket.close();
980        assertTrue("Socket should indicate it is closed(1):", serverSocket
981                .isClosed());
982
983        serverSocket = new ServerSocket(0, 5);
984        assertFalse("Socket should indicate it is not closed(1):", serverSocket
985                .isClosed());
986        serverSocket.close();
987        assertTrue("Socket should indicate it is closed(1):", serverSocket
988                .isClosed());
989    }
990
991    /**
992     * @tests java.net.ServerSocket#setReuseAddress(boolean)
993     */
994    @TestTargetNew(
995      level = TestLevel.COMPLETE,
996      notes = "",
997      method = "setReuseAddress",
998      args = {boolean.class}
999    )
1000    public void test_setReuseAddressZ() {
1001        try {
1002            // set up server and connect
1003            InetSocketAddress anyAddress = new InetSocketAddress(InetAddress
1004                    .getLocalHost(), 0);
1005            ServerSocket serverSocket = new ServerSocket();
1006            serverSocket.setReuseAddress(false);
1007            serverSocket.bind(anyAddress);
1008            SocketAddress theAddress = serverSocket.getLocalSocketAddress();
1009
1010            // make a connection to the server, then close the server
1011            Socket theSocket = new Socket();
1012            theSocket.connect(theAddress);
1013            Socket stillActiveSocket = serverSocket.accept();
1014            serverSocket.close();
1015
1016            // now try to rebind the server which should fail with
1017            // setReuseAddress to false. On windows platforms the bind is
1018            // allowed even then reUseAddress is false so our test uses
1019            // the platform to determine what the expected result is.
1020            String platform = System.getProperty("os.name");
1021            try {
1022                serverSocket = new ServerSocket();
1023                serverSocket.setReuseAddress(false);
1024                serverSocket.bind(theAddress);
1025                if ((!platform.startsWith("Windows"))) {
1026                    fail("No exception when setReuseAddress is false and we bind:"
1027                            + theAddress.toString());
1028                }
1029            } catch (IOException ex) {
1030                if (platform.startsWith("Windows")) {
1031                    fail("Got unexpected exception when binding with setReuseAddress false on windows platform:"
1032                            + theAddress.toString() + ":" + ex.toString());
1033                }
1034            }
1035            stillActiveSocket.close();
1036            theSocket.close();
1037
1038            // now test case were we set it to true
1039            anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
1040            serverSocket = new ServerSocket();
1041            serverSocket.setReuseAddress(true);
1042            serverSocket.bind(anyAddress);
1043            theAddress = serverSocket.getLocalSocketAddress();
1044
1045            // make a connection to the server, then close the server
1046            theSocket = new Socket();
1047            theSocket.connect(theAddress);
1048            stillActiveSocket = serverSocket.accept();
1049            serverSocket.close();
1050
1051            // now try to rebind the server which should pass with
1052            // setReuseAddress to true
1053            try {
1054                serverSocket = new ServerSocket();
1055                serverSocket.setReuseAddress(true);
1056                serverSocket.bind(theAddress);
1057            } catch (IOException ex) {
1058                fail("Unexpected exception when setReuseAddress is true and we bind:"
1059                        + theAddress.toString() + ":" + ex.toString());
1060            }
1061            stillActiveSocket.close();
1062            theSocket.close();
1063            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
1064
1065            // now test default case were we expect this to work regardless of
1066            // the value set
1067            anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
1068            serverSocket = new ServerSocket();
1069            serverSocket.bind(anyAddress);
1070            theAddress = serverSocket.getLocalSocketAddress();
1071
1072            // make a connection to the server, then close the server
1073            theSocket = new Socket();
1074            theSocket.connect(theAddress);
1075            stillActiveSocket = serverSocket.accept();
1076            serverSocket.close();
1077
1078            // now try to rebind the server which should pass
1079            try {
1080                serverSocket = new ServerSocket();
1081                serverSocket.bind(theAddress);
1082            } catch (IOException ex) {
1083                fail("Unexpected exception when setReuseAddress is the default case and we bind:"
1084                        + theAddress.toString() + ":" + ex.toString());
1085            }
1086            stillActiveSocket.close();
1087            theSocket.close();
1088            try {
1089                theSocket.setReuseAddress(true);
1090                fail("SocketException was not thrown.");
1091            } catch(SocketException se) {
1092                //expected
1093            }
1094            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
1095        } catch (Exception e) {
1096            handleException(e, SO_REUSEADDR);
1097        }
1098    }
1099
1100    /**
1101     * @tests java.net.ServerSocket#getReuseAddress()
1102     */
1103    @TestTargetNew(
1104      level = TestLevel.COMPLETE,
1105      notes = "",
1106      method = "getReuseAddress",
1107      args = {}
1108    )
1109    public void test_getReuseAddress() {
1110        try {
1111            ServerSocket theSocket = new ServerSocket();
1112            theSocket.setReuseAddress(true);
1113            assertTrue("getReuseAddress false when it should be true",
1114                    theSocket.getReuseAddress());
1115            theSocket.setReuseAddress(false);
1116            assertFalse("getReuseAddress true when it should be False",
1117                    theSocket.getReuseAddress());
1118            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
1119        } catch (Exception e) {
1120            handleException(e, SO_REUSEADDR);
1121        }
1122
1123        try {
1124            ServerSocket newSocket = new ServerSocket();
1125            newSocket.close();
1126            try {
1127                newSocket.getReuseAddress();
1128                fail("SocketException was not thrown.");
1129            } catch(SocketException e) {
1130                //expected
1131            }
1132        } catch(Exception e) {
1133            fail("Unexpected exception.");
1134        }
1135    }
1136
1137    /**
1138     * @tests java.net.ServerSocket#setReceiveBufferSize(int)
1139     */
1140    @TestTargetNew(
1141      level = TestLevel.COMPLETE,
1142      notes = "",
1143      method = "setReceiveBufferSize",
1144      args = {int.class}
1145    )
1146    public void test_setReceiveBufferSizeI() {
1147        try {
1148            // now validate case where we try to set to 0
1149            ServerSocket theSocket = new ServerSocket();
1150            try {
1151                theSocket.setReceiveBufferSize(0);
1152                fail("No exception when receive buffer size set to 0");
1153            } catch (IllegalArgumentException ex) {
1154            }
1155            theSocket.close();
1156
1157            // now validate case where we try to set to a negative value
1158            theSocket = new ServerSocket();
1159            try {
1160                theSocket.setReceiveBufferSize(-1000);
1161                fail("No exception when receive buffer size set to -1000");
1162            } catch (IllegalArgumentException ex) {
1163            }
1164            theSocket.close();
1165
1166            // now just try to set a good value to make sure it is set and there
1167            // are not exceptions
1168            theSocket = new ServerSocket();
1169            theSocket.setReceiveBufferSize(1000);
1170            theSocket.close();
1171            try {
1172                theSocket.setReceiveBufferSize(10);
1173                fail("SocketException was not thrown.");
1174            } catch(SocketException se) {
1175                //expected
1176            }
1177            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
1178        } catch (Exception e) {
1179            handleException(e, SO_RCVBUF);
1180        }
1181
1182    }
1183
1184    /*
1185     * @tests java.net.ServerSocket#getReceiveBufferSize()
1186     */
1187    @TestTargetNew(
1188      level = TestLevel.COMPLETE,
1189      notes = "",
1190      method = "getReceiveBufferSize",
1191      args = {}
1192    )
1193     public void test_getReceiveBufferSize() {
1194        try {
1195            ServerSocket theSocket = new ServerSocket();
1196
1197            // since the value returned is not necessary what we set we are
1198            // limited in what we can test
1199            // just validate that it is not 0 or negative
1200            assertFalse("get Buffer size returns 0:", 0 == theSocket
1201                    .getReceiveBufferSize());
1202            assertFalse("get Buffer size returns  a negative value:",
1203                    0 > theSocket.getReceiveBufferSize());
1204
1205            ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
1206        } catch (Exception e) {
1207            handleException(e, SO_RCVBUF);
1208        }
1209        try {
1210            ServerSocket newSocket = new ServerSocket();
1211            newSocket.close();
1212            try {
1213                newSocket.getReceiveBufferSize();
1214                fail("SocketException was not thrown.");
1215            } catch(SocketException e) {
1216                //expected
1217            }
1218        } catch(Exception e) {
1219            fail("Unexpected exception.");
1220        }
1221    }
1222
1223    /**
1224     * @tests java.net.ServerSocket#getChannel()
1225     */
1226    @TestTargetNew(
1227      level = TestLevel.COMPLETE,
1228      notes = "",
1229      method = "getChannel",
1230      args = {}
1231    )
1232    public void test_getChannel() throws Exception {
1233        assertNull(new ServerSocket().getChannel());
1234    }
1235
1236    /*
1237     * @tests java.net.ServerSocket#setPerformancePreference()
1238     */
1239    @TestTargetNew(
1240      level = TestLevel.COMPLETE,
1241      notes = "",
1242      method = "setPerformancePreferences",
1243      args = {int.class, int.class, int.class}
1244    )
1245    public void test_setPerformancePreference_Int_Int_Int() throws Exception {
1246        performancePreferenceTest(1, 0, 0);
1247        performancePreferenceTest(1, 1, 1);
1248        performancePreferenceTest(0, 1, 2);
1249        performancePreferenceTest(Integer.MAX_VALUE, Integer.MAX_VALUE,
1250                Integer.MAX_VALUE);
1251    }
1252
1253    void performancePreferenceTest(int connectionTime, int latency,
1254            int bandwidth) throws Exception {
1255        ServerSocket theSocket = new ServerSocket();
1256        theSocket.setPerformancePreferences(connectionTime, latency, bandwidth);
1257
1258        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
1259                .getLocalHost(), 0);
1260        theSocket.bind(theAddress);
1261        int portNumber = theSocket.getLocalPort();
1262        assertTrue(
1263                "Returned incorrect InetSocketAddress(2):"
1264                        + theSocket.getLocalSocketAddress().toString()
1265                        + "Expected: "
1266                        + (new InetSocketAddress(InetAddress.getLocalHost(),
1267                                portNumber)).toString(), theSocket
1268                        .getLocalSocketAddress().equals(
1269                                new InetSocketAddress(InetAddress
1270                                        .getLocalHost(), portNumber)));
1271        assertTrue("Server socket not bound when it should be:", theSocket
1272                .isBound());
1273
1274        // now make sure that it is actually bound and listening on the
1275        // address we provided
1276        Socket clientSocket = new Socket();
1277        InetSocketAddress clAddress = new InetSocketAddress(InetAddress
1278                .getLocalHost(), portNumber);
1279        clientSocket.connect(clAddress);
1280        Socket servSock = theSocket.accept();
1281
1282        assertEquals(clAddress, clientSocket.getRemoteSocketAddress());
1283        theSocket.close();
1284        servSock.close();
1285        clientSocket.close();
1286    }
1287
1288    /**
1289     * Sets up the fixture, for example, open a network connection. This method
1290     * is called before a test is executed.
1291     */
1292    protected void setUp() {
1293    }
1294
1295    /**
1296     * Tears down the fixture, for example, close a network connection. This
1297     * method is called after a test is executed.
1298     */
1299    protected void tearDown() {
1300
1301        try {
1302            if (s != null)
1303                s.close();
1304            if (sconn != null)
1305                sconn.close();
1306            if (t != null)
1307                t.interrupt();
1308        } catch (Exception e) {
1309        }
1310    }
1311
1312    /**
1313     * Sets up the fixture, for example, open a network connection. This method
1314     * is called before a test is executed.
1315     */
1316    protected void startClient(int port) {
1317        t = new Thread(new SSClient(port), "SSClient");
1318        t.start();
1319        try {
1320            Thread.sleep(1000);
1321        } catch (InterruptedException e) {
1322            System.out.println("Exception during startClinet()" + e.toString());
1323        }
1324    }
1325
1326    /**
1327     * @tests java.net.ServerSocket#implAccept
1328     */
1329    @TestTargetNew(
1330      level = TestLevel.COMPLETE,
1331      notes = "Regression test.",
1332      method = "implAccept",
1333      args = {java.net.Socket.class}
1334    )
1335    public void test_implAcceptLjava_net_Socket() throws Exception {
1336        // regression test for Harmony-1235
1337        try {
1338            new MockServerSocket().mockImplAccept(new MockSocket(
1339                    new MockSocketImpl()));
1340        } catch (SocketException e) {
1341            // expected
1342        }
1343    }
1344
1345    class MockSocketImpl extends SocketImpl {
1346        public MockSocketImpl() {
1347            isCreateCalled = true;
1348        }
1349
1350        protected void create(boolean arg0) throws IOException {
1351            //empty
1352        }
1353
1354        protected void connect(String arg0, int arg1) throws IOException {
1355            // empty
1356        }
1357
1358        protected void connect(InetAddress arg0, int arg1) throws IOException {
1359            // empty
1360        }
1361
1362        protected void connect(SocketAddress arg0, int arg1) throws IOException {
1363            // empty
1364        }
1365
1366        protected void bind(InetAddress arg0, int arg1) throws IOException {
1367            // empty
1368        }
1369
1370        protected void listen(int arg0) throws IOException {
1371            // empty
1372        }
1373
1374        protected void accept(SocketImpl arg0) throws IOException {
1375            // empty
1376        }
1377
1378        protected InputStream getInputStream() throws IOException {
1379            return null;
1380        }
1381
1382        protected OutputStream getOutputStream() throws IOException {
1383            return null;
1384        }
1385
1386        protected int available() throws IOException {
1387            return 0;
1388        }
1389
1390        protected void close() throws IOException {
1391            // empty
1392        }
1393
1394        protected void sendUrgentData(int arg0) throws IOException {
1395            // empty
1396        }
1397
1398        public void setOption(int arg0, Object arg1) throws SocketException {
1399            // empty
1400        }
1401
1402        public Object getOption(int arg0) throws SocketException {
1403            return null;
1404        }
1405    }
1406
1407    static class MockSocket extends Socket {
1408        public MockSocket(SocketImpl impl) throws SocketException {
1409            super(impl);
1410        }
1411    }
1412
1413    static class MockServerSocket extends ServerSocket {
1414        public MockServerSocket() throws Exception {
1415            super();
1416        }
1417
1418        public void mockImplAccept(Socket s) throws Exception {
1419            super.implAccept(s);
1420        }
1421    }
1422
1423    @TestTargetNew(
1424      level = TestLevel.PARTIAL_COMPLETE,
1425      notes = "",
1426      method = "getLocalPort",
1427      args = {}
1428    )
1429    public void test_LocalPort() throws IOException {
1430        ServerSocket ss1 = new ServerSocket(4242);
1431        assertEquals(ss1.getLocalPort(), 4242);
1432        ss1.close();
1433
1434        ServerSocket ss2 = new ServerSocket();
1435        ss2.bind(new InetSocketAddress("127.0.0.1", 4343));
1436        assertEquals(ss2.getLocalPort(), 4343);
1437        ss2.close();
1438
1439        ServerSocket ss3 = new ServerSocket(0);
1440        assertTrue(ss3.getLocalPort() != 0);
1441        ss3.close();
1442    }
1443
1444    /**
1445     * @tests java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
1446     */
1447    @TestTargetNew(
1448      level = TestLevel.SUFFICIENT,
1449      notes = "",
1450      method = "setSocketFactory",
1451      args = {java.net.SocketImplFactory.class}
1452    )
1453    public void test_setSocketFactoryLjava_net_SocketImplFactory() {
1454
1455        SecurityManager sm = new SecurityManager() {
1456
1457            public void checkPermission(Permission perm) {
1458            }
1459
1460            public void checkSetFactory() {
1461                throw new SecurityException();
1462            }
1463        };
1464
1465        MockSocketFactory sf = new MockSocketFactory();
1466        SecurityManager oldSm = System.getSecurityManager();
1467        System.setSecurityManager(sm);
1468        try {
1469            ServerSocket.setSocketFactory(sf);
1470            fail("SecurityException should be thrown.");
1471        } catch (SecurityException e) {
1472            // expected
1473        } catch (IOException e) {
1474            fail("IOException was thrown.");
1475        } finally {
1476            System.setSecurityManager(oldSm);
1477        }
1478/*
1479*        try {
1480*            ServerSocket.setSocketFactory(sf);
1481*            ServerSocket ss1 = new ServerSocket();
1482*            assertTrue(isCreateCalled);
1483*            isCreateCalled = false;
1484*            ServerSocket ss2 = new ServerSocket(0);
1485*            assertTrue(isCreateCalled);
1486*        } catch(IOException ioe) {
1487*            fail("IOException was thrown: " + ioe.toString());
1488*        }
1489
1490*        try {
1491*            ServerSocket.setSocketFactory(null);
1492*            fail("IOException was not thrown.");
1493*        } catch(IOException ioe) {
1494*            //expected
1495*        }
1496*/
1497    }
1498
1499    class MockSocketFactory implements SocketImplFactory {
1500        public SocketImpl createSocketImpl() {
1501            return new MockSocketImpl();
1502        }
1503    }
1504}
1505