1/*
2 *  Licensed to the Apache Software Foundation (ASF) under one or more
3 *  contributor license agreements.  See the NOTICE file distributed with
4 *  this work for additional information regarding copyright ownership.
5 *  The ASF licenses this file to You under the Apache License, Version 2.0
6 *  (the "License"); you may not use this file except in compliance with
7 *  the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *  Unless required by applicable law or agreed to in writing, software
12 *  distributed under the License is distributed on an "AS IS" BASIS,
13 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *  See the License for the specific language governing permissions and
15 *  limitations under the License.
16 */
17
18package org.apache.harmony.nio.tests.java.nio.channels;
19
20import dalvik.annotation.TestTargetNew;
21import dalvik.annotation.TestTargets;
22import dalvik.annotation.TestLevel;
23import dalvik.annotation.TestTargetClass;
24
25import java.io.IOException;
26import java.net.DatagramPacket;
27import java.net.DatagramSocket;
28import java.net.InetAddress;
29import java.net.InetSocketAddress;
30import java.net.SocketAddress;
31import java.net.SocketException;
32import java.nio.ByteBuffer;
33import java.nio.channels.AsynchronousCloseException;
34import java.nio.channels.ClosedByInterruptException;
35import java.nio.channels.ClosedChannelException;
36import java.nio.channels.DatagramChannel;
37import java.nio.channels.IllegalBlockingModeException;
38import java.nio.channels.NotYetConnectedException;
39import java.nio.channels.SelectionKey;
40import java.nio.channels.UnresolvedAddressException;
41import java.nio.channels.UnsupportedAddressTypeException;
42import java.nio.channels.spi.SelectorProvider;
43
44import junit.framework.TestCase;
45import tests.support.Support_PortManager;
46
47/**
48 * Test for DatagramChannel
49 *
50 */
51@TestTargetClass(
52    value = DatagramChannel.class,
53    untestedMethods = {
54        @TestTargetNew(
55            level = TestLevel.SUFFICIENT,
56            notes = "AsynchronousCloseException can not easily be tested",
57            method = "connect",
58            args = {java.net.SocketAddress.class}
59        ),
60        @TestTargetNew(
61            level = TestLevel.SUFFICIENT,
62            notes = "AsynchronousCloseException can not easily be tested",
63            method = "read",
64            args = {java.nio.ByteBuffer.class}
65        ),
66        @TestTargetNew(
67            level = TestLevel.SUFFICIENT,
68            notes = "AsynchronousCloseException can not easily be tested",
69            method = "read",
70            args = {java.nio.ByteBuffer[].class}
71        ),
72        @TestTargetNew(
73            level = TestLevel.SUFFICIENT,
74            notes = "AsynchronousCloseException can not easily be tested",
75            method = "read",
76            args = {java.nio.ByteBuffer[].class, int.class, int.class}
77        ),
78        @TestTargetNew(
79            level = TestLevel.SUFFICIENT,
80            notes = "AsynchronousCloseException can not easily be tested",
81            method = "send",
82            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
83        ),
84        @TestTargetNew(
85            level = TestLevel.SUFFICIENT,
86            notes = "AsynchronousCloseException can not easily be tested",
87            method = "write",
88            args = {java.nio.ByteBuffer.class}
89        ),
90        @TestTargetNew(
91            level = TestLevel.SUFFICIENT,
92            notes = "AsynchronousCloseException can not easily be tested",
93            method = "write",
94            args = {java.nio.ByteBuffer[].class}
95        ),
96        @TestTargetNew(
97            level = TestLevel.SUFFICIENT,
98            notes = "AsynchronousCloseException can not easily be tested",
99            method = "write",
100            args = {java.nio.ByteBuffer[].class, int.class, int.class}
101        ),
102        @TestTargetNew(
103            level = TestLevel.SUFFICIENT,
104            notes = "ClosedByInterruptException can not easily be tested",
105            method = "connect",
106            args = {java.net.SocketAddress.class}
107        ),
108        @TestTargetNew(
109            level = TestLevel.SUFFICIENT,
110            notes = "ClosedByInterruptException can not easily be tested",
111            method = "read",
112            args = {java.nio.ByteBuffer[].class}
113        ),
114        @TestTargetNew(
115            level = TestLevel.SUFFICIENT,
116            notes = "ClosedByInterruptException can not easily be tested",
117            method = "send",
118            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
119        ),
120        @TestTargetNew(
121            level = TestLevel.SUFFICIENT,
122            notes = "ClosedByInterruptException can not easily be tested",
123            method = "write",
124            args = {java.nio.ByteBuffer.class}
125        ),
126        @TestTargetNew(
127            level = TestLevel.SUFFICIENT,
128            notes = "ClosedByInterruptException can not easily be tested",
129            method = "write",
130            args = {java.nio.ByteBuffer[].class}
131        ),
132        @TestTargetNew(
133            level = TestLevel.SUFFICIENT,
134            notes = "ClosedByInterruptException can not easily be tested",
135            method = "write",
136            args = {java.nio.ByteBuffer[].class, int.class, int.class}
137        )
138    }
139)
140public class DatagramChannelTest extends TestCase {
141
142    private static final int CAPACITY_NORMAL = 200;
143
144    private static final int CAPACITY_1KB = 1024;
145
146    private static final int CAPACITY_64KB = 65536;
147
148    private static final int CAPACITY_ZERO = 0;
149
150    private static final int CAPACITY_ONE = 1;
151
152    private static final int TIME_UNIT = 500;
153
154    private InetSocketAddress localAddr1;
155
156    private InetSocketAddress localAddr2;
157
158    private DatagramChannel channel1;
159
160    private DatagramChannel channel2;
161
162    private DatagramSocket datagramSocket1;
163
164    private DatagramSocket datagramSocket2;
165
166    // The port to be used in test cases.
167    private int testPort;
168
169    protected void setUp() throws Exception {
170        super.setUp();
171        this.channel1 = DatagramChannel.open();
172        this.channel2 = DatagramChannel.open();
173        int[] ports = Support_PortManager.getNextPortsForUDP(5);
174        this.localAddr1 = new InetSocketAddress("127.0.0.1", ports[0]);
175        this.localAddr2 = new InetSocketAddress("127.0.0.1", ports[1]);
176        this.datagramSocket1 = new DatagramSocket(ports[2]);
177        this.datagramSocket2 = new DatagramSocket(ports[3]);
178        testPort = ports[4];
179    }
180
181    protected void tearDown() throws Exception {
182        if (null != this.channel1) {
183            try {
184                this.channel1.close();
185            } catch (Exception e) {
186                //ignore
187            }
188        }
189        if (null != this.channel2) {
190            try {
191                this.channel2.close();
192            } catch (Exception e) {
193                //ignore
194            }
195        }
196        if (null != this.datagramSocket1) {
197            try {
198                this.datagramSocket1.close();
199            } catch (Exception e) {
200                //ignore
201            }
202        }
203        if (null != this.datagramSocket2) {
204            try {
205                this.datagramSocket2.close();
206            } catch (Exception e) {
207                //ignore
208            }
209        }
210        localAddr1 = null;
211        localAddr2 = null;
212        super.tearDown();
213    }
214
215    // -------------------------------------------------------------------
216    // Test for methods in abstract class.
217    // -------------------------------------------------------------------
218    /*
219     * Test method for 'java.nio.channels.DatagramChannel()'
220     */
221    @TestTargetNew(
222        level = TestLevel.COMPLETE,
223        notes = "",
224        method = "DatagramChannel",
225        args = {java.nio.channels.spi.SelectorProvider.class}
226    )
227    public void testConstructor() throws IOException {
228        DatagramChannel channel =
229                SelectorProvider.provider().openDatagramChannel();
230        assertNotNull(channel);
231        assertSame(SelectorProvider.provider(),channel.provider());
232        channel = DatagramChannel.open();
233        assertNotNull(channel);
234        assertSame(SelectorProvider.provider(), channel.provider());
235    }
236
237    /*
238     * Test method for 'java.nio.channels.DatagramChannel.validOps()'
239     */
240    @TestTargetNew(
241        level = TestLevel.PARTIAL_COMPLETE,
242        notes = "",
243        method = "validOps",
244        args = {}
245    )
246    public void testValidOps() {
247        MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider
248                .provider());
249        MockDatagramChannel testMocknull = new MockDatagramChannel(null);
250        int val = this.channel1.validOps();
251        assertEquals(5, val);
252        assertEquals(val, testMock.validOps());
253        assertEquals(val, testMocknull.validOps());
254    }
255
256    /*
257     * Test method for 'java.nio.channels.DatagramChannel.open()'
258     */
259    @TestTargetNew(
260        level = TestLevel.COMPLETE,
261        notes = "Verifies the result of the setUp method.",
262        method = "open",
263        args = {}
264    )
265    public void testOpen() {
266        MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider
267                .provider());
268        MockDatagramChannel testMocknull = new MockDatagramChannel(null);
269        assertNull(testMocknull.provider());
270        assertNotNull(testMock.provider());
271        assertEquals(this.channel1.provider(), testMock.provider());
272        assertEquals(5, testMock.validOps());
273    }
274
275    /*
276     * Test method for 'java.nio.channels.DatagramChannel.open()'
277     */
278    @TestTargetNew(
279        level = TestLevel.PARTIAL_COMPLETE,
280        notes = "",
281        method = "isOpen",
282        args = {}
283    )
284    public void testIsOpen() throws Exception {
285        assertTrue(this.channel1.isOpen());
286        this.channel1.close();
287        assertFalse(this.channel1.isOpen());
288    }
289
290    @TestTargets({
291        @TestTargetNew(
292            level = TestLevel.PARTIAL_COMPLETE,
293            notes = "Verifies default status of DatagramChannel.",
294            method = "validOps",
295            args = {}
296        ),
297        @TestTargetNew(
298            level = TestLevel.PARTIAL_COMPLETE,
299            notes = "Verifies default status of DatagramChannel.",
300            method = "provider",
301            args = {}
302        ),
303        @TestTargetNew(
304            level = TestLevel.PARTIAL_COMPLETE,
305            notes = "Verifies default status of DatagramChannel.",
306            method = "isRegistered",
307            args = {}
308        ),
309        @TestTargetNew(
310            level = TestLevel.PARTIAL_COMPLETE,
311            notes = "Verifies default status of DatagramChannel.",
312            method = "isBlocking",
313            args = {}
314        )
315    })
316    public void testChannelBasicStatus() {
317        DatagramSocket gotSocket = this.channel1.socket();
318        assertFalse(gotSocket.isClosed());
319        assertTrue(this.channel1.isBlocking());
320        assertFalse(this.channel1.isRegistered());
321        assertEquals((SelectionKey.OP_READ | SelectionKey.OP_WRITE),
322                this.channel1.validOps());
323        assertEquals(SelectorProvider.provider(), this.channel1.provider());
324    }
325
326    /*
327     * Test method for 'java.nio.channels.DatagramChannel.read(ByteBuffer)'
328     */
329    @TestTargetNew(
330        level = TestLevel.PARTIAL_COMPLETE,
331        notes = "",
332        method = "read",
333        args = {java.nio.ByteBuffer[].class}
334    )
335    public void testReadByteBufferArray() throws IOException {
336        ByteBuffer[] readBuf = new ByteBuffer[2];
337        readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
338        readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
339        InetSocketAddress ipAddr = localAddr1;
340        try {
341            this.channel1.read(readBuf);
342            fail("should throw NotYetConnectedException");
343        } catch (NotYetConnectedException e) {
344            // correct
345        }
346        this.channel1.connect(ipAddr);
347        assertTrue(this.channel1.isConnected());
348        this.channel1.configureBlocking(false);
349        // note : blocking-mode will make the read process endless!
350        assertEquals(0, this.channel1.read(readBuf));
351        this.channel1.close();
352        assertFalse(this.channel1.isOpen());
353        try {
354            assertEquals(0, this.channel1.read(readBuf));
355        } catch (ClosedChannelException e) {
356            // correct
357        }
358    }
359
360    @TestTargetNew(
361        level = TestLevel.PARTIAL_COMPLETE,
362        notes = "",
363        method = "read",
364        args = {java.nio.ByteBuffer[].class}
365    )
366    public void testReadByteBufferArray_ConnectedBufNull()
367            throws IOException {
368        ByteBuffer[] readBuf = new ByteBuffer[2];
369        readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
370        InetSocketAddress ipAddr = localAddr1;
371        this.channel1.connect(ipAddr);
372        assertTrue(this.channel1.isConnected());
373        this.channel1.configureBlocking(false);
374        // note : blocking-mode will make the read process endless!
375        try {
376            this.channel1.read((ByteBuffer[])null);
377            fail("should throw NPE");
378        } catch (NullPointerException e) {
379            // correct
380        }
381        try {
382            this.channel1.read(readBuf);
383            fail("should throw NPE");
384        } catch (NullPointerException e) {
385            // correct
386        }
387        datagramSocket1.close();
388    }
389
390    @TestTargetNew(
391        level = TestLevel.PARTIAL_COMPLETE,
392        notes = "",
393        method = "read",
394        args = {java.nio.ByteBuffer[].class}
395    )
396    public void testReadByteBufferArray_NotConnectedBufNull()
397            throws IOException {
398        ByteBuffer[] readBuf = new ByteBuffer[2];
399        readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
400        InetSocketAddress ipAddr = localAddr1;
401        try {
402            this.channel1.read((ByteBuffer[])null);
403            fail("should throw NPE");
404        } catch (NullPointerException e) {
405            // correct
406        }
407        try {
408            this.channel1.read(readBuf);
409            fail("should throw NotYetConnectedException");
410        } catch (NotYetConnectedException e) {
411            // correct
412        }
413    }
414
415    /*
416     * Test method for 'DatagramChannelImpl.write(ByteBuffer[])'
417     */
418    @TestTargetNew(
419        level = TestLevel.PARTIAL_COMPLETE,
420        notes = "Doesn't verify all exceptions according to specification.",
421        method = "write",
422        args = {java.nio.ByteBuffer[].class}
423    )
424    public void testWriteByteBufferArray_Block() throws IOException {
425        ByteBuffer[] writeBuf = new ByteBuffer[2];
426        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
427        writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
428        InetSocketAddress ipAddr = localAddr1;
429        try {
430            this.channel1.write(writeBuf);
431            fail("Should throw NotYetConnectedException.");
432        } catch (NotYetConnectedException e) {
433            // correct
434        }
435        this.channel1.connect(ipAddr);
436        assertTrue(this.channel1.isConnected());
437        assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf));
438        // cannot be buffered again!
439        assertEquals(0, this.channel1.write(writeBuf));
440    }
441
442    public void disabled_testWriteByteBufferArray_Block_close() throws Exception {
443        // bind and connect
444        this.channel1.socket().bind(localAddr2);
445        this.channel1.connect(localAddr1);
446        this.channel2.socket().bind(localAddr1);
447        this.channel2.connect(localAddr2);
448        ByteBuffer[] targetBuf = new ByteBuffer[2];
449        targetBuf[0] = ByteBuffer.wrap(new byte[2]);
450        targetBuf[1] = ByteBuffer.wrap(new byte[2]);
451
452        new Thread() {
453            public void run() {
454                try {
455                    Thread.sleep(TIME_UNIT);
456                    channel1.close();
457                } catch (Exception e) {
458                    //ignore
459                }
460            }
461        }.start();
462        try {
463            this.channel1.write(targetBuf);
464            fail("should throw AsynchronousCloseException");
465        } catch (AsynchronousCloseException e) {
466            // ok
467        }
468    }
469
470    public void disabled_testWriteByteBufferArray_Block_interrupt() throws Exception {
471        // bind and connect
472        this.channel1.socket().bind(localAddr2);
473        this.channel1.connect(localAddr1);
474        this.channel2.socket().bind(localAddr1);
475        this.channel2.connect(localAddr2);
476
477        class MyThread extends Thread {
478            public String errMsg = null;
479            public void run() {
480                try {
481                    ByteBuffer[] targetBuf = new ByteBuffer[2];
482                    targetBuf[0] = ByteBuffer.wrap(new byte[2]);
483                    targetBuf[1] = ByteBuffer.wrap(new byte[2]);
484                    channel1.write(targetBuf);
485                    errMsg = "should throw ClosedByInterruptException";
486                } catch (ClosedByInterruptException e) {
487                    // expected
488                } catch (IOException e) {
489                    errMsg = "Unexcted Exception was thrown: " + e.getClass() +
490                            ": " + e.getMessage();
491                }
492            }
493        }
494        MyThread thread = new MyThread();
495        thread.start();
496        try {
497            Thread.sleep(TIME_UNIT);
498            thread.interrupt();
499        } catch (InterruptedException e) {
500            // ok
501        }
502        thread.join(TIME_UNIT);
503        if (thread.errMsg != null) {
504            fail(thread.errMsg);
505        }
506    }
507
508    /*
509     * Test method for 'DatagramChannelImpl.write(ByteBuffer[])'
510     */
511    @TestTargetNew(
512        level = TestLevel.PARTIAL_COMPLETE,
513        notes = "",
514        method = "write",
515        args = {java.nio.ByteBuffer[].class}
516    )
517    public void testWriteByteBufferArray_NonBlock() throws IOException {
518        ByteBuffer[] writeBuf = new ByteBuffer[2];
519        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
520        writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
521        InetSocketAddress ipAddr = localAddr1;
522        // non-block mode
523        this.channel1.configureBlocking(false);
524        try {
525            this.channel1.write(writeBuf);
526            fail("Should throw NotYetConnectedException.");
527        } catch (NotYetConnectedException e) {
528            // correct
529        }
530        this.channel1.connect(ipAddr);
531        assertTrue(this.channel1.isConnected());
532        assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf));
533        // cannot be buffered again!
534        assertEquals(0, this.channel1.write(writeBuf));
535        this.channel1.close();
536        try {
537            this.channel1.write(writeBuf, 0, 1);
538            fail("Should throw ClosedChannelEception.");
539        } catch (ClosedChannelException e) {
540            // expected
541        }
542    }
543
544    @TestTargetNew(
545        level = TestLevel.PARTIAL_COMPLETE,
546        notes = "",
547        method = "write",
548        args = {java.nio.ByteBuffer[].class}
549    )
550    public void testWriteByteBufferArray_BlockClosed() throws IOException {
551        ByteBuffer[] writeBuf = new ByteBuffer[2];
552        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
553        writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
554        InetSocketAddress ipAddr = localAddr1;
555        // non-block mode
556        this.channel1.configureBlocking(false);
557        this.channel1.connect(ipAddr);
558        assertTrue(this.channel1.isConnected());
559        this.channel1.close();
560        try {
561            channel1.write(writeBuf);
562            fail("should throw ClosedChannelException");
563        } catch (ClosedChannelException e) {
564            // correct
565        }
566    }
567
568    @TestTargetNew(
569        level = TestLevel.PARTIAL_COMPLETE,
570        notes = "",
571        method = "write",
572        args = {java.nio.ByteBuffer[].class}
573    )
574    public void testWriteByteBufferArray_NonBlockClosed() throws IOException {
575        ByteBuffer[] writeBuf = new ByteBuffer[2];
576        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
577        writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
578        InetSocketAddress ipAddr = localAddr1;
579        this.channel1.connect(ipAddr);
580        assertTrue(this.channel1.isConnected());
581        this.channel1.close();
582        try {
583            channel1.write(writeBuf);
584            fail("should throw ClosedChannelException");
585        } catch (ClosedChannelException e) {
586            // correct
587        }
588    }
589
590    /*
591     * Test method for 'DatagramChannelImpl.write(ByteBuffer[])'
592     */
593    @TestTargetNew(
594        level = TestLevel.PARTIAL_COMPLETE,
595        notes = "",
596        method = "write",
597        args = {java.nio.ByteBuffer[].class}
598    )
599    public void testWriteByteBufferArray_NotConnectedBufNull()
600            throws IOException {
601        ByteBuffer[] writeBuf = new ByteBuffer[2];
602        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
603        try {
604            this.channel1.write((ByteBuffer[])null);
605            fail("should throw NPE");
606        } catch (NullPointerException e) {
607            // correct
608        }
609        try {
610            this.channel1.write(writeBuf);
611            fail("should throw NotYetConnectedException");
612        } catch (NotYetConnectedException e) {
613            // correct
614        }
615    }
616
617    /*
618     * Test method for 'DatagramChannelImpl.write(ByteBuffer[])'
619     */
620    @TestTargetNew(
621        level = TestLevel.PARTIAL_COMPLETE,
622        notes = "",
623        method = "write",
624        args = {java.nio.ByteBuffer[].class}
625    )
626    public void testWriteByteBufferArray_ConnectedBufNull()
627            throws IOException {
628        ByteBuffer[] writeBuf = new ByteBuffer[2];
629        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
630        InetSocketAddress ipAddr = localAddr1;
631        this.channel1.connect(ipAddr);
632        assertTrue(this.channel1.isConnected());
633        try {
634            this.channel1.write((ByteBuffer[])null);
635            fail("should throw NPE");
636        } catch (NullPointerException e) {
637            // correct
638        }
639        try {
640            this.channel1.write(writeBuf);
641            fail("should throw NullPointerException");
642        } catch (NullPointerException e) {
643            // correct
644        }
645        datagramSocket1.close();
646        try {
647            this.channel1.write((ByteBuffer[])null);
648            fail("should throw NPE");
649        } catch (NullPointerException e) {
650            // correct
651        }
652    }
653
654    // -------------------------------------------------------------------
655    // Test for socket()
656    // -------------------------------------------------------------------
657
658    /**
659     * Test method for 'DatagramChannelImpl.socket()'
660     *
661     * @throws SocketException
662     */
663    @TestTargetNew(
664        level = TestLevel.PARTIAL_COMPLETE,
665        notes = "",
666        method = "socket",
667        args = {}
668    )
669    public void testSocket_BasicStatusBeforeConnect() throws SocketException {
670        assertFalse(this.channel1.isConnected());// not connected
671        DatagramSocket s1 = this.channel1.socket();
672        assertSocketBeforeConnect(s1);
673        DatagramSocket s2 = this.channel1.socket();
674        // same
675        assertSame(s1, s2);
676    }
677
678    /**
679     * Test method for 'DatagramChannelImpl.socket()'
680     *
681     * @throws IOException
682     */
683    @TestTargetNew(
684        level = TestLevel.PARTIAL_COMPLETE,
685        notes = "",
686        method = "socket",
687        args = {}
688    )
689    public void testSocket_Block_BasicStatusAfterConnect() throws IOException {
690        this.channel1.connect(localAddr1);
691        DatagramSocket s1 = this.channel1.socket();
692        assertSocketAfterConnect(s1);
693        DatagramSocket s2 = this.channel1.socket();
694        // same
695        assertSame(s1, s2);
696    }
697
698    @TestTargetNew(
699        level = TestLevel.PARTIAL_COMPLETE,
700        notes = "",
701        method = "socket",
702        args = {}
703    )
704    public void testSocket_NonBlock_BasicStatusAfterConnect()
705            throws IOException {
706        this.channel1.connect(localAddr1);
707        this.channel1.configureBlocking(false);
708        DatagramSocket s1 = this.channel1.socket();
709        assertSocketAfterConnect(s1);
710        DatagramSocket s2 = this.channel1.socket();
711        // same
712        assertSame(s1, s2);
713    }
714
715    /**
716     * Test method for 'DatagramChannelImpl.socket()'
717     *
718     * @throws IOException
719     */
720    @TestTargetNew(
721        level = TestLevel.PARTIAL_COMPLETE,
722        notes = "",
723        method = "socket",
724        args = {}
725    )
726    public void testSocket_ActionsBeforeConnect() throws IOException {
727        assertFalse(this.channel1.isConnected());// not connected
728        DatagramSocket s = this.channel1.socket();
729        assertSocketActionBeforeConnect(s);
730    }
731
732    /**
733     * Test method for 'DatagramChannelImpl.socket()'
734     *
735     * @throws IOException
736     */
737    @TestTargetNew(
738        level = TestLevel.PARTIAL_COMPLETE,
739        notes = "",
740        method = "socket",
741        args = {}
742    )
743    public void testSocket_Block_ActionsAfterConnect() throws IOException {
744        assertFalse(this.channel1.isConnected());// not connected
745        this.channel1.connect(localAddr1);
746        DatagramSocket s = this.channel1.socket();
747        assertSocketActionAfterConnect(s);
748    }
749
750    @TestTargetNew(
751        level = TestLevel.PARTIAL_COMPLETE,
752        notes = "",
753        method = "socket",
754        args = {}
755    )
756    public void testSocket_NonBlock_ActionsAfterConnect() throws IOException {
757        this.channel1.connect(localAddr1);
758        this.channel1.configureBlocking(false);
759        DatagramSocket s = this.channel1.socket();
760        assertSocketActionAfterConnect(s);
761    }
762
763    private void assertSocketBeforeConnect(DatagramSocket s)
764            throws SocketException {
765        assertFalse(s.isBound());
766        assertFalse(s.isClosed());
767        assertFalse(s.isConnected());
768        assertFalse(s.getBroadcast());
769        assertFalse(s.getReuseAddress());
770        assertNull(s.getInetAddress());
771        assertTrue(s.getLocalAddress().isAnyLocalAddress());
772        assertEquals(s.getLocalPort(), 0);
773        assertNull(s.getLocalSocketAddress());
774        assertEquals(s.getPort(), -1);
775        assertTrue(s.getReceiveBufferSize() >= 8192);
776        assertNull(s.getRemoteSocketAddress());
777        assertFalse(s.getReuseAddress());
778        assertTrue(s.getSendBufferSize() >= 8192);
779        assertEquals(s.getSoTimeout(), 0);
780        assertEquals(s.getTrafficClass(), 0);
781    }
782
783    private void assertSocketAfterConnect(DatagramSocket s)
784            throws SocketException {
785        assertTrue(s.isBound());
786        assertFalse(s.isClosed());
787        assertTrue(s.isConnected());
788        assertFalse(s.getBroadcast());
789        assertFalse(s.getReuseAddress());
790        assertSame(s.getInetAddress(), localAddr1.getAddress());
791        assertEquals(s.getLocalAddress(), localAddr1.getAddress());
792        assertNotNull(s.getLocalSocketAddress());
793        assertEquals(s.getPort(), localAddr1.getPort());
794        assertTrue(s.getReceiveBufferSize() >= 8192);
795        // not same , but equals
796        assertNotSame(s.getRemoteSocketAddress(), localAddr1);
797        assertEquals(s.getRemoteSocketAddress(), localAddr1);
798        assertFalse(s.getReuseAddress());
799        assertTrue(s.getSendBufferSize() >= 8192);
800        assertEquals(s.getSoTimeout(), 0);
801        assertEquals(s.getTrafficClass(), 0);
802    }
803
804    private void assertSocketActionBeforeConnect(DatagramSocket s)
805            throws IOException {
806        s.connect(localAddr2);
807        assertFalse(this.channel1.isConnected());
808        assertFalse(s.isConnected());
809
810        s.disconnect();
811        assertFalse(this.channel1.isConnected());
812        assertFalse(s.isConnected());
813
814        s.close();
815        assertTrue(s.isClosed());
816        assertFalse(this.channel1.isOpen());
817    }
818
819    private void assertSocketActionAfterConnect(DatagramSocket s)
820            throws IOException {
821        assertEquals(s.getPort(), localAddr1.getPort());
822        s.connect(localAddr2);
823        assertTrue(this.channel1.isConnected());
824        assertTrue(s.isConnected());
825        // not changed
826        assertEquals(s.getPort(), localAddr1.getPort());
827
828        s.disconnect();
829        assertFalse(this.channel1.isConnected());
830        assertFalse(s.isConnected());
831
832        s.close();
833        assertTrue(s.isClosed());
834        assertFalse(this.channel1.isOpen());
835    }
836
837    // -------------------------------------------------------------------
838    // Test for configureBlocking()
839    // -------------------------------------------------------------------
840    @TestTargetNew(
841        level = TestLevel.PARTIAL_COMPLETE,
842        notes = "",
843        method = "receive",
844        args = {ByteBuffer.class}
845    )
846    public void testConfigureBlocking_Read() throws Exception {
847        assertTrue(this.channel1.isBlocking());
848        ByteBuffer buf = ByteBuffer.allocate(CAPACITY_1KB);
849        new Thread() {
850            public void run() {
851                try {
852                    sleep(TIME_UNIT * 5);
853                    channel1.configureBlocking(false);
854                    assertFalse(channel1.isBlocking());
855                    datagramSocket1.close();
856                } catch (Exception e) {
857                    // do nothing
858                }
859            }
860        }.start();
861        SocketAddress addr = channel1.receive(buf);
862        assertNull(addr);
863    }
864
865    // -------------------------------------------------------------------
866    // Test for isConnected()
867    // -------------------------------------------------------------------
868
869    /**
870     * Test method for 'DatagramChannelImpl.isConnected()'
871     *
872     * @throws IOException
873     */
874    @TestTargetNew(
875        level = TestLevel.COMPLETE,
876        notes = "",
877        method = "isConnected",
878        args = {}
879    )
880    public void testIsConnected_WithServer() throws IOException {
881        connectLocalServer();
882        assertTrue(this.channel1.isConnected());
883        disconnectAfterConnected();
884        this.datagramSocket1.close();
885        this.channel1.close();
886        assertFalse(this.channel1.isConnected());
887    }
888
889    // -------------------------------------------------------------------
890    // Test for connect()
891    // -------------------------------------------------------------------
892
893    /**
894     * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
895     */
896    @TestTargetNew(
897        level = TestLevel.PARTIAL_COMPLETE,
898        notes = "",
899        method = "connect",
900        args = {java.net.SocketAddress.class}
901    )
902    public void testConnect_BlockWithServer() throws IOException {
903        // blocking mode
904        assertTrue(this.channel1.isBlocking());
905        connectLocalServer();
906        datagramSocket1.close();
907        disconnectAfterConnected();
908    }
909
910    /**
911     * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
912     */
913    @TestTargetNew(
914        level = TestLevel.PARTIAL_COMPLETE,
915        notes = "",
916        method = "connect",
917        args = {java.net.SocketAddress.class}
918    )
919    public void testConnect_BlockNoServer() throws IOException {
920        connectWithoutServer();
921        disconnectAfterConnected();
922    }
923
924    /**
925     * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
926     *
927     * @throws IOException
928     */
929    @TestTargetNew(
930        level = TestLevel.PARTIAL_COMPLETE,
931        notes = "",
932        method = "connect",
933        args = {java.net.SocketAddress.class}
934    )
935    public void testConnect_NonBlockWithServer() throws IOException {
936        // Non blocking mode
937        this.channel1.configureBlocking(false);
938        connectLocalServer();
939        datagramSocket1.close();
940        disconnectAfterConnected();
941    }
942
943    /**
944     * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
945     *
946     * @throws IOException
947     */
948    @TestTargetNew(
949        level = TestLevel.PARTIAL_COMPLETE,
950        notes = "Verifies IllegalArgumentException.",
951        method = "connect",
952        args = {java.net.SocketAddress.class}
953    )
954    public void testConnect_Null() throws IOException {
955        assertFalse(this.channel1.isConnected());
956        try {
957            this.channel1.connect(null);
958            fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$
959        } catch (IllegalArgumentException e) {
960            // OK.
961        }
962    }
963
964    /**
965     * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
966     *
967     * @throws IOException
968     */
969    @TestTargetNew(
970        level = TestLevel.PARTIAL_COMPLETE,
971        notes = "Verifies UnsupportedAddressTypeException.",
972        method = "connect",
973        args = {java.net.SocketAddress.class}
974    )
975    public void testConnect_UnsupportedType() throws IOException {
976        assertFalse(this.channel1.isConnected());
977        class SubSocketAddress extends SocketAddress {
978            private static final long serialVersionUID = 1L;
979
980            public SubSocketAddress() {
981                super();
982            }
983        }
984        SocketAddress newTypeAddress = new SubSocketAddress();
985        try {
986            this.channel1.connect(newTypeAddress);
987            fail("Should throw an UnsupportedAddressTypeException here.");
988        } catch (UnsupportedAddressTypeException e) {
989            // OK.
990        }
991    }
992
993    public void disabled_testConnect_Block_close() throws Exception {
994        new Thread() {
995            public void run() {
996                try {
997                    Thread.sleep(TIME_UNIT);
998                    channel1.close();
999                } catch (Exception e) {
1000                    //ignore
1001                }
1002            }
1003        }.start();
1004        try {
1005            this.channel1.connect(localAddr1);
1006            fail("should throw AsynchronousCloseException");
1007        } catch (AsynchronousCloseException e) {
1008            // ok
1009        }
1010    }
1011
1012    public void disabled_testConnect_Block_interrupt() throws Exception {
1013        class MyThread extends Thread {
1014            public String errMsg = null;
1015            public void run() {
1016                try {
1017                    channel1.connect(localAddr1);
1018                    errMsg = "should throw ClosedByInterruptException";
1019                } catch (ClosedByInterruptException e) {
1020                    // expected
1021                } catch (IOException e) {
1022                    errMsg = "Unexcted Exception was thrown: " + e.getClass() +
1023                            ": " + e.getMessage();
1024                }
1025            }
1026        }
1027        MyThread thread = new MyThread();
1028        thread.start();
1029        try {
1030            Thread.sleep(TIME_UNIT);
1031            thread.interrupt();
1032        } catch (InterruptedException e) {
1033            // ok
1034        }
1035        thread.join(TIME_UNIT);
1036        if (thread.errMsg != null) {
1037            fail(thread.errMsg);
1038        }
1039    }
1040
1041    /**
1042     * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
1043     *
1044     * @throws IOException
1045     */
1046    @TestTargetNew(
1047        level = TestLevel.PARTIAL_COMPLETE,
1048        notes = "Verifies UnresolvedAddressException.",
1049        method = "connect",
1050        args = {java.net.SocketAddress.class}
1051    )
1052    public void testConnect_Unresolved() throws IOException {
1053        assertFalse(this.channel1.isConnected());
1054        InetSocketAddress unresolved = new InetSocketAddress(
1055                "unresolved address", 1080);
1056        try {
1057            this.channel1.connect(unresolved);
1058            fail("Should throw an UnresolvedAddressException here."); //$NON-NLS-1$
1059        } catch (UnresolvedAddressException e) {
1060            // OK.
1061        }
1062    }
1063
1064    @TestTargetNew(
1065        level = TestLevel.PARTIAL_COMPLETE,
1066        notes = "",
1067        method = "connect",
1068        args = {java.net.SocketAddress.class}
1069    )
1070    public void testConnect_EmptyHost() throws Exception {
1071        assertFalse(this.channel1.isConnected());
1072
1073        assertEquals(this.channel1, this.channel1
1074                .connect(new InetSocketAddress("", 1081))); //$NON-NLS-1$
1075
1076    }
1077
1078    /**
1079     * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
1080     *
1081     * @throws IOException
1082     *
1083     */
1084    @TestTargetNew(
1085        level = TestLevel.PARTIAL_COMPLETE,
1086        notes = "Verifies ClosedChannelException.",
1087        method = "connect",
1088        args = {java.net.SocketAddress.class}
1089    )
1090    public void testConnect_ClosedChannelException() throws IOException {
1091        assertFalse(this.channel1.isConnected());
1092        this.channel1.close();
1093        assertFalse(this.channel1.isOpen());
1094        try {
1095            this.channel1.connect(localAddr1);
1096            fail("Should throw ClosedChannelException."); //$NON-NLS-1$
1097        } catch (ClosedChannelException e) {
1098            // OK.
1099        }
1100    }
1101
1102    /**
1103     * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
1104     *
1105     * @throws IOException
1106     *
1107     */
1108    @TestTargetNew(
1109        level = TestLevel.PARTIAL_COMPLETE,
1110        notes = "Verifies IllegalStateException.",
1111        method = "connect",
1112        args = {java.net.SocketAddress.class}
1113    )
1114    public void testConnect_IllegalStateException() throws IOException {
1115        assertFalse(this.channel1.isConnected());
1116        this.channel1.connect(localAddr1);
1117        assertTrue(this.channel1.isConnected());
1118        // connect after connected.
1119        try {
1120            this.channel1.connect(localAddr1);
1121            fail("Should throw IllegalStateException."); //$NON-NLS-1$
1122        } catch (IllegalStateException e) {
1123            // OK.
1124        }
1125    }
1126
1127    /**
1128     * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
1129     *
1130     * @throws IOException
1131     *
1132     */
1133    @TestTargetNew(
1134        level = TestLevel.PARTIAL_COMPLETE,
1135        notes = "Verifies ClosedChannelException.",
1136        method = "connect",
1137        args = {java.net.SocketAddress.class}
1138    )
1139    public void testConnect_CheckOpenBeforeStatus() throws IOException {
1140        assertFalse(this.channel1.isConnected());
1141        this.channel1.connect(localAddr1);
1142        assertTrue(this.channel1.isConnected());
1143        // connect after connected.
1144        this.channel1.close();
1145        assertFalse(this.channel1.isOpen());
1146        // checking open is before checking status.
1147        try {
1148            this.channel1.connect(localAddr1);
1149            fail("Should throw ClosedChannelException."); //$NON-NLS-1$
1150        } catch (ClosedChannelException e) {
1151            // OK.
1152        }
1153    }
1154
1155    private void disconnectAfterConnected() throws IOException {
1156        assertTrue(this.channel1.isConnected());
1157        this.channel1.disconnect();
1158        assertFalse(this.channel1.isConnected());
1159    }
1160
1161    private void disconnectAfterClosed() throws IOException {
1162        assertFalse(this.channel1.isOpen());
1163        assertFalse(this.channel1.isConnected());
1164        this.channel1.disconnect();
1165        assertFalse(this.channel1.isConnected());
1166    }
1167
1168    private void connectLocalServer() throws IOException {
1169        assertFalse(this.channel1.isConnected());
1170        assertTrue(this.datagramSocket1.isBound());
1171        assertSame(this.channel1, this.channel1.connect(localAddr1));
1172        assertTrue(this.channel1.isConnected());
1173    }
1174
1175    private void connectWithoutServer() throws IOException {
1176        assertFalse(this.channel1.isConnected());
1177        this.datagramSocket1.close();
1178        assertTrue(this.datagramSocket1.isClosed());
1179        assertSame(this.channel1, this.channel1.connect(localAddr1));
1180        assertTrue(this.channel1.isConnected());
1181    }
1182
1183    // -------------------------------------------------------------------
1184    // Test for disconnect()
1185    // -------------------------------------------------------------------
1186
1187    /**
1188     * Test method for 'DatagramChannelImpl.disconnect()'
1189     *
1190     * @throws IOException
1191     */
1192    @TestTargetNew(
1193        level = TestLevel.PARTIAL_COMPLETE,
1194        notes = "Doesn't verify IOException.",
1195        method = "disconnect",
1196        args = {}
1197    )
1198    public void testDisconnect_BeforeConnect() throws IOException {
1199        assertFalse(this.channel1.isConnected());
1200        assertEquals(this.channel1, this.channel1.disconnect());
1201        assertFalse(this.channel1.isConnected());
1202    }
1203
1204    /**
1205     * Test method for 'DatagramChannelImpl.disconnect()'
1206     *
1207     * @throws IOException
1208     */
1209    @TestTargetNew(
1210        level = TestLevel.PARTIAL_COMPLETE,
1211        notes = "",
1212        method = "disconnect",
1213        args = {}
1214    )
1215    public void testDisconnect_UnconnectedClosed() throws IOException {
1216        assertFalse(this.channel1.isConnected());
1217        this.channel1.close();
1218        assertFalse(this.channel1.isOpen());
1219        assertEquals(this.channel1, this.channel1.disconnect());
1220        assertFalse(this.channel1.isConnected());
1221    }
1222
1223    /**
1224     * Test method for 'DatagramChannelImpl.disconnect()'
1225     *
1226     * @throws IOException
1227     */
1228    @TestTargetNew(
1229        level = TestLevel.PARTIAL_COMPLETE,
1230        notes = "",
1231        method = "disconnect",
1232        args = {}
1233    )
1234    public void testDisconnect_BlockWithServerChannelClosed()
1235            throws IOException {
1236        assertTrue(this.channel1.isBlocking());
1237        connectLocalServer();
1238        // disconnect after channel close
1239        this.channel1.close();
1240        disconnectAfterClosed();
1241    }
1242
1243    /**
1244     * Test method for 'DatagramChannelImpl.disconnect()'
1245     *
1246     * @throws IOException
1247     */
1248    @TestTargetNew(
1249        level = TestLevel.PARTIAL_COMPLETE,
1250        notes = "",
1251        method = "disconnect",
1252        args = {}
1253    )
1254    public void testDisconnect_NonBlockWithServerChannelClosed()
1255            throws IOException {
1256        this.channel1.configureBlocking(false);
1257        connectLocalServer();
1258        // disconnect after channel close
1259        this.channel1.close();
1260        disconnectAfterClosed();
1261    }
1262
1263    /**
1264     * Test method for 'DatagramChannelImpl.disconnect()'
1265     *
1266     * @throws IOException
1267     */
1268    @TestTargetNew(
1269        level = TestLevel.PARTIAL_COMPLETE,
1270        notes = "",
1271        method = "disconnect",
1272        args = {}
1273    )
1274    public void testDisconnect_BlockWithServerServerClosed()
1275            throws IOException {
1276        assertTrue(this.channel1.isBlocking());
1277        connectLocalServer();
1278        // disconnect after server close
1279        this.datagramSocket1.close();
1280        assertTrue(this.channel1.isOpen());
1281        assertTrue(this.channel1.isConnected());
1282        disconnectAfterConnected();
1283    }
1284
1285    /**
1286     * Test method for 'DatagramChannelImpl.disconnect()'
1287     *
1288     * @throws IOException
1289     */
1290    @TestTargetNew(
1291        level = TestLevel.PARTIAL_COMPLETE,
1292        notes = "",
1293        method = "disconnect",
1294        args = {}
1295    )
1296    public void testDisconnect_NonBlockWithServerServerClosed()
1297            throws IOException {
1298        this.channel1.configureBlocking(false);
1299        assertFalse(this.channel1.isBlocking());
1300        connectLocalServer();
1301        // disconnect after server close
1302        this.datagramSocket1.close();
1303        assertTrue(this.channel1.isOpen());
1304        assertTrue(this.channel1.isConnected());
1305        disconnectAfterConnected();
1306    }
1307
1308    // -------------------------------------------------------------------
1309    // Test for receive(): Behavior Without Server.
1310    // -------------------------------------------------------------------
1311
1312    /**
1313     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1314     *
1315     * @throws Exception
1316     */
1317    @TestTargetNew(
1318        level = TestLevel.PARTIAL_COMPLETE,
1319        notes = "",
1320        method = "receive",
1321        args = {java.nio.ByteBuffer.class}
1322    )
1323    public void testReceive_UnconnectedNull() throws Exception {
1324        assertFalse(this.channel1.isConnected());
1325        try {
1326            this.channel1.receive(null);
1327            fail("Should throw a NPE here."); //$NON-NLS-1$
1328        } catch (NullPointerException e) {
1329            // OK.
1330        }
1331    }
1332
1333    /**
1334     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1335     *
1336     * @throws Exception
1337     */
1338    @TestTargetNew(
1339        level = TestLevel.PARTIAL_COMPLETE,
1340        notes = "",
1341        method = "receive",
1342        args = {java.nio.ByteBuffer.class}
1343    )
1344    public void testReceive_UnconnectedReadonly() throws Exception {
1345        assertFalse(this.channel1.isConnected());
1346        ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL)
1347                .asReadOnlyBuffer();
1348        assertTrue(dst.isReadOnly());
1349        try {
1350            this.channel1.receive(dst);
1351            fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$
1352        } catch (IllegalArgumentException e) {
1353            // OK.
1354        }
1355    }
1356
1357    /**
1358     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1359     *
1360     * @throws Exception
1361     */
1362    @TestTargetNew(
1363        level = TestLevel.PARTIAL_COMPLETE,
1364        notes = "",
1365        method = "receive",
1366        args = {java.nio.ByteBuffer.class}
1367    )
1368    public void testReceive_UnconnectedBufEmpty() throws Exception {
1369        this.channel1.configureBlocking(false);
1370        assertFalse(this.channel1.isConnected());
1371        ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
1372        assertNull(this.channel1.receive(dst));
1373    }
1374
1375    /**
1376     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1377     *
1378     * @throws Exception
1379     */
1380    @TestTargetNew(
1381        level = TestLevel.PARTIAL_COMPLETE,
1382        notes = "",
1383        method = "receive",
1384        args = {java.nio.ByteBuffer.class}
1385    )
1386    public void testReceive_UnconnectedBufZero() throws Exception {
1387        assertFalse(this.channel1.isConnected());
1388        ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ZERO);
1389        assertNull(this.channel1.receive(dst));
1390    }
1391
1392    /**
1393     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1394     *
1395     * @throws Exception
1396     */
1397    @TestTargetNew(
1398        level = TestLevel.PARTIAL_COMPLETE,
1399        notes = "",
1400        method = "receive",
1401        args = {java.nio.ByteBuffer.class}
1402    )
1403    public void testReceive_UnconnectedBufNotEmpty() throws Exception {
1404        assertFalse(this.channel1.isConnected());
1405        ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
1406        // buf is not empty
1407        dst.put((byte) 88);
1408        assertEquals(dst.position() + CAPACITY_NORMAL - 1, dst.limit());
1409        assertNull(this.channel1.receive(dst));
1410    }
1411
1412    /**
1413     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1414     *
1415     * @throws Exception
1416     */
1417    @TestTargetNew(
1418        level = TestLevel.PARTIAL_COMPLETE,
1419        notes = "",
1420        method = "receive",
1421        args = {java.nio.ByteBuffer.class}
1422    )
1423    public void testReceive_UnconnectedBufFull() throws Exception {
1424        assertFalse(this.channel1.isConnected());
1425        ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ONE);
1426        // buf is full
1427        dst.put((byte) 88);
1428        assertEquals(dst.position(), dst.limit());
1429        assertNull(this.channel1.receive(dst));
1430    }
1431
1432    /**
1433     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1434     *
1435     * @throws Exception
1436     */
1437    @TestTargetNew(
1438        level = TestLevel.PARTIAL_COMPLETE,
1439        notes = "",
1440        method = "receive",
1441        args = {java.nio.ByteBuffer.class}
1442    )
1443    public void testReceive_UnconnectedClose() throws Exception {
1444        assertFalse(this.channel1.isConnected());
1445        ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
1446        this.channel1.close();
1447        assertFalse(this.channel1.isOpen());
1448        try {
1449            assertNull(this.channel1.receive(dst));
1450            fail("Should throw a ClosedChannelException here."); //$NON-NLS-1$
1451        } catch (ClosedChannelException e) {
1452            // OK.
1453        }
1454    }
1455
1456    /**
1457     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1458     *
1459     * @throws Exception
1460     */
1461    @TestTargetNew(
1462        level = TestLevel.PARTIAL_COMPLETE,
1463        notes = "",
1464        method = "receive",
1465        args = {java.nio.ByteBuffer.class}
1466    )
1467    public void testReceive_UnconnectedCloseNull() throws Exception {
1468        assertFalse(this.channel1.isConnected());
1469        this.channel1.close();
1470        assertFalse(this.channel1.isOpen());
1471        // checking buffer before checking open
1472        try {
1473            this.channel1.receive(null);
1474            fail("Should throw a NPE here."); //$NON-NLS-1$
1475        } catch (NullPointerException e) {
1476            // OK.
1477        }
1478    }
1479
1480    /**
1481     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1482     *
1483     * @throws Exception
1484     */
1485    @TestTargetNew(
1486        level = TestLevel.PARTIAL_COMPLETE,
1487        notes = "",
1488        method = "receive",
1489        args = {java.nio.ByteBuffer.class}
1490    )
1491    public void testReceive_UnconnectedCloseReadonly() throws Exception {
1492        assertFalse(this.channel1.isConnected());
1493        ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL)
1494                .asReadOnlyBuffer();
1495        assertTrue(dst.isReadOnly());
1496        this.channel1.close();
1497        assertFalse(this.channel1.isOpen());
1498        try {
1499            this.channel1.receive(dst);
1500            fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$
1501        } catch (IllegalArgumentException e) {
1502            // OK.
1503        }
1504    }
1505
1506    /**
1507     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1508     *
1509     * @throws Exception
1510     */
1511    @TestTargetNew(
1512        level = TestLevel.PARTIAL_COMPLETE,
1513        notes = "",
1514        method = "receive",
1515        args = {java.nio.ByteBuffer.class}
1516    )
1517    public void testReceive_NonBlockNoServerBufEmpty() throws Exception {
1518        this.channel1.configureBlocking(false);
1519        receiveNonBlockNoServer(CAPACITY_NORMAL);
1520    }
1521
1522    /**
1523     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1524     *
1525     * @throws Exception
1526     */
1527    @TestTargetNew(
1528        level = TestLevel.PARTIAL_COMPLETE,
1529        notes = "",
1530        method = "receive",
1531        args = {java.nio.ByteBuffer.class}
1532    )
1533    public void testReceive_BlockNoServerNull() throws Exception {
1534        assertTrue(this.channel1.isBlocking());
1535        receiveNoServerNull();
1536    }
1537
1538    /**
1539     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1540     *
1541     * @throws Exception
1542     */
1543    @TestTargetNew(
1544        level = TestLevel.PARTIAL_COMPLETE,
1545        notes = "",
1546        method = "receive",
1547        args = {java.nio.ByteBuffer.class}
1548    )
1549    public void testReceive_NonBlockNoServerNull() throws Exception {
1550        this.channel1.configureBlocking(false);
1551        receiveNoServerNull();
1552    }
1553
1554    /**
1555     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1556     *
1557     * @throws Exception
1558     */
1559    @TestTargetNew(
1560        level = TestLevel.PARTIAL_COMPLETE,
1561        notes = "",
1562        method = "receive",
1563        args = {java.nio.ByteBuffer.class}
1564    )
1565    public void testReceive_BlockNoServerReadonly() throws Exception {
1566        assertTrue(this.channel1.isBlocking());
1567        receiveNoServerReadonly();
1568    }
1569
1570    /**
1571     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1572     *
1573     * @throws Exception
1574     */
1575    @TestTargetNew(
1576        level = TestLevel.PARTIAL_COMPLETE,
1577        notes = "",
1578        method = "receive",
1579        args = {java.nio.ByteBuffer.class}
1580    )
1581    public void testReceive_NonBlockNoServerReadonly() throws Exception {
1582        this.channel1.configureBlocking(false);
1583        receiveNoServerReadonly();
1584    }
1585
1586    /**
1587     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1588     *
1589     * @throws Exception
1590     */
1591    @TestTargetNew(
1592        level = TestLevel.PARTIAL_COMPLETE,
1593        notes = "",
1594        method = "receive",
1595        args = {java.nio.ByteBuffer.class}
1596    )
1597    public void testReceive_NonBlockNoServerBufZero() throws Exception {
1598        this.channel1.configureBlocking(false);
1599        receiveNonBlockNoServer(CAPACITY_ZERO);
1600    }
1601
1602    /**
1603     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1604     *
1605     * @throws Exception
1606     */
1607    @TestTargetNew(
1608        level = TestLevel.PARTIAL_COMPLETE,
1609        notes = "",
1610        method = "receive",
1611        args = {java.nio.ByteBuffer.class}
1612    )
1613    public void testReceive_NonBlockNoServerBufNotEmpty() throws Exception {
1614        this.channel1.configureBlocking(false);
1615        connectWithoutServer();
1616        ByteBuffer dst = allocateNonEmptyBuf();
1617        assertNull(this.channel1.receive(dst));
1618    }
1619
1620
1621    /**
1622     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1623     *
1624     * @throws Exception
1625     */
1626    @TestTargetNew(
1627        level = TestLevel.PARTIAL_COMPLETE,
1628        notes = "",
1629        method = "receive",
1630        args = {java.nio.ByteBuffer.class}
1631    )
1632    public void testReceive_NonBlockNoServerBufFull() throws Exception {
1633        this.channel1.configureBlocking(false);
1634        connectWithoutServer();
1635        ByteBuffer dst = allocateFullBuf();
1636        assertNull(this.channel1.receive(dst));
1637    }
1638
1639    /**
1640     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1641     *
1642     * @throws Exception
1643     */
1644    @TestTargetNew(
1645        level = TestLevel.PARTIAL_COMPLETE,
1646        notes = "",
1647        method = "receive",
1648        args = {java.nio.ByteBuffer.class}
1649    )
1650    public void testReceive_BlockNoServerChannelClose() throws Exception {
1651        assertTrue(this.channel1.isBlocking());
1652        receiveNoServerChannelClose();
1653    }
1654
1655    /**
1656     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1657     *
1658     * @throws Exception
1659     */
1660    @TestTargetNew(
1661        level = TestLevel.PARTIAL_COMPLETE,
1662        notes = "",
1663        method = "receive",
1664        args = {java.nio.ByteBuffer.class}
1665    )
1666    public void testReceive_NonBlockNoServerChannelClose() throws Exception {
1667        this.channel1.configureBlocking(false);
1668        receiveNoServerChannelClose();
1669    }
1670
1671    /**
1672     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1673     *
1674     * @throws Exception
1675     */
1676    @TestTargetNew(
1677        level = TestLevel.PARTIAL_COMPLETE,
1678        notes = "",
1679        method = "receive",
1680        args = {java.nio.ByteBuffer.class}
1681    )
1682    public void testReceive_BlockNoServerCloseNull() throws Exception {
1683        assertTrue(this.channel1.isBlocking());
1684        receiveNoServerChannelCloseNull();
1685    }
1686
1687    /**
1688     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1689     *
1690     * @throws Exception
1691     */
1692    @TestTargetNew(
1693        level = TestLevel.PARTIAL_COMPLETE,
1694        notes = "",
1695        method = "receive",
1696        args = {java.nio.ByteBuffer.class}
1697    )
1698    public void testReceive_NonBlockNoServerCloseNull() throws Exception {
1699        this.channel1.configureBlocking(false);
1700        receiveNoServerChannelCloseNull();
1701    }
1702
1703    /**
1704     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1705     *
1706     * @throws Exception
1707     */
1708    @TestTargetNew(
1709        level = TestLevel.PARTIAL_COMPLETE,
1710        notes = "",
1711        method = "receive",
1712        args = {java.nio.ByteBuffer.class}
1713    )
1714    public void testReceive_NonBlockNoServerCloseReadonly() throws Exception {
1715        this.channel1.configureBlocking(false);
1716        receiveNoServerChannelCloseReadonly();
1717    }
1718
1719    /**
1720     * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
1721     *
1722     * @throws Exception
1723     */
1724    @TestTargetNew(
1725        level = TestLevel.PARTIAL_COMPLETE,
1726        notes = "",
1727        method = "receive",
1728        args = {java.nio.ByteBuffer.class}
1729    )
1730    public void testReceive_BlockNoServerCloseReadonly() throws Exception {
1731        assertTrue(this.channel1.isBlocking());
1732        receiveNoServerChannelCloseReadonly();
1733    }
1734
1735    private void receiveNoServerNull() throws IOException {
1736        connectWithoutServer();
1737        try {
1738            this.channel1.receive(null);
1739            fail("Should throw a NPE here."); //$NON-NLS-1$
1740        } catch (NullPointerException e) {
1741            // OK.
1742        }
1743    }
1744
1745    private void receiveNoServerReadonly() throws IOException {
1746        connectWithoutServer();
1747        ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL)
1748                .asReadOnlyBuffer();
1749        assertTrue(dst.isReadOnly());
1750        try {
1751            this.channel1.receive(dst);
1752            fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$
1753        } catch (IllegalArgumentException e) {
1754            // OK.
1755        }
1756    }
1757
1758    private void receiveNonBlockNoServer(int size) throws IOException {
1759        connectWithoutServer();
1760        ByteBuffer dst = ByteBuffer.allocateDirect(size);
1761        assertNull(this.channel1.receive(dst));
1762    }
1763
1764    private void receiveNoServerChannelClose() throws IOException {
1765        connectWithoutServer();
1766        ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
1767        this.channel1.close();
1768        assertFalse(this.channel1.isOpen());
1769        try {
1770            assertNull(this.channel1.receive(dst));
1771            fail("Should throw a ClosedChannelException here."); //$NON-NLS-1$
1772        } catch (ClosedChannelException e) {
1773            // OK.
1774        }
1775    }
1776
1777    private void receiveNoServerChannelCloseNull() throws IOException {
1778        connectWithoutServer();
1779        this.channel1.close();
1780        assertFalse(this.channel1.isOpen());
1781        try {
1782            this.channel1.receive(null);
1783            fail("Should throw a NPE here."); //$NON-NLS-1$
1784        } catch (NullPointerException e) {
1785            // OK.
1786        }
1787    }
1788
1789    private void receiveNoServerChannelCloseReadonly() throws IOException {
1790        connectWithoutServer();
1791        this.channel1.close();
1792        assertFalse(this.channel1.isOpen());
1793        ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL)
1794                .asReadOnlyBuffer();
1795        assertTrue(dst.isReadOnly());
1796        try {
1797            this.channel1.receive(dst);
1798            fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$
1799        } catch (IllegalArgumentException e) {
1800            // OK.
1801        }
1802    }
1803
1804    private ByteBuffer allocateFullBuf() {
1805        ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ONE);
1806        // buf is full
1807        dst.put((byte) 88);
1808        assertEquals(dst.position(), dst.limit());
1809        return dst;
1810    }
1811
1812    private ByteBuffer allocateNonEmptyBuf() {
1813        ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
1814        // buf is not empty
1815        dst.put((byte) 88);
1816        dst.put((byte) 99);
1817        assertEquals(dst.position() + CAPACITY_NORMAL - 2, dst.limit());
1818        return dst;
1819    }
1820
1821    // -------------------------------------------------------------------
1822    // Test for send(): Behavior without server.
1823    // -------------------------------------------------------------------
1824
1825    private void sendDataBlocking(InetSocketAddress addr, ByteBuffer writeBuf)
1826            throws IOException {
1827        InetSocketAddress ipAddr = addr;
1828        assertEquals(CAPACITY_NORMAL, this.channel1.send(writeBuf, ipAddr));
1829        assertTrue(this.channel1.isOpen());
1830        assertTrue(this.channel1.isBlocking());
1831        this.channel1.connect(ipAddr);
1832        assertTrue(this.channel1.isConnected());
1833    }
1834
1835    private void sendDataNonBlocking(InetSocketAddress addr, ByteBuffer writeBuf)
1836            throws IOException {
1837        InetSocketAddress ipAddr = addr;
1838        this.channel1.configureBlocking(false);
1839        assertEquals(CAPACITY_NORMAL, this.channel1.send(writeBuf, ipAddr));
1840        assertTrue(this.channel1.isOpen());
1841        assertFalse(this.channel1.isBlocking());
1842        this.channel1.connect(ipAddr);
1843        assertTrue(this.channel1.isConnected());
1844    }
1845
1846    /*
1847     * Test method for 'DatagramChannelImpl.send(ByteBuffer, SocketAddress)'
1848     */
1849    @TestTargetNew(
1850        level = TestLevel.PARTIAL_COMPLETE,
1851        notes = "",
1852        method = "send",
1853        args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
1854    )
1855    public void testSend_NoServerBlockingCommon() throws IOException {
1856        ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
1857        sendDataBlocking(localAddr1, writeBuf);
1858    }
1859
1860    @TestTargetNew(
1861        level = TestLevel.PARTIAL_COMPLETE,
1862        notes = "",
1863        method = "send",
1864        args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
1865    )
1866    public void testSend_NoServerNonblockingCommon() throws IOException {
1867        ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
1868        sendDataNonBlocking(localAddr1, writeBuf);
1869    }
1870
1871    @TestTargetNew(
1872        level = TestLevel.PARTIAL_COMPLETE,
1873        notes = "",
1874        method = "send",
1875        args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
1876    )
1877    public void testSend_NoServerTwice() throws IOException {
1878        ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
1879        sendDataBlocking(localAddr1, writeBuf);
1880        // can not buffer twice!
1881        assertEquals(0, this.channel1.send(writeBuf, localAddr1));
1882        try {
1883            channel1.send(writeBuf, localAddr2);
1884            fail("Should throw IllegalArgumentException");
1885        } catch (IllegalArgumentException e) {
1886            // correct
1887        }
1888    }
1889
1890    @TestTargetNew(
1891        level = TestLevel.PARTIAL_COMPLETE,
1892        notes = "",
1893        method = "send",
1894        args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
1895    )
1896    public void testSend_NoServerNonBlockingTwice() throws IOException {
1897        ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
1898        sendDataNonBlocking(localAddr1, writeBuf);
1899        // can not buffer twice!
1900        assertEquals(0, this.channel1.send(writeBuf, localAddr1));
1901        try {
1902            channel1.send(writeBuf, localAddr2);
1903            fail("Should throw IllegalArgumentException");
1904        } catch (IllegalArgumentException e) {
1905            // correct
1906        }
1907    }
1908
1909    @TestTargetNew(
1910        level = TestLevel.PARTIAL_COMPLETE,
1911        notes = "",
1912        method = "send",
1913        args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
1914    )
1915    public void testSend_NoServerBufNull() throws IOException {
1916        try {
1917            sendDataBlocking(localAddr1, null);
1918            fail("Should throw a NPE here.");
1919        } catch (NullPointerException e) {
1920            // correct
1921        }
1922    }
1923
1924    @TestTargetNew(
1925        level = TestLevel.PARTIAL_COMPLETE,
1926        notes = "",
1927        method = "send",
1928        args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
1929    )
1930    public void testSend_NoServerBufNullTwice() throws IOException {
1931        ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
1932        try {
1933            sendDataBlocking(localAddr1, null);
1934            fail("Should throw a NPE here.");
1935        } catch (NullPointerException e) {
1936            // correct
1937        }
1938        sendDataBlocking(localAddr1, writeBuf);
1939        try {
1940            channel1.send(null, localAddr2);
1941            fail("Should throw NPE");
1942        } catch (NullPointerException e) {
1943            // correct
1944        }
1945    }
1946
1947    @TestTargetNew(
1948        level = TestLevel.PARTIAL_COMPLETE,
1949        notes = "DOesn't verify all exceptions according to spec.",
1950        method = "send",
1951        args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
1952    )
1953    public void testSend_NoServerAddrNull() throws IOException {
1954        ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
1955        try {
1956            sendDataBlocking(null, writeBuf);
1957            fail("Should throw a NPE here.");
1958        } catch (NullPointerException e) {
1959            // correct
1960        }
1961    }
1962
1963    @TestTargetNew(
1964        level = TestLevel.PARTIAL_COMPLETE,
1965        notes = "",
1966        method = "send",
1967        args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
1968    )
1969    public void testSend_NoServerAddrNullTwice() throws IOException {
1970        ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
1971        try {
1972            sendDataBlocking(null, writeBuf);
1973            fail("Should throw NPE");
1974        } catch (NullPointerException e) {
1975            // correct
1976        }
1977        sendDataBlocking(localAddr1, writeBuf);
1978        try {
1979            channel1.send(writeBuf, null);
1980            fail("Should throw NPE");
1981        } catch (NullPointerException e) {
1982            // correct
1983        }
1984    }
1985
1986    // -------------------------------------------------------------------
1987    // Test for receive()and send(): Send and Receive with Real Data
1988    // -------------------------------------------------------------------
1989    @TestTargets({
1990        @TestTargetNew(
1991            level = TestLevel.PARTIAL_COMPLETE,
1992            notes = "",
1993            method = "receive",
1994            args = {java.nio.ByteBuffer.class}
1995        ),
1996        @TestTargetNew(
1997            level = TestLevel.PARTIAL_COMPLETE,
1998            notes = "",
1999            method = "send",
2000            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2001        )
2002    })
2003    public void testReceiveSend_Block_Normal() throws Exception {
2004        this.channel1.socket().bind(localAddr2);
2005        sendByChannel("some normal string in testReceiveSend_Normal",
2006                localAddr2);
2007        receiveByChannel(CAPACITY_NORMAL, localAddr2,
2008                "some normal string in testReceiveSend_Normal");
2009    }
2010
2011    @TestTargets({
2012        @TestTargetNew(
2013            level = TestLevel.PARTIAL_COMPLETE,
2014            notes = "",
2015            method = "receive",
2016            args = {java.nio.ByteBuffer.class}
2017        ),
2018        @TestTargetNew(
2019            level = TestLevel.PARTIAL_COMPLETE,
2020            notes = "",
2021            method = "send",
2022            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2023        )
2024    })
2025    public void testReceiveSend_Block_NotBound() throws Exception {
2026        // not bound
2027        sendByChannel("some normal string in testReceiveSend_Normal",
2028                localAddr2);
2029        ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
2030        assertNull(channel1.receive(buf));
2031        assertFalse(channel1.socket().isBound());
2032    }
2033
2034    @TestTargets({
2035        @TestTargetNew(
2036            level = TestLevel.PARTIAL_COMPLETE,
2037            notes = "",
2038            method = "receive",
2039            args = {java.nio.ByteBuffer.class}
2040        ),
2041        @TestTargetNew(
2042            level = TestLevel.PARTIAL_COMPLETE,
2043            notes = "",
2044            method = "send",
2045            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2046        )
2047    })
2048    public void testReceiveSend_NonBlock_NotBound() throws Exception {
2049        // not bound
2050        this.channel1.configureBlocking(false);
2051        this.channel2.configureBlocking(false);
2052        sendByChannel("some normal string in testReceiveSend_Normal",
2053                localAddr2);
2054        ByteBuffer buf = ByteBuffer.wrap(new byte[CAPACITY_NORMAL]);
2055        assertNull(this.channel1.receive(buf));
2056    }
2057
2058    @TestTargets({
2059        @TestTargetNew(
2060            level = TestLevel.PARTIAL_COMPLETE,
2061            notes = "",
2062            method = "receive",
2063            args = {java.nio.ByteBuffer.class}
2064        ),
2065        @TestTargetNew(
2066            level = TestLevel.PARTIAL_COMPLETE,
2067            notes = "",
2068            method = "send",
2069            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2070        )
2071    })
2072    public void testReceiveSend_Block_Normal_S2C() throws Exception {
2073        this.channel1.socket().bind(localAddr2);
2074        sendByDatagramSocket(
2075                "some normal string in testReceiveSend_Normal_S2C", localAddr2);
2076        receiveByChannel(CAPACITY_NORMAL, localAddr2,
2077                "some normal string in testReceiveSend_Normal_S2C");
2078    }
2079
2080    @TestTargets({
2081        @TestTargetNew(
2082            level = TestLevel.PARTIAL_COMPLETE,
2083            notes = "",
2084            method = "receive",
2085            args = {java.nio.ByteBuffer.class}
2086        ),
2087        @TestTargetNew(
2088            level = TestLevel.PARTIAL_COMPLETE,
2089            notes = "",
2090            method = "send",
2091            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2092        )
2093    })
2094    public void testReceiveSend_Block_Normal_C2S() throws Exception {
2095        this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
2096        String str1 = "some normal string in testReceiveSend_Normal_C2S";
2097        sendByChannel(str1, localAddr2);
2098        receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, str1);
2099    }
2100
2101    @TestTargets({
2102        @TestTargetNew(
2103            level = TestLevel.PARTIAL_COMPLETE,
2104            notes = "",
2105            method = "receive",
2106            args = {java.nio.ByteBuffer.class}
2107        ),
2108        @TestTargetNew(
2109            level = TestLevel.PARTIAL_COMPLETE,
2110            notes = "",
2111            method = "send",
2112            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2113        )
2114    })
2115    public void testReceiveSend_NonBlock_Normal_C2S() throws Exception {
2116        this.channel1.configureBlocking(false);
2117        this.channel2.configureBlocking(false);
2118        this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
2119        String str1 = "some normal string in testReceiveSend_Normal_C2S";
2120        sendByChannel(str1, localAddr2);
2121        receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, str1);
2122    }
2123
2124    @TestTargets({
2125        @TestTargetNew(
2126            level = TestLevel.PARTIAL_COMPLETE,
2127            notes = "",
2128            method = "receive",
2129            args = {java.nio.ByteBuffer.class}
2130        ),
2131        @TestTargetNew(
2132            level = TestLevel.PARTIAL_COMPLETE,
2133            notes = "",
2134            method = "send",
2135            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2136        )
2137    })
2138    public void testReceiveSend_Normal_S2S() throws Exception {
2139        String msg = "normal string in testReceiveSend_Normal_S2S";
2140        this.datagramSocket1 = new DatagramSocket(testPort);
2141        DatagramPacket rdp = new DatagramPacket(msg.getBytes(), msg.length(),
2142                localAddr2);
2143        datagramSocket2 = new DatagramSocket(localAddr2.getPort());
2144        this.datagramSocket1.send(rdp);
2145        byte[] buf = new byte[CAPACITY_NORMAL];
2146        this.datagramSocket2.setSoTimeout(TIME_UNIT);
2147        rdp = new DatagramPacket(buf, buf.length);
2148        this.datagramSocket2.receive(rdp);
2149        assertEquals(new String(buf, 0, CAPACITY_NORMAL).trim(), msg);
2150    }
2151
2152    @TestTargets({
2153        @TestTargetNew(
2154            level = TestLevel.PARTIAL_COMPLETE,
2155            notes = "",
2156            method = "receive",
2157            args = {java.nio.ByteBuffer.class}
2158        ),
2159        @TestTargetNew(
2160            level = TestLevel.PARTIAL_COMPLETE,
2161            notes = "",
2162            method = "send",
2163            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2164        )
2165    })
2166    public void testReceiveSend_Block_Empty() throws Exception {
2167        this.channel1.socket().bind(localAddr2);
2168        sendByChannel("", localAddr2);
2169        receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
2170    }
2171
2172    @TestTargets({
2173        @TestTargetNew(
2174            level = TestLevel.PARTIAL_COMPLETE,
2175            notes = "",
2176            method = "receive",
2177            args = {java.nio.ByteBuffer.class}
2178        ),
2179        @TestTargetNew(
2180            level = TestLevel.PARTIAL_COMPLETE,
2181            notes = "",
2182            method = "send",
2183            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2184        )
2185    })
2186    public void testReceiveSend_NonBlock_Empty() throws Exception {
2187        this.channel1.configureBlocking(false);
2188        this.channel2.configureBlocking(false);
2189        this.channel1.socket().bind(localAddr2);
2190        sendByChannel("", localAddr2);
2191        receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
2192    }
2193
2194    @TestTargets({
2195        @TestTargetNew(
2196            level = TestLevel.PARTIAL_COMPLETE,
2197            notes = "",
2198            method = "receive",
2199            args = {java.nio.ByteBuffer.class}
2200        ),
2201        @TestTargetNew(
2202            level = TestLevel.PARTIAL_COMPLETE,
2203            notes = "",
2204            method = "send",
2205            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2206        )
2207    })
2208    public void testReceiveSend_Block_Empty_S2C() throws Exception {
2209        this.channel1.socket().bind(localAddr2);
2210        sendByDatagramSocket("", localAddr2);
2211        receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
2212    }
2213
2214    @TestTargets({
2215        @TestTargetNew(
2216            level = TestLevel.PARTIAL_COMPLETE,
2217            notes = "",
2218            method = "receive",
2219            args = {java.nio.ByteBuffer.class}
2220        ),
2221        @TestTargetNew(
2222            level = TestLevel.PARTIAL_COMPLETE,
2223            notes = "",
2224            method = "send",
2225            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2226        )
2227    })
2228    public void testReceiveSend_NonBlock_Empty_S2C() throws Exception {
2229        this.channel1.configureBlocking(false);
2230        this.channel2.configureBlocking(false);
2231        this.channel1.socket().bind(localAddr2);
2232        sendByDatagramSocket("", localAddr2);
2233        receiveByChannel(CAPACITY_NORMAL, localAddr2, "");
2234    }
2235
2236    @TestTargets({
2237        @TestTargetNew(
2238            level = TestLevel.PARTIAL_COMPLETE,
2239            notes = "",
2240            method = "receive",
2241            args = {java.nio.ByteBuffer.class}
2242        ),
2243        @TestTargetNew(
2244            level = TestLevel.PARTIAL_COMPLETE,
2245            notes = "",
2246            method = "send",
2247            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2248        )
2249    })
2250    public void testReceiveSend_Block_Empty_C2S() throws Exception {
2251        this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
2252        sendByChannel("", localAddr2);
2253        receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, "");
2254    }
2255
2256    @TestTargets({
2257        @TestTargetNew(
2258            level = TestLevel.PARTIAL_COMPLETE,
2259            notes = "",
2260            method = "receive",
2261            args = {java.nio.ByteBuffer.class}
2262        ),
2263        @TestTargetNew(
2264            level = TestLevel.PARTIAL_COMPLETE,
2265            notes = "",
2266            method = "send",
2267            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2268        )
2269    })
2270    public void testReceiveSend_NonBlock_Empty_C2S() throws Exception {
2271        this.channel1.configureBlocking(false);
2272        this.channel2.configureBlocking(false);
2273        this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
2274        sendByChannel("", localAddr2);
2275        receiveByDatagramSocket(CAPACITY_NORMAL, localAddr2, "");
2276    }
2277
2278    @TestTargetNew(
2279        level = TestLevel.PARTIAL_COMPLETE,
2280        notes = "",
2281        method = "receive",
2282        args = {java.nio.ByteBuffer.class}
2283    )
2284    public void testReceiveSend_Empty_S2S() throws Exception {
2285        String msg = "";
2286        this.datagramSocket1 = new DatagramSocket(testPort);
2287        DatagramPacket rdp = new DatagramPacket(msg.getBytes(), msg.length(),
2288                localAddr2);
2289        datagramSocket2 = new DatagramSocket(localAddr2.getPort());
2290        this.datagramSocket1.send(rdp);
2291        byte[] buf = new byte[CAPACITY_NORMAL];
2292        this.datagramSocket2.setSoTimeout(TIME_UNIT);
2293        rdp = new DatagramPacket(buf, buf.length);
2294        this.datagramSocket2.receive(rdp);
2295        assertEquals(new String(buf, 0, CAPACITY_NORMAL).trim(), msg);
2296    }
2297
2298    @TestTargets({
2299        @TestTargetNew(
2300            level = TestLevel.PARTIAL_COMPLETE,
2301            notes = "",
2302            method = "receive",
2303            args = {java.nio.ByteBuffer.class}
2304        ),
2305        @TestTargetNew(
2306            level = TestLevel.PARTIAL_COMPLETE,
2307            notes = "",
2308            method = "send",
2309            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2310        )
2311    })
2312    public void testReceiveSend_Block_Oversize() throws Exception {
2313        this.channel1.socket().bind(localAddr2);
2314        sendByChannel("0123456789", localAddr2);
2315        receiveByChannel(5, localAddr2, "01234");
2316    }
2317
2318    @TestTargets({
2319        @TestTargetNew(
2320            level = TestLevel.PARTIAL_COMPLETE,
2321            notes = "",
2322            method = "receive",
2323            args = {java.nio.ByteBuffer.class}
2324        ),
2325        @TestTargetNew(
2326            level = TestLevel.PARTIAL_COMPLETE,
2327            notes = "",
2328            method = "send",
2329            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2330        )
2331    })
2332    public void testReceiveSend_Block_Oversize_C2S() throws Exception {
2333        this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
2334        sendByChannel("0123456789", localAddr2);
2335        receiveByDatagramSocket(5, localAddr2, "01234");
2336    }
2337
2338    @TestTargets({
2339        @TestTargetNew(
2340            level = TestLevel.PARTIAL_COMPLETE,
2341            notes = "",
2342            method = "receive",
2343            args = {java.nio.ByteBuffer.class}
2344        ),
2345        @TestTargetNew(
2346            level = TestLevel.PARTIAL_COMPLETE,
2347            notes = "",
2348            method = "send",
2349            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2350        )
2351    })
2352    public void testReceiveSend_NonBlock_Oversize_C2S() throws Exception {
2353        this.channel1.configureBlocking(false);
2354        this.channel2.configureBlocking(false);
2355        this.datagramSocket1 = new DatagramSocket(localAddr2.getPort());
2356        sendByChannel("0123456789", localAddr2);
2357        receiveByDatagramSocket(5, localAddr2, "01234");
2358    }
2359
2360    @TestTargets({
2361        @TestTargetNew(
2362            level = TestLevel.PARTIAL_COMPLETE,
2363            notes = "",
2364            method = "receive",
2365            args = {java.nio.ByteBuffer.class}
2366        ),
2367        @TestTargetNew(
2368            level = TestLevel.PARTIAL_COMPLETE,
2369            notes = "",
2370            method = "send",
2371            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2372        )
2373    })
2374    public void testReceiveSend_Block_Oversize_S2C() throws Exception {
2375        this.channel1.socket().bind(localAddr2);
2376        sendByDatagramSocket("0123456789", localAddr2);
2377        receiveByChannel(5, localAddr2, "01234");
2378    }
2379
2380    @TestTargets({
2381        @TestTargetNew(
2382            level = TestLevel.PARTIAL_COMPLETE,
2383            notes = "",
2384            method = "receive",
2385            args = {java.nio.ByteBuffer.class}
2386        ),
2387        @TestTargetNew(
2388            level = TestLevel.PARTIAL_COMPLETE,
2389            notes = "",
2390            method = "send",
2391            args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2392        )
2393    })
2394    public void testReceiveSend_8K() throws Exception {
2395        StringBuffer str8k = new StringBuffer();
2396        for (int i = 0; i < 8 * CAPACITY_1KB; i++) {
2397            str8k.append("a");
2398        }
2399        String str = str8k.toString();
2400        this.channel1.socket().bind(localAddr2);
2401        sendByChannel(str, localAddr2);
2402        receiveByChannel(8 * CAPACITY_1KB, localAddr2, str);
2403    }
2404
2405    @TestTargetNew(
2406        level = TestLevel.PARTIAL_COMPLETE,
2407        notes = "",
2408        method = "send",
2409        args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2410    )
2411    public void testReceiveSend_64K() throws Exception {
2412        StringBuffer str64k = new StringBuffer();
2413        for (int i = 0; i < CAPACITY_64KB; i++) {
2414            str64k.append("a");
2415        }
2416        String str = str64k.toString();
2417        try {
2418            Thread.sleep(TIME_UNIT);
2419            channel2.send(ByteBuffer.wrap(str.getBytes()), localAddr1);
2420            fail("Should throw SocketException!");
2421        } catch (SocketException e) {
2422            //expected
2423        }
2424    }
2425
2426    private void sendByChannel(String data, InetSocketAddress address)
2427            throws Exception {
2428        try {
2429            assertEquals(data.length(), this.channel2.send(ByteBuffer.wrap(data
2430                    .getBytes()), address));
2431        } finally {
2432            this.channel2.close();
2433        }
2434    }
2435
2436    private void sendByDatagramSocket(String data, InetSocketAddress address)
2437            throws Exception {
2438        this.datagramSocket1 = new DatagramSocket(testPort);
2439        DatagramPacket rdp = new DatagramPacket(data.getBytes(), data.length(),
2440                address);
2441        this.datagramSocket1.send(rdp);
2442    }
2443
2444    private void receiveByChannel(int bufSize, InetSocketAddress address,
2445            String expectedString) throws IOException {
2446        try {
2447            ByteBuffer buf = ByteBuffer.wrap(new byte[bufSize]);
2448            InetSocketAddress returnAddr = null;
2449            long startTime = System.currentTimeMillis();
2450            do {
2451                returnAddr = (InetSocketAddress) this.channel1.receive(buf);
2452                // continue loop when channel1 is non-blocking and no data was
2453                // received.
2454                if (channel1.isBlocking() || null != returnAddr) {
2455                    break;
2456                }
2457                // avoid dead loop
2458                assertTimeout(startTime, 10000);
2459            } while (true);
2460            int length = returnAddr.getAddress().getAddress().length;
2461            for (int i = 0; i < length; i++) {
2462                assertEquals(returnAddr.getAddress().getAddress()[i],
2463                        InetAddress.getByName("127.0.0.1").getAddress()[i]);
2464            }
2465            // port is NOT equal
2466            assertFalse(returnAddr.getPort() == address.getPort());
2467            assertEquals(new String(buf.array(), 0, bufSize).trim(),
2468                    expectedString);
2469        } finally {
2470            this.channel1.close();
2471        }
2472    }
2473
2474    /*
2475     * Fails if the difference between current time and start time is greater
2476     * than timeout.
2477     */
2478    private void assertTimeout(long startTime, long timeout) {
2479        long currentTime = System.currentTimeMillis();
2480        if ((currentTime - startTime) > timeout) {
2481            fail("Timeout");
2482        }
2483    }
2484
2485    private void receiveByDatagramSocket(int bufSize,
2486            InetSocketAddress address, String expectedString)
2487            throws IOException {
2488        byte[] buf = new byte[bufSize];
2489        this.datagramSocket1.setSoTimeout(6000);
2490        DatagramPacket rdp = new DatagramPacket(buf, buf.length);
2491        this.datagramSocket1.receive(rdp);
2492        assertEquals(new String(buf, 0, bufSize).trim(), expectedString);
2493    }
2494
2495    // -------------------------------------------------------------------
2496    // Test for security check of receive and send
2497    // -------------------------------------------------------------------
2498
2499    private class mockAddress extends SocketAddress {
2500        private static final long serialVersionUID = 1L;
2501    }
2502
2503    @TestTargetNew(
2504        level = TestLevel.PARTIAL_COMPLETE,
2505        notes = "",
2506        method = "send",
2507        args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
2508    )
2509    public void testSend_MockSocketAddress() throws Exception {
2510
2511        SocketAddress badAddr = new mockAddress();
2512        final SecurityManager sm = System.getSecurityManager();
2513        System.setSecurityManager(new MockSecurityManager());
2514        try {
2515            // no problem.
2516            this.channel1
2517                    .send(ByteBuffer.allocate(CAPACITY_NORMAL), localAddr1);
2518            // re open
2519            this.channel1.close();
2520            this.channel1 = DatagramChannel.open();
2521            try {
2522                this.channel1.send(ByteBuffer.allocate(CAPACITY_NORMAL),
2523                        badAddr);
2524                fail("Should throw ClassCastException");
2525            } catch (ClassCastException e) {
2526                // ok
2527            }
2528        } finally {
2529            System.setSecurityManager(sm);
2530        }
2531    }
2532
2533    @TestTargetNew(
2534        level = TestLevel.PARTIAL_COMPLETE,
2535        notes = "Doesn't verify AsynchronousCloseException, ClosedByInterruptException, IOException.",
2536        method = "send",
2537        args = {java.nio.ByteBuffer.class, SocketAddress.class}
2538    )
2539    public void testSend_Security() throws Exception {
2540        ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
2541        String strHello = "hello";
2542        localAddr1 = new InetSocketAddress("127.0.0.1", testPort);
2543        this.channel1.socket().bind(localAddr1);
2544        this.channel2.socket().bind(localAddr2);
2545        this.channel1.connect(localAddr2);
2546
2547        final SecurityManager sm = System.getSecurityManager();
2548        MockSecurityManager mockManager = new MockSecurityManager("127.0.0.1");
2549        System.setSecurityManager(mockManager);
2550
2551        try {
2552            this.channel2.send(ByteBuffer.wrap(strHello.getBytes()), localAddr1);
2553            assertEquals(strHello.length(), this.channel1.read(buf));
2554        } finally {
2555            System.setSecurityManager(sm);
2556        }
2557
2558        assertTrue(mockManager.checkConnectCalled);
2559    }
2560
2561    public void disabled_testSend_Block_close() throws Exception {
2562        // bind and connect
2563        this.channel1.socket().bind(localAddr2);
2564        this.channel1.connect(localAddr1);
2565        this.channel2.socket().bind(localAddr1);
2566        this.channel2.connect(localAddr2);
2567        ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
2568
2569        new Thread() {
2570            public void run() {
2571                try {
2572                    Thread.sleep(TIME_UNIT);
2573                    channel1.close();
2574                } catch (Exception e) {
2575                    //ignore
2576                }
2577            }
2578        }.start();
2579        try {
2580            this.channel1.send(targetBuf, localAddr1);
2581            fail("should throw AsynchronousCloseException");
2582        } catch (AsynchronousCloseException e) {
2583            // ok
2584        }
2585    }
2586
2587    public void disabled_testSend_Block_interrupt() throws Exception {
2588        // bind and connect
2589        this.channel1.socket().bind(localAddr2);
2590        this.channel1.connect(localAddr1);
2591        this.channel2.socket().bind(localAddr1);
2592        this.channel2.connect(localAddr2);
2593
2594        class MyThread extends Thread {
2595            public String errMsg = null;
2596            public void run() {
2597                try {
2598                    ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
2599                    channel1.send(targetBuf, localAddr1);
2600                    errMsg = "should throw ClosedByInterruptException";
2601                } catch (ClosedByInterruptException e) {
2602                    // expected
2603                } catch (IOException e) {
2604                    errMsg = "Unexcted Exception was thrown: " + e.getClass() +
2605                            ": " + e.getMessage();
2606                }
2607            }
2608        }
2609        MyThread thread = new MyThread();
2610        thread.start();
2611        try {
2612            Thread.sleep(TIME_UNIT);
2613            thread.interrupt();
2614        } catch (InterruptedException e) {
2615            // ok
2616        }
2617        thread.join(TIME_UNIT);
2618        if (thread.errMsg != null) {
2619            fail(thread.errMsg);
2620        }
2621    }
2622
2623    @TestTargetNew(
2624        level = TestLevel.PARTIAL_COMPLETE,
2625        notes = "",
2626        method = "receive",
2627        args = {java.nio.ByteBuffer.class}
2628    )
2629    public void testReceive_Security() throws Exception {
2630        ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
2631        String strHello = "hello";
2632        localAddr1 = new InetSocketAddress("127.0.0.1", testPort);
2633        this.channel1.socket().bind(localAddr1);
2634        sendByChannel(strHello, localAddr1);
2635
2636        final SecurityManager sm = System.getSecurityManager();
2637        MockSecurityManager mockManager = new MockSecurityManager("10.0.0.1");
2638        System.setSecurityManager(mockManager);
2639
2640        try {
2641            this.channel1.configureBlocking(false);
2642            assertNull(this.channel1.receive(buf));
2643        } finally {
2644            System.setSecurityManager(sm);
2645        }
2646
2647        assertTrue(mockManager.checkAcceptCalled);
2648    }
2649
2650    @TestTargetNew(
2651        level = TestLevel.PARTIAL_COMPLETE,
2652        notes = "",
2653        method = "receive",
2654        args = {java.nio.ByteBuffer.class}
2655    )
2656    public void testReceive_Block_close() throws Exception {
2657        // bind and connect
2658        this.channel1.socket().bind(localAddr2);
2659        this.channel1.connect(localAddr1);
2660        this.channel2.socket().bind(localAddr1);
2661        this.channel2.connect(localAddr2);
2662        ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
2663
2664        new Thread() {
2665            public void run() {
2666                try {
2667                    Thread.sleep(TIME_UNIT);
2668                    channel1.close();
2669                } catch (Exception e) {
2670                    //ignore
2671                }
2672            }
2673        }.start();
2674        try {
2675            this.channel1.receive(targetBuf);
2676            fail("should throw AsynchronousCloseException");
2677        } catch (AsynchronousCloseException e) {
2678            // ok
2679        }
2680    }
2681
2682    @TestTargetNew(
2683        level = TestLevel.PARTIAL_COMPLETE,
2684        notes = "",
2685        method = "receive",
2686        args = {java.nio.ByteBuffer.class}
2687    )
2688    public void testReceive_Block_interrupt() throws Exception {
2689        // bind and connect
2690        this.channel1.socket().bind(localAddr2);
2691        this.channel1.connect(localAddr1);
2692        this.channel2.socket().bind(localAddr1);
2693        this.channel2.connect(localAddr2);
2694
2695        class MyThread extends Thread {
2696            public String errMsg = null;
2697            public void run() {
2698                try {
2699                    ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
2700                    channel1.receive(targetBuf);
2701                    errMsg = "should throw ClosedByInterruptException";
2702                } catch (ClosedByInterruptException e) {
2703                    // expected
2704                } catch (IOException e) {
2705                    errMsg = "Unexcted Exception was thrown: " + e.getClass() +
2706                            ": " + e.getMessage();
2707                }
2708            }
2709        }
2710        MyThread thread = new MyThread();
2711        thread.start();
2712        try {
2713            Thread.sleep(TIME_UNIT);
2714            thread.interrupt();
2715        } catch (InterruptedException e) {
2716            // ok
2717        }
2718        thread.join(TIME_UNIT);
2719        if (thread.errMsg != null) {
2720            fail(thread.errMsg);
2721        }
2722    }
2723
2724    @TestTargetNew(
2725        level = TestLevel.PARTIAL_COMPLETE,
2726        notes = "",
2727        method = "connect",
2728        args = {java.net.SocketAddress.class}
2729    )
2730    public void testConnect_Security() throws IOException {
2731        localAddr1 = new InetSocketAddress("127.0.0.1", testPort);
2732        SecurityManager sm = System.getSecurityManager();
2733        MockSecurityManager mockManager = new MockSecurityManager("127.0.0.1");
2734        System.setSecurityManager(mockManager);
2735
2736        try {
2737            this.channel1.connect(localAddr1);
2738        } finally {
2739            System.setSecurityManager(sm);
2740        }
2741
2742        assertTrue(mockManager.checkConnectCalled);
2743    }
2744
2745    // -------------------------------------------------------------------
2746    // Test for write()
2747    // -------------------------------------------------------------------
2748
2749    private void connectWriteBuf(InetSocketAddress ipAddr, ByteBuffer buf)
2750            throws IOException {
2751        this.channel1.connect(ipAddr);
2752        assertTrue(this.channel1.isConnected());
2753        assertEquals(CAPACITY_NORMAL, this.channel1.write(buf));
2754        assertEquals(0, this.channel1.write(buf));
2755    }
2756
2757    private void noconnectWrite(ByteBuffer buf) throws IOException {
2758        try {
2759            this.channel1.write(buf);
2760            fail("should throw NotYetConnectedException");
2761        } catch (NotYetConnectedException e) {
2762            // correct
2763        }
2764    }
2765
2766    /*
2767     * Test method for 'DatagramChannelImpl.write(ByteBuffer)'
2768     */
2769    @TestTargetNew(
2770        level = TestLevel.PARTIAL_COMPLETE,
2771        notes = "",
2772        method = "write",
2773        args = {java.nio.ByteBuffer.class}
2774    )
2775    public void testWriteByteBuffer_Block() throws IOException {
2776        ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
2777        connectWriteBuf(localAddr1, writeBuf);
2778    }
2779
2780    @TestTargetNew(
2781        level = TestLevel.PARTIAL_COMPLETE,
2782        notes = "",
2783        method = "write",
2784        args = {java.nio.ByteBuffer.class}
2785    )
2786    public void testWriteByteBuffer_NonBlock() throws IOException {
2787        ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
2788        this.channel1.configureBlocking(false);
2789        connectWriteBuf(localAddr1, writeBuf);
2790    }
2791
2792    @TestTargetNew(
2793        level = TestLevel.PARTIAL_COMPLETE,
2794        notes = "",
2795        method = "write",
2796        args = {java.nio.ByteBuffer.class}
2797    )
2798    public void testWriteByteBuffer_BlockClosed() throws IOException {
2799        ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
2800        InetSocketAddress ipAddr = localAddr1;
2801        noconnectWrite(writeBuf);
2802        this.channel1.connect(ipAddr);
2803        assertTrue(this.channel1.isConnected());
2804        this.channel1.close();
2805        try {
2806            channel1.write(writeBuf);
2807            fail("should throw ClosedChannelException");
2808        } catch (ClosedChannelException e) {
2809            // correct
2810        }
2811    }
2812
2813    @TestTargetNew(
2814        level = TestLevel.PARTIAL_COMPLETE,
2815        notes = "",
2816        method = "write",
2817        args = {java.nio.ByteBuffer.class}
2818    )
2819    public void testWriteByteBuffer_NonBlockClosed() throws IOException {
2820        ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
2821        InetSocketAddress ipAddr = localAddr1;
2822        // non block mode
2823        this.channel1.configureBlocking(false);
2824        noconnectWrite(writeBuf);
2825        this.channel1.connect(ipAddr);
2826        assertTrue(this.channel1.isConnected());
2827        this.channel1.close();
2828        try {
2829            channel1.write(writeBuf);
2830            fail("should throw ClosedChannelException");
2831        } catch (ClosedChannelException e) {
2832            // correct
2833        }
2834    }
2835
2836    @TestTargetNew(
2837        level = TestLevel.PARTIAL_COMPLETE,
2838        notes = "",
2839        method = "write",
2840        args = {java.nio.ByteBuffer.class}
2841    )
2842    public void testWriteByteBuffer_BlockBufNull() throws IOException {
2843        ByteBuffer writeBuf = ByteBuffer.allocateDirect(0);
2844        InetSocketAddress ipAddr = localAddr1;
2845        try {
2846            this.channel1.write((ByteBuffer) null);
2847            fail("Should throw NPE.");
2848        } catch (NullPointerException e) {
2849            // correct
2850        }
2851        this.channel1.connect(ipAddr);
2852        assertTrue(this.channel1.isConnected());
2853        try {
2854            this.channel1.write((ByteBuffer) null);
2855            fail("Should throw NPE.");
2856        } catch (NullPointerException e) {
2857            // correct
2858        }
2859        assertEquals(0, this.channel1.write(writeBuf));
2860        datagramSocket1.close();
2861        try {
2862            this.channel1.write((ByteBuffer) null);
2863            fail("Should throw NPE.");
2864        } catch (NullPointerException e) {
2865            // correct
2866        }
2867    }
2868
2869    @TestTargetNew(
2870        level = TestLevel.PARTIAL_COMPLETE,
2871        notes = "",
2872        method = "write",
2873        args = {java.nio.ByteBuffer.class}
2874    )
2875    public void testWriteByteBuffer_NonBlockBufNull() throws IOException {
2876        ByteBuffer writeBuf = ByteBuffer.allocateDirect(0);
2877        InetSocketAddress ipAddr = localAddr1;
2878
2879        // non block mode
2880        this.channel1.configureBlocking(false);
2881
2882        try {
2883            this.channel1.write((ByteBuffer) null);
2884            fail("Should throw NPE.");
2885        } catch (NullPointerException e) {
2886            // correct
2887        }
2888        this.channel1.connect(ipAddr);
2889        assertTrue(this.channel1.isConnected());
2890        try {
2891            this.channel1.write((ByteBuffer) null);
2892            fail("Should throw NPE.");
2893        } catch (NullPointerException e) {
2894            // correct
2895        }
2896        assertEquals(0, this.channel1.write(writeBuf));
2897        datagramSocket1.close();
2898        try {
2899            this.channel1.write((ByteBuffer) null);
2900            fail("Should throw NPE.");
2901        } catch (NullPointerException e) {
2902            // correct
2903        }
2904    }
2905
2906    /*
2907     * Test method for 'DatagramChannelImpl.write(ByteBuffer[], int, int)'
2908     */
2909    @TestTargetNew(
2910        level = TestLevel.PARTIAL_COMPLETE,
2911        notes = "Doesn't verify all exceptions according to specification.",
2912        method = "write",
2913        args = {java.nio.ByteBuffer[].class, int.class, int.class}
2914    )
2915    public void testWriteByteBufferArrayII_Block() throws IOException {
2916        ByteBuffer[] writeBuf = new ByteBuffer[2];
2917        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
2918        writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
2919        InetSocketAddress ipAddr = localAddr1;
2920        try {
2921            this.channel1.write(writeBuf, 0, 2);
2922            fail("Should throw NotYetConnectedException.");
2923        } catch (NotYetConnectedException e) {
2924            // correct
2925        }
2926        this.channel1.connect(ipAddr);
2927        assertTrue(this.channel1.isConnected());
2928        assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2));
2929        // cannot be buffered again!
2930        assertEquals(0, this.channel1.write(writeBuf, 0, 1));
2931        this.channel1.close();
2932        try {
2933            this.channel1.write(writeBuf, 0, 1);
2934            fail("Should throw ClosedChannelEception.");
2935        } catch (ClosedChannelException e) {
2936            // expected
2937        }
2938    }
2939
2940    public void disabled_testWriteByteBufferArrayII_Block_close() throws Exception {
2941        // bind and connect
2942        this.channel1.socket().bind(localAddr2);
2943        this.channel1.connect(localAddr1);
2944        this.channel2.socket().bind(localAddr1);
2945        this.channel2.connect(localAddr2);
2946        ByteBuffer[] targetBuf = new ByteBuffer[2];
2947        targetBuf[0] = ByteBuffer.wrap(new byte[2]);
2948        targetBuf[1] = ByteBuffer.wrap(new byte[2]);
2949
2950        new Thread() {
2951            public void run() {
2952                try {
2953                    Thread.sleep(TIME_UNIT);
2954                    channel1.close();
2955                } catch (Exception e) {
2956                    //ignore
2957                }
2958            }
2959        }.start();
2960        try {
2961            this.channel1.write(targetBuf, 0 ,2);
2962            fail("should throw AsynchronousCloseException");
2963        } catch (AsynchronousCloseException e) {
2964            // ok
2965        }
2966    }
2967
2968    public void disabled_testWriteByteBufferArrayII_Block_interrupt() throws Exception {
2969        // bind and connect
2970        this.channel1.socket().bind(localAddr2);
2971        this.channel1.connect(localAddr1);
2972        this.channel2.socket().bind(localAddr1);
2973        this.channel2.connect(localAddr2);
2974
2975        class MyThread extends Thread {
2976            public String errMsg = null;
2977            public void run() {
2978                try {
2979                    ByteBuffer[] targetBuf = new ByteBuffer[2];
2980                    targetBuf[0] = ByteBuffer.wrap(new byte[2]);
2981                    targetBuf[1] = ByteBuffer.wrap(new byte[2]);
2982                    channel1.write(targetBuf, 0, 2);
2983                    errMsg = "should throw ClosedByInterruptException";
2984                } catch (ClosedByInterruptException e) {
2985                    // expected
2986                } catch (IOException e) {
2987                    errMsg = "Unexcted Exception was thrown: " + e.getClass() +
2988                            ": " + e.getMessage();
2989                }
2990            }
2991        }
2992        MyThread thread = new MyThread();
2993        thread.start();
2994        try {
2995            Thread.sleep(TIME_UNIT);
2996            thread.interrupt();
2997        } catch (InterruptedException e) {
2998            // ok
2999        }
3000        thread.join(TIME_UNIT);
3001        if (thread.errMsg != null) {
3002            fail(thread.errMsg);
3003        }
3004    }
3005
3006    @TestTargetNew(
3007        level = TestLevel.PARTIAL_COMPLETE,
3008        notes = "",
3009        method = "write",
3010        args = {java.nio.ByteBuffer[].class, int.class, int.class}
3011    )
3012    public void testWriteByteBufferArrayII_NonBlock() throws IOException {
3013        ByteBuffer[] writeBuf = new ByteBuffer[2];
3014        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3015        writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3016        InetSocketAddress ipAddr = localAddr1;
3017        // non-block mode
3018        this.channel1.configureBlocking(false);
3019        try {
3020            this.channel1.write(writeBuf, 0, 2);
3021            fail("Should throw NotYetConnectedException.");
3022        } catch (NotYetConnectedException e) {
3023            // correct
3024        }
3025        this.channel1.connect(ipAddr);
3026        assertTrue(this.channel1.isConnected());
3027        assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2));
3028        // cannot be buffered again!
3029        assertEquals(0, this.channel1.write(writeBuf, 0, 1));
3030        this.channel1.close();
3031        try {
3032            this.channel1.write(writeBuf, 0, 1);
3033            fail("Should throw ClosedChannelEception.");
3034        } catch (ClosedChannelException e) {
3035            // expected
3036        }
3037    }
3038
3039    @TestTargetNew(
3040        level = TestLevel.PARTIAL_COMPLETE,
3041        notes = "",
3042        method = "write",
3043        args = {java.nio.ByteBuffer[].class, int.class, int.class}
3044    )
3045    public void testWriteByteBufferArrayII_BlockClosed() throws IOException {
3046        ByteBuffer[] writeBuf = new ByteBuffer[2];
3047        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3048        writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3049        InetSocketAddress ipAddr = localAddr1;
3050        // non-block mode
3051        this.channel1.configureBlocking(false);
3052        this.channel1.connect(ipAddr);
3053        assertTrue(this.channel1.isConnected());
3054        this.channel1.close();
3055        try {
3056            channel1.write(writeBuf, 0, 2);
3057            fail("should throw ClosedChannelException");
3058        } catch (ClosedChannelException e) {
3059            // correct
3060        }
3061    }
3062
3063    @TestTargetNew(
3064        level = TestLevel.PARTIAL_COMPLETE,
3065        notes = "",
3066        method = "write",
3067        args = {java.nio.ByteBuffer[].class, int.class, int.class}
3068    )
3069    public void testWriteByteBufferArrayII_NonBlockClosed() throws IOException {
3070        ByteBuffer[] writeBuf = new ByteBuffer[2];
3071        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3072        writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3073        InetSocketAddress ipAddr = localAddr1;
3074        this.channel1.connect(ipAddr);
3075        assertTrue(this.channel1.isConnected());
3076        this.channel1.close();
3077        try {
3078            channel1.write(writeBuf, 0, 2);
3079            fail("should throw ClosedChannelException");
3080        } catch (ClosedChannelException e) {
3081            // correct
3082        }
3083    }
3084
3085    @TestTargetNew(
3086        level = TestLevel.PARTIAL_COMPLETE,
3087        notes = "",
3088        method = "write",
3089        args = {java.nio.ByteBuffer[].class, int.class, int.class}
3090    )
3091    public void testWriteByteBufferArrayII_NotConnectedIndexBad()
3092            throws IOException {
3093        ByteBuffer[] writeBuf = new ByteBuffer[2];
3094        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3095        writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3096        InetSocketAddress ipAddr = localAddr1;
3097        try {
3098            this.channel1.write(writeBuf, -1, 0);
3099            fail("should throw IndexOutOfBoundsException");
3100        } catch (IndexOutOfBoundsException e) {
3101            // correct
3102        }
3103        try {
3104            this.channel1.write(writeBuf, 0, -1);
3105            fail("should throw IndexOutOfBoundsException");
3106        } catch (IndexOutOfBoundsException e) {
3107            // correct
3108        }
3109        try {
3110            this.channel1.write(writeBuf, 0, 3);
3111            fail("should throw IndexOutOfBoundsException");
3112        } catch (IndexOutOfBoundsException e) {
3113            // correct
3114        }
3115        try {
3116            this.channel1.write(writeBuf, 1, 2);
3117            fail("should throw IndexOutOfBoundsException");
3118        } catch (IndexOutOfBoundsException e) {
3119            // correct
3120        }
3121        try {
3122            this.channel1.write(writeBuf, 2, 1);
3123            fail("should throw IndexOutOfBoundsException");
3124        } catch (IndexOutOfBoundsException e) {
3125            // correct
3126        }
3127        try {
3128            this.channel1.write(writeBuf, 3, 0);
3129            fail("should throw IndexOutOfBoundsException");
3130        } catch (IndexOutOfBoundsException e) {
3131            // correct
3132        }
3133    }
3134
3135    @TestTargetNew(
3136        level = TestLevel.PARTIAL_COMPLETE,
3137        notes = "",
3138        method = "write",
3139        args = {java.nio.ByteBuffer[].class, int.class, int.class}
3140    )
3141    public void testWriteByteBufferArrayII_ConnectedIndexBad()
3142            throws IOException {
3143        ByteBuffer[] writeBuf = new ByteBuffer[2];
3144        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3145        writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3146        InetSocketAddress ipAddr = localAddr1;
3147        this.channel1.connect(ipAddr);
3148        assertTrue(this.channel1.isConnected());
3149        try {
3150            this.channel1.write(writeBuf, -1, 0);
3151            fail("should throw IndexOutOfBoundsException");
3152        } catch (IndexOutOfBoundsException e) {
3153            // correct
3154        }
3155        try {
3156            this.channel1.write(writeBuf, 0, -1);
3157            fail("should throw IndexOutOfBoundsException");
3158        } catch (IndexOutOfBoundsException e) {
3159            // correct
3160        }
3161        try {
3162            this.channel1.write(writeBuf, 0, 3);
3163            fail("should throw IndexOutOfBoundsException");
3164        } catch (IndexOutOfBoundsException e) {
3165            // correct
3166        }
3167        try {
3168            this.channel1.write(writeBuf, 1, 2);
3169            fail("should throw IndexOutOfBoundsException");
3170        } catch (IndexOutOfBoundsException e) {
3171            // correct
3172        }
3173        try {
3174            this.channel1.write(writeBuf, 2, 1);
3175            fail("should throw IndexOutOfBoundsException");
3176        } catch (IndexOutOfBoundsException e) {
3177            // correct
3178        }
3179        try {
3180            this.channel1.write(writeBuf, 3, 0);
3181            fail("should throw IndexOutOfBoundsException");
3182        } catch (IndexOutOfBoundsException e) {
3183            // correct
3184        }
3185    }
3186
3187    @TestTargetNew(
3188        level = TestLevel.PARTIAL_COMPLETE,
3189        notes = "",
3190        method = "write",
3191        args = {java.nio.ByteBuffer[].class, int.class, int.class}
3192    )
3193    public void testWriteByteBufferArrayII_NotConnectedBufNull()
3194            throws IOException {
3195        ByteBuffer[] writeBuf = new ByteBuffer[2];
3196        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3197        try {
3198            this.channel1.write(null, 0, 20);
3199            fail("should throw NPE");
3200        } catch (NullPointerException e) {
3201            // correct
3202        }
3203        try {
3204            this.channel1.write(writeBuf, 0, 2);
3205            fail("should throw NotYetConnectedException");
3206        } catch (NotYetConnectedException e) {
3207            // correct
3208        }
3209    }
3210
3211    @TestTargetNew(
3212        level = TestLevel.PARTIAL_COMPLETE,
3213        notes = "",
3214        method = "write",
3215        args = {java.nio.ByteBuffer[].class, int.class, int.class}
3216    )
3217    public void testWriteByteBufferArrayII_ConnectedBufNull()
3218            throws IOException {
3219        ByteBuffer[] writeBuf = new ByteBuffer[2];
3220        writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3221        InetSocketAddress ipAddr = localAddr1;
3222        this.channel1.connect(ipAddr);
3223        assertTrue(this.channel1.isConnected());
3224        try {
3225            this.channel1.write(null, 0, 20);
3226            fail("should throw NPE");
3227        } catch (NullPointerException e) {
3228            // correct
3229        }
3230        try {
3231            this.channel1.write(writeBuf, 0, 2);
3232            fail("should throw NullPointerException");
3233        } catch (NullPointerException e) {
3234            // correct
3235        }
3236        datagramSocket1.close();
3237        try {
3238            this.channel1.write(null, 0, 20);
3239            fail("should throw NPE");
3240        } catch (NullPointerException e) {
3241            // correct
3242        }
3243        try {
3244            this.channel1.write(writeBuf, 0, 2);
3245            fail("should throw NullPointerException");
3246        } catch (NullPointerException e) {
3247            // correct
3248        }
3249    }
3250
3251    // -------------------------------------------------------------------
3252    // Test for read()
3253    // -------------------------------------------------------------------
3254
3255    /*
3256     * Test method for 'DatagramChannelImpl.read(ByteBuffer)'
3257     */
3258    @TestTargetNew(
3259        level = TestLevel.PARTIAL_COMPLETE,
3260        notes = "",
3261        method = "read",
3262        args = {java.nio.ByteBuffer.class}
3263    )
3264    public void testReadByteBuffer() throws IOException {
3265        ByteBuffer readBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3266        try {
3267            this.channel1.read(readBuf);
3268            fail("should throw NotYetConnectedException");
3269        } catch (NotYetConnectedException e) {
3270            // correct
3271        }
3272        this.channel1.connect(localAddr1);
3273        assertTrue(this.channel1.isConnected());
3274        this.channel1.configureBlocking(false);
3275        // note : blocking-mode will make the read process endless!
3276        assertEquals(0, this.channel1.read(readBuf));
3277        this.channel1.close();
3278        try {
3279            this.channel1.read(readBuf);
3280            fail("Should throw ClosedChannelException");
3281        } catch (ClosedChannelException e) {
3282            // OK.
3283        }
3284    }
3285
3286    @TestTargetNew(
3287        level = TestLevel.PARTIAL_COMPLETE,
3288        notes = "",
3289        method = "read",
3290        args = {java.nio.ByteBuffer.class}
3291    )
3292    public void testReadByteBuffer_BufNull() throws IOException {
3293        ByteBuffer readBuf = ByteBuffer.allocateDirect(0);
3294        InetSocketAddress ipAddr = localAddr1;
3295        try {
3296            this.channel1.read(readBuf);
3297            fail("should throw NotYetConnectedException");
3298        } catch (NotYetConnectedException e) {
3299            // correct
3300        }
3301        this.channel1.connect(ipAddr);
3302        assertTrue(this.channel1.isConnected());
3303        try {
3304            channel1.read((ByteBuffer) null);
3305            fail("should throw NPE");
3306        } catch (NullPointerException e) {
3307            // correct
3308        }
3309        this.channel1.configureBlocking(false);
3310        // note : blocking-mode will make the read process endless!
3311        assertEquals(0, this.channel1.read(readBuf));
3312        datagramSocket1.close();
3313    }
3314
3315    /*
3316     * Test method for 'DatagramChannelImpl.read(ByteBuffer[], int, int)'
3317     */
3318    @TestTargetNew(
3319        level = TestLevel.PARTIAL_COMPLETE,
3320        notes = "Doesn't verify AsynchronousCloseException, ClosedByInterruptException, IOException.",
3321        method = "read",
3322        args = {java.nio.ByteBuffer[].class, int.class, int.class}
3323    )
3324    public void testReadByteBufferArrayII() throws IOException {
3325        ByteBuffer[] readBuf = new ByteBuffer[2];
3326        readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3327        readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3328        InetSocketAddress ipAddr = localAddr1;
3329        try {
3330            this.channel1.read(readBuf, 0, 2);
3331            fail("should throw NotYetConnectedException");
3332        } catch (NotYetConnectedException e) {
3333            // correct
3334        }
3335        this.channel1.connect(ipAddr);
3336        assertTrue(this.channel1.isConnected());
3337        this.channel1.configureBlocking(false);
3338        // note : blocking-mode will make the read process endless!
3339        assertEquals(0, this.channel1.read(readBuf, 0, 1));
3340        assertEquals(0, this.channel1.read(readBuf, 0, 2));
3341        this.channel1.close();
3342        assertFalse(this.channel1.isOpen());
3343        try {
3344            assertEquals(0, this.channel1.read(readBuf, 0, 1));
3345        } catch (ClosedChannelException e) {
3346            // correct
3347        }
3348
3349        datagramSocket1.close();
3350        //regression test for HARMONY-932
3351        try {
3352            DatagramChannel.open().read(new ByteBuffer[] {}, 2, Integer.MAX_VALUE);
3353            fail("should throw IndexOutOfBoundsException");
3354        } catch (IndexOutOfBoundsException e) {
3355            // correct
3356        }
3357        try {
3358            DatagramChannel.open().write(new ByteBuffer[] {}, 2, Integer.MAX_VALUE);
3359            fail("should throw IndexOutOfBoundsException");
3360        } catch (IndexOutOfBoundsException e) {
3361            // correct
3362        }
3363        try {
3364            DatagramChannel.open().write((ByteBuffer[])null, -1, 2);
3365            fail("should throw IndexOutOfBoundsException");
3366        } catch (IndexOutOfBoundsException e) {
3367            // correct
3368        }
3369    }
3370
3371    @TestTargetNew(
3372        level = TestLevel.PARTIAL_COMPLETE,
3373        notes = "",
3374        method = "read",
3375        args = {java.nio.ByteBuffer[].class, int.class, int.class}
3376    )
3377    public void testReadByteBufferArrayII_ConnectedBufNull()
3378            throws IOException {
3379        ByteBuffer[] readBuf = new ByteBuffer[2];
3380        readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3381        InetSocketAddress ipAddr = localAddr1;
3382        this.channel1.connect(ipAddr);
3383        assertTrue(this.channel1.isConnected());
3384        this.channel1.configureBlocking(false);
3385        // note : blocking-mode will make the read process endless!
3386        try {
3387            this.channel1.read(null, 0, 2);
3388            fail("should throw NPE");
3389        } catch (NullPointerException e) {
3390            // correct
3391        }
3392        assertEquals(0, this.channel1.read(readBuf, 0, 1));
3393        try {
3394            this.channel1.read(readBuf, 0, 2);
3395            fail("should throw NPE");
3396        } catch (NullPointerException e) {
3397            // correct
3398        }
3399        datagramSocket1.close();
3400    }
3401
3402    @TestTargetNew(
3403        level = TestLevel.PARTIAL_COMPLETE,
3404        notes = "",
3405        method = "read",
3406        args = {java.nio.ByteBuffer[].class, int.class, int.class}
3407    )
3408    public void testReadByteBufferArrayII_NotConnectedBufNull()
3409            throws IOException {
3410        ByteBuffer[] readBuf = new ByteBuffer[2];
3411        readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3412        InetSocketAddress ipAddr = localAddr1;
3413        try {
3414            this.channel1.read(null, 0, 2);
3415            fail("should throw NPE");
3416        } catch (NullPointerException e) {
3417            // correct
3418        }
3419        try {
3420            this.channel1.read(readBuf, 0, 2);
3421            fail("should throw NotYetConnectedException");
3422        } catch (NotYetConnectedException e) {
3423            // correct
3424        }
3425    }
3426
3427    @TestTargetNew(
3428        level = TestLevel.PARTIAL_COMPLETE,
3429        notes = "",
3430        method = "read",
3431        args = {java.nio.ByteBuffer[].class, int.class, int.class}
3432    )
3433    public void testReadByteBufferArrayII_ConnectedIndexBad() throws IOException {
3434        ByteBuffer[] readBuf = new ByteBuffer[2];
3435        readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3436        readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3437        InetSocketAddress ipAddr = localAddr1;
3438        this.channel1.connect(ipAddr);
3439        assertTrue(this.channel1.isConnected());
3440        this.channel1.configureBlocking(false);
3441        // note : blocking-mode will make the read process endless!
3442        try {
3443            this.channel1.read(readBuf, -1, 0);
3444            fail("should throw IndexOutOfBoundsException");
3445        } catch (IndexOutOfBoundsException e) {
3446            // correct
3447        }
3448        try {
3449            this.channel1.read(readBuf, 0, -1);
3450            fail("should throw IndexOutOfBoundsException");
3451        } catch (IndexOutOfBoundsException e) {
3452            // correct
3453        }
3454        try {
3455            this.channel1.read(readBuf, 0, 3);
3456            fail("should throw IndexOutOfBoundsException");
3457        } catch (IndexOutOfBoundsException e) {
3458            // correct
3459        }
3460        try {
3461            this.channel1.read(readBuf, 1, 2);
3462            fail("should throw IndexOutOfBoundsException");
3463        } catch (IndexOutOfBoundsException e) {
3464            // correct
3465        }
3466        try {
3467            this.channel1.read(readBuf, 2, 1);
3468            fail("should throw IndexOutOfBoundsException");
3469        } catch (IndexOutOfBoundsException e) {
3470            // correct
3471        }
3472        try {
3473            this.channel1.read(readBuf, 3, 0);
3474            fail("should throw IndexOutOfBoundsException");
3475        } catch (IndexOutOfBoundsException e) {
3476            // correct
3477        }
3478    }
3479
3480    @TestTargetNew(
3481        level = TestLevel.PARTIAL_COMPLETE,
3482        notes = "",
3483        method = "read",
3484        args = {java.nio.ByteBuffer[].class, int.class, int.class}
3485    )
3486    public void testReadByteBufferArrayII_NotConnectedIndexBad()
3487            throws IOException {
3488        ByteBuffer[] readBuf = new ByteBuffer[2];
3489        readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3490        readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
3491        InetSocketAddress ipAddr = localAddr1;
3492        try {
3493            this.channel1.write(readBuf, -1, 0);
3494            fail("should throw IndexOutOfBoundsException");
3495        } catch (IndexOutOfBoundsException e) {
3496            // correct
3497        }
3498        try {
3499            this.channel1.write(readBuf, 0, -1);
3500            fail("should throw IndexOutOfBoundsException");
3501        } catch (IndexOutOfBoundsException e) {
3502            // correct
3503        }
3504        try {
3505            this.channel1.write(readBuf, 0, 3);
3506            fail("should throw IndexOutOfBoundsException");
3507        } catch (IndexOutOfBoundsException e) {
3508            // correct
3509        }
3510        try {
3511            this.channel1.write(readBuf, 1, 2);
3512            fail("should throw IndexOutOfBoundsException");
3513        } catch (IndexOutOfBoundsException e) {
3514            // correct
3515        }
3516        try {
3517            this.channel1.write(readBuf, 2, 1);
3518            fail("should throw IndexOutOfBoundsException");
3519        } catch (IndexOutOfBoundsException e) {
3520            // correct
3521        }
3522        try {
3523            this.channel1.write(readBuf, 3, 0);
3524            fail("should throw IndexOutOfBoundsException");
3525        } catch (IndexOutOfBoundsException e) {
3526            // correct
3527        }
3528    }
3529
3530    public void disabled_testReadByteBufferArrayII_Block_close() throws Exception {
3531        // bind and connect
3532        this.channel1.socket().bind(localAddr2);
3533        this.channel1.connect(localAddr1);
3534        this.channel2.socket().bind(localAddr1);
3535        this.channel2.connect(localAddr2);
3536        ByteBuffer[] targetBuf = new ByteBuffer[2];
3537        targetBuf[0] = ByteBuffer.wrap(new byte[2]);
3538        targetBuf[1] = ByteBuffer.wrap(new byte[2]);
3539
3540        new Thread() {
3541            public void run() {
3542                try {
3543                    Thread.sleep(TIME_UNIT);
3544                    channel1.close();
3545                } catch (Exception e) {
3546                    //ignore
3547                }
3548            }
3549        }.start();
3550        try {
3551            this.channel1.read(targetBuf, 0, 2);
3552            fail("should throw AsynchronousCloseException");
3553        } catch (AsynchronousCloseException e) {
3554            // ok
3555        }
3556    }
3557
3558    @TestTargetNew(
3559        level = TestLevel.PARTIAL_COMPLETE,
3560        notes = "",
3561        method = "read",
3562        args = {java.nio.ByteBuffer[].class, int.class, int.class}
3563    )
3564    public void testReadByteBufferArrayII_Block_interrupt() throws Exception {
3565        // bind and connect
3566        this.channel1.socket().bind(localAddr2);
3567        this.channel1.connect(localAddr1);
3568        this.channel2.socket().bind(localAddr1);
3569        this.channel2.connect(localAddr2);
3570
3571        class MyThread extends Thread {
3572            public String errMsg = null;
3573            public void run() {
3574                try {
3575                    ByteBuffer[] targetBuf = new ByteBuffer[2];
3576                    targetBuf[0] = ByteBuffer.wrap(new byte[2]);
3577                    targetBuf[1] = ByteBuffer.wrap(new byte[2]);
3578                    channel1.read(targetBuf, 0, 2);
3579                    errMsg = "should throw ClosedByInterruptException";
3580                } catch (ClosedByInterruptException e) {
3581                    // expected
3582                } catch (IOException e) {
3583                    errMsg = "Unexcted Exception was thrown: " + e.getClass() +
3584                            ": " + e.getMessage();
3585                }
3586            }
3587        }
3588        MyThread thread = new MyThread();
3589        thread.start();
3590        try {
3591            Thread.sleep(TIME_UNIT);
3592            thread.interrupt();
3593        } catch (InterruptedException e) {
3594            // ok
3595        }
3596        thread.join(TIME_UNIT);
3597        if (thread.errMsg != null) {
3598            fail(thread.errMsg);
3599        }
3600    }
3601
3602    // -------------------------------------------------------------------
3603    // test read and write
3604    // -------------------------------------------------------------------
3605    @TestTargetNew(
3606        level = TestLevel.PARTIAL_COMPLETE,
3607        notes = "",
3608        method = "read",
3609        args = {java.nio.ByteBuffer.class}
3610    )
3611    public void testReadWrite_configureBlock() throws Exception {
3612        byte[] targetArray = new byte[2];
3613        // bind and connect
3614        this.channel1.socket().bind(localAddr2);
3615        this.channel1.connect(localAddr1);
3616        this.channel2.socket().bind(localAddr1);
3617        this.channel2.connect(localAddr2);
3618        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
3619
3620        new Thread() {
3621            public void run() {
3622                try {
3623                    Thread.sleep(TIME_UNIT);
3624                    channel1.configureBlocking(false);
3625                    channel1.close();
3626                } catch (Exception e) {
3627                    //ignore
3628                }
3629            }
3630        }.start();
3631        try {
3632            this.channel1.read(targetBuf);
3633            fail("should throw AsynchronousCloseException");
3634        } catch (AsynchronousCloseException e) {
3635            // ok
3636        }
3637        this.channel1.close();
3638        try {
3639            this.channel1.configureBlocking(true);
3640            fail("should throw ClosedChannelException");
3641        } catch (ClosedChannelException e) {
3642            // expected
3643        }
3644
3645        this.channel1 = SelectorProvider.provider().openDatagramChannel();
3646        this.channel1.configureBlocking(false);
3647        this.channel1.register(SelectorProvider.provider().openSelector(),
3648                SelectionKey.OP_READ);
3649        try {
3650            this.channel1.configureBlocking(true);
3651            fail("should throw IllegalBlockingModeException");
3652        } catch (IllegalBlockingModeException e) {
3653            // expected
3654        }
3655    }
3656
3657    @TestTargets({
3658        @TestTargetNew(
3659            level = TestLevel.PARTIAL_COMPLETE,
3660            notes = "",
3661            method = "read",
3662            args = {java.nio.ByteBuffer.class}
3663        ),
3664        @TestTargetNew(
3665            level = TestLevel.PARTIAL_COMPLETE,
3666            notes = "",
3667            method = "write",
3668            args = {java.nio.ByteBuffer.class}
3669        )
3670    })
3671    public void testReadWrite_Block_Zero() throws Exception {
3672        byte[] sourceArray = new byte[0];
3673        byte[] targetArray = new byte[0];
3674        // bind and connect
3675        this.channel1.socket().bind(localAddr2);
3676        this.channel1.connect(localAddr1);
3677        this.channel2.socket().bind(localAddr1);
3678        this.channel2.connect(localAddr2);
3679
3680        // write
3681        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
3682        assertEquals(0, this.channel1.write(sourceBuf));
3683
3684        // read
3685        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
3686        assertEquals(0, this.channel2.read(targetBuf));
3687    }
3688
3689    @TestTargets({
3690        @TestTargetNew(
3691            level = TestLevel.PARTIAL_COMPLETE,
3692            notes = "",
3693            method = "read",
3694            args = {java.nio.ByteBuffer.class}
3695        ),
3696        @TestTargetNew(
3697            level = TestLevel.PARTIAL_COMPLETE,
3698            notes = "",
3699            method = "write",
3700            args = {java.nio.ByteBuffer.class}
3701        )
3702    })
3703    public void testReadWrite_Block_Normal() throws Exception {
3704        byte[] sourceArray = new byte[CAPACITY_NORMAL];
3705        byte[] targetArray = new byte[CAPACITY_NORMAL];
3706        for (int i = 0; i < sourceArray.length; i++) {
3707            sourceArray[i] = (byte) i;
3708        }
3709
3710        // bind and connect
3711        this.channel1.socket().bind(localAddr2);
3712        this.channel1.connect(localAddr1);
3713        this.channel2.socket().bind(localAddr1);
3714        this.channel2.connect(localAddr2);
3715
3716        readWriteReadData(this.channel1, sourceArray, this.channel2,
3717                targetArray, CAPACITY_NORMAL, "testReadWrite_Block_Normal");
3718    }
3719
3720    @TestTargets({
3721        @TestTargetNew(
3722            level = TestLevel.PARTIAL_COMPLETE,
3723            notes = "",
3724            method = "read",
3725            args = {java.nio.ByteBuffer.class}
3726        ),
3727        @TestTargetNew(
3728            level = TestLevel.PARTIAL_COMPLETE,
3729            notes = "",
3730            method = "write",
3731            args = {java.nio.ByteBuffer.class}
3732        )
3733    })
3734    public void testReadWrite_Block_Empty() throws Exception {
3735        // empty buf
3736        byte[] sourceArray = "".getBytes();
3737        byte[] targetArray = new byte[CAPACITY_NORMAL];
3738
3739        // bind and connect
3740
3741        this.channel1.socket().bind(localAddr2);
3742        this.channel1.connect(localAddr1);
3743        this.channel2.socket().bind(localAddr1);
3744        this.channel2.connect(localAddr2);
3745
3746        // write
3747        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
3748        assertEquals(0, this.channel1.write(sourceBuf));
3749
3750        // read
3751        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
3752        // empty message let the reader blocked
3753        closeBlockedReaderChannel2(targetBuf);
3754    }
3755
3756    @TestTargets({
3757        @TestTargetNew(
3758            level = TestLevel.PARTIAL_COMPLETE,
3759            notes = "",
3760            method = "read",
3761            args = {java.nio.ByteBuffer.class}
3762        ),
3763        @TestTargetNew(
3764            level = TestLevel.PARTIAL_COMPLETE,
3765            notes = "",
3766            method = "write",
3767            args = {java.nio.ByteBuffer.class}
3768        )
3769    })
3770    public void testReadWrite_changeBlock_Empty() throws Exception {
3771        // empty buf
3772        byte[] sourceArray = "".getBytes();
3773        byte[] targetArray = new byte[CAPACITY_NORMAL];
3774
3775        // bind and connect
3776
3777        this.channel1.socket().bind(localAddr2);
3778        this.channel1.connect(localAddr1);
3779        this.channel2.socket().bind(localAddr1);
3780        this.channel2.connect(localAddr2);
3781
3782        // write
3783        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
3784        assertEquals(0, this.channel1.write(sourceBuf));
3785
3786        // read
3787        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
3788        // empty message let the reader blocked
3789        new Thread() {
3790            public void run() {
3791                try {
3792                    Thread.sleep(TIME_UNIT);
3793                    channel2.configureBlocking(false);
3794                    Thread.sleep(TIME_UNIT * 5);
3795                    channel2.close();
3796                } catch (Exception e) {
3797                    // do nothing
3798                }
3799            }
3800        }.start();
3801        try {
3802            assertTrue(this.channel2.isBlocking());
3803            this.channel2.read(targetBuf);
3804            fail("Should throw AsynchronousCloseException");
3805        } catch (AsynchronousCloseException e) {
3806            assertFalse(this.channel2.isBlocking());
3807            // OK.
3808        }
3809    }
3810
3811    @TestTargets({
3812        @TestTargetNew(
3813            level = TestLevel.PARTIAL_COMPLETE,
3814            notes = "",
3815            method = "read",
3816            args = {java.nio.ByteBuffer.class}
3817        ),
3818        @TestTargetNew(
3819            level = TestLevel.PARTIAL_COMPLETE,
3820            notes = "",
3821            method = "write",
3822            args = {java.nio.ByteBuffer.class}
3823        )
3824    })
3825    public void testReadWrite_Block_8KB() throws Exception {
3826        byte[] sourceArray = new byte[CAPACITY_1KB * 8];
3827        byte[] targetArray = new byte[CAPACITY_1KB * 8];
3828        for (int i = 0; i < sourceArray.length; i++) {
3829            sourceArray[i] = (byte) i;
3830        }
3831
3832        // bind and connect
3833        this.channel1.socket().bind(localAddr2);
3834        this.channel1.connect(localAddr1);
3835        this.channel2.socket().bind(localAddr1);
3836        this.channel2.connect(localAddr2);
3837
3838        readWriteReadData(this.channel1, sourceArray, this.channel2,
3839                targetArray, 8 * CAPACITY_1KB, "testReadWrite_Block_8KB");
3840    }
3841
3842    /*
3843     * sender write the sourceArray whose size is dataSize, and receiver read
3844     * the data into targetArray
3845     */
3846    private void readWriteReadData(DatagramChannel sender, byte[] sourceArray,
3847            DatagramChannel receiver, byte[] targetArray, int dataSize,
3848            String methodName) throws IOException {
3849        // write
3850        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
3851        assertEquals(dataSize, sender.write(sourceBuf));
3852
3853        // read
3854        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
3855
3856        int count = 0;
3857        int total = 0;
3858        long beginTime = System.currentTimeMillis();
3859        while (total < dataSize && (count = receiver.read(targetBuf)) != -1) {
3860            total = total + count;
3861            // 3s timeout to avoid dead loop
3862            if (System.currentTimeMillis() - beginTime > 3000){
3863                break;
3864            }
3865        }
3866
3867        assertEquals(dataSize, total);
3868        assertEquals(targetBuf.position(), total);
3869        targetBuf.flip();
3870        targetArray = targetBuf.array();
3871        for (int i = 0; i < targetArray.length; i++) {
3872            assertEquals(targetArray[i], (byte) i);
3873        }
3874    }
3875
3876    @TestTargetNew(
3877        level = TestLevel.PARTIAL_COMPLETE,
3878        notes = "",
3879        method = "write",
3880        args = {java.nio.ByteBuffer.class}
3881    )
3882    public void testReadWrite_Block_64K() throws Exception {
3883        byte[] sourceArray = new byte[CAPACITY_64KB];
3884        for (int i = 0; i < sourceArray.length; i++) {
3885            sourceArray[i] = (byte) i;
3886        }
3887
3888        // bind and connect
3889        this.channel1.socket().bind(localAddr2);
3890        this.channel1.connect(localAddr1);
3891        this.channel2.socket().bind(localAddr1);
3892        this.channel2.connect(localAddr2);
3893
3894        // write
3895        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
3896        try {
3897            channel1.write(sourceBuf);
3898            fail("Should throw IOException");
3899        } catch (IOException e) {
3900            // too big
3901        }
3902    }
3903
3904    @TestTargets({
3905        @TestTargetNew(
3906            level = TestLevel.PARTIAL_COMPLETE,
3907            notes = "",
3908            method = "read",
3909            args = {java.nio.ByteBuffer.class}
3910        ),
3911        @TestTargetNew(
3912            level = TestLevel.PARTIAL_COMPLETE,
3913            notes = "",
3914            method = "write",
3915            args = {java.nio.ByteBuffer.class}
3916        )
3917    })
3918    public void testReadWrite_Block_DifferentAddr() throws Exception {
3919        byte[] sourceArray = new byte[CAPACITY_NORMAL];
3920        byte[] targetArray = new byte[CAPACITY_NORMAL];
3921        for (int i = 0; i < sourceArray.length; i++) {
3922            sourceArray[i] = (byte) i;
3923        }
3924
3925        // bind and connect
3926        this.channel1.socket().bind(localAddr2);
3927        this.channel1.connect(localAddr1);
3928        this.channel2.socket().bind(localAddr1);
3929        this.channel2.connect(localAddr1);// the different addr
3930
3931        // write
3932        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
3933        assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
3934
3935        // read
3936        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
3937        // the wrong connected addr will make the read blocked.
3938        // we close the blocked channel
3939        closeBlockedReaderChannel2(targetBuf);
3940    }
3941
3942    @TestTargets({
3943        @TestTargetNew(
3944            level = TestLevel.PARTIAL_COMPLETE,
3945            notes = "",
3946            method = "read",
3947            args = {java.nio.ByteBuffer.class}
3948        ),
3949        @TestTargetNew(
3950            level = TestLevel.PARTIAL_COMPLETE,
3951            notes = "",
3952            method = "write",
3953            args = {java.nio.ByteBuffer.class}
3954        )
3955    })
3956    public void testReadWrite_Block_WriterNotBind() throws Exception {
3957        byte[] sourceArray = new byte[CAPACITY_NORMAL];
3958        byte[] targetArray = new byte[CAPACITY_NORMAL];
3959        for (int i = 0; i < sourceArray.length; i++) {
3960            sourceArray[i] = (byte) i;
3961        }
3962
3963        // bind and connect
3964        this.channel1.connect(localAddr1);
3965        this.channel2.socket().bind(localAddr1);
3966        this.channel2.connect(localAddr2);
3967
3968        // write
3969        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
3970        assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
3971
3972        // read
3973        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
3974        closeBlockedReaderChannel2(targetBuf);
3975    }
3976
3977    @TestTargets({
3978        @TestTargetNew(
3979            level = TestLevel.PARTIAL_COMPLETE,
3980            notes = "",
3981            method = "read",
3982            args = {java.nio.ByteBuffer.class}
3983        ),
3984        @TestTargetNew(
3985            level = TestLevel.PARTIAL_COMPLETE,
3986            notes = "",
3987            method = "write",
3988            args = {java.nio.ByteBuffer.class}
3989        )
3990    })
3991    public void testReadWrite_Block_WriterBindLater() throws Exception {
3992
3993        byte[] targetArray = new byte[CAPACITY_NORMAL];
3994
3995        // bind and connect
3996        // writer channel1 is bound later
3997        this.channel2.socket().bind(localAddr1);
3998        this.channel2.connect(localAddr2);
3999
4000        // read
4001        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
4002        new Thread() {
4003            public void run() {
4004                try {
4005                    Thread.sleep(TIME_UNIT);
4006                    // bind later
4007                    byte[] sourceArray = new byte[CAPACITY_NORMAL];
4008                    for (int i = 0; i < sourceArray.length; i++) {
4009                        sourceArray[i] = (byte) i;
4010                    }
4011                    channel1.socket().bind(localAddr2);
4012                    channel1.connect(localAddr1);
4013                    // write later
4014                    ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
4015                    assertEquals(CAPACITY_NORMAL, channel1.write(sourceBuf));
4016                } catch (Exception e) {
4017                    // do nothing
4018                }
4019            }
4020        }.start();
4021
4022        int count = 0;
4023        int total = 0;
4024        long beginTime = System.currentTimeMillis();
4025        while (total < CAPACITY_NORMAL && (count = channel2.read(targetBuf)) != -1) {
4026            total = total + count;
4027            // 3s timeout to avoid dead loop
4028            if (System.currentTimeMillis() - beginTime > 3000){
4029                break;
4030            }
4031        }
4032
4033        assertEquals(CAPACITY_NORMAL, total);
4034        assertEquals(targetBuf.position(), total);
4035        targetBuf.flip();
4036        targetArray = targetBuf.array();
4037        for (int i = 0; i < targetArray.length; i++) {
4038            assertEquals(targetArray[i], (byte) i);
4039        }
4040
4041    }
4042
4043    @TestTargets({
4044        @TestTargetNew(
4045            level = TestLevel.PARTIAL_COMPLETE,
4046            notes = "",
4047            method = "read",
4048            args = {java.nio.ByteBuffer.class}
4049        ),
4050        @TestTargetNew(
4051            level = TestLevel.PARTIAL_COMPLETE,
4052            notes = "",
4053            method = "write",
4054            args = {java.nio.ByteBuffer.class}
4055        )
4056    })
4057    public void testReadWrite_Block_ReaderNotBind() throws Exception {
4058        byte[] sourceArray = new byte[CAPACITY_NORMAL];
4059        byte[] targetArray = new byte[CAPACITY_NORMAL];
4060        for (int i = 0; i < sourceArray.length; i++) {
4061            sourceArray[i] = (byte) i;
4062        }
4063
4064        // bind and connect
4065        this.channel1.socket().bind(localAddr2);
4066        this.channel1.connect(localAddr1);
4067        // reader channel2 is not bound
4068        this.channel2.connect(localAddr2);
4069
4070        // write
4071        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
4072        assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
4073
4074        // read
4075        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
4076        closeBlockedReaderChannel2(targetBuf);
4077
4078    }
4079
4080    private void closeBlockedReaderChannel2(ByteBuffer targetBuf)
4081            throws IOException {
4082        new Thread() {
4083            public void run() {
4084                try {
4085                    Thread.sleep(TIME_UNIT);
4086                    channel2.close();
4087                } catch (Exception e) {
4088                    // do nothing
4089                }
4090            }
4091        }.start();
4092        try {
4093            assertTrue(this.channel2.isBlocking());
4094            this.channel2.read(targetBuf);
4095            fail("Should throw AsynchronousCloseException");
4096        } catch (AsynchronousCloseException e) {
4097            // OK.
4098        }
4099    }
4100
4101    // -------------------------------------------------------------------
4102    // Test read and write in non-block mode.
4103    // -------------------------------------------------------------------
4104    @TestTargets({
4105        @TestTargetNew(
4106            level = TestLevel.PARTIAL_COMPLETE,
4107            notes = "",
4108            method = "read",
4109            args = {java.nio.ByteBuffer.class}
4110        ),
4111        @TestTargetNew(
4112            level = TestLevel.PARTIAL_COMPLETE,
4113            notes = "",
4114            method = "write",
4115            args = {java.nio.ByteBuffer.class}
4116        )
4117    })
4118    public void testReadWrite_NonBlock_Normal() throws Exception {
4119        byte[] sourceArray = new byte[CAPACITY_NORMAL];
4120        byte[] targetArray = new byte[CAPACITY_NORMAL];
4121        for (int i = 0; i < sourceArray.length; i++) {
4122            sourceArray[i] = (byte) i;
4123        }
4124
4125        this.channel1.configureBlocking(false);
4126        this.channel2.configureBlocking(false);
4127
4128        // bind and connect
4129        this.channel1.socket().bind(localAddr2);
4130        this.channel1.connect(localAddr1);
4131        this.channel2.socket().bind(localAddr1);
4132        this.channel2.connect(localAddr2);
4133
4134        readWriteReadData(this.channel1, sourceArray, this.channel2,
4135                targetArray, CAPACITY_NORMAL, "testReadWrite_NonBlock_Normal");
4136    }
4137
4138    @TestTargets({
4139        @TestTargetNew(
4140            level = TestLevel.PARTIAL_COMPLETE,
4141            notes = "",
4142            method = "read",
4143            args = {java.nio.ByteBuffer.class}
4144        ),
4145        @TestTargetNew(
4146            level = TestLevel.PARTIAL_COMPLETE,
4147            notes = "",
4148            method = "write",
4149            args = {java.nio.ByteBuffer.class}
4150        )
4151    })
4152    public void testReadWrite_NonBlock_8KB() throws Exception {
4153        byte[] sourceArray = new byte[CAPACITY_1KB * 8];
4154        byte[] targetArray = new byte[CAPACITY_1KB * 8];
4155        for (int i = 0; i < sourceArray.length; i++) {
4156            sourceArray[i] = (byte) i;
4157        }
4158
4159        this.channel1.configureBlocking(false);
4160        this.channel2.configureBlocking(false);
4161
4162        // bind and connect
4163        this.channel1.socket().bind(localAddr2);
4164        this.channel1.connect(localAddr1);
4165        this.channel2.socket().bind(localAddr1);
4166        this.channel2.connect(localAddr2);
4167
4168        readWriteReadData(this.channel1, sourceArray, this.channel2,
4169                targetArray, 8 * CAPACITY_1KB, "testReadWrite_NonBlock_8KB");
4170    }
4171
4172    @TestTargets({
4173        @TestTargetNew(
4174            level = TestLevel.PARTIAL_COMPLETE,
4175            notes = "",
4176            method = "read",
4177            args = {java.nio.ByteBuffer.class}
4178        ),
4179        @TestTargetNew(
4180            level = TestLevel.PARTIAL_COMPLETE,
4181            notes = "",
4182            method = "write",
4183            args = {java.nio.ByteBuffer.class}
4184        )
4185    })
4186    public void testReadWrite_NonBlock_DifferentAddr() throws Exception {
4187        byte[] sourceArray = new byte[CAPACITY_NORMAL];
4188        byte[] targetArray = new byte[CAPACITY_NORMAL];
4189        for (int i = 0; i < sourceArray.length; i++) {
4190            sourceArray[i] = (byte) i;
4191        }
4192
4193        this.channel1.configureBlocking(false);
4194        this.channel2.configureBlocking(false);
4195
4196        // bind and connect
4197        this.channel1.socket().bind(localAddr2);
4198        this.channel1.connect(localAddr1);
4199        this.channel2.socket().bind(localAddr1);
4200        this.channel2.connect(localAddr1);// the different addr
4201
4202        // write
4203        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
4204        assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
4205
4206        // read
4207        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
4208        assertEquals(0, this.channel2.read(targetBuf));
4209    }
4210
4211    @TestTargets({
4212        @TestTargetNew(
4213            level = TestLevel.PARTIAL_COMPLETE,
4214            notes = "",
4215            method = "read",
4216            args = {java.nio.ByteBuffer.class}
4217        ),
4218        @TestTargetNew(
4219            level = TestLevel.PARTIAL_COMPLETE,
4220            notes = "",
4221            method = "write",
4222            args = {java.nio.ByteBuffer.class}
4223        )
4224    })
4225    public void testReadWrite_NonBlock_Empty() throws Exception {
4226        // empty buf
4227        byte[] sourceArray = "".getBytes();
4228        byte[] targetArray = new byte[CAPACITY_NORMAL];
4229
4230        this.channel1.configureBlocking(false);
4231        this.channel2.configureBlocking(false);
4232
4233        // bind and connect
4234
4235        this.channel1.socket().bind(localAddr2);
4236        this.channel1.connect(localAddr1);
4237        this.channel2.socket().bind(localAddr1);
4238        this.channel2.connect(localAddr2);
4239
4240        // write
4241        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
4242        assertEquals(0, this.channel1.write(sourceBuf));
4243
4244        // read
4245        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
4246        assertEquals(0, this.channel2.read(targetBuf));
4247    }
4248
4249    @TestTargets({
4250        @TestTargetNew(
4251            level = TestLevel.PARTIAL_COMPLETE,
4252            notes = "",
4253            method = "read",
4254            args = {java.nio.ByteBuffer.class}
4255        ),
4256        @TestTargetNew(
4257            level = TestLevel.PARTIAL_COMPLETE,
4258            notes = "",
4259            method = "write",
4260            args = {java.nio.ByteBuffer.class}
4261        )
4262    })
4263    public void testReadWrite_NonBlock_WriterNotBind() throws Exception {
4264        byte[] sourceArray = new byte[CAPACITY_NORMAL];
4265        byte[] targetArray = new byte[CAPACITY_NORMAL];
4266        for (int i = 0; i < sourceArray.length; i++) {
4267            sourceArray[i] = (byte) i;
4268        }
4269
4270        this.channel1.configureBlocking(false);
4271        this.channel2.configureBlocking(false);
4272
4273        // bind and connect
4274        this.channel1.connect(localAddr1);
4275        this.channel2.socket().bind(localAddr1);
4276        this.channel2.connect(localAddr2);
4277
4278        // write
4279        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
4280        assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
4281
4282        // read
4283        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
4284        assertEquals(0, this.channel2.read(targetBuf));
4285    }
4286
4287    @TestTargets({
4288        @TestTargetNew(
4289            level = TestLevel.PARTIAL_COMPLETE,
4290            notes = "",
4291            method = "read",
4292            args = {java.nio.ByteBuffer.class}
4293        ),
4294        @TestTargetNew(
4295            level = TestLevel.PARTIAL_COMPLETE,
4296            notes = "",
4297            method = "write",
4298            args = {java.nio.ByteBuffer.class}
4299        )
4300    })
4301    public void testReadWrite_NonBlock_Zero() throws Exception {
4302        byte[] sourceArray = new byte[0];
4303        byte[] targetArray = new byte[0];
4304
4305        this.channel1.configureBlocking(false);
4306        this.channel2.configureBlocking(false);
4307
4308        // bind and connect
4309        this.channel1.socket().bind(localAddr2);
4310        this.channel1.connect(localAddr1);
4311        this.channel2.socket().bind(localAddr1);
4312        this.channel2.connect(localAddr2);
4313
4314        // write
4315        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
4316        assertEquals(0, this.channel1.write(sourceBuf));
4317
4318        // read
4319        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
4320        assertEquals(0, this.channel2.read(targetBuf));
4321    }
4322
4323    @TestTargets({
4324        @TestTargetNew(
4325            level = TestLevel.PARTIAL_COMPLETE,
4326            notes = "",
4327            method = "read",
4328            args = {java.nio.ByteBuffer.class}
4329        ),
4330        @TestTargetNew(
4331            level = TestLevel.PARTIAL_COMPLETE,
4332            notes = "",
4333            method = "write",
4334            args = {java.nio.ByteBuffer.class}
4335        )
4336    })
4337    public void testReadWrite_NonBlock_ReaderNotBind() throws Exception {
4338        byte[] sourceArray = new byte[CAPACITY_NORMAL];
4339        byte[] targetArray = new byte[CAPACITY_NORMAL];
4340        for (int i = 0; i < sourceArray.length; i++) {
4341            sourceArray[i] = (byte) i;
4342        }
4343
4344        this.channel1.configureBlocking(false);
4345        this.channel2.configureBlocking(false);
4346
4347        // bind and connect
4348        this.channel1.socket().bind(localAddr2);
4349        this.channel1.connect(localAddr1);
4350        this.channel2.connect(localAddr2);
4351
4352        // write
4353        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
4354        assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
4355
4356        // read
4357        ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
4358        assertEquals(0, this.channel2.read(targetBuf));
4359    }
4360
4361    @TestTargetNew(
4362        level = TestLevel.PARTIAL_COMPLETE,
4363        notes = "",
4364        method = "write",
4365        args = {java.nio.ByteBuffer.class}
4366    )
4367    public void testWriteByteBuffer_Positioned() throws Exception {
4368        // Regression test for Harmony-683
4369        int postion = 16;
4370        DatagramChannel dc = DatagramChannel.open();
4371        byte[] sourceArray = new byte[CAPACITY_NORMAL];
4372        dc.connect(localAddr1);
4373        // write
4374        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
4375        sourceBuf.position(postion);
4376        assertEquals(CAPACITY_NORMAL - postion, dc.write(sourceBuf));
4377    }
4378
4379    public void disabled_testWriteByteBuffer_Block_close() throws Exception {
4380        // bind and connect
4381        this.channel1.socket().bind(localAddr2);
4382        this.channel1.connect(localAddr1);
4383        this.channel2.socket().bind(localAddr1);
4384        this.channel2.connect(localAddr2);
4385        ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
4386
4387        new Thread() {
4388            public void run() {
4389                try {
4390                    Thread.sleep(TIME_UNIT);
4391                    channel1.close();
4392                } catch (Exception e) {
4393                    //ignore
4394                }
4395            }
4396        }.start();
4397        try {
4398            this.channel1.send(targetBuf, localAddr1);
4399            fail("should throw AsynchronousCloseException");
4400        } catch (AsynchronousCloseException e) {
4401            // ok
4402        }
4403    }
4404
4405    public void disabled_testWriteByteBuffer_Block_interrupt() throws Exception {
4406        // bind and connect
4407        this.channel1.socket().bind(localAddr2);
4408        this.channel1.connect(localAddr1);
4409        this.channel2.socket().bind(localAddr1);
4410        this.channel2.connect(localAddr2);
4411
4412        class MyThread extends  Thread {
4413            public String errMsg = null;
4414            public void run() {
4415                try {
4416                    ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
4417                    channel1.send(targetBuf, localAddr1);
4418                    errMsg = "should throw ClosedByInterruptException";
4419                } catch (ClosedByInterruptException e) {
4420                    // expected
4421                } catch (IOException e) {
4422                    errMsg = "Unexcted Exception was thrown: " + e.getClass() +
4423                            ": " + e.getMessage();
4424                }
4425            }
4426        }
4427        MyThread thread = new MyThread();
4428        thread.start();
4429        try {
4430            Thread.sleep(TIME_UNIT);
4431            thread.interrupt();
4432        } catch (InterruptedException e) {
4433            // ok
4434        }
4435        thread.join(TIME_UNIT);
4436        if (thread.errMsg != null) {
4437            fail(thread.errMsg);
4438        }
4439    }
4440
4441    @TestTargetNew(
4442        level = TestLevel.PARTIAL_COMPLETE,
4443        notes = "",
4444        method = "send",
4445        args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
4446    )
4447    public void testSend_PositonNotZero()
4448            throws Exception {
4449        // regression test for Harmony-701
4450        int CAPACITY_NORMAL = 256;
4451        int postion = 16;
4452        DatagramChannel dc = DatagramChannel.open();
4453        byte[] sourceArray = new byte[CAPACITY_NORMAL];
4454        // send ByteBuffer whose position is not zero
4455        ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
4456        sourceBuf.position(postion);
4457        int ret = dc.send(sourceBuf, localAddr1);
4458        // assert send (256 - 16) bytes
4459        assertEquals(CAPACITY_NORMAL - postion, ret);
4460        // assert the position of ByteBuffer has been set
4461        assertEquals(CAPACITY_NORMAL, sourceBuf.position());
4462    }
4463
4464    /**
4465     * @tests DatagramChannel#read(ByteBuffer)
4466     */
4467    @TestTargetNew(
4468        level = TestLevel.PARTIAL_COMPLETE,
4469        notes = "",
4470        method = "read",
4471        args = {java.nio.ByteBuffer.class}
4472    )
4473    public void testReadByteBuffer2() throws Exception {
4474        // regression test for Harmony-754
4475        channel2.socket().bind(localAddr1);
4476        channel1.socket().bind(localAddr2);
4477        channel1.connect(localAddr1);
4478        channel2.connect(localAddr2);
4479        channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL));
4480
4481        ByteBuffer readBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
4482
4483        channel1.configureBlocking(true);
4484        assertEquals(CAPACITY_NORMAL, channel1.read(readBuf));
4485    }
4486
4487    public void disabled_testReadByteBuffer_Block_close() throws Exception {
4488        // bind and connect
4489        this.channel1.socket().bind(localAddr2);
4490        this.channel1.connect(localAddr1);
4491        this.channel2.socket().bind(localAddr1);
4492        this.channel2.connect(localAddr2);
4493        ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
4494
4495        new Thread() {
4496            public void run() {
4497                try {
4498                    Thread.sleep(TIME_UNIT);
4499                    channel1.close();
4500                } catch (Exception e) {
4501                    //ignore
4502                }
4503            }
4504        }.start();
4505        try {
4506            this.channel1.read(targetBuf);
4507            fail("should throw AsynchronousCloseException");
4508        } catch (AsynchronousCloseException e) {
4509            // ok
4510        }
4511    }
4512
4513    @TestTargetNew(
4514        level = TestLevel.PARTIAL_COMPLETE,
4515        notes = "",
4516        method = "read",
4517        args = {java.nio.ByteBuffer.class}
4518    )
4519    public void testReadByteBuffer_Block_interrupt() throws Exception {
4520        // bind and connect
4521        this.channel1.socket().bind(localAddr2);
4522        this.channel1.connect(localAddr1);
4523        this.channel2.socket().bind(localAddr1);
4524        this.channel2.connect(localAddr2);
4525
4526        class MyThread extends Thread {
4527            public String errMsg = null;
4528            public void run() {
4529                try {
4530                    ByteBuffer targetBuf = ByteBuffer.wrap(new byte[2]);
4531                    channel1.read(targetBuf);
4532                    errMsg = "should throw ClosedByInterruptException";
4533                } catch (ClosedByInterruptException e) {
4534                    // expected
4535                } catch (IOException e) {
4536                    errMsg = "Unexcted Exception was thrown: " + e.getClass() +
4537                            ": " + e.getMessage();
4538                }
4539            }
4540        }
4541        MyThread thread = new MyThread();
4542        thread.start();
4543        try {
4544            Thread.sleep(TIME_UNIT);
4545            thread.interrupt();
4546        } catch (InterruptedException e) {
4547            // ok
4548        }
4549        thread.join(TIME_UNIT);
4550        if (thread.errMsg != null) {
4551            fail(thread.errMsg);
4552        }
4553    }
4554
4555    /**
4556     * @tests DatagramChannel#read(ByteBuffer[])
4557     */
4558    @TestTargetNew(
4559        level = TestLevel.PARTIAL_COMPLETE,
4560        notes = "",
4561        method = "read",
4562        args = {java.nio.ByteBuffer[].class}
4563    )
4564    public void testReadByteBufferArray2() throws Exception {
4565        // regression test for Harmony-754
4566        channel2.socket().bind(localAddr1);
4567        channel1.socket().bind(localAddr2);
4568        channel1.connect(localAddr1);
4569        channel2.connect(localAddr2);
4570        channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL));
4571
4572        ByteBuffer[] readBuf = new ByteBuffer[2];
4573        readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
4574        readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
4575
4576        channel1.configureBlocking(true);
4577        assertEquals(CAPACITY_NORMAL, channel1.read(readBuf));
4578    }
4579
4580    public void disabled_testReadByteBufferArray_Block_close() throws Exception {
4581        // bind and connect
4582        this.channel1.socket().bind(localAddr2);
4583        this.channel1.connect(localAddr1);
4584        this.channel2.socket().bind(localAddr1);
4585        this.channel2.connect(localAddr2);
4586        ByteBuffer[] targetBuf = new ByteBuffer[2];
4587        targetBuf[0] = ByteBuffer.wrap(new byte[2]);
4588        targetBuf[1] = ByteBuffer.wrap(new byte[2]);
4589
4590        new Thread() {
4591            public void run() {
4592                try {
4593                    Thread.sleep(TIME_UNIT);
4594                    channel1.close();
4595                } catch (Exception e) {
4596                    //ignore
4597                }
4598            }
4599        }.start();
4600        try {
4601            this.channel1.read(targetBuf);
4602            fail("should throw AsynchronousCloseException");
4603        } catch (AsynchronousCloseException e) {
4604            // ok
4605        }
4606    }
4607
4608    public void disabled_testReadByteBufferArray_Block_interrupt() throws Exception {
4609        // makes emulator hang
4610        // bind and connect
4611        this.channel1.socket().bind(localAddr2);
4612        this.channel1.connect(localAddr1);
4613        this.channel2.socket().bind(localAddr1);
4614        this.channel2.connect(localAddr2);
4615
4616        class MyThread extends Thread {
4617            public String errMsg = null;
4618            public void run() {
4619                try {
4620                    ByteBuffer[] targetBuf = new ByteBuffer[2];
4621                    targetBuf[0] = ByteBuffer.wrap(new byte[2]);
4622                    targetBuf[1] = ByteBuffer.wrap(new byte[2]);
4623                    channel1.read(targetBuf);
4624                    errMsg = "should throw ClosedByInterruptException";
4625                } catch (ClosedByInterruptException e) {
4626                    // expected
4627                } catch (IOException e) {
4628                    errMsg = "Unexcted Exception was thrown: " + e.getClass() +
4629                            ": " + e.getMessage();
4630                }
4631            }
4632        }
4633        MyThread thread = new MyThread();
4634        thread.start();
4635        try {
4636            Thread.sleep(TIME_UNIT);
4637            thread.interrupt();
4638        } catch (InterruptedException e) {
4639            // ok
4640        }
4641        thread.join(TIME_UNIT);
4642        if (thread.errMsg != null) {
4643            fail(thread.errMsg);
4644        }
4645    }
4646
4647    /**
4648     * @tests DatagramChannel#read(ByteBuffer[],int,int)
4649     */
4650    @TestTargetNew(
4651        level = TestLevel.PARTIAL_COMPLETE,
4652        notes = "",
4653        method = "read",
4654        args = {java.nio.ByteBuffer[].class, int.class, int.class}
4655    )
4656    public void testReadByteBufferArrayII2() throws Exception {
4657        // regression test for Harmony-754
4658        channel2.socket().bind(localAddr1);
4659        channel1.socket().bind(localAddr2);
4660        channel1.connect(localAddr1);
4661        channel2.connect(localAddr2);
4662        channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL));
4663
4664        ByteBuffer[] readBuf = new ByteBuffer[2];
4665        readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
4666        readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
4667
4668        channel1.configureBlocking(true);
4669        assertEquals(CAPACITY_NORMAL, channel1.read(readBuf,0,2));
4670    }
4671
4672    /**
4673     * @tests DatagramChannel#read(ByteBuffer)
4674     */
4675    @TestTargetNew(
4676        level = TestLevel.PARTIAL_COMPLETE,
4677        notes = "",
4678        method = "read",
4679        args = {java.nio.ByteBuffer.class}
4680    )
4681    public void testReadByteBuffer_closed_nullBuf() throws Exception {
4682        // regression test for Harmony-754
4683        ByteBuffer c = null;
4684        DatagramChannel channel = DatagramChannel.open();
4685        channel.close();
4686        try{
4687            channel.read(c);
4688            fail("Should throw NullPointerException");
4689        } catch (NullPointerException e){
4690            // expected
4691        }
4692    }
4693
4694    /**
4695     * @tests DatagramChannel#read(ByteBuffer)
4696     */
4697    @TestTargetNew(
4698        level = TestLevel.PARTIAL_COMPLETE,
4699        notes = "",
4700        method = "read",
4701        args = {java.nio.ByteBuffer.class}
4702    )
4703    public void testReadByteBuffer_NotConnected_nullBuf() throws Exception {
4704        // regression test for Harmony-754
4705        ByteBuffer c = null;
4706        DatagramChannel channel = DatagramChannel.open();
4707        try{
4708            channel.read(c);
4709            fail("Should throw NullPointerException");
4710        } catch (NullPointerException e){
4711            // expected
4712        }
4713    }
4714
4715    /**
4716     * @tests DatagramChannel#read(ByteBuffer)
4717     */
4718    @TestTargetNew(
4719        level = TestLevel.PARTIAL_COMPLETE,
4720        notes = "",
4721        method = "read",
4722        args = {java.nio.ByteBuffer.class}
4723    )
4724    public void testReadByteBuffer_readOnlyBuf() throws Exception {
4725        // regression test for Harmony-754
4726        ByteBuffer c = ByteBuffer.allocate(1);
4727        DatagramChannel channel = DatagramChannel.open();
4728        try{
4729            channel.read(c.asReadOnlyBuffer());
4730            fail("Should throw NotYetConnectedException");
4731        } catch (NotYetConnectedException e){
4732            // expected
4733        }
4734        channel.connect(localAddr1);
4735        try{
4736            channel.read(c.asReadOnlyBuffer());
4737            fail("Should throw IllegalArgumentException");
4738        } catch (IllegalArgumentException e){
4739            // expected
4740        }
4741    }
4742
4743    /**
4744     * @tests DatagramChannel#send(ByteBuffer, SocketAddress)
4745     */
4746    @TestTargetNew(
4747        level = TestLevel.PARTIAL_COMPLETE,
4748        notes = "",
4749        method = "send",
4750        args = {java.nio.ByteBuffer.class, java.net.SocketAddress.class}
4751    )
4752    public void testSend_Closed() throws IOException{
4753        // regression test for Harmony-913
4754        channel1.close();
4755        ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
4756        try {
4757            channel1.send(buf, localAddr1);
4758            fail("Should throw ClosedChannelException");
4759        } catch (ClosedChannelException e) {
4760            //pass
4761        }
4762        try {
4763            channel1.send(null,localAddr1);
4764            fail("Should throw NullPointerException");
4765        } catch (NullPointerException e) {
4766            //pass
4767        }
4768        try {
4769            channel1.send(buf, null);
4770            fail("Should throw ClosedChannelException");
4771        } catch (ClosedChannelException e) {
4772            //pass
4773        }
4774        try {
4775            channel1.send(null, null);
4776            fail("Should throw NullPointerException");
4777        } catch (NullPointerException e) {
4778            //pass
4779        }
4780    }
4781
4782    /**
4783     * @tests DatagramChannel#socket()
4784     */
4785    @TestTargetNew(
4786        level = TestLevel.PARTIAL_COMPLETE,
4787        notes = "",
4788        method = "socket",
4789        args = {}
4790    )
4791    public void testSocket_NonBlock_IllegalBlockingModeException() throws Exception {
4792        // regression test for Harmony-1036
4793        DatagramChannel channel = DatagramChannel.open();
4794        channel.configureBlocking(false);
4795        DatagramSocket socket = channel.socket();
4796        try {
4797            socket.send(null);
4798            fail("should throw IllegalBlockingModeException");
4799        } catch (IllegalBlockingModeException e) {
4800            // expected
4801        }
4802        try {
4803            socket.receive(null);
4804            fail("should throw IllegalBlockingModeException");
4805        } catch (IllegalBlockingModeException e) {
4806            // expected
4807        }
4808    }
4809}
4810