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 org.apache.harmony.luni.tests.java.net;
19
20import java.io.IOException;
21import java.io.InputStream;
22import java.io.InterruptedIOException;
23import java.io.OutputStream;
24import java.net.BindException;
25import java.net.ConnectException;
26import java.net.InetAddress;
27import java.net.InetSocketAddress;
28import java.net.ServerSocket;
29import java.net.Socket;
30import java.net.SocketAddress;
31import java.net.SocketException;
32import java.net.SocketImpl;
33import java.net.SocketImplFactory;
34import java.net.UnknownHostException;
35import java.util.Date;
36import java.util.Locale;
37import java.util.Properties;
38
39import java.net.PlainServerSocketImpl;
40
41import tests.support.Support_Configuration;
42import tests.support.Support_Exec;
43
44public class ServerSocketTest extends junit.framework.TestCase {
45
46    boolean interrupted;
47
48    ServerSocket s;
49
50    Socket sconn;
51
52    Thread t;
53
54    static class SSClient implements Runnable {
55        Socket cs;
56
57        int port;
58
59        public SSClient(int prt) {
60            port = prt;
61        }
62
63        public void run() {
64            try {
65                // Go to sleep so the server can setup and wait for connection
66                Thread.sleep(1000);
67                cs = new Socket(InetAddress.getLocalHost().getHostName(), port);
68                // Sleep again to allow server side processing. Thread is
69                // stopped by server.
70                Thread.sleep(10000);
71            } catch (InterruptedException e) {
72                return;
73            } catch (Throwable e) {
74                System.out
75                        .println("Error establishing client: " + e.toString());
76            } finally {
77                try {
78                    if (cs != null)
79                        cs.close();
80                } catch (Exception e) {
81                }
82            }
83        }
84    }
85
86    /**
87     * @tests java.net.ServerSocket#ServerSocket()
88     */
89    public void test_Constructor() {
90        // Test for method java.net.ServerSocket(int)
91        assertTrue("Used during tests", true);
92    }
93
94    /**
95     * @tests java.net.ServerSocket#ServerSocket(int)
96     */
97    public void test_ConstructorI() {
98        // Test for method java.net.ServerSocket(int)
99        assertTrue("Used during tests", true);
100    }
101
102    /**
103     * @tests java.net.ServerSocket#ServerSocket(int)
104     */
105    public void test_ConstructorI_SocksSet() throws IOException {
106        // Harmony-623 regression test
107        ServerSocket ss = null;
108        Properties props = (Properties) System.getProperties().clone();
109        try {
110            System.setProperty("socksProxyHost", "127.0.0.1");
111            System.setProperty("socksProxyPort", "12345");
112            ss = new ServerSocket(0);
113        } finally {
114            System.setProperties(props);
115            if (null != ss) {
116                ss.close();
117            }
118        }
119    }
120
121    /**
122     * @tests java.net.ServerSocket#ServerSocket(int, int)
123     */
124    public void test_ConstructorII() throws IOException {
125        try {
126            s = new ServerSocket(0, 10);
127            s.setSoTimeout(2000);
128            startClient(s.getLocalPort());
129            sconn = s.accept();
130        } catch (InterruptedIOException e) {
131            return;
132        }
133
134        ServerSocket s1 = new ServerSocket(0);
135        try {
136            try {
137                ServerSocket s2 = new ServerSocket(s1.getLocalPort());
138                s2.close();
139                fail("Was able to create two serversockets on same port");
140            } catch (BindException e) {
141                // Expected
142            }
143        } finally {
144            s1.close();
145        }
146
147        s1 = new ServerSocket(0);
148        int allocatedPort = s1.getLocalPort();
149        s1.close();
150        s1 = new ServerSocket(allocatedPort);
151        s1.close();
152    }
153
154    /**
155     * @tests java.net.ServerSocket#ServerSocket(int, int, java.net.InetAddress)
156     */
157    public void test_ConstructorIILjava_net_InetAddress()
158            throws UnknownHostException, IOException {
159        s = new ServerSocket(0, 10, InetAddress.getLocalHost());
160        try {
161            s.setSoTimeout(5000);
162            startClient(s.getLocalPort());
163            sconn = s.accept();
164            assertNotNull("Was unable to accept connection", sconn);
165            sconn.close();
166        } finally {
167            s.close();
168        }
169    }
170
171    /**
172     * @tests java.net.ServerSocket#accept()
173     */
174    public void test_accept() throws IOException {
175        s = new ServerSocket(0);
176        try {
177            s.setSoTimeout(5000);
178            startClient(s.getLocalPort());
179            sconn = s.accept();
180            int localPort1 = s.getLocalPort();
181            int localPort2 = sconn.getLocalPort();
182            sconn.close();
183            assertEquals("Bad local port value", localPort1, localPort2);
184        } finally {
185            s.close();
186        }
187
188        try {
189            interrupted = false;
190            final ServerSocket ss = new ServerSocket(0);
191            ss.setSoTimeout(12000);
192            Runnable runnable = new Runnable() {
193                public void run() {
194                    try {
195                        ss.accept();
196                    } catch (InterruptedIOException e) {
197                        interrupted = true;
198                    } catch (IOException e) {
199                    }
200                }
201            };
202            Thread thread = new Thread(runnable, "ServerSocket.accept");
203            thread.start();
204            try {
205                do {
206                    Thread.sleep(500);
207                } while (!thread.isAlive());
208            } catch (InterruptedException e) {
209            }
210            ss.close();
211            int c = 0;
212            do {
213                try {
214                    Thread.sleep(500);
215                } catch (InterruptedException e) {
216                }
217                if (interrupted) {
218                    fail("accept interrupted");
219                }
220                if (++c > 4) {
221                    fail("accept call did not exit");
222                }
223            } while (thread.isAlive());
224
225            interrupted = false;
226            ServerSocket ss2 = new ServerSocket(0);
227            ss2.setSoTimeout(500);
228            Date start = new Date();
229            try {
230                ss2.accept();
231            } catch (InterruptedIOException e) {
232                interrupted = true;
233            }
234            assertTrue("accept not interrupted", interrupted);
235            Date finish = new Date();
236            int delay = (int) (finish.getTime() - start.getTime());
237            assertTrue("timeout too soon: " + delay + " " + start.getTime()
238                    + " " + finish.getTime(), delay >= 490);
239            ss2.close();
240        } catch (IOException e) {
241            fail("Unexpected IOException : " + e.getMessage());
242        }
243    }
244
245    /**
246     * @tests java.net.ServerSocket#close()
247     */
248    public void test_close() throws IOException {
249        try {
250            s = new ServerSocket(0);
251            try {
252                s.close();
253                s.accept();
254                fail("Close test failed");
255            } catch (SocketException e) {
256                // expected;
257            }
258        } finally {
259            s.close();
260        }
261    }
262
263    /**
264     * @tests java.net.ServerSocket#getInetAddress()
265     */
266    public void test_getInetAddress() throws IOException {
267        InetAddress addr = InetAddress.getLocalHost();
268        s = new ServerSocket(0, 10, addr);
269        try {
270            assertEquals("Returned incorrect InetAdrees", addr, s
271                    .getInetAddress());
272        } finally {
273            s.close();
274        }
275    }
276
277    /**
278     * @tests java.net.ServerSocket#getLocalPort()
279     */
280    public void test_getLocalPort() throws IOException {
281        // Try a specific port number, but don't complain if we don't get it
282        int portNumber = 63024; // I made this up
283        try {
284            try {
285                s = new ServerSocket(portNumber);
286            } catch (BindException e) {
287                // we could not get the port, give up
288                return;
289            }
290            assertEquals("Returned incorrect port", portNumber, s
291                    .getLocalPort());
292        } finally {
293            s.close();
294        }
295    }
296
297    /**
298     * @tests java.net.ServerSocket#getSoTimeout()
299     */
300    public void test_getSoTimeout() throws IOException {
301        s = new ServerSocket(0);
302        try {
303            s.setSoTimeout(100);
304            assertEquals("Returned incorrect sotimeout", 100, s.getSoTimeout());
305        } finally {
306            s.close();
307        }
308    }
309
310    /**
311     * @tests java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
312     */
313    public void test_setSocketFactoryLjava_net_SocketImplFactory()
314            throws IOException {
315        SocketImplFactory factory = new MockSocketImplFactory();
316        // Should not throw SocketException when set DatagramSocketImplFactory
317        // for the first time.
318        ServerSocket.setSocketFactory(factory);
319
320        try {
321            ServerSocket.setSocketFactory(null);
322            fail("Should throw SocketException");
323        } catch (SocketException e) {
324            // Expected
325        }
326
327        try {
328            ServerSocket.setSocketFactory(factory);
329            fail("Should throw SocketException");
330        } catch (SocketException e) {
331            // Expected
332        }
333    }
334
335    private static class MockSocketImplFactory implements SocketImplFactory {
336        public SocketImpl createSocketImpl() {
337            return new PlainServerSocketImpl();
338        }
339    }
340
341    /**
342     * @tests java.net.ServerSocket#setSoTimeout(int)
343     */
344    public void test_setSoTimeoutI() throws IOException {
345        // Timeout should trigger and throw InterruptedIOException
346        try {
347            s = new ServerSocket(0);
348            s.setSoTimeout(100);
349            s.accept();
350        } catch (InterruptedIOException e) {
351            assertEquals("Set incorrect sotimeout", 100, s.getSoTimeout());
352            return;
353        }
354
355        // Timeout should not trigger in this case
356        s = new ServerSocket(0);
357        startClient(s.getLocalPort());
358        s.setSoTimeout(10000);
359        sconn = s.accept();
360    }
361
362    /**
363     * @tests java.net.ServerSocket#toString()
364     */
365    public void test_toString() throws Exception {
366        s = new ServerSocket(0);
367        try {
368            int portNumber = s.getLocalPort();
369            assertEquals("ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport="
370                    + portNumber + "]", s.toString());
371        } finally {
372            s.close();
373        }
374    }
375
376    /**
377     * @tests java.net.ServerSocket#bind(java.net.SocketAddress)
378     */
379    public void test_bindLjava_net_SocketAddress() throws IOException {
380        class mySocketAddress extends SocketAddress {
381            public mySocketAddress() {
382            }
383        }
384        // create servers socket, bind it and then validate basic state
385        ServerSocket theSocket = new ServerSocket();
386        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
387                .getLocalHost(), 0);
388        theSocket.bind(theAddress);
389        int portNumber = theSocket.getLocalPort();
390        assertTrue(
391                "Returned incorrect InetSocketAddress(2):"
392                        + theSocket.getLocalSocketAddress().toString()
393                        + "Expected: "
394                        + (new InetSocketAddress(InetAddress.getLocalHost(),
395                                portNumber)).toString(), theSocket
396                        .getLocalSocketAddress().equals(
397                                new InetSocketAddress(InetAddress
398                                        .getLocalHost(), portNumber)));
399        assertTrue("Server socket not bound when it should be:", theSocket
400                .isBound());
401
402        // now make sure that it is actually bound and listening on the
403        // address we provided
404        Socket clientSocket = new Socket();
405        InetSocketAddress clAddress = new InetSocketAddress(InetAddress
406                .getLocalHost(), portNumber);
407        clientSocket.connect(clAddress);
408        Socket servSock = theSocket.accept();
409
410        assertEquals(clAddress, clientSocket.getRemoteSocketAddress());
411        theSocket.close();
412        servSock.close();
413        clientSocket.close();
414
415        // validate we can specify null for the address in the bind and all
416        // goes ok
417        theSocket = new ServerSocket();
418        theSocket.bind(null);
419        theSocket.close();
420
421        // Address that we have already bound to
422        theSocket = new ServerSocket();
423        ServerSocket theSocket2 = new ServerSocket();
424        try {
425            theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
426            theSocket.bind(theAddress);
427            SocketAddress localAddress = theSocket.getLocalSocketAddress();
428            theSocket2.bind(localAddress);
429            fail("No exception binding to address that is not available");
430        } catch (IOException ex) {
431        }
432        theSocket.close();
433        theSocket2.close();
434
435        // validate we get io address when we try to bind to address we
436        // cannot bind to
437        theSocket = new ServerSocket();
438        try {
439            theSocket.bind(new InetSocketAddress(InetAddress
440                    .getByAddress(Support_Configuration.nonLocalAddressBytes),
441                    0));
442            fail("No exception was thrown when binding to bad address");
443        } catch (IOException ex) {
444        }
445        theSocket.close();
446
447        // now validate case where we pass in an unsupported subclass of
448        // SocketAddress
449        theSocket = new ServerSocket();
450        try {
451            theSocket.bind(new mySocketAddress());
452            fail("No exception when binding using unsupported SocketAddress subclass");
453        } catch (IllegalArgumentException ex) {
454        }
455        theSocket.close();
456    }
457
458    /**
459     * @tests java.net.ServerSocket#bind(java.net.SocketAddress,int)
460     */
461    public void test_bindLjava_net_SocketAddressI() throws IOException {
462        class mySocketAddress extends SocketAddress {
463
464            public mySocketAddress() {
465            }
466        }
467
468        // create servers socket, bind it and then validate basic state
469        ServerSocket theSocket = new ServerSocket();
470        InetSocketAddress theAddress = new InetSocketAddress(InetAddress
471                .getLocalHost(), 0);
472        theSocket.bind(theAddress, 5);
473        int portNumber = theSocket.getLocalPort();
474        assertTrue(
475                "Returned incorrect InetSocketAddress(2):"
476                        + theSocket.getLocalSocketAddress().toString()
477                        + "Expected: "
478                        + (new InetSocketAddress(InetAddress.getLocalHost(),
479                                portNumber)).toString(), theSocket
480                        .getLocalSocketAddress().equals(
481                                new InetSocketAddress(InetAddress
482                                        .getLocalHost(), portNumber)));
483        assertTrue("Server socket not bound when it should be:", theSocket
484                .isBound());
485
486        // now make sure that it is actually bound and listening on the
487        // address we provided
488        SocketAddress localAddress = theSocket.getLocalSocketAddress();
489        Socket clientSocket = new Socket();
490        clientSocket.connect(localAddress);
491        Socket servSock = theSocket.accept();
492
493        assertTrue(clientSocket.getRemoteSocketAddress().equals(localAddress));
494        theSocket.close();
495        servSock.close();
496        clientSocket.close();
497
498        // validate we can specify null for the address in the bind and all
499        // goes ok
500        theSocket = new ServerSocket();
501        theSocket.bind(null, 5);
502        theSocket.close();
503
504        // Address that we have already bound to
505        theSocket = new ServerSocket();
506        ServerSocket theSocket2 = new ServerSocket();
507        try {
508            theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
509            theSocket.bind(theAddress, 5);
510            SocketAddress inuseAddress = theSocket.getLocalSocketAddress();
511            theSocket2.bind(inuseAddress, 5);
512            fail("No exception binding to address that is not available");
513        } catch (IOException ex) {
514            // expected
515        }
516        theSocket.close();
517        theSocket2.close();
518
519        // validate we get ioException when we try to bind to address we
520        // cannot bind to
521        theSocket = new ServerSocket();
522        try {
523            theSocket.bind(new InetSocketAddress(InetAddress
524                    .getByAddress(Support_Configuration.nonLocalAddressBytes),
525                    0), 5);
526            fail("No exception was thrown when binding to bad address");
527        } catch (IOException ex) {
528        }
529        theSocket.close();
530
531        // now validate case where we pass in an unsupported subclass of
532        // SocketAddress
533        theSocket = new ServerSocket();
534        try {
535            theSocket.bind(new mySocketAddress(), 5);
536            fail("Binding using unsupported SocketAddress subclass should have thrown exception");
537        } catch (IllegalArgumentException ex) {
538        }
539        theSocket.close();
540
541        // now validate that backlog is respected. We have to do a test that
542        // checks if it is a least a certain number as some platforms make
543        // it higher than we request. Unfortunately non-server versions of
544        // windows artificially limit the backlog to 5 and 5 is the
545        // historical default so it is not a great test.
546        theSocket = new ServerSocket();
547        theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
548        theSocket.bind(theAddress, 4);
549        localAddress = theSocket.getLocalSocketAddress();
550        Socket theSockets[] = new Socket[4];
551        int i = 0;
552        try {
553            for (i = 0; i < 4; i++) {
554                theSockets[i] = new Socket();
555                theSockets[i].connect(localAddress);
556            }
557        } catch (ConnectException ex) {
558            fail("Backlog does not seem to be respected in bind:" + i + ":"
559                    + ex.toString());
560        }
561
562        for (i = 0; i < 4; i++) {
563            theSockets[i].close();
564        }
565
566        theSocket.close();
567        servSock.close();
568    }
569
570    /**
571     * @tests java.net.ServerSocket#getLocalSocketAddress()
572     */
573    public void test_getLocalSocketAddress() throws Exception {
574        // set up server connect and then validate that we get the right
575        // response for the local address
576        ServerSocket theSocket = new ServerSocket(0, 5, InetAddress
577                .getLocalHost());
578        int portNumber = theSocket.getLocalPort();
579        assertTrue("Returned incorrect InetSocketAddress(1):"
580                + theSocket.getLocalSocketAddress().toString()
581                + "Expected: "
582                + (new InetSocketAddress(InetAddress.getLocalHost(),
583                        portNumber)).toString(), theSocket
584                .getLocalSocketAddress().equals(
585                        new InetSocketAddress(InetAddress.getLocalHost(),
586                                portNumber)));
587        theSocket.close();
588
589        // now create a socket that is not bound and validate we get the
590        // right answer
591        theSocket = new ServerSocket();
592        assertNull(
593                "Returned incorrect InetSocketAddress -unbound socket- Expected null",
594                theSocket.getLocalSocketAddress());
595
596        // now bind the socket and make sure we get the right answer
597        theSocket
598                .bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
599        int localPort = theSocket.getLocalPort();
600        assertEquals("Returned incorrect InetSocketAddress(2):", theSocket
601                .getLocalSocketAddress(), new InetSocketAddress(InetAddress
602                .getLocalHost(), localPort));
603        theSocket.close();
604    }
605
606    /**
607     * @tests java.net.ServerSocket#isBound()
608     */
609    public void test_isBound() throws IOException {
610        InetAddress addr = InetAddress.getLocalHost();
611        ServerSocket serverSocket = new ServerSocket();
612        assertFalse("Socket indicated bound when it should be (1)",
613                serverSocket.isBound());
614
615        // now bind and validate bound ok
616        serverSocket.bind(new InetSocketAddress(addr, 0));
617        assertTrue("Socket indicated  not bound when it should be (1)",
618                serverSocket.isBound());
619        serverSocket.close();
620
621        // now do with some of the other constructors
622        serverSocket = new ServerSocket(0);
623        assertTrue("Socket indicated  not bound when it should be (2)",
624                serverSocket.isBound());
625        serverSocket.close();
626
627        serverSocket = new ServerSocket(0, 5, addr);
628        assertTrue("Socket indicated  not bound when it should be (3)",
629                serverSocket.isBound());
630        serverSocket.close();
631
632        serverSocket = new ServerSocket(0, 5);
633        assertTrue("Socket indicated  not bound when it should be (4)",
634                serverSocket.isBound());
635        serverSocket.close();
636    }
637
638    /**
639     * @tests java.net.ServerSocket#isClosed()
640     */
641    public void test_isClosed() throws IOException {
642        InetAddress addr = InetAddress.getLocalHost();
643        ServerSocket serverSocket = new ServerSocket(0, 5, addr);
644
645        // validate isClosed returns expected values
646        assertFalse("Socket should indicate it is not closed(1):", serverSocket
647                .isClosed());
648        serverSocket.close();
649        assertTrue("Socket should indicate it is closed(1):", serverSocket
650                .isClosed());
651
652        // now do with some of the other constructors
653        serverSocket = new ServerSocket(0);
654        assertFalse("Socket should indicate it is not closed(1):", serverSocket
655                .isClosed());
656        serverSocket.close();
657        assertTrue("Socket should indicate it is closed(1):", serverSocket
658                .isClosed());
659
660        serverSocket = new ServerSocket(0, 5, addr);
661        assertFalse("Socket should indicate it is not closed(1):", serverSocket
662                .isClosed());
663        serverSocket.close();
664        assertTrue("Socket should indicate it is closed(1):", serverSocket
665                .isClosed());
666
667        serverSocket = new ServerSocket(0, 5);
668        assertFalse("Socket should indicate it is not closed(1):", serverSocket
669                .isClosed());
670        serverSocket.close();
671        assertTrue("Socket should indicate it is closed(1):", serverSocket
672                .isClosed());
673    }
674
675    /*
676     * Regression HARMONY-6090
677     */
678    public void test_defaultValueReuseAddress() throws Exception {
679        String platform = System.getProperty("os.name").toLowerCase(Locale.US);
680        if (!platform.startsWith("windows")) {
681            // on Unix
682            assertTrue(new ServerSocket().getReuseAddress());
683            assertTrue(new ServerSocket(0).getReuseAddress());
684            assertTrue(new ServerSocket(0, 50).getReuseAddress());
685            assertTrue(new ServerSocket(0, 50, InetAddress.getLocalHost()).getReuseAddress());
686        } else {
687            // on Windows
688            assertFalse(new ServerSocket().getReuseAddress());
689            assertFalse(new ServerSocket(0).getReuseAddress());
690            assertFalse(new ServerSocket(0, 50).getReuseAddress());
691            assertFalse(new ServerSocket(0, 50, InetAddress.getLocalHost()).getReuseAddress());
692        }
693    }
694
695    public void test_setReuseAddressZ() throws Exception {
696        // set up server and connect
697        InetSocketAddress anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
698        ServerSocket serverSocket = new ServerSocket();
699        serverSocket.setReuseAddress(false);
700        serverSocket.bind(anyAddress);
701        SocketAddress theAddress = serverSocket.getLocalSocketAddress();
702
703        // make a connection to the server, then close the server
704        Socket theSocket = new Socket();
705        theSocket.connect(theAddress);
706        Socket stillActiveSocket = serverSocket.accept();
707        serverSocket.close();
708
709        // now try to rebind the server which should fail with
710        // setReuseAddress to false. On windows platforms the bind is
711        // allowed even then reUseAddress is false so our test uses
712        // the platform to determine what the expected result is.
713        String platform = System.getProperty("os.name");
714        try {
715            serverSocket = new ServerSocket();
716            serverSocket.setReuseAddress(false);
717            serverSocket.bind(theAddress);
718            fail("No exception when setReuseAddress is false and we bind:" + theAddress.toString());
719        } catch (IOException expected) {
720        }
721        stillActiveSocket.close();
722        theSocket.close();
723
724        // now test case were we set it to true
725        anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
726        serverSocket = new ServerSocket();
727        serverSocket.setReuseAddress(true);
728        serverSocket.bind(anyAddress);
729        theAddress = serverSocket.getLocalSocketAddress();
730
731        // make a connection to the server, then close the server
732        theSocket = new Socket();
733        theSocket.connect(theAddress);
734        stillActiveSocket = serverSocket.accept();
735        serverSocket.close();
736
737        // now try to rebind the server which should pass with
738        // setReuseAddress to true
739        try {
740            serverSocket = new ServerSocket();
741            serverSocket.setReuseAddress(true);
742            serverSocket.bind(theAddress);
743        } catch (IOException ex) {
744            fail("Unexpected exception when setReuseAddress is true and we bind:"
745                + theAddress.toString() + ":" + ex.toString());
746        }
747        stillActiveSocket.close();
748        theSocket.close();
749
750        // now test default case were we expect this to work regardless of
751        // the value set
752        anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
753        serverSocket = new ServerSocket();
754        serverSocket.bind(anyAddress);
755        theAddress = serverSocket.getLocalSocketAddress();
756
757        // make a connection to the server, then close the server
758        theSocket = new Socket();
759        theSocket.connect(theAddress);
760        stillActiveSocket = serverSocket.accept();
761        serverSocket.close();
762
763        // now try to rebind the server which should pass
764        try {
765            serverSocket = new ServerSocket();
766            serverSocket.bind(theAddress);
767        } catch (IOException ex) {
768            fail("Unexpected exception when setReuseAddress is the default case and we bind:"
769                + theAddress.toString() + ":" + ex.toString());
770        }
771        stillActiveSocket.close();
772        theSocket.close();
773    }
774
775    public void test_getReuseAddress() throws Exception {
776        ServerSocket theSocket = new ServerSocket();
777        theSocket.setReuseAddress(true);
778        assertTrue("getReuseAddress false when it should be true", theSocket.getReuseAddress());
779        theSocket.setReuseAddress(false);
780        assertFalse("getReuseAddress true when it should be False", theSocket.getReuseAddress());
781    }
782
783    public void test_setReceiveBufferSizeI() throws Exception {
784        // now validate case where we try to set to 0
785        ServerSocket theSocket = new ServerSocket();
786        try {
787            theSocket.setReceiveBufferSize(0);
788            fail("No exception when receive buffer size set to 0");
789        } catch (IllegalArgumentException ex) {
790        }
791        theSocket.close();
792
793        // now validate case where we try to set to a negative value
794        theSocket = new ServerSocket();
795        try {
796            theSocket.setReceiveBufferSize(-1000);
797            fail("No exception when receive buffer size set to -1000");
798        } catch (IllegalArgumentException ex) {
799        }
800        theSocket.close();
801
802        // now just try to set a good value to make sure it is set and there
803        // are not exceptions
804        theSocket = new ServerSocket();
805        theSocket.setReceiveBufferSize(1000);
806        theSocket.close();
807    }
808
809    public void test_getReceiveBufferSize() throws Exception {
810        ServerSocket theSocket = new ServerSocket();
811
812        // since the value returned is not necessary what we set we are
813        // limited in what we can test
814        // just validate that it is not 0 or negative
815        assertFalse("get Buffer size returns 0:", 0 == theSocket.getReceiveBufferSize());
816        assertFalse("get Buffer size returns  a negative value:", 0 > theSocket.getReceiveBufferSize());
817    }
818
819    public void test_getChannel() throws Exception {
820        assertNull(new ServerSocket().getChannel());
821    }
822
823    public void test_setPerformancePreference_Int_Int_Int() throws Exception {
824        ServerSocket theSocket = new ServerSocket();
825        theSocket.setPerformancePreferences(1, 1, 1);
826    }
827
828    /**
829     * Sets up the fixture, for example, open a network connection. This method
830     * is called before a test is executed.
831     */
832    protected void setUp() {
833    }
834
835    /**
836     * Tears down the fixture, for example, close a network connection. This
837     * method is called after a test is executed.
838     */
839    protected void tearDown() {
840
841        try {
842            if (s != null)
843                s.close();
844            if (sconn != null)
845                sconn.close();
846            if (t != null)
847                t.interrupt();
848        } catch (Exception e) {
849        }
850    }
851
852    /**
853     * Sets up the fixture, for example, open a network connection. This method
854     * is called before a test is executed.
855     */
856    protected void startClient(int port) {
857        t = new Thread(new SSClient(port), "SSClient");
858        t.start();
859        try {
860            Thread.sleep(1000);
861        } catch (InterruptedException e) {
862            System.out.println("Exception during startClinet()" + e.toString());
863        }
864    }
865
866    /**
867     * @tests java.net.ServerSocket#implAccept
868     */
869    public void test_implAcceptLjava_net_Socket() throws Exception {
870        // regression test for Harmony-1235
871        try {
872            new MockServerSocket().mockImplAccept(new MockSocket(
873                    new MockSocketImpl()));
874        } catch (SocketException e) {
875            // expected
876        }
877    }
878
879    /**
880     * Regression for HARMONY-3265
881     * @throws Exception
882     */
883    public void test_ServerSocket_init() throws Exception {
884        String[] args = new String[]{"org.apache.harmony.luni.tests.java.net.TestServerSocketInit"};
885        Support_Exec.execJava(args, null, true);
886    }
887
888    static class MockSocketImpl extends SocketImpl {
889        protected void create(boolean arg0) throws IOException {
890            // empty
891        }
892
893        protected void connect(String arg0, int arg1) throws IOException {
894            // empty
895        }
896
897        protected void connect(InetAddress arg0, int arg1) throws IOException {
898            // empty
899        }
900
901        protected void connect(SocketAddress arg0, int arg1) throws IOException {
902            // empty
903        }
904
905        protected void bind(InetAddress arg0, int arg1) throws IOException {
906            // empty
907        }
908
909        protected void listen(int arg0) throws IOException {
910            // empty
911        }
912
913        protected void accept(SocketImpl arg0) throws IOException {
914            // empty
915        }
916
917        protected InputStream getInputStream() throws IOException {
918            return null;
919        }
920
921        protected OutputStream getOutputStream() throws IOException {
922            return null;
923        }
924
925        protected int available() throws IOException {
926            return 0;
927        }
928
929        protected void close() throws IOException {
930            // empty
931        }
932
933        protected void sendUrgentData(int arg0) throws IOException {
934            // empty
935        }
936
937        public void setOption(int arg0, Object arg1) throws SocketException {
938            // empty
939        }
940
941        public Object getOption(int arg0) throws SocketException {
942            return null;
943        }
944    }
945
946    static class MockSocket extends Socket {
947        public MockSocket(SocketImpl impl) throws SocketException {
948            super(impl);
949        }
950    }
951
952    static class MockServerSocket extends ServerSocket {
953        public MockServerSocket() throws Exception {
954            super();
955        }
956
957        public void mockImplAccept(Socket s) throws Exception {
958            super.implAccept(s);
959        }
960    }
961}
962