OSDN Git Service

069623d1a509e0146e629e34f5290829aa29afd3
[android-x86/dalvik.git] / libcore / nio / src / test / java / org / apache / harmony / nio / tests / java / nio / channels / SocketChannelTest.java
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.nio.tests.java.nio.channels;
19
20 import dalvik.annotation.TestTargets;
21 import dalvik.annotation.TestTargetNew;
22 import dalvik.annotation.TestTargetClass;
23 import dalvik.annotation.TestLevel;
24 import dalvik.annotation.AndroidOnly;
25
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.OutputStream;
29 import java.net.BindException;
30 import java.net.ConnectException;
31 import java.net.InetSocketAddress;
32 import java.net.ServerSocket;
33 import java.net.Socket;
34 import java.net.SocketAddress;
35 import java.net.SocketException;
36 import java.nio.ByteBuffer;
37 import java.nio.channels.AlreadyConnectedException;
38 import java.nio.channels.ClosedChannelException;
39 import java.nio.channels.ConnectionPendingException;
40 import java.nio.channels.IllegalBlockingModeException;
41 import java.nio.channels.NoConnectionPendingException;
42 import java.nio.channels.NotYetConnectedException;
43 import java.nio.channels.SelectableChannel;
44 import java.nio.channels.SelectionKey;
45 import java.nio.channels.ServerSocketChannel;
46 import java.nio.channels.SocketChannel;
47 import java.nio.channels.UnresolvedAddressException;
48 import java.nio.channels.UnsupportedAddressTypeException;
49 import java.nio.channels.spi.SelectorProvider;
50
51 import junit.framework.TestCase;
52 import tests.support.Support_PortManager;
53
54 @TestTargetClass(SocketChannel.class)
55 /**
56  * Tests for SocketChannel and its default implementation.
57  */
58 public class SocketChannelTest extends TestCase {
59
60     private static final int CAPACITY_NORMAL = 200;
61
62     private static final int CAPACITY_HUGE = 512 * 1024;
63
64     private InetSocketAddress localAddr1;
65
66     private InetSocketAddress localAddr2;
67
68     private SocketChannel channel1;
69
70     private SocketChannel channel2;
71
72     private ServerSocket server1;
73
74     private ServerSocket server2;
75
76     private final static int TIMEOUT = 60000;
77
78     private final static int EOF = -1;
79
80     protected void setUp() throws Exception {
81         super.setUp();
82         this.localAddr1 = new InetSocketAddress("127.0.0.1",
83                 Support_PortManager.getNextPort());
84         this.localAddr2 = new InetSocketAddress("127.0.0.1",
85                 Support_PortManager.getNextPort());
86         this.channel1 = SocketChannel.open();
87         this.channel2 = SocketChannel.open();
88         this.server1 = new ServerSocket(localAddr1.getPort());
89     }
90
91     protected void tearDown() throws Exception {
92         super.tearDown();
93         if (null != this.channel1) {
94             try {
95                 this.channel1.close();
96             } catch (Exception e) {
97                 // ignore
98             }
99         }
100         if (null != this.channel2) {
101             try {
102                 this.channel2.close();
103             } catch (Exception e) {
104                 // ignore
105             }
106         }
107         if (null != this.server1) {
108             try {
109                 this.server1.close();
110             } catch (Exception e) {
111                 // ignore
112             }
113         }
114         if (null != this.server2) {
115             try {
116                 this.server2.close();
117             } catch (Exception e) {
118                 // ignore
119             }
120         }
121     }
122
123     // -------------------------------------------------------------------
124     // Test for methods in abstract class.
125     // -------------------------------------------------------------------
126     /*
127      * Test method for 'java.nio.channels.SocketChannel()'
128      */
129     @TestTargets({
130         @TestTargetNew(
131             level = TestLevel.PARTIAL_COMPLETE,
132             notes = "",
133             method = "SocketChannel",
134             args = {SelectorProvider.class}
135         ),
136         @TestTargetNew(
137             level = TestLevel.PARTIAL_COMPLETE,
138             notes = "",
139             method = "provider",
140             args = {}
141         ),
142         @TestTargetNew(
143             level = TestLevel.PARTIAL_COMPLETE,
144             notes = "",
145             method = "open",
146             args = {}
147         ),
148         @TestTargetNew(
149             level = TestLevel.PARTIAL_COMPLETE,
150             notes = "",
151             clazz = SelectorProvider.class,
152             method = "openSocketChannel",
153             args = {}
154         )
155     })
156     public void testConstructor() throws IOException {
157         SocketChannel channel = 
158                 SelectorProvider.provider().openSocketChannel();
159         assertNotNull(channel);
160         assertSame(SelectorProvider.provider(), channel.provider());
161         channel = SocketChannel.open();
162         assertNotNull(channel);
163         assertSame(SelectorProvider.provider(), channel.provider());
164         MockSocketChannel chan = new MockSocketChannel(
165                 SelectorProvider.provider());
166         assertTrue(chan.isConstructorCalled);
167     }
168
169     /*
170      * Test method for 'java.nio.channels.SocketChannel.validOps()'
171      */
172     @TestTargetNew(
173         level = TestLevel.PARTIAL_COMPLETE,
174         notes = "",
175         method = "validOps",
176         args = {}
177     )
178     public void testValidOps() {
179         MockSocketChannel testMSChannel = new MockSocketChannel(null);
180         assertEquals(13, this.channel1.validOps());
181         assertEquals(13, testMSChannel.validOps());
182     }
183
184     /*
185      * Test method for 'java.nio.channels.SocketChannel.open()'
186      */
187     @TestTargets({
188         @TestTargetNew(
189             level = TestLevel.PARTIAL_COMPLETE,
190             notes = "",
191             method = "open",
192             args = {}
193         ),
194         @TestTargetNew(
195             level = TestLevel.PARTIAL_COMPLETE,
196             notes = "",
197             method = "SocketChannel",
198             args = {SelectorProvider.class}
199         )
200     })
201     public void testOpen() throws IOException {
202         java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1];
203         buf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
204         MockSocketChannel testMSChannel = new MockSocketChannel(null);
205         MockSocketChannel testMSChannelnotnull = new MockSocketChannel(
206                 SelectorProvider.provider());
207         SocketChannel testSChannel = MockSocketChannel.open();
208         assertTrue(testSChannel.isOpen());
209         assertNull(testMSChannel.provider());
210         assertNotNull(testSChannel.provider());
211         assertEquals(SelectorProvider.provider(), testSChannel.provider());
212         assertNotNull(testMSChannelnotnull.provider());
213         assertEquals(this.channel1.provider(), testMSChannelnotnull.provider());
214         try {
215             this.channel1.write(buf);
216             fail("Should throw NotYetConnectedException");
217         } catch (NotYetConnectedException e) {
218             // correct
219         }
220     }
221
222     @TestTargetNew(
223         level = TestLevel.PARTIAL_COMPLETE,
224         notes = "",
225         method = "isOpen",
226         args = {}
227     )
228     public void testIsOpen() throws Exception {
229         assertTrue(this.channel1.isOpen());
230         this.channel1.close();
231         assertFalse(this.channel1.isOpen());
232     }
233
234     @TestTargetNew(
235         level = TestLevel.COMPLETE,
236         notes = "",
237         method = "isConnected",
238         args = {}
239     )
240     public void testIsConnected() throws Exception {
241         assertFalse(this.channel1.isConnected());// not connected
242         this.channel1.configureBlocking(false);
243         assertFalse(this.channel1.connect(localAddr1));
244         assertFalse(this.channel1.isConnected());
245         assertTrue(this.channel1.isConnectionPending());
246         assertTrue(tryFinish());
247         assertTrue(this.channel1.isConnected());
248         this.channel1.close();
249         assertFalse(this.channel1.isConnected());
250     }
251
252     @TestTargetNew(
253         level = TestLevel.COMPLETE,
254         notes = "",
255         method = "isConnectionPending",
256         args = {}
257     )
258     public void testIsConnectionPending() throws Exception {
259         // ensure
260         ensureServerClosed();
261         this.channel1.configureBlocking(false);
262         assertFalse(this.channel1.isConnectionPending());
263         // finish
264         try {
265             this.channel1.finishConnect();
266             fail("Should throw NoConnectionPendingException");
267         } catch (NoConnectionPendingException e) {
268             // OK.
269         }
270         assertFalse(this.channel1.isConnectionPending());
271         // connect
272         assertFalse(this.channel1.connect(localAddr1));
273         assertTrue(this.channel1.isConnectionPending());
274         this.channel1.close();
275
276         assertFalse(this.channel1.isConnectionPending());
277     }
278
279     @TestTargets({
280         @TestTargetNew(
281             level = TestLevel.PARTIAL_COMPLETE,
282             notes = "Verifies default status of SocketChannel.",
283             method = "validOps",
284             args = {}
285         ),
286         @TestTargetNew(
287             level = TestLevel.PARTIAL_COMPLETE,
288             notes = "Verifies default status of SocketChannel.",
289             method = "provider",
290             args = {}
291         ),
292         @TestTargetNew(
293             level = TestLevel.PARTIAL_COMPLETE,
294             notes = "Verifies default status of SocketChannel.",
295             method = "isRegistered",
296             args = {}
297         ),
298         @TestTargetNew(
299             level = TestLevel.PARTIAL_COMPLETE,
300             notes = "Verifies default status of SocketChannel.",
301             method = "isBlocking",
302             args = {}
303         )
304     })
305     public void testChannelBasicStatus() {
306         Socket gotSocket = this.channel1.socket();
307         assertFalse(gotSocket.isClosed());
308         assertTrue(this.channel1.isBlocking());
309         assertFalse(this.channel1.isRegistered());
310         assertEquals((SelectionKey.OP_CONNECT | SelectionKey.OP_READ |
311                 SelectionKey.OP_WRITE), this.channel1.validOps());
312         assertEquals(SelectorProvider.provider(), this.channel1.provider());
313     }
314
315     /*
316      * Test method for 'java.nio.channels.SocketChannel.open(SocketAddress)'
317      */
318     @TestTargetNew(
319         level = TestLevel.PARTIAL_COMPLETE,
320         notes = "",
321         method = "open",
322         args = {java.net.SocketAddress.class}
323     )
324     public void testOpenSocketAddress() throws IOException {
325         this.channel1 = SocketChannel.open(localAddr1);
326         assertTrue(this.channel1.isConnected());
327         
328         SecurityManager smngr = System.getSecurityManager();
329         System.setSecurityManager(new MockSecurityManager("blargh"));
330         try {
331             this.channel1 = SocketChannel.open(localAddr2);
332             fail("Should throw SecurityException");
333         } catch (SecurityException e) {
334             // expected
335         }
336         System.setSecurityManager(smngr);
337
338         SocketAddress newTypeAddress = new SubSocketAddress();
339         try {
340             this.channel1 = SocketChannel.open(newTypeAddress);
341             fail("Should throw UnexpectedAddressTypeException");
342         } catch (UnsupportedAddressTypeException e) {
343             // expected
344         }
345
346         SocketAddress unresolvedAddress = 
347                 InetSocketAddress.createUnresolved("127.0.0.1", 8080);
348         try {
349             this.channel1 = SocketChannel.open(unresolvedAddress);
350             fail("Should throw UnresolvedAddressException");
351         } catch (UnresolvedAddressException e) {
352             // expected
353         }
354         
355         SocketChannel channel1IP = null;
356         try {
357             channel1IP = SocketChannel.open(null);
358             fail("Should throw an IllegalArgumentException");
359         } catch (IllegalArgumentException e) {
360             // correct
361         }
362         assertNull(channel1IP);
363     }
364
365     /*
366      * Test method for 'java.nio.channels.SocketChannel.read(ByteBuffer[])'
367      */
368     @TestTargetNew(
369         level = TestLevel.PARTIAL_COMPLETE,
370         notes = "",
371         method = "read",
372         args = {java.nio.ByteBuffer[].class}
373     )
374     public void testReadByteBufferArray() throws IOException {
375         java.nio.ByteBuffer[] byteBuf = null;
376         MockSocketChannel testMSChannelnull = new MockSocketChannel(null);
377         MockSocketChannel testMSChannel = new MockSocketChannel(
378                 SelectorProvider.provider());
379         ServerSocket testServer = new ServerSocket(Support_PortManager
380                 .getNextPort());
381         try {
382             try {
383                 this.channel1.read(byteBuf);
384                 fail("Should throw NPE");
385             } catch (NullPointerException e) {
386                 // correct
387             }
388             byteBuf = new java.nio.ByteBuffer[CAPACITY_NORMAL];
389             try {
390                 this.channel1.read(byteBuf);
391                 fail("Should throw NotYetConnectedException");
392             } catch (NotYetConnectedException e) {
393                 // correct
394             }
395             long readNum = CAPACITY_NORMAL;
396             readNum = testMSChannel.read(byteBuf);
397             assertEquals(0, readNum);
398             readNum = CAPACITY_NORMAL;
399             readNum = testMSChannelnull.read(byteBuf);
400             assertEquals(0, readNum);
401         } finally {
402             testServer.close();
403         }
404     }
405
406     /*
407      * Test method for 'java.nio.channels.SocketChannel.read(ByteBuffer[])'
408      */
409     @TestTargetNew(
410         level = TestLevel.PARTIAL_COMPLETE,
411         notes = "",
412         method = "read",
413         args = {java.nio.ByteBuffer[].class}
414     )
415     public void testReadByteBufferArray_BufNull() throws IOException {
416         java.nio.ByteBuffer[] byteBuf = null;
417         MockSocketChannel testMSChannelnull = new MockSocketChannel(null);
418         MockSocketChannel testMSChannel = new MockSocketChannel(
419                 SelectorProvider.provider());
420         try {
421             this.channel1.read(byteBuf);
422             fail("Should throw NPE");
423         } catch (NullPointerException e) {
424             // correct
425         }
426         try {
427             testMSChannel.read(byteBuf);
428             fail("Should throw NPE");
429         } catch (NullPointerException e) {
430             // correct
431         }
432         try {
433             testMSChannelnull.read(byteBuf);
434             fail("Should throw NPE");
435         } catch (NullPointerException e) {
436             // correct
437         }
438     }
439
440     /*
441      * Test method for 'java.nio.channels.SocketChannel.write(ByteBuffer[])'
442      */
443     @TestTargetNew(
444         level = TestLevel.PARTIAL_COMPLETE,
445         notes = "Doesn't verify AsynchronousCloseException," +
446                 "ClosedByInterruptException.",
447         method = "write",
448         args = {java.nio.ByteBuffer[].class}
449     )
450     public void testWriteByteBufferArray() throws IOException {
451         java.nio.ByteBuffer[] byteBuf = null;
452         MockSocketChannel testMSChannelnull = new MockSocketChannel(null);
453         MockSocketChannel testMSChannel = new MockSocketChannel(
454                 SelectorProvider.provider());
455         try {
456             this.channel1.write(byteBuf);
457             fail("Should throw NPE");
458         } catch (NullPointerException e) {
459             // correct
460         }
461         byteBuf = new java.nio.ByteBuffer[1];
462         byteBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
463         try {
464             this.channel1.write(byteBuf);
465             fail("Should throw NotYetConnectedException");
466         } catch (NotYetConnectedException e) {
467             // correct
468         }
469         testMSChannel.write(byteBuf);
470         testMSChannelnull.write(byteBuf);
471         
472         this.channel1.close();
473         try {
474             this.channel1.write(byteBuf);
475             fail("Should throw ClosedChannelException");
476         } catch (ClosedChannelException e) {
477             // correct
478         }
479     }
480
481     /*
482      * Test method for 'java.nio.channels.SocketChannel.write(ByteBuffer[])'
483      */
484     @TestTargetNew(
485         level = TestLevel.PARTIAL_COMPLETE,
486         notes = "",
487         method = "write",
488         args = {java.nio.ByteBuffer[].class}
489     )
490     public void testWriteByteBufferArray_BufNull() throws IOException {
491         java.nio.ByteBuffer[] byteBuf = null;
492         MockSocketChannel testMSChannelnull = new MockSocketChannel(null);
493         MockSocketChannel testMSChannel = new MockSocketChannel(
494                 SelectorProvider.provider());
495         this.channel1.connect(localAddr1);
496         try {
497             this.channel1.write(byteBuf);
498             fail("Should throw NPE");
499         } catch (NullPointerException e) {
500             // correct
501         }
502         byteBuf = new java.nio.ByteBuffer[1];
503         try {
504             this.channel1.write(byteBuf);
505             fail("Should throw NPE");
506         } catch (NullPointerException e) {
507             // correct
508         }
509     }
510
511     @TestTargetNew(
512         level = TestLevel.PARTIAL_COMPLETE,
513         notes = "",
514         method = "socket",
515         args = {}
516     )
517     @AndroidOnly("Fails on RI. See comment below")
518     public void testSocket_BasicStatusBeforeConnect() throws IOException {
519         assertFalse(this.channel1.isConnected());// not connected
520         Socket s1 = this.channel1.socket();
521         // RI fails here. RI returns 0 while spec says getLocalPort()
522         // shall return -1 for unbound socket
523         assertSocketBeforeConnect(s1);
524         Socket s2 = this.channel1.socket();
525         // same
526         assertSame(s1, s2);
527     }
528
529     @TestTargetNew(
530         level = TestLevel.PARTIAL_COMPLETE,
531         notes = "",
532         method = "socket",
533         args = {}
534     )
535     public void testSocket_Block_BasicStatusAfterConnect() throws IOException {
536         assertFalse(this.channel1.isConnected());// not connected
537         assertTrue(this.channel1.connect(localAddr1));
538
539         assertTrue(this.channel1.isConnected());
540         Socket s1 = this.channel1.socket();
541
542         assertSocketAfterConnect(s1, localAddr1);
543         Socket s2 = this.channel1.socket();
544         // same
545         assertSame(s1, s2);
546     }
547
548     @TestTargetNew(
549         level = TestLevel.PARTIAL_COMPLETE,
550         notes = "",
551         method = "socket",
552         args = {}
553     )
554     @AndroidOnly("Fails on RI. See comment below")
555     public void testSocket_NonBlock_BasicStatusAfterConnect() throws Exception {
556         assertFalse(this.channel1.isConnected());// not connected
557         this.channel1.configureBlocking(false);
558         assertFalse(this.channel1.connect(localAddr1));
559         assertFalse(this.channel1.isConnected());
560         assertTrue(this.channel1.isConnectionPending());
561         Socket s1 = this.channel1.socket();
562         // status of not connected
563         // RI fails here. RI returns 0 while spec says getLocalPort()
564         // shall return -1 for unbound socket 
565         assertSocketBeforeConnect(s1);
566         Socket s2 = this.channel1.socket();
567         // same
568         assertSame(s1, s2);
569
570         assertTrue(tryFinish());
571         assertTrue(this.channel1.isConnected());
572         s1 = this.channel1.socket();
573         assertSocketAfterConnect(s1, localAddr1);
574         s2 = this.channel1.socket();
575         // same
576         assertSame(s1, s2);
577     }
578
579     @TestTargetNew(
580         level = TestLevel.PARTIAL_COMPLETE,
581         notes = "",
582         method = "socket",
583         args = {}
584     )
585     public void testSocket_Block_ActionsBeforeConnect() throws IOException {
586         assertFalse(this.channel1.isConnected());// not connected
587         Socket s = this.channel1.socket();
588         assertSocketAction_Block_BeforeConnect(s);
589     }
590
591     @TestTargetNew(
592         level = TestLevel.PARTIAL_COMPLETE,
593         notes = "",
594         method = "socket",
595         args = {}
596     )
597     public void testSocket_Block_ActionsAfterConnect() throws IOException {
598         assertFalse(this.channel1.isConnected());// not connected
599         assertTrue(this.channel1.connect(localAddr1));
600         assertTrue(this.channel1.isConnected());
601         Socket s = this.channel1.socket();
602         assertSocketAction_Block_AfterConnect(s);
603
604     }
605
606     @TestTargetNew(
607         level = TestLevel.PARTIAL_COMPLETE,
608         notes = "",
609         method = "socket",
610         args = {}
611     )
612     public void testSocket_NonBlock_ActionsAfterConnectBeforeFinish()
613             throws IOException {
614         assertFalse(this.channel1.isConnected());// not connected
615         this.channel1.configureBlocking(false);
616         assertFalse(this.channel1.connect(localAddr1));
617         assertFalse(this.channel1.isConnected());
618         assertTrue(this.channel1.isConnectionPending());
619         Socket s1 = this.channel1.socket();
620         // Action of not connected
621         assertSocketAction_NonBlock_BeforeConnect(s1);
622         Socket s2 = this.channel1.socket();
623         // same
624         assertSame(s1, s2);
625     }
626
627     @TestTargetNew(
628         level = TestLevel.PARTIAL_COMPLETE,
629         notes = "",
630         method = "socket",
631         args = {}
632     )
633     public void testSocket_NonBlock_ActionsAfterConnectAfterFinish()
634             throws Exception {
635         assertFalse(this.channel1.isConnected());// not connected
636         this.channel1.configureBlocking(false);
637         assertFalse(this.channel1.connect(localAddr1));
638         assertTrue(tryFinish());
639         Socket s1 = this.channel1.socket();
640         assertSocketAction_NonBlock_AfterConnect(s1);
641         Socket s2 = this.channel1.socket();
642         // same
643         assertSame(s1, s2);
644     }
645
646     private void assertSocketBeforeConnect(Socket s) throws IOException {
647         assertFalse(s.isBound());
648         assertFalse(s.isClosed());
649         assertFalse(s.isConnected());
650         assertFalse(s.getKeepAlive());
651         try {
652             s.getInputStream();
653             fail("Should throw SocketException.");
654         } catch (SocketException e) {
655             // OK.
656         }
657         assertFalse(s.getOOBInline());
658         try {
659             s.getOutputStream();
660             fail("Should throw SocketException.");
661         } catch (SocketException e) {
662             // OK.
663         }
664         assertEquals(-1, s.getSoLinger());
665         assertFalse(s.getTcpNoDelay());
666
667         assertFalse(s.isInputShutdown());
668         assertFalse(s.isOutputShutdown());
669
670         assertNull(s.getInetAddress());
671         assertEquals(s.getLocalAddress().getHostAddress(), "0.0.0.0");
672         assertFalse(s.getReuseAddress());
673         assertNull(s.getLocalSocketAddress());
674
675         // not connected
676         assertEquals(0, s.getPort());
677         assertTrue(s.getReceiveBufferSize() >= 8192);
678         assertNull(s.getRemoteSocketAddress());
679         assertTrue(s.getSendBufferSize() >= 8192);
680         assertEquals(0, s.getSoTimeout());
681         assertEquals(0, s.getTrafficClass());
682
683         // RI fails here. RI returns 0 while spec says unbound socket should
684         // return -1.
685         assertEquals(-1, s.getLocalPort());
686     }
687
688     private void assertSocketAfterConnect(Socket s, InetSocketAddress address)
689             throws IOException {
690         assertTrue(s.isBound());
691         assertFalse(s.isClosed());
692         assertTrue(s.isConnected());
693         assertFalse(s.getKeepAlive());
694
695         assertNotNull(s.getInputStream());
696         assertNotNull(s.getOutputStream());
697
698         assertFalse(s.getOOBInline());
699         assertEquals(-1, s.getSoLinger());
700         assertFalse(s.getTcpNoDelay());
701
702         assertFalse(s.isInputShutdown());
703         assertFalse(s.isOutputShutdown());
704
705         assertSame(s.getInetAddress(), address.getAddress());
706
707         assertEquals(this.localAddr1.getAddress(), s.getLocalAddress());
708         assertEquals(address.getPort(), s.getPort());
709         assertNotNull(s.getLocalSocketAddress());
710         assertTrue(s.getReceiveBufferSize() >= 8192);
711         // equal , not same
712         assertNotSame(address, s.getRemoteSocketAddress());
713         assertEquals(address, s.getRemoteSocketAddress());
714         // assertFalse(s.getReuseAddress());
715         assertTrue(s.getSendBufferSize() >= 8192);
716         assertEquals(0, s.getSoTimeout());
717         assertEquals(0, s.getTrafficClass());
718     }
719
720     private void assertSocketAction_Block_BeforeConnect(Socket s)
721             throws IOException {
722         assertFalse(this.channel1.isConnected());
723         this.server2 = new ServerSocket(localAddr2.getPort());
724         s.connect(localAddr2);
725         assertTrue(this.channel1.isConnected());
726         assertTrue(s.isConnected());
727
728         assertSocketAfterConnect(s, localAddr2);
729
730         try {
731             s.bind(localAddr2);
732             fail("Should throw AlreadyConnectedException");
733         } catch (AlreadyConnectedException e) {
734             // OK.
735         }
736
737         s.close();
738         assertTrue(s.isClosed());
739         assertFalse(this.channel1.isOpen());
740     }
741
742     private void assertSocketAction_NonBlock_BeforeConnect(Socket s)
743             throws IOException {
744         assertFalse(this.channel1.isConnected());
745         this.server2 = new ServerSocket(localAddr2.getPort());
746         try {
747             s.connect(localAddr2);
748             fail("Should throw IllegalBlockingModeException");
749         } catch (IllegalBlockingModeException e1) {
750             // OK.
751         }
752
753         if (this.channel1.isConnectionPending()) {
754             try {
755                 s.bind(localAddr2);
756                 fail("Should throw ConnectionPendingException");
757             } catch (ConnectionPendingException e1) {
758                 // OK.
759             }
760         } else {
761             try {
762                 s.bind(localAddr2);
763                 fail("Should throw BindException");
764             } catch (BindException e1) {
765                 // OK.
766             }
767         }
768
769         assertFalse(this.channel1.isConnected());
770         assertFalse(s.isConnected());
771
772         s.close();
773         assertTrue(s.isClosed());
774         assertFalse(this.channel1.isOpen());
775     }
776
777     private void assertSocketAction_Block_AfterConnect(Socket s)
778             throws IOException {
779         assertEquals(localAddr1.getPort(), s.getPort());
780         assertTrue(this.channel1.isConnected());
781         assertTrue(s.isConnected());
782         try {
783             s.connect(localAddr2);
784             fail("Should throw AlreadyConnectedException");
785         } catch (AlreadyConnectedException e) {
786             // OK.
787         }
788
789         try {
790             s.bind(localAddr2);
791             fail("Should throw AlreadyConnectedException");
792         } catch (AlreadyConnectedException e) {
793             // OK.
794         }
795
796         s.close();
797         assertTrue(s.isClosed());
798         assertFalse(this.channel1.isOpen());
799     }
800
801     private void assertSocketAction_NonBlock_AfterConnect(Socket s)
802             throws IOException {
803         assertEquals(localAddr1.getPort(), s.getPort());
804         assertTrue(this.channel1.isConnected());
805         assertTrue(s.isConnected());
806
807         if (this.channel1.isConnectionPending()) {
808             try {
809                 s.connect(localAddr2);
810                 fail("Should throw AlreadyConnectedException");
811             } catch (AlreadyConnectedException e) {
812                 // OK.
813             }
814         } else {
815             try {
816                 s.connect(localAddr2);
817                 fail("Should throw IllegalBlockingModeException");
818             } catch (IllegalBlockingModeException e) {
819                 // OK.
820             }
821         }
822
823         try {
824             s.bind(localAddr2);
825             fail("Should throw AlreadyConnectedException");
826         } catch (AlreadyConnectedException e) {
827             // OK.
828         }
829
830         s.close();
831         assertTrue(s.isClosed());
832         assertFalse(this.channel1.isOpen());
833     }
834
835     // -------------------------------------------------------------------
836     // Tests for connect(), finishConnect(),isConnected(),isConnectionPending()
837     // These methods are very close, so we test them together, call them "CFII".
838     // -------------------------------------------------------------------
839     /**
840      * connect-->finish-->close
841      */
842     @TestTargets({
843         @TestTargetNew(
844             level = TestLevel.PARTIAL_COMPLETE,
845             notes = "",
846             method = "connect",
847             args = {java.net.SocketAddress.class}
848         ),
849         @TestTargetNew(
850             level = TestLevel.PARTIAL_COMPLETE,
851             notes = "",
852             method = "finishConnect",
853             args = {}
854         )
855     })
856     public void testCFII_Norml_NoServer_Block() throws Exception {
857         // ensure
858         ensureServerClosed();
859         assertTrue(this.channel1.isBlocking());
860         statusNotConnected_NotPending();
861         // connect
862         try {
863             this.channel1.connect(localAddr1);
864             fail("Should throw a ConnectException here.");
865         } catch (ConnectException e) {
866             // OK.
867         }
868         statusChannelClosed();
869         try {
870             this.channel1.finishConnect();
871             fail("Should throw a ClosedChannelException here.");
872         } catch (ClosedChannelException e) {
873             // OK.
874         }
875     }
876
877     /**
878      * connect-->finish-->close
879      */
880     @TestTargets({
881         @TestTargetNew(
882             level = TestLevel.PARTIAL_COMPLETE,
883             notes = "",
884             method = "connect",
885             args = {java.net.SocketAddress.class}
886         ),
887         @TestTargetNew(
888             level = TestLevel.PARTIAL_COMPLETE,
889             notes = "",
890             method = "finishConnect",
891             args = {}
892         )
893     })
894     public void testCFII_Norml_NoServer_NonBlock() throws Exception {
895         connectNoServerNonBlock();
896
897         this.channel1.close();
898         statusChannelClosed();
899     }
900
901     /**
902      * connect-->finish-->close
903      */
904     @TestTargets({
905         @TestTargetNew(
906             level = TestLevel.PARTIAL_COMPLETE,
907             notes = "",
908             method = "connect",
909             args = {java.net.SocketAddress.class}
910         ),
911         @TestTargetNew(
912             level = TestLevel.PARTIAL_COMPLETE,
913             notes = "",
914             method = "finishConnect",
915             args = {}
916         )
917     })
918     public void testCFII_Norml_Server_Block() throws Exception {
919         connectServerBlock();
920
921         this.channel1.close();
922         statusChannelClosed();
923
924     }
925
926     /**
927      * connect-->finish-->close
928      */
929     @TestTargets({
930         @TestTargetNew(
931             level = TestLevel.PARTIAL_COMPLETE,
932             notes = "",
933             method = "connect",
934             args = {java.net.SocketAddress.class}
935         ),
936         @TestTargetNew(
937             level = TestLevel.PARTIAL_COMPLETE,
938             notes = "",
939             method = "finishConnect",
940             args = {}
941         )
942     })
943     public void testCFII_Norml_Server_NonBlock() throws Exception {
944         connectServerNonBlock();
945
946         this.channel1.close();
947         statusChannelClosed();
948     }
949
950     /**
951      * connect-->server closed-->finish-->close
952      */
953     @TestTargets({
954         @TestTargetNew(
955             level = TestLevel.PARTIAL_COMPLETE,
956             notes = "",
957             method = "connect",
958             args = {java.net.SocketAddress.class}
959         ),
960         @TestTargetNew(
961             level = TestLevel.PARTIAL_COMPLETE,
962             notes = "",
963             method = "finishConnect",
964             args = {}
965         )
966     })
967     public void testCFII_ServerClosed_Block() throws Exception {
968         // ensure
969         ensureServerOpen();
970         assertTrue(this.channel1.isBlocking());
971         statusNotConnected_NotPending();
972         // connect
973         assertTrue(this.channel1.connect(localAddr1));
974         statusConnected_NotPending();
975
976         ensureServerClosed();
977
978         tryFinish();
979
980         this.channel1.close();
981         statusChannelClosed();
982
983     }
984
985     /**
986      * connect-->server closed-->finish-->close
987      */
988     @TestTargets({
989         @TestTargetNew(
990             level = TestLevel.PARTIAL_COMPLETE,
991             notes = "",
992             method = "connect",
993             args = {java.net.SocketAddress.class}
994         ),
995         @TestTargetNew(
996             level = TestLevel.PARTIAL_COMPLETE,
997             notes = "",
998             method = "finishConnect",
999             args = {}
1000         )
1001     })
1002     public void testCFII_ServerClosed_NonBlock() throws Exception {
1003         // ensure
1004         ensureServerOpen();
1005         this.channel1.configureBlocking(false);
1006         statusNotConnected_NotPending();
1007         // connect
1008         assertFalse(this.channel1.connect(localAddr1));
1009         statusNotConnected_Pending();
1010
1011         ensureServerClosed();
1012
1013         tryFinish();
1014
1015         this.channel1.close();
1016         statusChannelClosed();
1017     }
1018
1019     /**
1020      * connect-->finish-->server closed-->close
1021      */
1022     @TestTargets({
1023         @TestTargetNew(
1024             level = TestLevel.PARTIAL_COMPLETE,
1025             notes = "",
1026             method = "connect",
1027             args = {java.net.SocketAddress.class}
1028         ),
1029         @TestTargetNew(
1030             level = TestLevel.PARTIAL_COMPLETE,
1031             notes = "",
1032             method = "finishConnect",
1033             args = {}
1034         )
1035     })
1036     public void testCFII_ServerClosedAfterFinish_Block() throws Exception {
1037         connectServerBlock();
1038
1039         ensureServerClosed();
1040         assertTrue(this.channel1.isOpen());
1041         this.channel1.close();
1042         statusChannelClosed();
1043
1044     }
1045
1046     /**
1047      * connect-->finish-->server closed-->close
1048      */
1049     @TestTargets({
1050         @TestTargetNew(
1051             level = TestLevel.PARTIAL_COMPLETE,
1052             notes = "",
1053             method = "connect",
1054             args = {java.net.SocketAddress.class}
1055         ),
1056         @TestTargetNew(
1057             level = TestLevel.PARTIAL_COMPLETE,
1058             notes = "",
1059             method = "finishConnect",
1060             args = {}
1061         )
1062     })
1063     public void testCFII_ServerClosedAfterFinish_NonBlock() throws Exception {
1064         connectServerNonBlock();
1065
1066         ensureServerClosed();
1067         assertTrue(this.channel1.isOpen());
1068         this.channel1.close();
1069         statusChannelClosed();
1070     }
1071
1072     /**
1073      * no server-->connect-->server open-->finish-->close
1074      */
1075     @TestTargets({
1076         @TestTargetNew(
1077             level = TestLevel.PARTIAL_COMPLETE,
1078             notes = "",
1079             method = "connect",
1080             args = {java.net.SocketAddress.class}
1081         ),
1082         @TestTargetNew(
1083             level = TestLevel.PARTIAL_COMPLETE,
1084             notes = "",
1085             method = "finishConnect",
1086             args = {}
1087         )
1088     })
1089     public void testCFII_ServerStartLater_Block() throws Exception {
1090         // ensure
1091         ensureServerClosed();
1092         assertTrue(this.channel1.isBlocking());
1093         statusNotConnected_NotPending();
1094         // connect
1095         try {
1096             this.channel1.connect(localAddr1);
1097             fail("Should throw a ConnectException here.");
1098         } catch (ConnectException e) {
1099             // OK.
1100         }
1101         statusChannelClosed();
1102         ensureServerOpen();
1103         try {
1104             this.channel1.finishConnect();
1105             fail("Should throw a ClosedChannelException here.");
1106         } catch (ClosedChannelException e) {
1107             // OK.
1108         }
1109     }
1110
1111     /**
1112      * no server-->connect-->server open-->finish-->close
1113      */
1114     @TestTargets({
1115         @TestTargetNew(
1116             level = TestLevel.PARTIAL_COMPLETE,
1117             notes = "",
1118             method = "connect",
1119             args = {java.net.SocketAddress.class}
1120         ),
1121         @TestTargetNew(
1122             level = TestLevel.PARTIAL_COMPLETE,
1123             notes = "",
1124             method = "finishConnect",
1125             args = {}
1126         )
1127     })
1128     public void testCFII_ServerStartLater_NonBlock() throws Exception {
1129         // ensure
1130         ensureServerClosed();
1131         this.channel1.configureBlocking(false);
1132         statusNotConnected_NotPending();
1133         // connect
1134         assertFalse(this.channel1.connect(localAddr1));
1135         statusNotConnected_Pending();
1136
1137         ensureServerOpen();
1138
1139         try {
1140             assertFalse(this.channel1.finishConnect());
1141             statusNotConnected_Pending();
1142             this.channel1.close();
1143         } catch (ConnectException e) {
1144             // OK
1145         }
1146     }
1147
1148     /**
1149      * connect-->finish-->finish-->close
1150      */
1151     @TestTargets({
1152         @TestTargetNew(
1153             level = TestLevel.PARTIAL_COMPLETE,
1154             notes = "",
1155             method = "connect",
1156             args = {java.net.SocketAddress.class}
1157         ),
1158         @TestTargetNew(
1159             level = TestLevel.PARTIAL_COMPLETE,
1160             notes = "",
1161             method = "finishConnect",
1162             args = {}
1163         )
1164     })
1165     public void testCFII_FinishTwice_NoServer_NonBlock() throws Exception {
1166         // ensure
1167         ensureServerClosed();
1168         this.channel1.configureBlocking(false);
1169         statusNotConnected_NotPending();
1170         // connect
1171         assertFalse(this.channel1.connect(localAddr1));
1172         statusNotConnected_Pending();
1173         try {
1174             assertFalse(this.channel1.finishConnect());
1175         } catch (ConnectException e) {
1176             // OK
1177         }
1178         statusChannelClosed();
1179         try {
1180             assertFalse(this.channel1.finishConnect());
1181         } catch (ClosedChannelException e) {
1182             // OK
1183         }
1184         statusChannelClosed();
1185         
1186         this.channel1.close();
1187         statusChannelClosed();
1188     }
1189
1190     /**
1191      * connect-->finish-->finish-->close
1192      */
1193     @TestTargets({
1194         @TestTargetNew(
1195             level = TestLevel.PARTIAL_COMPLETE,
1196             notes = "",
1197             method = "connect",
1198             args = {java.net.SocketAddress.class}
1199         ),
1200         @TestTargetNew(
1201             level = TestLevel.PARTIAL_COMPLETE,
1202             notes = "",
1203             method = "finishConnect",
1204             args = {}
1205         )
1206     })
1207     public void testCFII_FinishTwice_Server_Block() throws Exception {
1208         connectServerBlock();
1209         tryFinish();
1210         this.channel1.close();
1211         statusChannelClosed();
1212
1213     }
1214
1215     /**
1216      * connect-->finish-->finish-->close
1217      */
1218     @TestTargets({
1219         @TestTargetNew(
1220             level = TestLevel.PARTIAL_COMPLETE,
1221             notes = "",
1222             method = "connect",
1223             args = {java.net.SocketAddress.class}
1224         ),
1225         @TestTargetNew(
1226             level = TestLevel.PARTIAL_COMPLETE,
1227             notes = "",
1228             method = "finishConnect",
1229             args = {}
1230         )
1231     })
1232     public void testCFII_FinishTwice_Server_NonBlock() throws Exception {
1233         connectServerNonBlock();
1234         tryFinish();
1235         this.channel1.close();
1236         statusChannelClosed();
1237     }
1238
1239     /**
1240      * connect-->finish-->connect-->close
1241      */
1242     @TestTargets({
1243         @TestTargetNew(
1244             level = TestLevel.PARTIAL_COMPLETE,
1245             notes = "Verifies case:  connect-->finish-->connect-->close. Verifies ClosedChannelException, ConnectException.",
1246             method = "connect",
1247             args = {java.net.SocketAddress.class}
1248         ),
1249         @TestTargetNew(
1250             level = TestLevel.PARTIAL_COMPLETE,
1251             notes = "Verifies case:  connect-->finish-->connect-->close. Verifies ClosedChannelException, ConnectException.",
1252             method = "finishConnect",
1253             args = {}
1254         )
1255     })   
1256     public void testCFII_ConnectAfterFinish_NoServer_Block() throws Exception {
1257         // ensure
1258         ensureServerClosed();
1259         assertTrue(this.channel1.isBlocking());
1260         statusNotConnected_NotPending();
1261         // connect
1262         try {
1263             this.channel1.connect(localAddr1);
1264             fail("Should throw a ConnectException here.");
1265         } catch (ConnectException e) {
1266             // OK.
1267         }
1268         statusChannelClosed();
1269         try {
1270             this.channel1.finishConnect();
1271             fail("Should throw a ClosedChannelException here.");
1272         } catch (ClosedChannelException e) {
1273             // OK.
1274         }
1275         statusChannelClosed();
1276         try {
1277             this.channel1.connect(localAddr1);
1278             fail("Should throw a ClosedChannelException here.");
1279         } catch (ClosedChannelException e) {
1280             // OK.
1281         }
1282         statusChannelClosed();
1283     }
1284
1285     /**
1286      * connect-->finish-->connect-->close
1287      */
1288     @TestTargets({
1289         @TestTargetNew(
1290             level = TestLevel.PARTIAL_COMPLETE,
1291             notes = "Verifies case: connect-->finish-->connect-->close. Verifies ConnectionPendingException, ConnectException.",
1292             method = "connect",
1293             args = {java.net.SocketAddress.class}
1294         ),
1295         @TestTargetNew(
1296             level = TestLevel.PARTIAL_COMPLETE,
1297             notes = "Verifies case: connect-->finish-->connect-->close. Verifies ConnectionPendingException, ConnectException.",
1298             method = "finishConnect",
1299             args = {}
1300         )
1301     })    
1302     public void testCFII_ConnectAfterFinish_NoServer_NonBlock()
1303             throws Exception {
1304         // ensure
1305         ensureServerClosed();
1306         this.channel1.configureBlocking(false);
1307         statusNotConnected_NotPending();
1308         // connect
1309         assertFalse(this.channel1.connect(localAddr1));
1310         statusNotConnected_Pending();
1311
1312         try {
1313             this.channel1.connect(localAddr1);
1314             fail("Should throw a ConnectionPendingException here.");
1315         } catch (ConnectionPendingException e) {
1316             // OK.
1317         }
1318         statusNotConnected_Pending();
1319
1320         // connect another addr
1321         try {
1322             this.channel1.connect(localAddr2);
1323             fail("Should throw a ConnectionPendingException here.");
1324         } catch (ConnectionPendingException e) {
1325             // OK.
1326         }
1327         statusNotConnected_Pending();
1328
1329         // connect if server closed
1330         ensureServerClosed();
1331
1332         try {
1333             this.channel1.connect(localAddr1);
1334             fail("Should throw a ConnectionPendingException here.");
1335         } catch (ConnectionPendingException e) {
1336             // OK.
1337         }
1338         statusNotConnected_Pending();
1339
1340         this.channel1.close();
1341
1342         statusChannelClosed();
1343     }
1344
1345     /**
1346      * connect-->finish-->connect-->close
1347      */
1348     @TestTargetNew(
1349         level = TestLevel.PARTIAL_COMPLETE,
1350         notes = "Verifies AlreadyConnectedException.",
1351         method = "connect",
1352         args = {java.net.SocketAddress.class}
1353     )        
1354     public void testCFII_ConnectAfterFinish_Server_Block() throws Exception {
1355         connectServerBlock();
1356
1357         if (!this.channel1.isConnected()) {
1358             fail("Connection failed," +
1359                     "testCFII_ConnectAfterFinish_Server_Block not finished.");
1360         }
1361
1362         try {
1363             this.channel1.connect(localAddr1);
1364             fail("Should throw an AlreadyConnectedException here.");
1365         } catch (AlreadyConnectedException e) {
1366             // OK.
1367         }
1368         statusConnected_NotPending();
1369
1370         // connect another addr
1371         try {
1372             this.channel1.connect(localAddr2);
1373             fail("Should throw an AlreadyConnectedException here.");
1374         } catch (AlreadyConnectedException e) {
1375             // OK.
1376         }
1377         statusConnected_NotPending();
1378
1379         // connect if server closed
1380         ensureServerClosed();
1381
1382         try {
1383             this.channel1.connect(localAddr1);
1384             fail("Should throw an AlreadyConnectedException here.");
1385         } catch (AlreadyConnectedException e) {
1386             // OK.
1387         }
1388         statusConnected_NotPending();
1389
1390         this.channel1.close();
1391         statusChannelClosed();
1392
1393     }
1394
1395     /**
1396      * connect-->finish-->connect-->close
1397      */
1398     @TestTargetNew(
1399         level = TestLevel.PARTIAL_COMPLETE,
1400         notes = "Verifies AlreadyConnectedException.",
1401         method = "connect",
1402         args = {java.net.SocketAddress.class}
1403     )    
1404     public void testCFII_ConnectAfterFinish_Server_NonBlock() throws Exception {
1405         connectServerNonBlock();
1406
1407         if (!this.channel1.isConnected()) {
1408             fail("Connection failed," +
1409                     "testCFII_ConnectAfterFinish_Server_Block not finished.");
1410         }
1411         try {
1412             this.channel1.connect(localAddr1);
1413             fail("Should throw an AlreadyConnectedException or a ConnectionPendingException here.");
1414         } catch (AlreadyConnectedException e) {
1415             // OK.
1416         }
1417
1418         statusConnected_NotPending();
1419
1420         // connect another addr
1421         try {
1422             this.channel1.connect(localAddr2);
1423             fail("Should throw an AlreadyConnectedException here.");
1424         } catch (AlreadyConnectedException e) {
1425             // OK.
1426         }
1427         statusConnected_NotPending();
1428
1429         // connect if server closed
1430         ensureServerClosed();
1431
1432         try {
1433             this.channel1.connect(localAddr1);
1434             fail("Should throw an AlreadyConnectedException here.");
1435         } catch (AlreadyConnectedException e) {
1436             // OK.
1437         }
1438         statusConnected_NotPending();
1439
1440         this.channel1.close();
1441         statusChannelClosed();
1442     }
1443
1444     /**
1445      * connect-->connect-->finish-->close
1446      */
1447     @TestTargets({
1448         @TestTargetNew(
1449             level = TestLevel.PARTIAL_COMPLETE,
1450             notes = "Verifies case: connect-->connect-->finish-->close. Verifies ConnectionPendingException, ConnectException.",
1451             method = "connect",
1452             args = {java.net.SocketAddress.class}
1453         ),
1454         @TestTargetNew(
1455             level = TestLevel.PARTIAL_COMPLETE,
1456             notes = "Verifies case: connect-->connect-->finish-->close. Verifies ConnectionPendingException, ConnectException.",
1457             method = "finishConnect",
1458             args = {}
1459         )
1460     }) 
1461     public void testCFII_ConnectTwice_NoServer_NonBlock() throws Exception {
1462         // ensure
1463         ensureServerClosed();
1464         this.channel1.configureBlocking(false);
1465         statusNotConnected_NotPending();
1466         // connect
1467         assertFalse(this.channel1.connect(localAddr1));
1468         statusNotConnected_Pending();
1469
1470         try {
1471             this.channel1.connect(localAddr1);
1472             fail("Should throw a ConnectionPendingException here.");
1473         } catch (ConnectionPendingException e) {
1474             // OK.
1475         }
1476         statusNotConnected_Pending();
1477
1478         // connect another addr
1479         try {
1480             this.channel1.connect(localAddr2);
1481             fail("Should throw a ConnectionPendingException here.");
1482         } catch (ConnectionPendingException e) {
1483             // OK.
1484         }
1485         statusNotConnected_Pending();
1486
1487         // connect if server closed
1488         ensureServerClosed();
1489
1490         try {
1491             this.channel1.connect(localAddr1);
1492             fail("Should throw a ConnectionPendingException here.");
1493         } catch (ConnectionPendingException e) {
1494             // OK.
1495         }
1496         statusNotConnected_Pending();
1497         this.channel1.close();
1498
1499         statusChannelClosed();
1500     }
1501
1502     /**
1503      * connect-->connect-->finish-->close
1504      */
1505     @TestTargets({
1506         @TestTargetNew(
1507             level = TestLevel.PARTIAL_COMPLETE,
1508             notes = "Verifies case connect-->connect-->finish-->close. Verifies AlreadyConnectedException.",
1509             method = "connect",
1510             args = {java.net.SocketAddress.class}
1511         ),
1512         @TestTargetNew(
1513             level = TestLevel.PARTIAL_COMPLETE,
1514             notes = "Verifies case connect-->connect-->finish-->close. Verifies AlreadyConnectedException.",
1515             method = "finishConnect",
1516             args = {}
1517         )
1518     }) 
1519     public void testCFII_ConnectTwice_Server_Block() throws Exception {
1520         // ensure
1521         ensureServerOpen();
1522         assertTrue(this.channel1.isBlocking());
1523         statusNotConnected_NotPending();
1524         // connect
1525         assertTrue(this.channel1.connect(localAddr1));
1526         statusConnected_NotPending();
1527
1528         try {
1529             this.channel1.connect(localAddr1);
1530             fail("Should throw an AlreadyConnectedException here.");
1531         } catch (AlreadyConnectedException e) {
1532             // OK.
1533         }
1534         statusConnected_NotPending();
1535
1536         // connect another addr
1537         try {
1538             this.channel1.connect(localAddr2);
1539             fail("Should throw an AlreadyConnectedException here.");
1540         } catch (AlreadyConnectedException e) {
1541             // OK.
1542         }
1543         statusConnected_NotPending();
1544
1545         // connect if server closed
1546         ensureServerClosed();
1547
1548         try {
1549             this.channel1.connect(localAddr1);
1550             fail("Should throw an AlreadyConnectedException here.");
1551         } catch (AlreadyConnectedException e) {
1552             // OK.
1553         }
1554         statusConnected_NotPending();
1555
1556         tryFinish();
1557
1558         this.channel1.close();
1559         statusChannelClosed();
1560
1561     }
1562
1563     /**
1564      * connect-->connect-->finish-->close
1565      */
1566     @TestTargets({
1567         @TestTargetNew(
1568             level = TestLevel.PARTIAL_COMPLETE,
1569             notes = "Verifies case connect-->connect-->finish-->close. Verifies ConnectionPendingException.",
1570             method = "connect",
1571             args = {java.net.SocketAddress.class}
1572         ),
1573         @TestTargetNew(
1574             level = TestLevel.PARTIAL_COMPLETE,
1575             notes = "Verifies case connect-->connect-->finish-->close. Verifies ConnectionPendingException.",
1576             method = "finishConnect",
1577             args = {}
1578         )
1579     }) 
1580     public void testCFII_ConnectTwice_Server_NonBlock() throws Exception {
1581         // ensure
1582         ensureServerOpen();
1583         this.channel1.configureBlocking(false);
1584         statusNotConnected_NotPending();
1585         // connect
1586         assertFalse(this.channel1.connect(localAddr1));
1587         statusNotConnected_Pending();
1588
1589         try {
1590             this.channel1.connect(localAddr1);
1591             fail("Should throw a ConnectionPendingException here.");
1592         } catch (ConnectionPendingException e) {
1593             // OK.
1594         }
1595         statusNotConnected_Pending();
1596
1597         // connect another addr
1598         try {
1599             this.channel1.connect(localAddr2);
1600             fail("Should throw a ConnectionPendingException here.");
1601         } catch (ConnectionPendingException e) {
1602             // OK.
1603         }
1604         statusNotConnected_Pending();
1605
1606         // connect if server closed
1607         ensureServerClosed();
1608
1609         try {
1610             this.channel1.connect(localAddr1);
1611             fail("Should throw a ConnectionPendingException here.");
1612         } catch (ConnectionPendingException e) {
1613             // OK.
1614         }
1615         statusNotConnected_Pending();
1616
1617         tryFinish();
1618
1619         this.channel1.close();
1620         statusChannelClosed();
1621     }
1622
1623     /**
1624      * finish-->connect-->finish-->close
1625      */
1626     @TestTargets({
1627         @TestTargetNew(
1628             level = TestLevel.PARTIAL_COMPLETE,
1629             notes = "",
1630             method = "connect",
1631             args = {java.net.SocketAddress.class}
1632         ),
1633         @TestTargetNew(
1634             level = TestLevel.PARTIAL_COMPLETE,
1635             notes = "",
1636             method = "finishConnect",
1637             args = {}
1638         )
1639     })
1640     public void testCFII_FinishFirst_NoServer_Block() throws Exception {
1641         // ensure
1642         ensureServerClosed();
1643         assertTrue(this.channel1.isBlocking());
1644         statusNotConnected_NotPending();
1645         // finish
1646         try {
1647             this.channel1.finishConnect();
1648             fail("Should throw NoConnectionPendingException");
1649         } catch (NoConnectionPendingException e) {
1650             // OK.
1651         }
1652         statusNotConnected_NotPending();
1653         // connect
1654         try {
1655             this.channel1.connect(localAddr1);
1656             fail("Should throw a ConnectException here.");
1657         } catch (ConnectException e) {
1658             // OK.
1659         }
1660         statusChannelClosed();
1661         try {
1662             this.channel1.finishConnect();
1663             fail("Should throw a ClosedChannelException here.");
1664         } catch (ClosedChannelException e) {
1665             // OK.
1666         }
1667         statusChannelClosed();
1668     }
1669
1670     /**
1671      * finish-->connect-->finish-->close
1672      */
1673     @TestTargets({
1674         @TestTargetNew(
1675             level = TestLevel.PARTIAL_COMPLETE,
1676             notes = "",
1677             method = "connect",
1678             args = {java.net.SocketAddress.class}
1679         ),
1680         @TestTargetNew(
1681             level = TestLevel.PARTIAL_COMPLETE,
1682             notes = "",
1683             method = "finishConnect",
1684             args = {}
1685         )
1686     })
1687     public void testCFII_FinishFirst_NoServer_NonBlock() throws Exception {
1688         // ensure
1689         ensureServerClosed();
1690         this.channel1.configureBlocking(false);
1691         statusNotConnected_NotPending();
1692         // finish
1693         try {
1694             this.channel1.finishConnect();
1695             fail("Should throw NoConnectionPendingException");
1696         } catch (NoConnectionPendingException e) {
1697             // OK.
1698         }
1699         statusNotConnected_NotPending();
1700         // connect
1701         assertFalse(this.channel1.connect(localAddr1));
1702         statusNotConnected_Pending();
1703         this.channel1.close();
1704
1705         statusChannelClosed();
1706     }
1707
1708     /**
1709      * finish-->connect-->finish-->close
1710      */
1711     @TestTargets({
1712         @TestTargetNew(
1713             level = TestLevel.PARTIAL_COMPLETE,
1714             notes = "",
1715             method = "connect",
1716             args = {java.net.SocketAddress.class}
1717         ),
1718         @TestTargetNew(
1719             level = TestLevel.PARTIAL_COMPLETE,
1720             notes = "",
1721             method = "finishConnect",
1722             args = {}
1723         )
1724     })    
1725     public void testCFII_FinishFirst_Server_Block() throws Exception {
1726         // ensure
1727         ensureServerOpen();
1728         assertTrue(this.channel1.isBlocking());
1729         statusNotConnected_NotPending();
1730         // finish
1731         try {
1732             this.channel1.finishConnect();
1733             fail("Should throw NoConnectionPendingException");
1734         } catch (NoConnectionPendingException e) {
1735             // OK.
1736         }
1737         statusNotConnected_NotPending();
1738         // connect
1739         assertTrue(this.channel1.connect(localAddr1));
1740         statusConnected_NotPending();
1741
1742         tryFinish();
1743
1744         this.channel1.close();
1745         statusChannelClosed();
1746
1747     }
1748
1749     /**
1750      * finish-->connect-->finish-->close
1751      */
1752     @TestTargets({
1753         @TestTargetNew(
1754             level = TestLevel.PARTIAL_COMPLETE,
1755             notes = "",
1756             method = "connect",
1757             args = {java.net.SocketAddress.class}
1758         ),
1759         @TestTargetNew(
1760             level = TestLevel.PARTIAL_COMPLETE,
1761             notes = "",
1762             method = "finishConnect",
1763             args = {}
1764         )
1765     })    
1766     public void testCFII_FinishFirst_Server_NonBlock() throws Exception {
1767         // ensure
1768         ensureServerOpen();
1769         this.channel1.configureBlocking(false);
1770         statusNotConnected_NotPending();
1771         // finish
1772         try {
1773             this.channel1.finishConnect();
1774             fail("Should throw NoConnectionPendingException");
1775         } catch (NoConnectionPendingException e) {
1776             // OK.
1777         }
1778         statusNotConnected_NotPending();
1779         // connect
1780         assertFalse(this.channel1.connect(localAddr1));
1781         statusNotConnected_Pending();
1782
1783         tryFinish();
1784
1785         this.channel1.close();
1786         statusChannelClosed();
1787     }
1788
1789     @TestTargetNew(
1790         level = TestLevel.PARTIAL_COMPLETE,
1791         notes = "",
1792         method = "connect",
1793         args = {java.net.SocketAddress.class}
1794     )
1795     public void testCFII_Null() throws Exception {
1796         statusNotConnected_NotPending();
1797         try {
1798             this.channel1.connect(null);
1799             fail("Should throw an IllegalArgumentException here.");
1800         } catch (IllegalArgumentException e) {
1801             // OK.
1802         }
1803     }
1804
1805     @TestTargetNew(
1806         level = TestLevel.PARTIAL_COMPLETE,
1807         notes = "",
1808         method = "connect",
1809         args = {java.net.SocketAddress.class}
1810     )
1811     public void testCFII_UnsupportedType() throws Exception {
1812         statusNotConnected_NotPending();
1813         SocketAddress newTypeAddress = new SubSocketAddress();
1814         try {
1815             this.channel1.connect(newTypeAddress);
1816             fail("Should throw an UnsupportedAddressTypeException here.");
1817         } catch (UnsupportedAddressTypeException e) {
1818             // OK.
1819         }
1820     }
1821
1822     @TestTargetNew(
1823         level = TestLevel.PARTIAL_COMPLETE,
1824         notes = "",
1825         method = "connect",
1826         args = {java.net.SocketAddress.class}
1827     )
1828     public void testCFII_Unresolved() throws IOException {
1829         statusNotConnected_NotPending();
1830         InetSocketAddress unresolved = new InetSocketAddress(
1831                 "unresolved address", 1080);
1832         try {
1833             this.channel1.connect(unresolved);
1834             fail("Should throw an UnresolvedAddressException here.");
1835         } catch (UnresolvedAddressException e) {
1836             // OK.
1837         }
1838     }
1839
1840     @TestTargetNew(
1841         level = TestLevel.PARTIAL_COMPLETE,
1842         notes = "",
1843         method = "connect",
1844         args = {java.net.SocketAddress.class}
1845     )
1846     public void testCFII_EmptyHost() throws Exception {
1847         statusNotConnected_NotPending();
1848         ServerSocket server = new ServerSocket(0);
1849         int port = server.getLocalPort();
1850         server.close();
1851         try {
1852             this.channel1.connect(new InetSocketAddress("", port));
1853             fail("Should throw ConnectException");
1854         } catch (ConnectException e) {
1855             // correct
1856         }
1857     }
1858
1859     @TestTargets({
1860         @TestTargetNew(
1861             level = TestLevel.PARTIAL_COMPLETE,
1862             notes = "Verifies ClosedChannelException.",
1863             method = "connect",
1864             args = {java.net.SocketAddress.class}
1865         ),
1866         @TestTargetNew(
1867             level = TestLevel.PARTIAL_COMPLETE,
1868             notes = "Verifies ClosedChannelException.",
1869             method = "finishConnect",
1870             args = {}
1871         )
1872     })
1873     public void testCFII_CloseFirst() throws Exception {
1874         this.channel1.close();
1875         statusChannelClosed();
1876         ensureServerOpen();
1877         try {
1878             this.channel1.connect(localAddr1);
1879             fail("Should throw ClosedChannelException.");
1880         } catch (ClosedChannelException e) {
1881             // OK.
1882         }
1883         statusChannelClosed();
1884         try {
1885             this.channel1.finishConnect();
1886             fail("Should throw ClosedChannelException.");
1887         } catch (ClosedChannelException e) {
1888             // OK.
1889         }
1890         statusChannelClosed();
1891         try {
1892             this.channel1.configureBlocking(false);
1893             fail("Should throw ClosedChannelException.");
1894         } catch (ClosedChannelException e) {
1895             // OK.
1896         }
1897         statusChannelClosed();
1898     }
1899
1900     @TestTargets({
1901         @TestTargetNew(
1902             level = TestLevel.PARTIAL_COMPLETE,
1903             notes = "",
1904             method = "connect",
1905             args = {java.net.SocketAddress.class}
1906         ),
1907         @TestTargetNew(
1908             level = TestLevel.PARTIAL_COMPLETE,
1909             notes = "",
1910             method = "finishConnect",
1911             args = {}
1912         )
1913     })
1914     public void testCFII_StatusAfterFinish() throws Exception {
1915         // 1. close server, finish must return false, check the status
1916         ensureServerClosed();
1917
1918         // 1.1 block mode
1919         assertTrue(this.channel1.isBlocking());
1920         try {
1921             channel1.connect(localAddr1);
1922             fail("Should throw ConnectException");
1923         } catch (ConnectException e) {
1924             // OK.
1925         }
1926
1927         assertFalse(this.channel1.isOpen());
1928         assertTrue(this.channel1.isBlocking());
1929         assertFalse(this.channel1.isConnectionPending());
1930
1931         // 1.2 non block mode
1932         this.channel1 = SocketChannel.open();
1933         this.channel1.configureBlocking(false);
1934         assertFalse(this.channel1.connect(localAddr1));
1935         try {
1936             assertFalse(this.channel1.finishConnect());
1937             fail("Should throw IOException: Connection refused");
1938         } catch (ConnectException e) {
1939             // OK
1940         }
1941         statusChannelClosed();
1942
1943         // 2. start server, finish usually return true, check the status
1944         ensureServerOpen();
1945
1946         // 2.1 block mode
1947         this.channel1 = SocketChannel.open();
1948         assertTrue(this.channel1.isBlocking());
1949         assertTrue(this.channel1.connect(localAddr1));
1950         assertTrue(this.channel1.finishConnect());
1951         statusConnected_NotPending();
1952         this.channel1.close();
1953
1954         // 2.2 non block mode
1955         this.channel1 = SocketChannel.open();
1956         this.channel1.configureBlocking(false);
1957         assertFalse(this.channel1.connect(localAddr1));
1958         tryFinish();
1959         this.channel1.close();
1960     }
1961
1962     private void ensureServerClosed() throws IOException {
1963         if (null != this.server1) {
1964             this.server1.close();
1965             assertTrue(this.server1.isClosed());
1966         }
1967         if (null != this.server2) {
1968             this.server2.close();
1969             assertTrue(this.server2.isClosed());
1970         }
1971     }
1972
1973     private void ensureServerOpen() throws IOException {
1974         ensureServerClosed();
1975         this.server1 = new ServerSocket(localAddr1.getPort());
1976         this.server2 = new ServerSocket(localAddr2.getPort());
1977         assertTrue(this.server1.isBound());
1978         assertTrue(this.server2.isBound());
1979     }
1980
1981     private void connectNoServerNonBlock() throws Exception {
1982         // ensure
1983         ensureServerClosed();
1984         this.channel1.configureBlocking(false);
1985         statusNotConnected_NotPending();
1986         // connect
1987         assertFalse(this.channel1.connect(localAddr1));
1988         statusNotConnected_Pending();
1989         try {
1990             assertFalse(this.channel1.finishConnect());
1991         } catch (ConnectException e) {
1992             // OK
1993         }
1994         ensureServerClosed();
1995     }
1996
1997     private void connectServerNonBlock() throws Exception {
1998         // ensure
1999         ensureServerOpen();
2000         this.channel1.configureBlocking(false);
2001         statusNotConnected_NotPending();
2002         // connect
2003         assertFalse(this.channel1.connect(localAddr1));
2004         statusNotConnected_Pending();
2005
2006         tryFinish();
2007     }
2008
2009     private void connectServerBlock() throws Exception {
2010         // ensure
2011         ensureServerOpen();
2012         assertTrue(this.channel1.isBlocking());
2013         statusNotConnected_NotPending();
2014         // connect
2015         assertTrue(this.channel1.connect(localAddr1));
2016         statusConnected_NotPending();
2017
2018         tryFinish();
2019     }
2020
2021     private void statusChannelClosed() {
2022         assertFalse(this.channel1.isConnected());
2023         assertFalse(this.channel1.isConnectionPending());
2024         assertFalse(this.channel1.isOpen());
2025     }
2026
2027     private void statusNotConnected_NotPending() {
2028         assertFalse(this.channel1.isConnected());
2029         assertFalse(this.channel1.isConnectionPending());
2030         assertTrue(this.channel1.isOpen());
2031     }
2032
2033     private void statusNotConnected_Pending() {
2034         assertFalse(this.channel1.isConnected());
2035         assertTrue(this.channel1.isConnectionPending());
2036         assertTrue(this.channel1.isOpen());
2037     }
2038
2039     private void statusConnected_NotPending() {
2040         assertTrue(this.channel1.isConnected());
2041         assertFalse(this.channel1.isConnectionPending());
2042         assertTrue(this.channel1.isOpen());
2043     }
2044
2045     private boolean tryFinish() throws IOException {
2046         /*
2047          * the result of finish will be asserted in multi-thread tests.
2048          */
2049         boolean connected = false;
2050         assertTrue(this.channel1.isOpen());
2051         try {
2052             connected = this.channel1.finishConnect();
2053         } catch (SocketException e) {
2054             // Finish connection failed, probably due to reset by peer error.
2055         }
2056         if (connected) {
2057             statusConnected_NotPending();
2058         }
2059         return connected;
2060     }
2061
2062     // -------------------------------------------------------------------
2063     // Original tests. Test method for CFII with real data.
2064     // -------------------------------------------------------------------
2065
2066     /**
2067      * 
2068      * 'SocketChannelImpl.connect(SocketAddress)'
2069      */
2070     @TestTargetNew(
2071         level = TestLevel.PARTIAL_COMPLETE,
2072         notes = "",
2073         method = "connect",
2074         args = {java.net.SocketAddress.class}
2075     )
2076     public void testCFII_Data_ConnectWithServer() throws Exception {
2077         ensureServerOpen();
2078         java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer
2079                 .allocate(CAPACITY_NORMAL);
2080         java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
2081         writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
2082         assertFalse(this.channel1.isRegistered());
2083         assertTrue(this.channel1.isBlocking());
2084
2085         this.channel1.connect(localAddr1);
2086
2087         assertTrue(this.channel1.isBlocking());
2088         assertTrue(this.channel1.isConnected());
2089         assertFalse(this.channel1.isConnectionPending());
2090         assertTrue(this.channel1.isOpen());
2091         assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf));
2092         assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBufArr, 0, 1));
2093
2094         this.channel1.configureBlocking(false);
2095         try {
2096             this.channel1.connect(localAddr1);
2097             fail("Should throw AlreadyConnectedException");
2098         } catch (AlreadyConnectedException e) {
2099             // correct
2100         }
2101
2102         assertFalse(this.channel1.isRegistered());
2103         tryFinish();
2104     }
2105
2106     /*
2107      * Test method for 'SocketChannelImpl.connect(SocketAddress)'
2108      */
2109     @TestTargets({
2110         @TestTargetNew(
2111             level = TestLevel.PARTIAL_COMPLETE,
2112             notes = "",
2113             method = "connect",
2114             args = {java.net.SocketAddress.class}
2115         ),
2116         @TestTargetNew(
2117             level = TestLevel.PARTIAL_COMPLETE,
2118             notes = "",
2119             method = "finishConnect",
2120             args = {}
2121         )
2122     }) 
2123     public void testCFII_Data_ConnectWithServer_nonBlocking() throws Exception {
2124         ensureServerOpen();
2125         java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer
2126                 .allocate(CAPACITY_NORMAL);
2127         java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
2128         writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
2129         assertFalse(this.channel1.isRegistered());
2130         assertTrue(this.channel1.isBlocking());
2131         this.channel1.configureBlocking(false);
2132         this.channel1.connect(localAddr1);
2133
2134         assertFalse(this.channel1.isBlocking());
2135         assertFalse(this.channel1.isConnected());
2136         assertTrue(this.channel1.isConnectionPending());
2137         assertTrue(this.channel1.isOpen());
2138         assertTrue(tryFinish());
2139         assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf));
2140         assertEquals(CAPACITY_NORMAL, this.channel1
2141                 .write(writeBufArr, 0, 1));
2142
2143         this.channel1.configureBlocking(false);
2144         try {
2145             this.channel1.connect(localAddr1);
2146             fail("Should throw AlreadyConnectedException");
2147         } catch (AlreadyConnectedException e) {
2148             // correct
2149         }
2150
2151         assertFalse(this.channel1.isRegistered());
2152         tryFinish();
2153     }
2154
2155     /*
2156      * Test method for 'SocketChannelImpl.finishConnect()'
2157      */
2158     @TestTargetNew(
2159         level = TestLevel.PARTIAL_COMPLETE,
2160         notes = "",
2161         method = "finishConnect",
2162         args = {}
2163     )
2164     public void testCFII_Data_FinishConnect_nonBlocking() throws IOException {
2165         ensureServerOpen();
2166
2167         java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer
2168                 .allocate(CAPACITY_NORMAL);
2169         java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
2170         writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
2171
2172         this.channel1.configureBlocking(false);
2173         try {
2174             this.channel1.finishConnect();
2175             fail("Should throw NoConnectionPendingException");
2176         } catch (NoConnectionPendingException e) {
2177             // correct
2178         }
2179         this.channel1.connect(localAddr1);
2180         assertFalse(this.channel1.isBlocking());
2181         assertFalse(this.channel1.isConnected());
2182         assertTrue(this.channel1.isConnectionPending());
2183         assertTrue(this.channel1.isOpen());
2184         this.server1.accept();
2185         assertTrue(tryFinish());
2186         assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf));
2187         assertEquals(CAPACITY_NORMAL, this.channel1
2188                 .write(writeBufArr, 0, 1));
2189         try {
2190             this.channel1.connect(localAddr1);
2191             fail("Should throw AlreadyConnectedException");
2192         } catch (AlreadyConnectedException e) {
2193             // correct
2194         }
2195
2196         assertFalse(this.channel1.isRegistered());
2197         tryFinish();
2198     }
2199
2200     @TestTargets({
2201         @TestTargetNew(
2202             level = TestLevel.PARTIAL_COMPLETE,
2203             notes = "",
2204             method = "connect",
2205             args = {java.net.SocketAddress.class}
2206         ),
2207         @TestTargetNew(
2208             level = TestLevel.PARTIAL_COMPLETE,
2209             notes = "",
2210             method = "finishConnect",
2211             args = {}
2212         ),
2213         @TestTargetNew(
2214             level = TestLevel.PARTIAL_COMPLETE,
2215             notes = "Verifies IOException",
2216             method = "open",
2217             args = {SocketAddress.class}
2218         )
2219     }) 
2220     public void testCFII_Data_FinishConnect_AddrSetServerStartLater()
2221             throws IOException {
2222         ensureServerClosed();
2223         java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
2224         writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
2225         this.channel1.configureBlocking(false);
2226         try {
2227             SocketChannel.open(localAddr1);
2228             fail("Should throw ConnectException");
2229         } catch (ConnectException e) {
2230             // correct
2231         }
2232         assertTrue(this.channel1.isOpen());
2233         assertFalse(this.channel1.isBlocking());
2234         assertFalse(this.channel1.isConnectionPending());
2235         this.channel1.configureBlocking(true);
2236         try {
2237             this.channel1.finishConnect();
2238             fail("Should throw NoConnectionPendingException");
2239         } catch (NoConnectionPendingException e) {
2240             // correct
2241         }
2242         try {
2243             this.channel1.connect(localAddr2);
2244             fail("Should throw ConnectException");
2245         } catch (ConnectException e) {
2246             // correct
2247         }
2248
2249         assertTrue(this.channel1.isBlocking());
2250         try {
2251             this.channel1.finishConnect();
2252             fail("Should throw ClosedChannelException");
2253         } catch (ClosedChannelException e) {
2254             // correct
2255         }
2256         assertFalse(this.channel1.isConnected());
2257         // finish after finish OK
2258         assertFalse(this.channel1.isConnectionPending());
2259         this.channel1 = SocketChannel.open();
2260         this.channel1.configureBlocking(false);
2261         this.channel1.connect(localAddr1);
2262         assertFalse(this.channel1.isConnected());
2263         ensureServerOpen();
2264         // cannot connect?
2265             assertFalse(this.channel1.isBlocking());
2266         assertFalse(this.channel1.isConnected());
2267         assertTrue(this.channel1.isConnectionPending());
2268         assertTrue(this.channel1.isOpen());
2269         try {
2270             this.channel1.connect(localAddr1);
2271             fail("Should throw ConnectionPendingException");
2272         } catch (ConnectionPendingException e) {
2273             // correct
2274         }
2275         this.channel1.configureBlocking(true);
2276         try {
2277             this.channel1.connect(localAddr1);
2278             fail("Should throw ConnectionPendingException");
2279         } catch (ConnectionPendingException e) {
2280             // correct
2281         }
2282         tryFinish();
2283     }
2284
2285     @TestTargetNew(
2286         level = TestLevel.PARTIAL_COMPLETE,
2287         notes = "",
2288         method = "finishConnect",
2289         args = {}
2290     ) 
2291     public void testCFII_Data_FinishConnect_ServerStartLater()
2292             throws IOException {
2293         ensureServerClosed();
2294         java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
2295         writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
2296         this.channel1.configureBlocking(true);
2297         try {
2298             this.channel1.finishConnect();
2299             fail("Should throw NoConnectionPendingException");
2300         } catch (NoConnectionPendingException e) {
2301             // correct
2302         }
2303         try {
2304             this.channel1.connect(localAddr1);
2305             fail("Should throw ConnectException");
2306         } catch (ConnectException e) {
2307             // correct
2308         }
2309
2310         try {
2311             this.channel1.finishConnect();
2312             fail("Should throw ClosedChannelException");
2313         } catch (ClosedChannelException e) {
2314             // correct
2315         }
2316         assertFalse(this.channel1.isConnected());
2317         // finish after finish OK
2318         assertFalse(this.channel1.isConnectionPending());
2319         this.channel1 = SocketChannel.open();
2320         this.channel1.configureBlocking(false);
2321         this.channel1.connect(localAddr1);
2322         assertFalse(this.channel1.isConnected());
2323         ensureServerOpen();
2324         // cannot connect?
2325         assertFalse(this.channel1.isBlocking());
2326         assertFalse(this.channel1.isConnected());
2327         assertTrue(this.channel1.isConnectionPending());
2328         assertTrue(this.channel1.isOpen());
2329         try {
2330             this.channel1.connect(localAddr1);
2331             fail("Should throw ConnectionPendingException");
2332         } catch (ConnectionPendingException e) {
2333             // correct
2334         }
2335         this.channel1.configureBlocking(true);
2336         try {
2337             this.channel1.connect(localAddr1);
2338             fail("Should throw ConnectionPendingException");
2339         } catch (ConnectionPendingException e) {
2340             // correct
2341         }
2342         tryFinish();
2343     }
2344
2345     @TestTargetNew(
2346         level = TestLevel.PARTIAL_COMPLETE,
2347         notes = "",
2348         method = "finishConnect",
2349         args = {}
2350     )
2351     public void testCFII_Data_FinishConnect_Blocking() throws IOException {
2352         ensureServerOpen();
2353         java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer
2354                 .allocate(CAPACITY_NORMAL);
2355         java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
2356         writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
2357         this.channel1.configureBlocking(true);
2358         try {
2359             this.channel1.finishConnect();
2360             fail("Should throw NoConnectionPendingException");
2361         } catch (NoConnectionPendingException e) {
2362             // correct
2363         }
2364
2365         this.channel1.connect(localAddr1);
2366
2367         assertTrue(this.channel1.isConnected());
2368         assertFalse(this.channel1.isConnectionPending());
2369         assertTrue(this.channel1.isOpen());
2370         assertTrue(tryFinish());
2371         assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf));
2372         assertEquals(CAPACITY_NORMAL, this.channel1
2373                 .write(writeBufArr, 0, 1));
2374
2375         try {
2376             this.channel1.connect(localAddr1);
2377             fail("Should throw AlreadyConnectedException");
2378         } catch (AlreadyConnectedException e) {
2379             // correct
2380         }
2381
2382         assertFalse(this.channel1.isRegistered());
2383         tryFinish();
2384     }
2385
2386     /**
2387      * Regression test for Harmony-1947.
2388      */
2389     @TestTargetNew(
2390         level = TestLevel.PARTIAL_COMPLETE,
2391         notes = "Doesn't verify exceptions.",
2392         method = "finishConnect",
2393         args = {}
2394     )  
2395     public void test_finishConnect() throws Exception {
2396         SocketAddress address = new InetSocketAddress("localhost", 2046);
2397
2398         ServerSocketChannel theServerChannel = ServerSocketChannel.open();
2399         ServerSocket serversocket = theServerChannel.socket();
2400         serversocket.setReuseAddress(true);
2401         // Bind the socket
2402         serversocket.bind(address);
2403
2404         boolean doneNonBlockingConnect = false;
2405         // Loop so that we make sure we're definitely testing finishConnect()
2406         while (!doneNonBlockingConnect) {
2407             channel1 = SocketChannel.open();
2408
2409             // Set the SocketChannel to non-blocking so that connect(..) does
2410             // not block
2411             channel1.configureBlocking(false);
2412             boolean connected = channel1.connect(address);
2413             if (!connected) {
2414                 // Now set the SocketChannel back to blocking so that
2415                 // finishConnect() blocks.
2416                 channel1.configureBlocking(true);
2417                 doneNonBlockingConnect = channel1.finishConnect();
2418             } else {
2419                 fail("Non blocking connect was connected too fast." +
2420                         "Could not test finishConnect().");
2421             }
2422             if (doneNonBlockingConnect) {
2423                 tryFinish();
2424             } else {
2425                 fail("finishConnect() did not finish the connection.");
2426             }
2427             channel1.close();
2428         }
2429         if (!serversocket.isClosed()) {
2430             serversocket.close();
2431         }
2432     }
2433
2434     // -------------------------------------------------------------------
2435     // End of original tests. Test method for CFII with real data.
2436     // -------------------------------------------------------------------
2437
2438     /**
2439      * @tests java.nio.channels.SocketChannel#read(ByteBuffer)
2440      */
2441     @TestTargetNew(
2442         level = TestLevel.PARTIAL_COMPLETE,
2443         notes = "",
2444         method = "read",
2445         args = {java.nio.ByteBuffer[].class}
2446     ) 
2447     public void test_readLByteBuffer_Blocking() throws IOException {
2448         // initialize write content
2449         byte[] writeContent = new byte[CAPACITY_NORMAL];
2450         for (int i = 0; i < writeContent.length; i++) {
2451             writeContent[i] = (byte) i;
2452         }
2453         // establish connection
2454         channel1.connect(localAddr1);
2455         Socket acceptedSocket = server1.accept();
2456
2457         // use OutputStream.write to send CAPACITY_NORMAL bytes data
2458         OutputStream out = acceptedSocket.getOutputStream();
2459         out.write(writeContent);
2460         // use close to guarantee all data is sent
2461         acceptedSocket.close();
2462
2463         ByteBuffer readContent = ByteBuffer.allocate(CAPACITY_NORMAL + 1);
2464         int totalCount = 0;
2465         int count = 0;
2466         long startTime = System.currentTimeMillis();
2467         // use SocketChannel.read to read data
2468         while (totalCount <= CAPACITY_NORMAL) {
2469             count = channel1.read(readContent);
2470             if (EOF == count) {
2471                 break;
2472             }
2473             totalCount += count;
2474             // if the channel could not finish reading in TIMEOUT ms, the
2475             // test fails. It is used to guarantee the test never hangs even
2476             // if there are bugs of SocketChannel implementation. For
2477             // blocking read, it possibly returns 0 in some cases.
2478             assertTimeout(startTime, TIMEOUT);
2479         }
2480
2481         // assert read content
2482         assertEquals(CAPACITY_NORMAL, totalCount);
2483         assertEquals(CAPACITY_NORMAL, readContent.position());
2484         readContent.flip();
2485         for (int i = 0; i < CAPACITY_NORMAL; i++) {
2486             assertEquals(writeContent[i], readContent.get());
2487         }
2488     }
2489
2490     /**
2491      * @tests java.nio.channels.SocketChannel#read(ByteBuffer)
2492      */
2493     @TestTargetNew(
2494         level = TestLevel.PARTIAL_COMPLETE,
2495         notes = "",
2496         method = "read",
2497         args = {java.nio.ByteBuffer[].class}
2498     ) 
2499     public void test_readLByteBuffer_Nonblocking() throws IOException {
2500         // initialize write content
2501         byte[] writeContent = new byte[CAPACITY_NORMAL];
2502         for (int i = 0; i < writeContent.length; i++) {
2503             writeContent[i] = (byte) i;
2504         }
2505
2506         // establish connection
2507         channel1.connect(localAddr1);
2508         Socket acceptedSocket = server1.accept();
2509         // use OutputStream.write to write CAPACITY_NORMAL bytes data.
2510         OutputStream out = acceptedSocket.getOutputStream();
2511         out.write(writeContent);
2512         // use close to guarantee all data is sent
2513         acceptedSocket.close();
2514
2515         channel1.configureBlocking(false);
2516         ByteBuffer readContent = ByteBuffer.allocate(CAPACITY_NORMAL + 1);
2517         int totalCount = 0;
2518         int count = 0;
2519         long startTime = System.currentTimeMillis();
2520         // use SocketChannel.read to read data
2521         while (totalCount <= CAPACITY_NORMAL) {
2522             count = channel1.read(readContent);
2523             if (EOF == count) {
2524                 break;
2525             }
2526             totalCount += count;
2527             // if the channel could not finish reading in TIMEOUT ms, the
2528             // test fails. It is used to guarantee the test never hangs even
2529             // if there are bugs of SocketChannel implementation.
2530             assertTimeout(startTime, TIMEOUT);
2531         }
2532
2533         // assert read content
2534         assertEquals(CAPACITY_NORMAL, totalCount);
2535         assertEquals(CAPACITY_NORMAL, readContent.position());
2536         readContent.flip();
2537         for (int i = 0; i < CAPACITY_NORMAL; i++) {
2538             assertEquals(writeContent[i], readContent.get());
2539         }
2540     }
2541
2542     /**
2543      * @tests java.nio.channels.SocketChannel#write(ByteBuffer)
2544      */
2545     @TestTargetNew(
2546         level = TestLevel.PARTIAL_COMPLETE,
2547         notes = "",
2548         method = "write",
2549         args = {java.nio.ByteBuffer.class}
2550     )
2551     public void test_writeLjava_nio_ByteBuffer_Blocking() throws IOException {
2552         // initialize write content
2553         ByteBuffer writeContent = ByteBuffer.allocate(CAPACITY_NORMAL);
2554         for (int i = 0; i < CAPACITY_NORMAL; i++) {
2555             writeContent.put((byte) i);
2556         }
2557         writeContent.flip();
2558         // establish connection
2559         channel1.connect(localAddr1);
2560         Socket acceptedSocket = server1.accept();
2561
2562         // use SocketChannel.write(ByteBuffer) to write CAPACITY_NORMAL bytes
2563         // data
2564         int writtenCount = channel1.write(writeContent);
2565         // assert written count and ByteBuffer position
2566         assertEquals(CAPACITY_NORMAL, writtenCount);
2567         assertEquals(CAPACITY_NORMAL, writeContent.position());
2568         // use close to guarantee all data is sent
2569         channel1.close();
2570
2571         InputStream in = acceptedSocket.getInputStream();
2572         int totalCount = 0;
2573         int count = 0;
2574         byte[] readContent = new byte[CAPACITY_NORMAL + 1];
2575         // if the channel could not finish reading in TIMEOUT ms, the test
2576         // fails. It is used to guarantee the test never hangs even if there
2577         // are bugs of SocketChannel implementation.
2578         acceptedSocket.setSoTimeout(TIMEOUT);
2579
2580         // use InputStream.read to read data.
2581         while (totalCount <= CAPACITY_NORMAL) {
2582             count = in.read(readContent, totalCount, readContent.length
2583                     - totalCount);
2584             if (EOF == count) {
2585                 break;
2586             }
2587             totalCount += count;
2588         }
2589
2590         // assert read content
2591         assertEquals(CAPACITY_NORMAL, totalCount);
2592         writeContent.flip();
2593         for (int i = 0; i < CAPACITY_NORMAL; i++) {
2594             assertEquals(writeContent.get(), readContent[i]);
2595         }
2596     }
2597
2598     /**
2599      * @tests java.nio.channels.SocketChannel#write(ByteBuffer)
2600      */
2601     @TestTargetNew(
2602         level = TestLevel.PARTIAL_COMPLETE,
2603         notes = "",
2604         method = "write",
2605         args = {java.nio.ByteBuffer.class}
2606     )
2607     public void test_writeLjava_nio_ByteBuffer_NonBlocking() throws Exception {
2608         // initialize write content
2609         ByteBuffer writeContent = ByteBuffer.allocate(CAPACITY_NORMAL);
2610         for (int i = 0; i < CAPACITY_NORMAL; i++) {
2611             writeContent.put((byte) i);
2612         }
2613         writeContent.flip();
2614
2615         // establish connection
2616         channel1.connect(localAddr1);
2617         Socket acceptedSocket = server1.accept();
2618
2619         channel1.configureBlocking(false);
2620         int writtenTotalCount = 0;
2621         int writtenCount = 0;
2622         long startTime = System.currentTimeMillis();
2623         // use SocketChannel.write(ByteBuffer) to write CAPACITY_NORMAL bytes
2624         while (writtenTotalCount < CAPACITY_NORMAL) {
2625             writtenCount = channel1.write(writeContent);
2626             writtenTotalCount += writtenCount;
2627             // if the channel could not finish writing in TIMEOUT ms, the
2628             // test fails. It is used to guarantee the test never hangs even
2629             // if there are bugs of SocketChannel implementation.
2630             assertTimeout(startTime, TIMEOUT);
2631         }
2632         // assert written count and ByteBuffer position
2633         assertEquals(CAPACITY_NORMAL, writtenTotalCount);
2634         assertEquals(CAPACITY_NORMAL, writeContent.position());
2635         // use close to guarantee all data is sent
2636         channel1.close();
2637
2638         InputStream in = acceptedSocket.getInputStream();
2639         byte[] readContent = new byte[CAPACITY_NORMAL + 1];
2640         int totalCount = 0;
2641         int count = 0;
2642         // if the channel could not finish reading in TIMEOUT ms, the test
2643         // fails. It is used to guarantee the test never hangs even if there
2644         // are bugs of SocketChannel implementation.
2645         acceptedSocket.setSoTimeout(TIMEOUT);
2646         // use InputStream.read to read data.
2647         while (totalCount <= CAPACITY_NORMAL) {
2648             count = in.read(readContent, totalCount, readContent.length
2649                     - totalCount);
2650             if (EOF == count) {
2651                 break;
2652             }
2653             totalCount += count;
2654         }
2655         // assert read content
2656         assertEquals(CAPACITY_NORMAL, totalCount);
2657         writeContent.flip();
2658         for (int i = 0; i < CAPACITY_NORMAL; i++) {
2659             assertEquals(writeContent.get(), readContent[i]);
2660         }
2661     }
2662
2663     /**
2664      * @tests java.nio.channels.SocketChannel#read(ByteBuffer)
2665      */
2666     @TestTargetNew(
2667         level = TestLevel.PARTIAL_COMPLETE,
2668         notes = "",
2669         method = "write",
2670         args = {java.nio.ByteBuffer.class}
2671     )
2672     public void test_writeLjava_nio_ByteBuffer_Nonblocking_HugeData() throws IOException {
2673         // initialize write content
2674         ByteBuffer writeContent = ByteBuffer.allocate(CAPACITY_HUGE);
2675         for (int i = 0; i < CAPACITY_HUGE; i++) {
2676             writeContent.put((byte) i);
2677         }
2678         writeContent.flip();
2679
2680         // establish connection
2681         channel1.connect(localAddr1);
2682         Socket acceptedSocket = server1.accept();
2683
2684         channel1.configureBlocking(false);
2685         int writtenTotalCount = 0;
2686         int writtenCount = 1;
2687         long startTime = System.currentTimeMillis();
2688         // use SocketChannel.write(ByteBuffer) to try to write CAPACITY_HUGE bytes
2689         while (writtenTotalCount < CAPACITY_HUGE && writtenCount > 0) {
2690             writtenCount = channel1.write(writeContent);
2691             if (writtenCount == 0 && writtenTotalCount < CAPACITY_HUGE) {
2692                 assertEquals(0, channel1.write(writeContent));
2693                 break;
2694             }
2695             writtenTotalCount += writtenCount;
2696             // if the channel could not finish writing in TIMEOUT ms, the
2697             // test fails. It is used to guarantee the test never hangs even
2698             // if there are bugs of SocketChannel implementation.
2699             assertTimeout(startTime, TIMEOUT);
2700         }
2701     }
2702
2703     /*
2704      * Fails if the difference between current time and start time is greater
2705      * than timeout.
2706      */
2707     private void assertTimeout(long startTime, long timeout) {
2708         long currentTime = System.currentTimeMillis();
2709         if ((currentTime - startTime) > timeout) {
2710             fail("Timeout");
2711         }
2712     }
2713
2714     // -------------------------------------------------
2715     // Test for read/write but no real data expressed
2716     // -------------------------------------------------
2717     @TestTargetNew(
2718         level = TestLevel.PARTIAL_COMPLETE,
2719         notes = "Verifies ClosedChannelException",
2720         method = "read",
2721         args = {java.nio.ByteBuffer.class}
2722     )
2723     public void testReadByteBuffer() throws Exception {
2724         assertTrue(this.server1.isBound());
2725         java.nio.ByteBuffer readBuf = java.nio.ByteBuffer
2726                 .allocate(CAPACITY_NORMAL);
2727         assertFalse(this.channel1.isRegistered());
2728         assertTrue(this.channel1.isBlocking());
2729         assertFalse(this.channel1.isConnected());
2730         assertFalse(this.channel1.isConnectionPending());
2731         assertTrue(this.channel1.isOpen());
2732         // note: blocking-mode will make the read process endless!
2733         this.channel1.configureBlocking(false);
2734         try {
2735             channel1.read(readBuf);
2736             fail("Should throw NotYetConnectedException");
2737         } catch (NotYetConnectedException e) {
2738             // correct
2739         }
2740         this.channel1.connect(localAddr1);
2741         assertFalse(this.channel1.isBlocking());
2742         assertTrue(this.channel1.isConnectionPending());
2743         assertFalse(this.channel1.isConnected());
2744         assertTrue(tryFinish());
2745         assertEquals(0, this.channel1.read(readBuf));
2746
2747         this.channel1.close();
2748         try {
2749             channel1.read(readBuf);
2750             fail("Should throw ClosedChannelException");
2751         } catch (ClosedChannelException e) {
2752             // correct
2753         }
2754     }
2755
2756     @TestTargetNew(
2757         level = TestLevel.PARTIAL_COMPLETE,
2758         notes = "Verifies ClosedChannelException",
2759         method = "read",
2760         args = {java.nio.ByteBuffer.class}
2761     )
2762     public void testReadByteBuffer_Direct() throws Exception {
2763         assertTrue(this.server1.isBound());
2764         java.nio.ByteBuffer readBuf = java.nio.ByteBuffer
2765                 .allocateDirect(CAPACITY_NORMAL);
2766         assertFalse(this.channel1.isRegistered());
2767         assertTrue(this.channel1.isBlocking());
2768         assertFalse(this.channel1.isConnected());
2769         assertFalse(this.channel1.isConnectionPending());
2770         assertTrue(this.channel1.isOpen());
2771         // note: blocking-mode will make the read process endless!
2772         this.channel1.configureBlocking(false);
2773         try {
2774             channel1.read(readBuf);
2775             fail("Should throw NotYetConnectedException");
2776         } catch (NotYetConnectedException e) {
2777             // correct
2778         }
2779         this.channel1.connect(localAddr1);
2780         assertFalse(this.channel1.isBlocking());
2781         assertTrue(this.channel1.isConnectionPending());
2782         assertFalse(this.channel1.isConnected());
2783         assertTrue(tryFinish());
2784         assertEquals(0, this.channel1.read(readBuf));
2785
2786         this.channel1.close();
2787         try {
2788             channel1.read(readBuf);
2789             fail("Should throw ClosedChannelException");
2790         } catch (ClosedChannelException e) {
2791             // correct
2792         }
2793     }
2794
2795     @TestTargetNew(
2796         level = TestLevel.PARTIAL_COMPLETE,
2797         notes = "",
2798         method = "read",
2799         args = {java.nio.ByteBuffer.class}
2800     )
2801     public void testReadByteBuffer_BufNull() throws Exception {
2802         assertTrue(this.server1.isBound());
2803         java.nio.ByteBuffer readBuf = java.nio.ByteBuffer.allocate(0);
2804         // note: blocking-mode will make the read process endless!
2805         this.channel1.configureBlocking(false);
2806         try {
2807             channel1.read((java.nio.ByteBuffer) null);
2808             fail("Should throw NPE");
2809         } catch (NullPointerException e) {
2810             // correct
2811         }
2812         this.channel1.connect(localAddr1);
2813         assertTrue(tryFinish());
2814         try {
2815             this.channel1.read((java.nio.ByteBuffer) null);
2816             fail("Should throw NPE");
2817         } catch (NullPointerException e) {
2818             // correct
2819         }
2820         assertEquals(0, this.channel1.read(readBuf));
2821     }
2822
2823     /*
2824      * SocketChannelImpl.read(ByteBuffer[], int, int)'
2825      */
2826     @TestTargetNew(
2827         level = TestLevel.PARTIAL_COMPLETE,
2828         notes = "",
2829         method = "read",
2830         args = {java.nio.ByteBuffer[].class, int.class, int.class}
2831     )
2832     public void testReadByteBufferArrayIntInt() throws Exception {
2833         assertTrue(this.server1.isBound());
2834         java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[2];
2835         readBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
2836         readBuf[1] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
2837         assertFalse(this.channel1.isRegistered());
2838         assertTrue(this.channel1.isBlocking());
2839         assertFalse(this.channel1.isConnected());
2840         assertFalse(this.channel1.isConnectionPending());
2841         assertTrue(this.channel1.isOpen());
2842         // note: blocking-mode will make the read process endless!
2843         this.channel1.configureBlocking(false);
2844         try {
2845             channel1.read(readBuf, 0, 1);
2846             fail("Should throw NotYetConnectedException");
2847         } catch (NotYetConnectedException e) {
2848             // correct
2849         }
2850         this.channel1.connect(localAddr1);
2851         assertFalse(this.channel1.isBlocking());
2852         assertTrue(this.channel1.isConnectionPending());
2853         assertFalse(this.channel1.isConnected());
2854         assertTrue(tryFinish());
2855         assertEquals(0, this.channel1.read(readBuf, 0, 1));
2856         assertEquals(0, this.channel1.read(readBuf, 0, 2));
2857
2858         this.channel1.close();
2859         try {
2860             channel1.read(readBuf, 0, 1);
2861             fail("Should throw ClosedChannelException");
2862         } catch (ClosedChannelException e) {
2863             // correct
2864         }
2865     }
2866
2867     /*
2868      * SocketChannelImpl.read(ByteBuffer[], int, int)'
2869      */
2870     @TestTargetNew(
2871         level = TestLevel.PARTIAL_COMPLETE,
2872         notes = "",
2873         method = "read",
2874         args = {java.nio.ByteBuffer[].class, int.class, int.class}
2875     )    
2876     public void testReadByteBufferArrayIntInt_Direct() throws Exception {
2877         assertTrue(this.server1.isBound());
2878         java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[2];
2879         readBuf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
2880         readBuf[1] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
2881         assertFalse(this.channel1.isRegistered());
2882         assertTrue(this.channel1.isBlocking());
2883         assertFalse(this.channel1.isConnected());
2884         assertFalse(this.channel1.isConnectionPending());
2885         assertTrue(this.channel1.isOpen());
2886         // note: blocking-mode will make the read process endless!
2887         this.channel1.configureBlocking(false);
2888         try {
2889             channel1.read(readBuf, 0, 1);
2890             fail("Should throw NotYetConnectedException");
2891         } catch (NotYetConnectedException e) {
2892             // correct
2893         }
2894         this.channel1.connect(localAddr1);
2895         assertFalse(this.channel1.isBlocking());
2896         assertTrue(this.channel1.isConnectionPending());
2897         assertFalse(this.channel1.isConnected());
2898         assertTrue(tryFinish());
2899         assertEquals(0, this.channel1.read(readBuf, 0, 1));
2900         assertEquals(0, this.channel1.read(readBuf, 0, 2));
2901
2902         this.channel1.close();
2903         try {
2904             channel1.read(readBuf, 0, 1);
2905             fail("Should throw ClosedChannelException");
2906         } catch (ClosedChannelException e) {
2907             // correct
2908         }
2909     }
2910
2911     @TestTargetNew(
2912         level = TestLevel.PARTIAL_COMPLETE,
2913         notes = "",
2914         method = "read",
2915         args = {java.nio.ByteBuffer[].class, int.class, int.class}
2916     )
2917     public void testReadByteBufferArrayIntInt_BufNull() throws Exception {
2918         assertTrue(this.server1.isBound());
2919         java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[2];
2920         readBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
2921         assertFalse(this.channel1.isRegistered());
2922         assertTrue(this.channel1.isBlocking());
2923         assertFalse(this.channel1.isConnected());
2924         assertFalse(this.channel1.isConnectionPending());
2925         assertTrue(this.channel1.isOpen());
2926         // note: blocking-mode will make the read process endless!
2927         this.channel1.configureBlocking(false);
2928         try {
2929             channel1.read(null, 0, 0);
2930             fail("Should throw NPE");
2931         } catch (NullPointerException e) {
2932             // correct
2933         }
2934         this.channel1.connect(localAddr1);
2935         assertTrue(tryFinish());
2936
2937         try {
2938             channel1.read(null, 0, 0);
2939             fail("Should throw NPE");
2940         } catch (NullPointerException e) {
2941             // correct
2942         }
2943         try {
2944             channel1.read(readBuf, 0, 2);
2945             fail("Should throw NPE");
2946         } catch (NullPointerException e) {
2947             // correct
2948         }
2949
2950         assertEquals(0, this.channel1.read(readBuf, 0, 1));
2951
2952         this.channel1.close();
2953         try {
2954             channel1.read(null, 0, 1);
2955             fail("Should throw NPE");
2956         } catch (NullPointerException e) {
2957             // correct
2958         }
2959     }
2960
2961     @TestTargetNew(
2962         level = TestLevel.PARTIAL_COMPLETE,
2963         notes = "",
2964         method = "write",
2965         args = {java.nio.ByteBuffer.class}
2966     )
2967     public void testWriteByteBuffer() throws IOException {
2968         assertTrue(this.server1.isBound());
2969         java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer
2970                 .allocate(CAPACITY_NORMAL);
2971         assertFalse(this.channel1.isRegistered());
2972         assertTrue(this.channel1.isBlocking());
2973         assertFalse(this.channel1.isConnected());
2974         assertFalse(this.channel1.isConnectionPending());
2975         assertTrue(this.channel1.isOpen());
2976         try {
2977             channel1.write(writeBuf);
2978             fail("Should throw NotYetConnectedException");
2979         } catch (NotYetConnectedException e) {
2980             // correct
2981         }
2982         this.channel1.connect(localAddr1);
2983         assertTrue(this.channel1.isBlocking());
2984         assertTrue(this.channel1.isConnected());
2985         assertFalse(this.channel1.isConnectionPending());
2986         assertTrue(this.channel1.isOpen());
2987         assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf));
2988
2989         this.channel1.close();
2990         try {
2991             channel1.write(writeBuf);
2992             fail("Should throw ClosedChannelException");
2993         } catch (ClosedChannelException e) {
2994             // correct
2995         }
2996     }
2997
2998     @TestTargetNew(
2999         level = TestLevel.PARTIAL_COMPLETE,
3000         notes = "Doesn't verify AsynchronousCloseException, ClosedByInterruptException.",
3001         method = "write",
3002         args = {java.nio.ByteBuffer.class}
3003     )
3004     public void testWriteByteBuffer_Direct() throws IOException {
3005         assertTrue(this.server1.isBound());
3006         java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer
3007                 .allocateDirect(CAPACITY_NORMAL);
3008         assertFalse(this.channel1.isRegistered());
3009         assertTrue(this.channel1.isBlocking());
3010         assertFalse(this.channel1.isConnected());
3011         assertFalse(this.channel1.isConnectionPending());
3012         assertTrue(this.channel1.isOpen());
3013         try {
3014             channel1.write(writeBuf);
3015             fail("Should throw NotYetConnectedException");
3016         } catch (NotYetConnectedException e) {
3017             // correct
3018         }
3019         this.channel1.connect(localAddr1);
3020         assertTrue(this.channel1.isBlocking());
3021         assertTrue(this.channel1.isConnected());
3022         assertFalse(this.channel1.isConnectionPending());
3023         assertTrue(this.channel1.isOpen());
3024         assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf));
3025
3026         this.channel1.close();
3027         try {
3028             channel1.write(writeBuf);
3029             fail("Should throw ClosedChannelException");
3030         } catch (ClosedChannelException e) {
3031             // correct
3032         }
3033     }
3034
3035     @TestTargetNew(
3036         level = TestLevel.PARTIAL_COMPLETE,
3037         notes = "",
3038         method = "write",
3039         args = {java.nio.ByteBuffer.class}
3040     )
3041     public void testWriteByteBuffer_BufNull() throws IOException {
3042         assertTrue(this.server1.isBound());
3043         java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer.allocate(0);
3044         this.channel1.connect(localAddr1);
3045         assertEquals(this.channel1.write(writeBuf), 0);
3046         try {
3047             this.channel1.write((java.nio.ByteBuffer) null);
3048             fail("Should throw NPE");
3049         } catch (NullPointerException e) {
3050             // correct
3051         }
3052     }
3053
3054     /*
3055      * SocketChannelImpl.write(ByteBuffer[], int, int)'
3056      */
3057     @TestTargetNew(
3058         level = TestLevel.PARTIAL_COMPLETE,
3059         notes = "Doesn't verify AsynchronousCloseException," +
3060                 "ClosedByInterruptException.",
3061         method = "write",
3062         args = {java.nio.ByteBuffer[].class, int.class, int.class}
3063     )
3064     public void testWriteByteBufferArrayIntInt() throws IOException {
3065         java.nio.ByteBuffer[] writeBuf = new java.nio.ByteBuffer[2];
3066         writeBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
3067         writeBuf[1] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
3068         assertFalse(this.channel1.isRegistered());
3069         assertTrue(this.channel1.isBlocking());
3070         assertFalse(this.channel1.isConnected());
3071         assertFalse(this.channel1.isConnectionPending());
3072         assertTrue(this.channel1.isOpen());
3073         try {
3074             channel1.write(writeBuf, 0, 1);
3075             fail("Should throw NotYetConnectedException");
3076         } catch (NotYetConnectedException e) {
3077             // correct
3078         }
3079         this.channel1.connect(localAddr1);
3080         assertTrue(this.channel1.isBlocking());
3081         assertTrue(this.channel1.isConnected());
3082         assertFalse(this.channel1.isConnectionPending());
3083         assertTrue(this.channel1.isOpen());
3084         assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 1));
3085         // still writes the same size as above
3086         assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 2));
3087         writeBuf[0].flip();
3088         writeBuf[1].flip();
3089         assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2));
3090         this.channel1.close();
3091         try {
3092             channel1.write(writeBuf, 0, 1);
3093             fail("Should throw ClosedChannelException");
3094         } catch (ClosedChannelException e) {
3095             // correct
3096         }
3097     }
3098
3099     /*
3100      * SocketChannelImpl.write(ByteBuffer[], int, int)'
3101      */
3102     @TestTargetNew(
3103         level = TestLevel.PARTIAL_COMPLETE,
3104         notes = "",
3105         method = "write",
3106         args = {java.nio.ByteBuffer[].class, int.class, int.class}
3107     )
3108     public void testWriteByteBufferArrayIntInt_Direct() throws IOException {
3109         java.nio.ByteBuffer[] writeBuf = new java.nio.ByteBuffer[2];
3110         writeBuf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3111         writeBuf[1] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3112         assertFalse(this.channel1.isRegistered());
3113         assertTrue(this.channel1.isBlocking());
3114         assertFalse(this.channel1.isConnected());
3115         assertFalse(this.channel1.isConnectionPending());
3116         assertTrue(this.channel1.isOpen());
3117         try {
3118             channel1.write(writeBuf, 0, 1);
3119             fail("Should throw NotYetConnectedException");
3120         } catch (NotYetConnectedException e) {
3121             // correct
3122         }
3123         this.channel1.connect(localAddr1);
3124         assertTrue(this.channel1.isBlocking());
3125         assertTrue(this.channel1.isConnected());
3126         assertFalse(this.channel1.isConnectionPending());
3127         assertTrue(this.channel1.isOpen());
3128         assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 1));
3129         // still writes the same size as above
3130         assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 2));
3131         writeBuf[0].flip();
3132         writeBuf[1].flip();
3133         assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2));
3134         this.channel1.close();
3135         try {
3136             channel1.write(writeBuf, 0 ,1);
3137             fail("Should throw ClosedChannelException");
3138         } catch (ClosedChannelException e) {
3139             // correct
3140         }
3141     }
3142
3143     @TestTargetNew(
3144         level = TestLevel.PARTIAL_COMPLETE,
3145         notes = "",
3146         method = "write",
3147         args = {java.nio.ByteBuffer[].class, int.class, int.class}
3148     )
3149     public void testWriteByteBufferArrayIntInt_BufNull() throws IOException {
3150         java.nio.ByteBuffer[] writeBuf = new java.nio.ByteBuffer[0];
3151
3152         this.channel1.connect(localAddr1);
3153         try {
3154             this.channel1.write(null, 0, 1);
3155             fail("Should throw NPE");
3156         } catch (NullPointerException e) {
3157             // correct
3158         }
3159         assertEquals(0, this.channel1.write(writeBuf, 0, 0));
3160         try {
3161             this.channel1.write(writeBuf, 0, 1);
3162             fail("Should throw IndexOutOfBoundsException");
3163         } catch (IndexOutOfBoundsException e) {
3164             // correct
3165         }
3166         writeBuf = new java.nio.ByteBuffer[1];
3167         try {
3168             this.channel1.write(writeBuf, 0, 1);
3169             fail("Should throw NPE");
3170         } catch (NullPointerException e) {
3171             // correct
3172         }
3173         writeBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
3174         try {
3175             this.channel1.write(writeBuf, 0, 2);
3176             fail("Should throw IndexOutOfBoundsException");
3177         } catch (IndexOutOfBoundsException e) {
3178             // correct
3179         }
3180         this.server1.close();
3181         try {
3182             channel1.read(null, 0, 1);
3183             fail("Should throw NPE");
3184         } catch (NullPointerException e) {
3185             // correct
3186         }
3187     }
3188
3189     @TestTargetNew(
3190         level = TestLevel.PARTIAL_COMPLETE,
3191         notes = "Verifies IndexOutOfBoundsException.",
3192         method = "write",
3193         args = {java.nio.ByteBuffer[].class, int.class, int.class}
3194     )
3195     public void testWriteByteBufferArrayIntInt_SizeError() throws IOException {
3196         java.nio.ByteBuffer[] writeBuf = 
3197                 {java.nio.ByteBuffer.allocate(CAPACITY_NORMAL)};
3198
3199         this.channel1.connect(localAddr1);
3200         try {
3201             this.channel1.write(writeBuf, -1, 1);
3202             fail("Should throw IndexOutOfBoundsException");
3203         } catch (IndexOutOfBoundsException e) {
3204             // correct
3205         }
3206         assertEquals(0, this.channel1.write(writeBuf, 0, 0));
3207         try {
3208             this.channel1.write(writeBuf, 0, -1);
3209             fail("Should throw IndexOutOfBoundsException");
3210         } catch (IndexOutOfBoundsException e) {
3211             // correct
3212         }
3213         try {
3214             this.channel1.write(writeBuf, 1, 1);
3215             fail("Should throw IndexOutOfBoundsException");
3216         } catch (IndexOutOfBoundsException e) {
3217             // correct
3218         }
3219         try {
3220             this.channel1.write(writeBuf, 0, 2);
3221             fail("Should throw IndexOutOfBoundsException");
3222         } catch (IndexOutOfBoundsException e) {
3223             // correct
3224         }
3225     }
3226
3227     @TestTargetNew(
3228         level = TestLevel.PARTIAL_COMPLETE,
3229         notes = "",
3230         method = "read",
3231         args = {java.nio.ByteBuffer[].class, int.class, int.class}
3232     )
3233     public void testReadByteBufferArrayIntInt_SizeError() throws IOException {
3234         java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[0];
3235
3236         this.channel1.connect(localAddr1);
3237         try {
3238             this.channel1.read(null, -1, 1);
3239             fail("Should throw IndexOutOfBoundsException");
3240         } catch (IndexOutOfBoundsException e) {
3241             // correct
3242         }
3243         assertEquals(0, this.channel1.read(readBuf, 0, 0));
3244         try {
3245             this.channel1.read(readBuf, 0, -1);
3246             fail("Should throw IndexOutOfBoundsException");
3247         } catch (IndexOutOfBoundsException e) {
3248             // correct
3249         }
3250         readBuf = new java.nio.ByteBuffer[1];
3251         try {
3252             this.channel1.read(readBuf, 2, 1);
3253             fail("Should throw IndexOutOfBoundsException");
3254         } catch (IndexOutOfBoundsException e) {
3255             // correct
3256         }
3257         try {
3258             this.channel1.read(readBuf, 2, -1);
3259             fail("Should throw IndexOutOfBoundsException");
3260         } catch (IndexOutOfBoundsException e) {
3261             // correct
3262         }
3263         this.server1.close();
3264         try {
3265             assertEquals(CAPACITY_NORMAL, this.channel1.read(null, -1, -1));
3266             fail("Should throw IndexOutOfBoundsException");
3267         } catch (IndexOutOfBoundsException e) {
3268             // correct
3269         }
3270     }
3271
3272     /*
3273      * ==========================================================================
3274      * Tests for read/write real data
3275      * ==========================================================================
3276      */
3277
3278     /**
3279      * @tests java.nio.channels.SocketChannel#read(ByteBuffer[],int,int)
3280      */
3281     @TestTargetNew(
3282         level = TestLevel.PARTIAL_COMPLETE,
3283         notes = "",
3284         method = "read",
3285         args = {java.nio.ByteBuffer[].class}
3286     ) 
3287     public void test_read$LByteBuffer_blocking() throws Exception {
3288         assert_read$LByteBuffer(true);
3289     }
3290
3291     /**
3292      * @tests java.nio.channels.SocketChannel#read(ByteBuffer[],int,int)
3293      */
3294     @TestTargetNew(
3295         level = TestLevel.PARTIAL_COMPLETE,
3296         notes = "",
3297         method = "read",
3298         args = {java.nio.ByteBuffer[].class}
3299     ) 
3300     public void test_read$LByteBuffer_nonblocking() throws Exception {
3301         assert_read$LByteBuffer(false);
3302     }
3303
3304     private void assert_read$LByteBuffer(boolean isBlocking) throws IOException {
3305         // initialize write content
3306         byte[] writeContent = new byte[CAPACITY_NORMAL * 2];
3307         for (int i = 0; i < CAPACITY_NORMAL * 2; i++) {
3308             writeContent[i] = (byte) i;
3309         }
3310         ByteBuffer[] readContents = new ByteBuffer[2];
3311         readContents[0] = ByteBuffer.allocate(CAPACITY_NORMAL);
3312         readContents[1] = ByteBuffer.allocate(CAPACITY_NORMAL + 1);
3313         // establish connection
3314         channel1.connect(localAddr1);
3315         Socket acceptedSocket = server1.accept();
3316         // use OutputStream.write to send CAPACITY_NORMAL * 2 bytes data
3317         OutputStream out = acceptedSocket.getOutputStream();
3318         out.write(writeContent);
3319         // use close to guarantee all data is sent
3320         acceptedSocket.close();
3321         // configure block/nonblock mode
3322         channel1.configureBlocking(isBlocking);
3323         long startTime = System.currentTimeMillis();
3324         long totalRead = 0;
3325         long countRead = 0;
3326
3327         while (totalRead <= CAPACITY_NORMAL * 2) {
3328             countRead = channel1.read(readContents);
3329             if (0 == countRead && !readContents[1].hasRemaining()) {
3330                 // read returns 0 because readContents is full
3331                 break;
3332             }
3333             if (EOF == countRead) {
3334                 break;
3335             }
3336             totalRead += countRead;
3337             // if the channel could not finish reading in TIMEOUT ms, the
3338             // test fails. It is used to guarantee the test never hangs even
3339             // if there are bugs of SocketChannel implementation. For
3340             // blocking read, it possibly returns 0 in some cases.
3341             assertTimeout(startTime, TIMEOUT);
3342         }
3343
3344         // assert total bytes read and the position of ByteBuffers
3345         assertEquals(CAPACITY_NORMAL * 2, totalRead);
3346         assertEquals(CAPACITY_NORMAL, readContents[0].position());
3347         assertEquals(CAPACITY_NORMAL, readContents[1].position());
3348         // assert read content
3349         readContents[0].flip();
3350         readContents[1].flip();
3351         for (int i = 0; i < CAPACITY_NORMAL; i++) {
3352             assertEquals(writeContent[i], readContents[0].get());
3353         }
3354         for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) {
3355             assertEquals(writeContent[i], readContents[1].get());
3356         }
3357     }
3358
3359     /**
3360      * @tests java.nio.channels.SocketChannel#read(ByteBuffer[],int,int)
3361      */
3362     @TestTargetNew(
3363         level = TestLevel.PARTIAL_COMPLETE,
3364         notes = "",
3365         method = "read",
3366         args = {java.nio.ByteBuffer[].class, int.class, int.class}
3367     ) 
3368     public void test_read$LByteBufferII_blocking() throws Exception {
3369         assert_read$LByteBufferII(true);
3370     }
3371
3372     /**
3373      * @tests java.nio.channels.SocketChannel#read(ByteBuffer[],int,int)
3374      */
3375     @TestTargetNew(
3376         level = TestLevel.PARTIAL_COMPLETE,
3377         notes = "",
3378         method = "read",
3379         args = {java.nio.ByteBuffer[].class, int.class, int.class}
3380     ) 
3381     public void test_read$LByteBufferII_nonblocking() throws Exception {
3382         assert_read$LByteBufferII(false);
3383     }
3384
3385     private void assert_read$LByteBufferII(boolean isBlocking) throws IOException {
3386         // initialize write content
3387         byte[] writeContent = new byte[CAPACITY_NORMAL * 2];
3388         for (int i = 0; i < CAPACITY_NORMAL * 2; i++) {
3389             writeContent[i] = (byte) i;
3390         }
3391         ByteBuffer[] readContents = new ByteBuffer[2];
3392         readContents[0] = ByteBuffer.allocate(CAPACITY_NORMAL);
3393         readContents[1] = ByteBuffer.allocate(CAPACITY_NORMAL + 1);
3394         // establish connection
3395         channel1.connect(localAddr1);
3396         Socket acceptedSocket = server1.accept();
3397         // use OutputStream.write to send CAPACITY_NORMAL * 2 bytes data
3398         OutputStream out = acceptedSocket.getOutputStream();
3399         out.write(writeContent);
3400         // use close to guarantee all data is sent
3401         acceptedSocket.close();
3402         // configure block/nonblock mode
3403         channel1.configureBlocking(isBlocking);
3404         long startTime = System.currentTimeMillis();
3405         long totalRead = 0;
3406         long countRead = 0;
3407
3408         while (totalRead <= CAPACITY_NORMAL * 2) {
3409             countRead = channel1.read(readContents, 0, 2);
3410             if (0 == countRead && !readContents[1].hasRemaining()) {
3411                 // read returns 0 because readContents is full
3412                 break;
3413             }
3414             if (EOF == countRead) {
3415                 break;
3416             }
3417             totalRead += countRead;
3418             // if the channel could not finish reading in TIMEOUT ms, the
3419             // test fails. It is used to guarantee the test never hangs even
3420             // if there are bugs of SocketChannel implementation. For
3421             // blocking read, it possibly returns 0 in some cases.
3422             assertTimeout(startTime, TIMEOUT);
3423         }
3424
3425         // assert total bytes read and the position of ByteBuffers
3426         assertEquals(CAPACITY_NORMAL * 2, totalRead);
3427         assertEquals(CAPACITY_NORMAL, readContents[0].position());
3428         assertEquals(CAPACITY_NORMAL, readContents[1].position());
3429         // assert read content
3430         readContents[0].flip();
3431         readContents[1].flip();
3432         for (int i = 0; i < CAPACITY_NORMAL; i++) {
3433             assertEquals(writeContent[i], readContents[0].get());
3434         }
3435         for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) {
3436             assertEquals(writeContent[i], readContents[1].get());
3437         }
3438     }
3439
3440     /**
3441      * @tests java.nio.channels.SocketChannel#write(ByteBuffer[],int,int)
3442      */
3443     @TestTargetNew(
3444         level = TestLevel.PARTIAL_COMPLETE,
3445         notes = "",
3446         method = "write",
3447         args = {java.nio.ByteBuffer[].class}
3448     )
3449     public void test_write$LByteBuffer_blocking() throws Exception {
3450         assert_write$LByteBuffer(true);
3451     }
3452
3453     /**
3454      * @tests java.nio.channels.SocketChannel#write(ByteBuffer[],int,int)
3455      */
3456     @TestTargetNew(
3457         level = TestLevel.PARTIAL_COMPLETE,
3458         notes = "",
3459         method = "write",
3460         args = {java.nio.ByteBuffer[].class}
3461     )
3462     public void test_write$LByteBuffer_nonblocking() throws Exception {
3463         assert_write$LByteBuffer(false);
3464     }
3465
3466     private void assert_write$LByteBuffer(boolean isBlocking)
3467             throws IOException {
3468         // initialize write contents
3469         ByteBuffer writeContents[] = new ByteBuffer[2];
3470         writeContents[0] = ByteBuffer.allocate(CAPACITY_NORMAL);
3471         writeContents[1] = ByteBuffer.allocate(CAPACITY_NORMAL);
3472         for (int i = 0; i < CAPACITY_NORMAL; i++) {
3473             writeContents[0].put((byte) i);
3474         }
3475         for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) {
3476             writeContents[1].put((byte) i);
3477         }
3478         writeContents[0].flip();
3479         writeContents[1].flip();
3480         // establish connection
3481         channel1.connect(localAddr1);
3482         Socket acceptedSocket = server1.accept();
3483         // set blocking/nonblocking mode
3484         channel1.configureBlocking(isBlocking);
3485
3486         assertEquals(2 * CAPACITY_NORMAL, channel1.write(writeContents));
3487
3488         // assert written count and ByteBuffer position
3489         assertEquals(CAPACITY_NORMAL, writeContents[0].position());
3490         assertEquals(CAPACITY_NORMAL, writeContents[1].position());
3491         // use close to guarantee all data is sent
3492         channel1.close();
3493         InputStream in = acceptedSocket.getInputStream();
3494         byte[] readContent = new byte[CAPACITY_NORMAL * 2 + 1];
3495         int totalCount = 0;
3496         int count = 0;
3497         // if the channel could not finish reading in TIMEOUT ms, the test
3498         // fails. It is used to guarantee the test never hangs even if there
3499         // are bugs of SocketChannel implementation.
3500         acceptedSocket.setSoTimeout(TIMEOUT);
3501         // use InputStream.read to read data.
3502         while (totalCount <= CAPACITY_NORMAL) {
3503             count = in.read(readContent, totalCount, readContent.length
3504                     - totalCount);
3505             if (EOF == count) {
3506                 break;
3507             }
3508             totalCount += count;
3509         }
3510         // assert read content
3511         assertEquals(CAPACITY_NORMAL * 2, totalCount);
3512         writeContents[0].flip();
3513         writeContents[1].flip();
3514         for (int i = 0; i < CAPACITY_NORMAL; i++) {
3515             assertEquals(writeContents[0].get(), readContent[i]);
3516         }
3517         for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) {
3518             assertEquals(writeContents[1].get(), readContent[i]);
3519         }
3520     }
3521
3522     /**
3523      * @tests java.nio.channels.SocketChannel#write(ByteBuffer[],int,int)
3524      */
3525     @TestTargetNew(
3526         level = TestLevel.PARTIAL_COMPLETE,
3527         notes = "",
3528         method = "write",
3529         args = {java.nio.ByteBuffer[].class, int.class, int.class}
3530     )
3531     public void test_write$LByteBufferII_blocking() throws Exception {
3532         assert_write$LByteBufferII(true);
3533     }
3534
3535     /**
3536      * @tests java.nio.channels.SocketChannel#write(ByteBuffer[],int,int)
3537      */
3538     @TestTargetNew(
3539         level = TestLevel.PARTIAL_COMPLETE,
3540         notes = "",
3541         method = "write",
3542         args = {java.nio.ByteBuffer[].class, int.class, int.class}
3543     )
3544     public void test_write$LByteBufferII_nonblocking() throws Exception {
3545         assert_write$LByteBufferII(false);
3546     }
3547
3548     private void assert_write$LByteBufferII(boolean isBlocking)
3549             throws IOException {
3550         // initialize write contents
3551         ByteBuffer writeContents[] = new ByteBuffer[2];
3552         writeContents[0] = ByteBuffer.allocate(CAPACITY_NORMAL);
3553         writeContents[1] = ByteBuffer.allocate(CAPACITY_NORMAL);
3554         for (int i = 0; i < CAPACITY_NORMAL; i++) {
3555             writeContents[0].put((byte) i);
3556         }
3557         for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) {
3558             writeContents[1].put((byte) i);
3559         }
3560         writeContents[0].flip();
3561         writeContents[1].flip();
3562         // establish connection
3563         channel1.connect(localAddr1);
3564         Socket acceptedSocket = server1.accept();
3565         // set blocking/nonblocking mode
3566         channel1.configureBlocking(isBlocking);
3567
3568         assertEquals(CAPACITY_NORMAL, channel1.write(writeContents, 0, 1));
3569         assertEquals(CAPACITY_NORMAL, channel1.write(writeContents, 1, 1));
3570
3571         // assert written count and ByteBuffer position
3572         assertEquals(CAPACITY_NORMAL, writeContents[0].position());
3573         assertEquals(CAPACITY_NORMAL, writeContents[1].position());
3574         // use close to guarantee all data is sent
3575         channel1.close();
3576         InputStream in = acceptedSocket.getInputStream();
3577         byte[] readContent = new byte[CAPACITY_NORMAL * 2 + 1];
3578         int totalCount = 0;
3579         int count = 0;
3580         // if the channel could not finish reading in TIMEOUT ms, the test
3581         // fails. It is used to guarantee the test never hangs even if there
3582         // are bugs of SocketChannel implementation.
3583         acceptedSocket.setSoTimeout(TIMEOUT);
3584         // use InputStream.read to read data.
3585         while (totalCount <= CAPACITY_NORMAL) {
3586             count = in.read(readContent, totalCount, readContent.length
3587                     - totalCount);
3588             if (EOF == count) {
3589                 break;
3590             }
3591             totalCount += count;
3592         }
3593         // assert read content
3594         assertEquals(CAPACITY_NORMAL * 2, totalCount);
3595         writeContents[0].flip();
3596         writeContents[1].flip();
3597         for (int i = 0; i < CAPACITY_NORMAL; i++) {
3598             assertEquals(writeContents[0].get(), readContent[i]);
3599         }
3600         for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) {
3601             assertEquals(writeContents[1].get(), readContent[i]);
3602         }
3603     }
3604
3605     @TestTargets({
3606         @TestTargetNew(
3607             level = TestLevel.PARTIAL_COMPLETE,
3608             notes = "",
3609             method = "socket",
3610             args = {}
3611         ),
3612         @TestTargetNew(
3613             level = TestLevel.PARTIAL_COMPLETE,
3614             notes = "",
3615             clazz = SelectableChannel.class,
3616             method = "configureBlocking",
3617             args = {boolean.class}
3618         )
3619     })
3620     public void testSocket_configureblocking() throws IOException {
3621         byte[] serverWBuf = new byte[CAPACITY_NORMAL];
3622         for (int i = 0; i < serverWBuf.length; i++) {
3623             serverWBuf[i] = (byte) i;
3624         }
3625         java.nio.ByteBuffer buf = java.nio.ByteBuffer
3626                 .allocate(CAPACITY_NORMAL + 1);
3627         channel1.connect(localAddr1);
3628         server1.accept();
3629         Socket sock = this.channel1.socket();
3630         channel1.configureBlocking(false);
3631         assertFalse(channel1.isBlocking());
3632         OutputStream channelSocketOut = sock.getOutputStream();
3633         try {
3634             // write operation is not allowed in non-blocking mode
3635             channelSocketOut.write(buf.array());
3636             fail("Non-Blocking mode should cause IllegalBlockingModeException");
3637         } catch (IllegalBlockingModeException e) {
3638             // correct
3639         }
3640         channel1.configureBlocking(true);
3641         assertTrue(channel1.isBlocking());
3642         // write operation is allowed in blocking mode
3643         channelSocketOut.write(buf.array());
3644     }
3645
3646     /**
3647      * @tests SocketChannel#read(ByteBuffer[], int, int) when remote server
3648      *        closed
3649      */
3650     @TestTargetNew(
3651         level = TestLevel.PARTIAL_COMPLETE,
3652         notes = "",
3653         method = "read",
3654         args = {java.nio.ByteBuffer[].class, int.class, int.class}
3655     )
3656     public void test_socketChannel_read_ByteBufferII_remoteClosed()
3657             throws Exception {
3658         // regression 1 for HARMONY-549
3659         ServerSocketChannel ssc = ServerSocketChannel.open();
3660         ssc.socket().bind(localAddr2);
3661         SocketChannel sc = SocketChannel.open();
3662         sc.connect(localAddr2);
3663         ssc.accept().close();
3664         ByteBuffer[] buf = {ByteBuffer.allocate(10)};
3665         assertEquals(-1, sc.read(buf, 0, 1));
3666         ssc.close();
3667         sc.close();
3668     }
3669
3670     /**
3671      * @tests SocketChannel#write(ByteBuffer[], int, int)
3672      */
3673     @TestTargetNew(
3674         level = TestLevel.PARTIAL_COMPLETE,
3675         notes = "",
3676         method = "write",
3677         args = {java.nio.ByteBuffer[].class, int.class, int.class}
3678     )
3679     public void test_socketChannel_write_ByteBufferII() throws Exception {
3680         // regression 2 for HARMONY-549
3681         ServerSocketChannel ssc = ServerSocketChannel.open();
3682         ssc.socket().bind(localAddr2);
3683         SocketChannel sc = SocketChannel.open();
3684         sc.connect(localAddr2);
3685         SocketChannel sock = ssc.accept();
3686         ByteBuffer[] buf = {ByteBuffer.allocate(10), null};
3687         try {
3688             sc.write(buf, 0, 2);
3689             fail("should throw NPE");
3690         } catch (NullPointerException e) {
3691             // expected
3692         }
3693         ssc.close();
3694         sc.close();
3695         ByteBuffer target = ByteBuffer.allocate(10);
3696         assertEquals(-1, sock.read(target));
3697     }
3698
3699     /**
3700      * @tests SocketChannel#read(ByteBuffer[], int, int) with a null ByteBuffer
3701      */
3702     @TestTargetNew(
3703         level = TestLevel.PARTIAL_COMPLETE,
3704         notes = "",
3705         method = "read",
3706         args = {java.nio.ByteBuffer[].class, int.class, int.class}
3707     )
3708     public void test_socketChannel_read_ByteBufferII_bufNULL() throws Exception {
3709         // regression 3 for HARMONY-549
3710         ServerSocketChannel ssc = ServerSocketChannel.open();
3711         ssc.socket().bind(localAddr2);
3712         SocketChannel sc = SocketChannel.open();
3713         sc.connect(localAddr2);
3714         ssc.accept();
3715         ByteBuffer[] buf = new ByteBuffer[2];
3716         buf[0] = ByteBuffer.allocate(1);
3717         // let buf[1] be null
3718         try {
3719             sc.read(buf, 0, 2);
3720             fail("should throw NullPointerException");
3721         } catch (NullPointerException e) {
3722             // expected
3723         }
3724         ssc.close();
3725         sc.close();
3726     }
3727
3728     /**
3729      * @tests SocketChannel#write(ByteBuffer) after close
3730      */
3731     @TestTargetNew(
3732         level = TestLevel.PARTIAL_COMPLETE,
3733         notes = "",
3734         method = "write",
3735         args = {java.nio.ByteBuffer.class}
3736     )
3737     public void test_socketChannel_write_close() throws Exception {
3738         // regression 4 for HARMONY-549
3739         ServerSocketChannel ssc = ServerSocketChannel.open();
3740         ssc.socket().bind(localAddr2);
3741         SocketChannel sc = SocketChannel.open();
3742         sc.connect(localAddr2);
3743         SocketChannel sock = ssc.accept();
3744         ByteBuffer buf = null;
3745         ssc.close();
3746         sc.close();
3747         try {
3748             sc.write(buf);
3749             fail("should throw NPE");
3750         } catch (NullPointerException e) {
3751             // expected
3752         }
3753         sock.close();
3754     }
3755
3756     /**
3757      * @tests SocketChannel#write(ByteBuffer) if position is not zero
3758      */
3759     @TestTargetNew(
3760         level = TestLevel.PARTIAL_COMPLETE,
3761         notes = "",
3762         method = "write",
3763         args = {java.nio.ByteBuffer.class}
3764     )
3765     public void test_socketChannel_write_ByteBuffer_posNotZero()
3766             throws Exception {
3767         // regression 5 for HARMONY-549
3768         final String testStr = "Hello World";
3769         ByteBuffer readBuf = ByteBuffer.allocate(11);
3770         ByteBuffer buf = ByteBuffer.wrap(testStr.getBytes());
3771         ServerSocketChannel ssc = ServerSocketChannel.open();
3772         ssc.socket().bind(localAddr2);
3773         SocketChannel sc = SocketChannel.open();
3774         sc.connect(localAddr2);
3775         buf.position(2);
3776         ssc.accept().write(buf);
3777         assertEquals(9, sc.read(readBuf));
3778         buf.flip();
3779         readBuf.flip();
3780         byte[] read = new byte[9];
3781         byte[] write = new byte[11];
3782         buf.get(write);
3783         readBuf.get(read);
3784         for (int i = 0; i < 9; i++) {
3785             assertEquals(read[i], write[i + 2]);
3786         }
3787     }
3788
3789     /**
3790      * @tests SocketChannelImpl#read(ByteBuffer[])
3791      */
3792     @TestTargetNew(
3793         level = TestLevel.PARTIAL_COMPLETE,
3794         notes = "Doesn't verify exceptions.",
3795         method = "read",
3796         args = {java.nio.ByteBuffer[].class}
3797     ) 
3798     public void test_read$LByteBuffer_Blocking() throws IOException {
3799         // regression test for Harmony-728
3800         byte[] data = new byte[CAPACITY_NORMAL];
3801         for (int i = 0; i < CAPACITY_NORMAL; i++) {
3802             data[i] = (byte) i;
3803         }
3804         ByteBuffer[] buf = new ByteBuffer[2];
3805         buf[0] = ByteBuffer.allocate(CAPACITY_NORMAL);
3806         buf[1] = ByteBuffer.allocate(CAPACITY_NORMAL);
3807         channel1.connect(localAddr1);
3808         Socket socket = null;
3809         try {
3810             socket = server1.accept();
3811             OutputStream out = socket.getOutputStream();
3812             out.write(data);
3813             // should not block here
3814             channel1.read(buf);
3815         } finally {
3816             if (null != socket) {
3817                 socket.close();
3818             } else {
3819                 fail();
3820             }
3821         }
3822     }
3823
3824     /**
3825      * @tests SocketChannelImpl#socket().getOutputStream().read
3826      */
3827     @TestTargetNew(
3828         level = TestLevel.PARTIAL_COMPLETE,
3829         notes = "Verifies IllegalBlockingModeException, NullPointerException.",
3830         method = "socket",
3831         args = {}
3832     )
3833     public void test_socket_getOutputStream_nonBlocking_read_Exception()
3834             throws IOException {
3835         channel1.connect(this.localAddr1);
3836         InputStream is = channel1.socket().getInputStream();
3837         channel1.configureBlocking(false);
3838         try {
3839             is.read();
3840             fail("should throw IllegalBlockingModeException");
3841         } catch (IllegalBlockingModeException e) {
3842             // expected
3843         }
3844         try {
3845             is.read(null, 1, 1);
3846             fail("should throw NullPointerException");
3847         } catch (NullPointerException e) {
3848             // expected
3849         }
3850         try {
3851             is.read(null, -1, 1);
3852             fail("should throw IndexOutOfBoundsException");
3853         } catch (IndexOutOfBoundsException e) {
3854             // expected
3855         }
3856         // closed
3857         is.close();
3858         try {
3859             is.read(null);
3860             fail("should throw NullPointerException");
3861         } catch (NullPointerException e) {
3862             // expected
3863         }
3864         try {
3865             is.read();
3866             fail("should throw IllegalBlockingModeException");
3867         } catch (IllegalBlockingModeException e) {
3868             // expected
3869         }
3870         try {
3871             is.read(null, 1, 1);
3872             fail("should throw NullPointerException");
3873         } catch (NullPointerException e) {
3874             // expected
3875         }
3876         try {
3877             is.read(null, -1, 1);
3878             fail("should throw IndexOutOfBoundsException");
3879         } catch (IndexOutOfBoundsException e) {
3880             // expected
3881         }
3882     }
3883
3884     /**
3885      * @tests SocketChannelImpl#socket().getOutputStream().read
3886      */
3887     @TestTargetNew(
3888         level = TestLevel.PARTIAL_COMPLETE,
3889         notes = "Verifies NullPointerException, ClosedChannelException, IndexOutOfBoundsException.",
3890         method = "socket",
3891         args = {}
3892     )
3893     public void test_socket_getOutputStream_blocking_read_Exception()
3894             throws IOException {
3895         channel1.connect(this.localAddr1);
3896         InputStream is = channel1.socket().getInputStream();
3897         try {
3898             is.read(null);
3899             fail("should throw NullPointerException");
3900         } catch (NullPointerException e) {
3901             // expected
3902         }
3903         try {
3904             is.read(null, 1, 1);
3905             fail("should throw NullPointerException");
3906         } catch (NullPointerException e) {
3907             // expected
3908         }
3909         try {
3910             is.read(null, -1, 1);
3911             fail("should throw IndexOutOfBoundsException");
3912         } catch (IndexOutOfBoundsException e) {
3913             // expected
3914         }
3915         // closed
3916         is.close();
3917         try {
3918             is.read(null);
3919             fail("should throw NullPointerException");
3920         } catch (NullPointerException e) {
3921             // expected
3922         }
3923         try {
3924             is.read();
3925             fail("should throw ClosedChannelException");
3926         } catch (ClosedChannelException e) {
3927             // expected
3928         }
3929         try {
3930             is.read(null, 1, 1);
3931             fail("should throw NullPointerException");
3932         } catch (NullPointerException e) {
3933             // expected
3934         }
3935         try {
3936             is.read(null, -1, 1);
3937             fail("should throw IndexOutOfBoundsException");
3938         } catch (IndexOutOfBoundsException e) {
3939             // expected
3940         }
3941     }
3942
3943     /**
3944      * @tests SocketChannelImpl#socket().getOutputStream().write
3945      */
3946     @TestTargetNew(
3947         level = TestLevel.PARTIAL_COMPLETE,
3948         notes = "Verifies NullPointerException, IllegalBlockingModeException.",
3949         method = "socket",
3950         args = {}
3951     )
3952     public void test_socket_getOutputStream_nonBlocking_write_Exception()
3953             throws IOException {
3954         channel1.connect(this.localAddr1);
3955         OutputStream os = channel1.socket().getOutputStream();
3956         channel1.configureBlocking(false);
3957         try {
3958             os.write(null);
3959             fail("should throw NullPointerException");
3960         } catch (NullPointerException e) {
3961             // expected
3962         }
3963         try {
3964             os.write(1);
3965             fail("should throw IllegalBlockingModeException");
3966         } catch (IllegalBlockingModeException e) {
3967             // expected
3968         }
3969         try {
3970             os.write(1);
3971             fail("should throw IllegalBlockingModeException");
3972         } catch (IllegalBlockingModeException e) {
3973             // expected
3974         }
3975         try {
3976             os.write(null, 1, 1);
3977             fail("should throw NullPointerException");
3978         } catch (NullPointerException e) {
3979             // expected
3980         }
3981         try {
3982             os.write(null, -1, 1);
3983             fail("should throw IndexOutOfBoundsException");
3984         } catch (IndexOutOfBoundsException e) {
3985             // expected
3986         }
3987         // closed
3988         os.close();
3989         try {
3990             os.write(null);
3991             fail("should throw NullPointerException");
3992         } catch (NullPointerException e) {
3993             // expected
3994         }
3995         try {
3996             os.write(1);
3997             fail("should throw IllegalBlockingModeException");
3998         } catch (IllegalBlockingModeException e) {
3999             // expected
4000         }
4001         try {
4002             os.write(null, 1, 1);
4003             fail("should throw NullPointerException");
4004         } catch (NullPointerException e) {
4005             // expected
4006         }
4007         try {
4008             os.write(null, -1, 1);
4009             fail("should throw IndexOutOfBoundsException");
4010         } catch (IndexOutOfBoundsException e) {
4011             // expected
4012         }
4013     }
4014
4015     /**
4016      * @tests SocketChannelImpl#socket().getOutputStream().write
4017      */
4018     @TestTargetNew(
4019         level = TestLevel.PARTIAL_COMPLETE,
4020         notes = "Verifies NullPointerException, IndexOutOfBoundsException, ClosedChannelException.",
4021         method = "socket",
4022         args = {}
4023     )
4024     public void test_socket_getOutputStream_blocking_write_Exception()
4025             throws IOException {
4026         channel1.connect(this.localAddr1);
4027         OutputStream os = channel1.socket().getOutputStream();
4028         try {
4029             os.write(null);
4030             fail("should throw NullPointerException");
4031         } catch (NullPointerException e) {
4032             // expected
4033         }
4034         try {
4035             os.write(null, 1, 1);
4036             fail("should throw NullPointerException");
4037         } catch (NullPointerException e) {
4038             // expected
4039         }
4040         try {
4041             os.write(null, -1, 1);
4042             fail("should throw IndexOutOfBoundsException");
4043         } catch (IndexOutOfBoundsException e) {
4044             // expected
4045         }
4046         // closed
4047         os.close();
4048         try {
4049             os.write(null);
4050             fail("should throw NullPointerException");
4051         } catch (NullPointerException e) {
4052             // expected
4053         }
4054         try {
4055             os.write(1);
4056             fail("should throw ClosedChannelException");
4057         } catch (ClosedChannelException e) {
4058             // expected
4059         }
4060         try {
4061             os.write(null, 1, 1);
4062             fail("should throw NullPointerException");
4063         } catch (NullPointerException e) {
4064             // expected
4065         }
4066         try {
4067             os.write(null, -1, 1);
4068             fail("should throw IndexOutOfBoundsException");
4069         } catch (IndexOutOfBoundsException e) {
4070             // expected
4071         }
4072     }
4073
4074     /**
4075      * @tests SocketChannelImpl#socket().getOutputStream().write(int)
4076      */
4077     @TestTargetNew(
4078         level = TestLevel.PARTIAL_COMPLETE,
4079         notes = "",
4080         method = "socket",
4081         args = {}
4082     )
4083     public void test_socket_getOutputStream_write_oneByte()
4084             throws IOException {
4085
4086         // Regression test for Harmony-3475
4087
4088         int MAGIC = 123;
4089
4090         channel1.connect(this.localAddr1);
4091
4092         OutputStream os = channel1.socket().getOutputStream();
4093
4094         Socket acceptedSocket = server1.accept();
4095
4096         InputStream in = acceptedSocket.getInputStream();
4097
4098         os.write(MAGIC);
4099         channel1.close();
4100
4101         int lastByte = in.read();
4102         if (lastByte == -1) {
4103             fail("Server received nothing. Expected 1 byte.");
4104         } else if (lastByte != MAGIC) {
4105             fail("Server received wrong single byte: " + lastByte
4106                     + ", expected: " + MAGIC);
4107         }
4108
4109         lastByte = in.read();
4110         if (lastByte != -1) {
4111             fail("Server received too long sequence. Expected 1 byte.");
4112         }
4113     }
4114
4115     class MockSocketChannel extends SocketChannel {
4116
4117         private boolean isWriteCalled = false;
4118
4119         private boolean isReadCalled = false;
4120
4121         private boolean isConstructorCalled = false;
4122
4123         public MockSocketChannel(SelectorProvider provider) {
4124             super(provider);
4125             isConstructorCalled = true;
4126         }
4127
4128         public Socket socket() {
4129             return null;
4130         }
4131
4132         public boolean isConnected() {
4133             return false;
4134         }
4135
4136         public boolean isConnectionPending() {
4137             return false;
4138         }
4139
4140         public boolean connect(SocketAddress address) throws IOException {
4141             return false;
4142         }
4143
4144         public boolean finishConnect() throws IOException {
4145             return false;
4146         }
4147
4148         public int read(ByteBuffer target) throws IOException {
4149             return 0;
4150         }
4151
4152         public long read(ByteBuffer[] targets, int offset, int length)
4153                 throws IOException {
4154             // Verify that calling read(ByteBuffer[]) leads to the method
4155             // read(ByteBuffer[], int, int) being called with a 0 for the
4156             // second parameter and targets.length as the third parameter.
4157             if (0 == offset && length == targets.length) {
4158                 isReadCalled = true;
4159             }
4160             return 0;
4161         }
4162
4163         public int write(ByteBuffer source) throws IOException {
4164             return 0;
4165         }
4166
4167         public long write(ByteBuffer[] sources, int offset, int length)
4168                 throws IOException {
4169             // Verify that calling write(ByteBuffer[]) leads to the method
4170             // write(ByteBuffer[], int, int) being called with a 0 for the
4171             // second parameter and sources.length as the third parameter.
4172             if (0 == offset && length == sources.length) {
4173                 isWriteCalled = true;
4174             }
4175             return 0;
4176         }
4177
4178         protected void implCloseSelectableChannel() throws IOException {
4179             // empty
4180         }
4181
4182         protected void implConfigureBlocking(boolean blockingMode)
4183                 throws IOException {
4184             // empty
4185         }
4186     }
4187
4188     class SubSocketAddress extends SocketAddress {
4189         private static final long serialVersionUID = 1L;
4190
4191         // empty
4192         public SubSocketAddress() {
4193             super();
4194         }
4195     }
4196 }