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 
18 package org.apache.harmony.tests.java.nio.channels;
19 
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.net.InetSocketAddress;
24 import java.net.ServerSocket;
25 import java.net.Socket;
26 import java.nio.ByteBuffer;
27 import java.nio.channels.AsynchronousCloseException;
28 import java.nio.channels.ClosedChannelException;
29 import java.nio.channels.IllegalBlockingModeException;
30 import java.nio.channels.NotYetBoundException;
31 import java.nio.channels.SelectionKey;
32 import java.nio.channels.ServerSocketChannel;
33 import java.nio.channels.SocketChannel;
34 import java.nio.channels.spi.SelectorProvider;
35 import junit.framework.TestCase;
36 
37 /*
38  * test for ServerSocketChannel
39  */
40 public class ServerSocketChannelTest extends TestCase {
41 
42     private static final int CAPACITY_NORMAL = 200;
43 
44     private static final int CAPACITY_64KB = 65536;
45 
46     private static final int TIME_UNIT = 200;
47 
48     private ServerSocketChannel serverChannel;
49 
50     private SocketChannel clientChannel;
51 
setUp()52     protected void setUp() throws Exception {
53         super.setUp();
54         this.serverChannel = ServerSocketChannel.open();
55         this.clientChannel = SocketChannel.open();
56     }
57 
tearDown()58     protected void tearDown() throws Exception {
59         if (null != this.serverChannel) {
60             try {
61                 this.serverChannel.close();
62             } catch (Exception e) {
63                 //ignore
64             }
65 
66         }
67         if (null != this.clientChannel) {
68             try {
69                 this.clientChannel.close();
70             } catch (Exception e) {
71                 //ignore
72             }
73         }
74         super.tearDown();
75     }
76 
77     // -------------------------------------------------------------------
78     // Test for methods in abstract class.
79     // -------------------------------------------------------------------
80 
81     /*
82      * Test method for 'java.nio.channels.ServerSocketChannel.validOps()'
83      */
testValidOps()84     public void testValidOps() {
85         MockServerSocketChannel testMSChnlnull = new MockServerSocketChannel(
86                 null);
87         MockServerSocketChannel testMSChnl = new MockServerSocketChannel(
88                 SelectorProvider.provider());
89         assertEquals(SelectionKey.OP_ACCEPT, this.serverChannel.validOps());
90         assertEquals(SelectionKey.OP_ACCEPT, testMSChnl.validOps());
91         assertEquals(SelectionKey.OP_ACCEPT, testMSChnlnull.validOps());
92 
93     }
94 
95     /*
96      * Test method for 'java.nio.channels.ServerSocketChannel.open()'
97      */
testOpen()98     public void testOpen() {
99         MockServerSocketChannel testMSChnl = new MockServerSocketChannel(null);
100         MockServerSocketChannel testMSChnlnotnull = new MockServerSocketChannel(
101                 SelectorProvider.provider());
102         assertEquals(SelectionKey.OP_ACCEPT, testMSChnlnotnull.validOps());
103         assertNull(testMSChnl.provider());
104         assertNotNull(testMSChnlnotnull.provider());
105         assertNotNull(this.serverChannel.provider());
106         assertEquals(testMSChnlnotnull.provider(), this.serverChannel
107                 .provider());
108     }
109 
110     // -------------------------------------------------------------------
111     // Tests for bind()
112     // -------------------------------------------------------------------
113 
test_bind_null()114     public void test_bind_null() throws Exception {
115         ServerSocketChannel ssc = ServerSocketChannel.open();
116         try {
117             assertNull(ssc.socket().getLocalSocketAddress());
118 
119             ssc.socket().bind(null);
120 
121             InetSocketAddress localAddress = (InetSocketAddress) ssc.socket().getLocalSocketAddress();
122             assertTrue(localAddress.getAddress().isAnyLocalAddress());
123             assertTrue(localAddress.getPort() > 0);
124         } finally {
125             ssc.close();
126         }
127     }
128 
test_bind_failure()129     public void test_bind_failure() throws Exception {
130         ServerSocketChannel portHog = ServerSocketChannel.open();
131         portHog.socket().bind(null);
132 
133         ServerSocketChannel ssc = ServerSocketChannel.open();
134         try {
135             // Bind to a local address that is in use
136             ssc.socket().bind(portHog.socket().getLocalSocketAddress());
137             fail();
138         } catch (IOException expected) {
139         } finally {
140             ssc.close();
141             portHog.close();
142         }
143     }
144 
test_bind_closed()145     public void test_bind_closed() throws Exception {
146         ServerSocketChannel ssc = ServerSocketChannel.open();
147         ssc.close();
148 
149         try {
150             ssc.socket().bind(null);
151             fail();
152         } catch (IOException expected) {
153         } finally {
154             ssc.close();
155         }
156     }
157 
test_bind_explicitPort()158     public void test_bind_explicitPort() throws Exception {
159         ServerSocketChannel portPickingChannel = ServerSocketChannel.open();
160         // Have the OS find a free port.
161         portPickingChannel.socket().bind(null);
162 
163         InetSocketAddress address = (InetSocketAddress) portPickingChannel.socket().getLocalSocketAddress();
164         assertTrue(address.getPort() > 0);
165         portPickingChannel.close();
166 
167         // There is a risk of flakiness here if the port is allocated to something else between
168         // close() and bind().
169         ServerSocketChannel ssc = ServerSocketChannel.open();
170         InetSocketAddress bindAddress = new InetSocketAddress("localhost", address.getPort());
171         ssc.socket().bind(bindAddress);
172 
173         InetSocketAddress boundAddress = (InetSocketAddress) ssc.socket().getLocalSocketAddress();
174         assertEquals(bindAddress.getHostName(), boundAddress.getHostName());
175         assertEquals(bindAddress.getPort(), boundAddress.getPort());
176 
177         ssc.close();
178     }
179 
test_bind_socketSync()180     public void test_bind_socketSync() throws IOException {
181         ServerSocketChannel ssc = ServerSocketChannel.open();
182         assertNull(ssc.socket().getLocalSocketAddress());
183 
184         ServerSocket socket = ssc.socket();
185         assertNull(socket.getLocalSocketAddress());
186         assertFalse(socket.isBound());
187 
188         InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
189         ssc.socket().bind(bindAddr);
190 
191         InetSocketAddress actualAddr = (InetSocketAddress) ssc.socket().getLocalSocketAddress();
192         assertEquals(actualAddr, socket.getLocalSocketAddress());
193         assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
194         assertTrue(socket.isBound());
195         assertFalse(socket.isClosed());
196 
197         ssc.close();
198 
199         assertFalse(ssc.isOpen());
200         assertTrue(socket.isClosed());
201     }
202 
test_bind_socketSyncAfterBind()203     public void test_bind_socketSyncAfterBind() throws IOException {
204         ServerSocketChannel ssc = ServerSocketChannel.open();
205         assertNull(ssc.socket().getLocalSocketAddress());
206 
207         InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
208         ssc.socket().bind(bindAddr);
209 
210         // Socket creation after bind().
211         ServerSocket socket = ssc.socket();
212         InetSocketAddress actualAddr = (InetSocketAddress) ssc.socket().getLocalSocketAddress();
213         assertEquals(actualAddr, socket.getLocalSocketAddress());
214         assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
215         assertTrue(socket.isBound());
216         assertFalse(socket.isClosed());
217 
218         ssc.close();
219 
220         assertFalse(ssc.isOpen());
221         assertTrue(socket.isClosed());
222     }
223 
224     // -------------------------------------------------------------------
225     // Test for getLocalSocketAddress()
226     // -------------------------------------------------------------------
227 
test_getLocalSocketAddress_afterClose()228     public void test_getLocalSocketAddress_afterClose() throws IOException {
229         ServerSocketChannel ssc = ServerSocketChannel.open();
230         assertNull(ssc.socket().getLocalSocketAddress());
231 
232         InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
233         ssc.socket().bind(bindAddr);
234 
235         assertNotNull(ssc.socket().getLocalSocketAddress());
236 
237         ssc.close();
238 
239         assertFalse(ssc.isOpen());
240 
241         ssc.socket().getLocalSocketAddress();
242     }
243 
244     // -------------------------------------------------------------------
245     // Test for socket()
246     // -------------------------------------------------------------------
247 
248     /*
249      * Test method for 'java.nio.channels.ServerSocketChannel.socket()'
250      */
testSocket_Block_BeforeClose()251     public void testSocket_Block_BeforeClose() throws Exception {
252         assertTrue(this.serverChannel.isOpen());
253         assertTrue(this.serverChannel.isBlocking());
254         ServerSocket s1 = this.serverChannel.socket();
255         assertFalse(s1.isClosed());
256         assertSocketNotAccepted(s1);
257         ServerSocket s2 = this.serverChannel.socket();
258         // same
259         assertSame(s1, s2);
260 
261         // socket close makes the channel close
262         s1.close();
263         assertFalse(this.serverChannel.isOpen());
264 
265     }
266 
testSocket_NonBlock_BeforeClose()267     public void testSocket_NonBlock_BeforeClose() throws Exception {
268         assertTrue(this.serverChannel.isOpen());
269         this.serverChannel.configureBlocking(false);
270         ServerSocket s1 = this.serverChannel.socket();
271         assertFalse(s1.isClosed());
272         assertSocketNotAccepted(s1);
273         ServerSocket s2 = this.serverChannel.socket();
274         // same
275         assertSame(s1, s2);
276 
277         // socket close makes the channel close
278         s1.close();
279         assertFalse(this.serverChannel.isOpen());
280 
281     }
282 
testSocket_Block_Closed()283     public void testSocket_Block_Closed() throws Exception {
284         this.serverChannel.close();
285         assertFalse(this.serverChannel.isOpen());
286         assertTrue(this.serverChannel.isBlocking());
287         ServerSocket s1 = this.serverChannel.socket();
288         assertTrue(s1.isClosed());
289         assertSocketNotAccepted(s1);
290         ServerSocket s2 = this.serverChannel.socket();
291         // same
292         assertSame(s1, s2);
293     }
294 
testSocket_NonBlock_Closed()295     public void testSocket_NonBlock_Closed() throws Exception {
296         this.serverChannel.configureBlocking(false);
297         this.serverChannel.close();
298         assertFalse(this.serverChannel.isBlocking());
299         assertFalse(this.serverChannel.isOpen());
300         ServerSocket s1 = this.serverChannel.socket();
301         assertTrue(s1.isClosed());
302         assertSocketNotAccepted(s1);
303         ServerSocket s2 = this.serverChannel.socket();
304         // same
305         assertSame(s1, s2);
306     }
307 
assertSocketNotAccepted(ServerSocket s)308     private void assertSocketNotAccepted(ServerSocket s) throws IOException {
309         assertFalse(s.isBound());
310         assertNull(s.getInetAddress());
311         assertEquals(-1, s.getLocalPort());
312         assertNull(s.getLocalSocketAddress());
313         try {
314             assertEquals(0, s.getSoTimeout());
315         } catch (IOException expected) {
316             // Android doesn't cache the timeout, so the getsockopt(2) fails and throws.
317         }
318     }
319 
testChannelBasicStatus()320     public void testChannelBasicStatus() {
321         ServerSocket gotSocket = this.serverChannel.socket();
322         assertFalse(gotSocket.isClosed());
323         assertTrue(this.serverChannel.isBlocking());
324         assertFalse(this.serverChannel.isRegistered());
325         assertEquals(SelectionKey.OP_ACCEPT, this.serverChannel.validOps());
326         assertEquals(SelectorProvider.provider(), this.serverChannel.provider());
327     }
328 
329     // -------------------------------------------------------------------
330     // Test for accept()
331     // -------------------------------------------------------------------
332 
333     /*
334      * Test method for 'java.nio.channels.ServerSocketChannel.accept()'
335      */
336 
testAccept_Block_NotYetBound()337     public void testAccept_Block_NotYetBound() throws IOException {
338         assertTrue(this.serverChannel.isOpen());
339         assertTrue(this.serverChannel.isBlocking());
340         try {
341             this.serverChannel.accept();
342             fail("Should throw NotYetBoundException");
343         } catch (NotYetBoundException e) {
344             // correct
345         }
346     }
347 
testAccept_NonBlock_NotYetBound()348     public void testAccept_NonBlock_NotYetBound() throws IOException {
349         assertTrue(this.serverChannel.isOpen());
350         this.serverChannel.configureBlocking(false);
351         try {
352             this.serverChannel.accept();
353             fail("Should throw NotYetBoundException");
354         } catch (NotYetBoundException e) {
355             // correct
356         }
357     }
358 
testAccept_ClosedChannel()359     public void testAccept_ClosedChannel() throws Exception {
360         this.serverChannel.close();
361         assertFalse(this.serverChannel.isOpen());
362         try {
363             this.serverChannel.accept();
364             fail("Should throw ClosedChannelException");
365         } catch (ClosedChannelException e) {
366             // OK.
367         }
368     }
369 
testAccept_Block_NoConnect()370     public void testAccept_Block_NoConnect() throws IOException {
371         assertTrue(this.serverChannel.isBlocking());
372         serverChannel.socket().bind(null);
373         // blocking mode , will block and wait for ever...
374         // so must close the server channel with another thread.
375         new Thread() {
376             public void run() {
377                 try {
378                     Thread.sleep(TIME_UNIT);
379                     ServerSocketChannelTest.this.serverChannel.close();
380                 } catch (Exception e) {
381                     fail("Fail to close the server channel because of"
382                             + e.getClass().getName());
383                 }
384             }
385         }.start();
386         try {
387             this.serverChannel.accept();
388             fail("Should throw a AsynchronousCloseException");
389         } catch (AsynchronousCloseException e) {
390             // OK.
391         }
392     }
393 
testAccept_NonBlock_NoConnect()394     public void testAccept_NonBlock_NoConnect() throws IOException {
395         this.serverChannel.socket().bind(null);
396         this.serverChannel.configureBlocking(false);
397         // non-blocking mode , will immediately return
398         assertNull(this.serverChannel.accept());
399     }
400 
401     /**
402      * @tests ServerSocketChannel#accept().socket()
403      */
test_read_Blocking_RealData()404     public void test_read_Blocking_RealData() throws IOException {
405         serverChannel.socket().bind(null);
406         ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
407 
408         for (int i = 0; i < CAPACITY_NORMAL; i++) {
409             buf.put((byte) i);
410         }
411         clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
412         Socket serverSocket = serverChannel.accept().socket();
413         InputStream in = serverSocket.getInputStream();
414         buf.flip();
415         clientChannel.write(buf);
416         clientChannel.close();
417         assertReadResult(in,CAPACITY_NORMAL);
418     }
419 
420     /**
421      * Asserts read content. The read content should contain <code>size</code>
422      * bytes, and the value should be a sequence from 0 to size-1
423      * ([0,1,...size-1]). Otherwise, the method throws Exception.
424      *
425      */
assertReadResult(InputStream in, int size)426     private void assertReadResult(InputStream in, int size) throws IOException{
427         byte[] readContent = new byte[size + 1];
428         int count = 0;
429         int total = 0;
430         while ((count = in.read(readContent, total, size + 1 - total)) != -1) {
431             total = total + count;
432         }
433         assertEquals(size, total);
434         for (int i = 0; i < size; i++) {
435             assertEquals((byte) i, readContent[i]);
436         }
437     }
438 
439     /**
440      * @tests ServerSocketChannel#accept().socket()
441      */
test_read_NonBlocking_RealData()442     public void test_read_NonBlocking_RealData() throws Exception {
443         serverChannel.configureBlocking(false);
444         serverChannel.socket().bind(null);
445         ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
446         for (int i = 0; i < CAPACITY_NORMAL; i++) {
447             buf.put((byte) i);
448         }
449         buf.flip();
450         clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
451         Socket serverSocket = serverChannel.accept().socket();
452         InputStream in = serverSocket.getInputStream();
453         clientChannel.write(buf);
454         clientChannel.close();
455         assertReadResult(in,CAPACITY_NORMAL);
456     }
457 
458     /**
459      * @tests ServerSocketChannel#accept().socket()
460      */
test_write_Blocking_RealData()461     public void test_write_Blocking_RealData() throws IOException {
462         assertTrue(serverChannel.isBlocking());
463         serverChannel.socket().bind(null);
464 
465         byte[] writeContent = new byte[CAPACITY_NORMAL];
466         for (int i = 0; i < writeContent.length; i++) {
467             writeContent[i] = (byte) i;
468         }
469         clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
470         Socket socket = serverChannel.accept().socket();
471         OutputStream out = socket.getOutputStream();
472         out.write(writeContent);
473         out.flush();
474         socket.close();
475         assertWriteResult(CAPACITY_NORMAL);
476     }
477 
478 
479     /**
480      * @tests ServerSocketChannel#accept().socket()
481      */
test_write_NonBlocking_RealData()482     public void test_write_NonBlocking_RealData() throws Exception {
483         serverChannel.configureBlocking(false);
484         serverChannel.socket().bind(null);
485 
486         byte[] writeContent = new byte[CAPACITY_NORMAL];
487         for (int i = 0; i < CAPACITY_NORMAL; i++) {
488             writeContent[i] = (byte) i;
489         }
490         clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
491         Socket clientSocket = serverChannel.accept().socket();
492         OutputStream out = clientSocket.getOutputStream();
493         out.write(writeContent);
494         clientSocket.close();
495         assertWriteResult(CAPACITY_NORMAL);
496     }
497 
498     /**
499      * @throws InterruptedException
500      * @tests ServerSocketChannel#accept().socket()
501      */
test_read_LByteBuffer_Blocking_ReadWriteRealLargeData()502     public void test_read_LByteBuffer_Blocking_ReadWriteRealLargeData()
503             throws IOException, InterruptedException {
504         serverChannel.socket().bind(null);
505         ByteBuffer buf = ByteBuffer.allocate(CAPACITY_64KB);
506         for (int i = 0; i < CAPACITY_64KB; i++) {
507             buf.put((byte) i);
508         }
509         buf.flip();
510         clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
511         WriteChannelThread writeThread = new WriteChannelThread(clientChannel, buf);
512         writeThread.start();
513         Socket socket = serverChannel.accept().socket();
514         InputStream in = socket.getInputStream();
515         assertReadResult(in,CAPACITY_64KB);
516         writeThread.join();
517         // check if the thread threw any exceptions
518         if (writeThread.exception != null) {
519             throw writeThread.exception;
520         }
521     }
522 
523     class WriteChannelThread extends Thread {
524         SocketChannel channel;
525         ByteBuffer buffer;
526         IOException exception;
527 
WriteChannelThread(SocketChannel channel, ByteBuffer buffer)528         public WriteChannelThread(SocketChannel channel, ByteBuffer buffer) {
529             this.channel = channel;
530             this.buffer = buffer;
531         }
532 
run()533         public void run() {
534             try {
535                 channel.write(buffer);
536                 channel.close();
537             } catch (IOException e) {
538                 exception = e;
539             }
540         }
541     }
542 
543     /**
544      * @tests ServerSocketChannel#accept().socket()
545      */
test_read_LByteBuffer_NonBlocking_ReadWriteRealLargeData()546     public void test_read_LByteBuffer_NonBlocking_ReadWriteRealLargeData()
547             throws Exception {
548         serverChannel.configureBlocking(false);
549         serverChannel.socket().bind(null);
550         ByteBuffer buf = ByteBuffer.allocate(CAPACITY_64KB);
551         for (int i = 0; i < CAPACITY_64KB; i++) {
552             buf.put((byte) i);
553         }
554         buf.flip();
555         clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
556         WriteChannelThread writeThread = new WriteChannelThread(clientChannel, buf);
557         writeThread.start();
558         Socket socket = serverChannel.accept().socket();
559         InputStream in = socket.getInputStream();
560         assertReadResult(in,CAPACITY_64KB);
561         writeThread.join();
562         // check if the thread threw any exceptions
563         if (writeThread.exception != null) {
564             throw writeThread.exception;
565         }
566     }
567 
568     /**
569      * @tests ServerSocketChannel#accept().socket()
570      */
test_write_LByteBuffer_NonBlocking_ReadWriteRealLargeData()571     public void test_write_LByteBuffer_NonBlocking_ReadWriteRealLargeData()
572             throws Exception {
573         serverChannel.configureBlocking(false);
574         serverChannel.socket().bind(null);
575         byte[] writeContent = new byte[CAPACITY_64KB];
576         for (int i = 0; i < writeContent.length; i++) {
577             writeContent[i] = (byte) i;
578         }
579         clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
580         Socket socket = serverChannel.accept().socket();
581         WriteSocketThread writeThread = new WriteSocketThread(socket, writeContent);
582         writeThread.start();
583         assertWriteResult(CAPACITY_64KB);
584         writeThread.join();
585         // check if the thread threw any exceptions
586         if (writeThread.exception != null) {
587             throw writeThread.exception;
588         }
589     }
590 
591     class WriteSocketThread extends Thread {
592         Socket socket;
593         byte[] buffer;
594         IOException exception;
595 
WriteSocketThread(Socket socket, byte[] buffer)596         public WriteSocketThread(Socket socket, byte[] buffer) {
597             this.socket = socket;
598             this.buffer = buffer;
599         }
600 
run()601         public void run() {
602             try {
603                 OutputStream out = socket.getOutputStream();
604                 out.write(buffer);
605                 socket.close();
606             } catch (IOException e) {
607                 exception = e;
608             }
609         }
610     }
611 
612     /**
613      * @tests ServerSocketChannel#accept().socket()
614      */
test_write_LByteBuffer_Blocking_ReadWriteRealLargeData()615     public void test_write_LByteBuffer_Blocking_ReadWriteRealLargeData()
616             throws Exception {
617         serverChannel.socket().bind(null);
618         byte[] writeContent = new byte[CAPACITY_64KB];
619         for (int i = 0; i < writeContent.length; i++) {
620             writeContent[i] = (byte) i;
621         }
622         clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
623         Socket socket = serverChannel.accept().socket();
624         WriteSocketThread writeThread = new WriteSocketThread(socket, writeContent);
625         writeThread.start();
626         assertWriteResult(CAPACITY_64KB);
627         writeThread.join();
628         // check if the thread threw any exceptions
629         if (writeThread.exception != null) {
630             throw writeThread.exception;
631         }
632     }
633 
634     /**
635      * Uses SocketChannel.read(ByteBuffer) to verify write result.
636      */
assertWriteResult(int size)637     private void assertWriteResult(int size) throws IOException{
638         ByteBuffer buf = ByteBuffer.allocate(size + 1);
639         int count = 0;
640         int total = 0;
641         long beginTime = System.currentTimeMillis();
642         while ((count = clientChannel.read(buf)) != -1) {
643             total = total + count;
644             // 10s timeout to avoid dead loop
645             if (System.currentTimeMillis() - beginTime > 10000){
646                 break;
647             }
648         }
649         assertEquals(total, size);
650         buf.flip();
651         for (int i = 0; i < count; i++) {
652             assertEquals((byte) i, buf.get(i));
653         }
654     }
655 
656     /**
657      * @tests ServerSocketChannel#socket().getSoTimeout()
658      */
test_accept_SOTIMEOUT()659     public void test_accept_SOTIMEOUT() throws IOException {
660         // Regression test for Harmony-707
661         // The timeout actually used may be different from the one set due to
662         // rounding by the Linux Kernel (see sock_set_timeout() in net/core/sock.c).
663         // getSoTimeout() can return a different value from the one set with
664         // setSoTimeout(). Consequently we do not check for equality with what was
665         // set.
666 
667         ServerSocketChannel sc = ServerSocketChannel.open();
668         try {
669             sc.socket().bind(null);
670 
671             // Non blocking mode, accept() will return NULL since there are no pending connections.
672             sc.configureBlocking(false);
673 
674             ServerSocket ss = sc.socket();
675 
676             int defaultTimeout = ss.getSoTimeout();
677             assertEquals(0, defaultTimeout);
678             // The timeout value is unimportant, providing it is large enough to be accepted
679             // by the Kernel as distinct from the default.
680             final int SO_TIMEOUT = 200;
681             ss.setSoTimeout(SO_TIMEOUT);
682             int nonDefaultTimeout = ss.getSoTimeout();
683             assertTrue(nonDefaultTimeout != defaultTimeout);
684 
685             SocketChannel client = sc.accept();
686             assertNull(client);
687             // Confirm the timeout was unchanged.
688             assertEquals(nonDefaultTimeout, ss.getSoTimeout());
689         } finally {
690             sc.close();
691         }
692     }
693 
694     /**
695      * @tests ServerSocket#socket().accept()
696      */
test_socket_accept_Blocking_NotBound()697     public void test_socket_accept_Blocking_NotBound() throws IOException {
698         // regression test for Harmony-748
699         ServerSocket gotSocket = serverChannel.socket();
700         serverChannel.configureBlocking(true);
701         try {
702             gotSocket.accept();
703             fail("Should throw an IllegalBlockingModeException");
704         } catch (IllegalBlockingModeException expected) {
705         }
706         serverChannel.close();
707         try {
708             gotSocket.accept();
709             fail("Should throw an IllegalBlockingModeException");
710         } catch (IllegalBlockingModeException expected) {
711         }
712     }
713 
714     /**
715      * @tests ServerSocket#socket().accept()
716      */
test_socket_accept_Nonblocking_NotBound()717     public void test_socket_accept_Nonblocking_NotBound() throws IOException {
718         // regression test for Harmony-748
719         ServerSocket gotSocket = serverChannel.socket();
720         serverChannel.configureBlocking(false);
721         try {
722             gotSocket.accept();
723             fail("Should throw an IllegalBlockingModeException");
724         } catch (IllegalBlockingModeException expected) {
725         }
726         serverChannel.close();
727         try {
728             gotSocket.accept();
729             fail("Should throw an IllegalBlockingModeException");
730         } catch (IllegalBlockingModeException expected) {
731         }
732     }
733 
734     /**
735      * @tests ServerSocket#socket().accept()
736      */
test_socket_accept_Nonblocking_Bound()737     public void test_socket_accept_Nonblocking_Bound() throws IOException {
738         // regression test for Harmony-748
739         serverChannel.configureBlocking(false);
740         serverChannel.socket().bind(null);
741         ServerSocket gotSocket = serverChannel.socket();
742         try {
743             gotSocket.accept();
744             fail("Should throw an IllegalBlockingModeException");
745         } catch (IllegalBlockingModeException expected) {
746         }
747         serverChannel.close();
748         try {
749             gotSocket.accept();
750             fail("Should throw a ClosedChannelException");
751         } catch (ClosedChannelException expected) {
752         }
753     }
754 
755     /**
756      * @tests ServerSocket#socket().accept()
757      */
test_socket_accept_Blocking_Bound()758     public void test_socket_accept_Blocking_Bound() throws IOException {
759         // regression test for Harmony-748
760         serverChannel.configureBlocking(true);
761         serverChannel.socket().bind(null);
762         serverChannel.close();
763         try {
764             serverChannel.socket().accept();
765             fail("Should throw a ClosedChannelException");
766         } catch (ClosedChannelException expected) {
767         }
768     }
769     /**
770      * Regression test for HARMONY-4961
771      */
test_socket_getLocalPort()772     public void test_socket_getLocalPort() throws IOException {
773         serverChannel.socket().bind(null);
774         clientChannel.connect(serverChannel.socket().getLocalSocketAddress());
775         SocketChannel myChannel = serverChannel.accept();
776         int port = myChannel.socket().getLocalPort();
777         assertEquals(serverChannel.socket().getLocalPort(), port);
778         myChannel.close();
779         clientChannel.close();
780         serverChannel.close();
781     }
782 
783     /**
784      * Regression test for HARMONY-6375
785      */
test_accept_configureBlocking()786     public void test_accept_configureBlocking() throws Exception {
787         InetSocketAddress localAddr = new InetSocketAddress("localhost", 0);
788         serverChannel.socket().bind(localAddr);
789 
790         // configure the channel non-blocking
791         // when it is accepting in main thread
792         new Thread() {
793             public void run() {
794                 try {
795                     Thread.sleep(TIME_UNIT);
796                     serverChannel.configureBlocking(false);
797                     serverChannel.close();
798                 } catch (Exception e) {
799                     e.printStackTrace();
800                 }
801             }
802         }.start();
803 
804         try {
805             serverChannel.accept();
806             fail("should throw AsynchronousCloseException");
807         } catch (AsynchronousCloseException expected) {
808         }
809         serverChannel.close();
810     }
811 }
812