Home | History | Annotate | Download | only in channels
      1 /*
      2  *  Licensed to the Apache Software Foundation (ASF) under one or more
      3  *  contributor license agreements.  See the NOTICE file distributed with
      4  *  this work for additional information regarding copyright ownership.
      5  *  The ASF licenses this file to You under the Apache License, Version 2.0
      6  *  (the "License"); you may not use this file except in compliance with
      7  *  the License.  You may obtain a copy of the License at
      8  *
      9  *     http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  *  Unless required by applicable law or agreed to in writing, software
     12  *  distributed under the License is distributed on an "AS IS" BASIS,
     13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  *  See the License for the specific language governing permissions and
     15  *  limitations under the License.
     16  */
     17 
     18 package org.apache.harmony.tests.java.nio.channels;
     19 
     20 import java.io.IOException;
     21 import java.net.DatagramPacket;
     22 import java.net.DatagramSocket;
     23 import java.net.Inet6Address;
     24 import java.net.InetSocketAddress;
     25 import java.net.SocketAddress;
     26 import java.net.SocketException;
     27 import java.nio.ByteBuffer;
     28 import java.nio.channels.AsynchronousCloseException;
     29 import java.nio.channels.ClosedChannelException;
     30 import java.nio.channels.DatagramChannel;
     31 import java.nio.channels.IllegalBlockingModeException;
     32 import java.nio.channels.NotYetConnectedException;
     33 import java.nio.channels.UnresolvedAddressException;
     34 import java.nio.channels.UnsupportedAddressTypeException;
     35 import java.nio.channels.spi.SelectorProvider;
     36 import junit.framework.TestCase;
     37 import libcore.io.IoUtils;
     38 
     39 /**
     40  * Test for DatagramChannel
     41  */
     42 public class DatagramChannelTest extends TestCase {
     43 
     44     private static final int CAPACITY_NORMAL = 200;
     45 
     46     private static final int CAPACITY_1KB = 1024;
     47 
     48     private static final int CAPACITY_64KB = 65536;
     49 
     50     private static final int CAPACITY_ZERO = 0;
     51 
     52     private static final int CAPACITY_ONE = 1;
     53 
     54     private static final int TIME_UNIT = 500;
     55 
     56     private InetSocketAddress datagramSocket1Address;
     57     private InetSocketAddress datagramSocket2Address;
     58 
     59     private InetSocketAddress channel1Address;
     60     private InetSocketAddress channel2Address;
     61 
     62     private DatagramChannel channel1;
     63     private DatagramChannel channel2;
     64 
     65     private DatagramSocket datagramSocket1;
     66     private DatagramSocket datagramSocket2;
     67 
     68     protected void setUp() throws Exception {
     69         super.setUp();
     70 
     71         channel1 = DatagramChannel.open();
     72         channel2 = DatagramChannel.open();
     73 
     74         channel1.socket().bind(new InetSocketAddress(Inet6Address.LOOPBACK, 0));
     75         channel2.socket().bind(new InetSocketAddress(Inet6Address.LOOPBACK, 0));
     76 
     77         channel1Address = (InetSocketAddress) channel1.socket().getLocalSocketAddress();
     78         channel2Address = (InetSocketAddress) channel2.socket().getLocalSocketAddress();
     79 
     80         this.datagramSocket1 = new DatagramSocket(0, Inet6Address.LOOPBACK);
     81         this.datagramSocket2 = new DatagramSocket(0, Inet6Address.LOOPBACK);
     82 
     83         datagramSocket1Address = (InetSocketAddress) datagramSocket1.getLocalSocketAddress();
     84         datagramSocket2Address = (InetSocketAddress) datagramSocket2.getLocalSocketAddress();
     85     }
     86 
     87     protected void tearDown() throws Exception {
     88         IoUtils.closeQuietly(channel1);
     89         IoUtils.closeQuietly(channel2);
     90         IoUtils.closeQuietly(datagramSocket1);
     91         IoUtils.closeQuietly(datagramSocket2);
     92 
     93         datagramSocket1Address = null;
     94         datagramSocket2Address = null;
     95         super.tearDown();
     96     }
     97 
     98     // -------------------------------------------------------------------
     99     // Test for methods in abstract class.
    100     // -------------------------------------------------------------------
    101     /*
    102      * Test method for 'java.nio.channels.DatagramChannel.validOps()'
    103      */
    104     public void testValidOps() {
    105         MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider
    106                 .provider());
    107         MockDatagramChannel testMocknull = new MockDatagramChannel(null);
    108         int val = this.channel1.validOps();
    109         assertEquals(5, val);
    110         assertEquals(val, testMock.validOps());
    111         assertEquals(val, testMocknull.validOps());
    112     }
    113 
    114     /*
    115      * Test method for 'java.nio.channels.DatagramChannel.open()'
    116      */
    117     public void testOpen() {
    118         MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider
    119                 .provider());
    120         MockDatagramChannel testMocknull = new MockDatagramChannel(null);
    121         assertNull(testMocknull.provider());
    122         assertNotNull(testMock.provider());
    123         assertEquals(this.channel1.provider(), testMock.provider());
    124         assertEquals(5, testMock.validOps());
    125     }
    126 
    127     /*
    128      * Test method for 'java.nio.channels.DatagramChannel.read(ByteBuffer)'
    129      */
    130     public void testReadByteBufferArray() throws IOException {
    131         final int testNum = 0;
    132         MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider
    133                 .provider());
    134         MockDatagramChannel testMocknull = new MockDatagramChannel(null);
    135         int bufSize = 10;
    136         ByteBuffer[] readBuf = null;
    137         try {
    138             this.channel1.read(readBuf);
    139             fail("Should throw NPE");
    140         } catch (NullPointerException e) {
    141             // correct
    142         }
    143 
    144         long readres;
    145         try {
    146             readres = testMock.read(readBuf);
    147             fail("Should throw NPE");
    148         } catch (NullPointerException e) {
    149             // correct
    150         }
    151         readBuf = new ByteBuffer[bufSize];
    152         try {
    153             readres = this.channel1.read(readBuf);
    154             fail("Should throw NotYetConnectedException");
    155         } catch (NotYetConnectedException expected) {
    156         }
    157 
    158         readres = testMock.read(readBuf);
    159         assertEquals(testNum, readres);
    160         readres = testMocknull.read(readBuf);
    161         assertEquals(testNum, readres);
    162     }
    163 
    164     /*
    165      * Test method for 'java.nio.channels.DatagramChannel.read(ByteBuffer)'
    166      */
    167     public void testReadByteBufferArray_BufNull() throws IOException {
    168         MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider
    169                 .provider());
    170         MockDatagramChannel testMocknull = new MockDatagramChannel(null);
    171 
    172         ByteBuffer[] readBuf = null;
    173         try {
    174             this.channel1.read(readBuf);
    175             fail("Should throw NPE");
    176         } catch (NullPointerException expected) {
    177         }
    178         try {
    179             testMock.read(readBuf);
    180             fail("Should throw NPE");
    181         } catch (NullPointerException expected) {
    182         }
    183         try {
    184             testMocknull.read(readBuf);
    185             fail("Should throw NPE");
    186         } catch (NullPointerException expected) {
    187         }
    188     }
    189 
    190     /*
    191      * Test method for 'java.nio.channels.DatagramChannel.write(ByteBuffer)'
    192      */
    193     public void testWriteByteBuffer() throws IOException {
    194         MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider
    195                 .provider());
    196         MockDatagramChannel testMocknull = new MockDatagramChannel(null);
    197         int bufSize = 10;
    198         ByteBuffer[] readBuf = null;
    199         try {
    200             this.channel1.write(readBuf);
    201             fail("Should throw NPE");
    202         } catch (NullPointerException e) {
    203             // correct
    204         }
    205         try {
    206             testMock.write(readBuf);
    207             fail("Should throw NPE");
    208         } catch (NullPointerException e) {
    209             // correct
    210         }
    211         readBuf = new ByteBuffer[bufSize];
    212         try {
    213             this.channel1.write(readBuf);
    214             fail("Should throw NotYetConnectedException");
    215         } catch (NotYetConnectedException e) {
    216             // correct
    217         }
    218         long writeres = 0;
    219         writeres = testMock.write(readBuf);
    220 
    221         assertEquals(0, writeres);
    222         writeres = testMocknull.write(readBuf);
    223         assertEquals(0, writeres);
    224     }
    225 
    226     /*
    227      * Test method for 'java.nio.channels.DatagramChannel.write(ByteBuffer)'
    228      */
    229     public void testWriteByteBuffer_Bufnull() throws IOException {
    230         MockDatagramChannel testMock = new MockDatagramChannel(SelectorProvider
    231                 .provider());
    232         MockDatagramChannel testMocknull = new MockDatagramChannel(null);
    233         ByteBuffer[] readBuf = null;
    234         try {
    235             this.channel1.write(readBuf);
    236             fail("Should throw NPE");
    237         } catch (NullPointerException e) {
    238             // correct
    239         }
    240         try {
    241             testMock.write(readBuf);
    242             fail("Should throw NPE");
    243         } catch (NullPointerException e) {
    244             // correct
    245         }
    246         try {
    247             testMocknull.write(readBuf);
    248             fail("Should throw NPE");
    249         } catch (NullPointerException e) {
    250             // correct
    251         }
    252     }
    253 
    254     // -------------------------------------------------------------------
    255     // Test for socket()
    256     // -------------------------------------------------------------------
    257 
    258     /**
    259      * Test method for 'DatagramChannelImpl.socket()'
    260      */
    261     public void testSocket_BasicStatusBeforeConnect() throws Exception {
    262         final DatagramChannel dc = DatagramChannel.open();
    263 
    264         assertFalse(dc.isConnected());// not connected
    265         DatagramSocket s1 = dc.socket();
    266 
    267         assertFalse(s1.isBound());
    268         assertFalse(s1.isClosed());
    269         assertFalse(s1.isConnected());
    270         assertFalse(s1.getBroadcast());
    271         assertFalse(s1.getReuseAddress());
    272         assertNull(s1.getInetAddress());
    273         assertTrue(s1.getLocalAddress().isAnyLocalAddress());
    274         assertEquals(s1.getLocalPort(), 0);
    275         assertNull(s1.getLocalSocketAddress());
    276         assertEquals(s1.getPort(), -1);
    277         assertTrue(s1.getReceiveBufferSize() >= 8192);
    278         assertNull(s1.getRemoteSocketAddress());
    279         assertFalse(s1.getReuseAddress());
    280         assertTrue(s1.getSendBufferSize() >= 8192);
    281         assertEquals(s1.getSoTimeout(), 0);
    282         assertEquals(s1.getTrafficClass(), 0);
    283 
    284         DatagramSocket s2 = dc.socket();
    285         // same
    286         assertSame(s1, s2);
    287 
    288         dc.close();
    289     }
    290 
    291     /**
    292      * Test method for 'DatagramChannelImpl.socket()'
    293      */
    294     public void testSocket_Block_BasicStatusAfterConnect() throws IOException {
    295         final DatagramChannel dc = DatagramChannel.open();
    296 
    297         dc.connect(datagramSocket1Address);
    298         DatagramSocket s1 = dc.socket();
    299         assertSocketAfterConnect(s1);
    300         DatagramSocket s2 = dc.socket();
    301         // same
    302         assertSame(s1, s2);
    303 
    304         dc.close();
    305     }
    306 
    307     public void testSocket_NonBlock_BasicStatusAfterConnect() throws IOException {
    308         final DatagramChannel dc = DatagramChannel.open();
    309         dc.connect(datagramSocket1Address);
    310         dc.configureBlocking(false);
    311 
    312         DatagramSocket s1 = dc.socket();
    313         assertSocketAfterConnect(s1);
    314         DatagramSocket s2 = dc.socket();
    315         // same
    316         assertSame(s1, s2);
    317 
    318         dc.close();
    319     }
    320 
    321     private void assertSocketAfterConnect(DatagramSocket s) throws SocketException {
    322         assertTrue(s.isBound());
    323         assertFalse(s.isClosed());
    324         assertTrue(s.isConnected());
    325         assertFalse(s.getBroadcast());
    326         assertFalse(s.getReuseAddress());
    327         assertNotNull(s.getLocalSocketAddress());
    328         assertEquals(s.getPort(), datagramSocket1Address.getPort());
    329         assertTrue(s.getReceiveBufferSize() >= 8192);
    330         // not same , but equals
    331         assertNotSame(s.getRemoteSocketAddress(), datagramSocket1Address);
    332         assertEquals(s.getRemoteSocketAddress(), datagramSocket1Address);
    333         assertFalse(s.getReuseAddress());
    334         assertTrue(s.getSendBufferSize() >= 8192);
    335         assertEquals(s.getSoTimeout(), 0);
    336         assertEquals(s.getTrafficClass(), 0);
    337     }
    338 
    339     /**
    340      * Test method for 'DatagramChannelImpl.socket()'
    341      */
    342     public void testSocket_ActionsBeforeConnect() throws IOException {
    343         assertFalse(channel1.isConnected());// not connected
    344         assertTrue(channel1.isBlocking());
    345         DatagramSocket s = channel1.socket();
    346 
    347         s.connect(datagramSocket2Address);
    348         assertTrue(channel1.isConnected());
    349         assertTrue(s.isConnected());
    350 
    351         s.disconnect();
    352         assertFalse(channel1.isConnected());
    353         assertFalse(s.isConnected());
    354 
    355         s.close();
    356         assertTrue(s.isClosed());
    357         assertFalse(channel1.isOpen());
    358     }
    359 
    360     /**
    361      * Test method for 'DatagramChannelImpl.socket()'
    362      */
    363     public void testSocket_Block_ActionsAfterConnect() throws IOException {
    364         assertFalse(this.channel1.isConnected());// not connected
    365         this.channel1.connect(datagramSocket1Address);
    366         DatagramSocket s = this.channel1.socket();
    367         assertSocketActionAfterConnect(s);
    368     }
    369 
    370     public void testSocket_NonBlock_ActionsAfterConnect() throws IOException {
    371         this.channel1.connect(datagramSocket1Address);
    372         this.channel1.configureBlocking(false);
    373         DatagramSocket s = this.channel1.socket();
    374         assertSocketActionAfterConnect(s);
    375     }
    376 
    377     private void assertSocketActionAfterConnect(DatagramSocket s) throws IOException {
    378         assertEquals(s.getPort(), datagramSocket1Address.getPort());
    379         try {
    380             s.connect(datagramSocket2Address);
    381             fail();
    382         } catch (IllegalStateException expected) {
    383         }
    384 
    385         assertTrue(this.channel1.isConnected());
    386         assertTrue(s.isConnected());
    387         // not changed
    388         assertEquals(s.getPort(), datagramSocket1Address.getPort());
    389 
    390         s.disconnect();
    391         assertFalse(this.channel1.isConnected());
    392         assertFalse(s.isConnected());
    393 
    394         s.close();
    395         assertTrue(s.isClosed());
    396         assertFalse(this.channel1.isOpen());
    397     }
    398 
    399     // -------------------------------------------------------------------
    400     // Test for isConnected()
    401     // -------------------------------------------------------------------
    402 
    403     /**
    404      * Test method for 'DatagramChannelImpl.isConnected()'
    405      */
    406     public void testIsConnected_WithServer() throws IOException {
    407         connectLocalServer();
    408         disconnectAfterConnected();
    409         this.datagramSocket1.close();
    410         this.channel1.close();
    411         assertFalse(this.channel1.isConnected());
    412     }
    413 
    414     // -------------------------------------------------------------------
    415     // Test for connect()
    416     // -------------------------------------------------------------------
    417 
    418     /**
    419      * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
    420      */
    421     public void testConnect_BlockWithServer() throws IOException {
    422         // blocking mode
    423         assertTrue(this.channel1.isBlocking());
    424         connectLocalServer();
    425         datagramSocket1.close();
    426         disconnectAfterConnected();
    427     }
    428 
    429     /**
    430      * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
    431      */
    432     public void testConnect_BlockNoServer() throws IOException {
    433         connectWithoutServer();
    434         disconnectAfterConnected();
    435     }
    436 
    437     /**
    438      * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
    439      */
    440     public void testConnect_NonBlockWithServer() throws IOException {
    441         // Non blocking mode
    442         this.channel1.configureBlocking(false);
    443         connectLocalServer();
    444         datagramSocket1.close();
    445         disconnectAfterConnected();
    446     }
    447 
    448     /**
    449      * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
    450      */
    451     public void testConnect_Null() throws IOException {
    452         assertFalse(this.channel1.isConnected());
    453         try {
    454             this.channel1.connect(null);
    455             fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$
    456         } catch (IllegalArgumentException e) {
    457             // OK.
    458         }
    459     }
    460 
    461     /**
    462      * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
    463      */
    464     public void testConnect_UnsupportedType() throws IOException {
    465         assertFalse(this.channel1.isConnected());
    466         class SubSocketAddress extends SocketAddress {
    467             private static final long serialVersionUID = 1L;
    468 
    469             public SubSocketAddress() {
    470                 super();
    471             }
    472         }
    473         SocketAddress newTypeAddress = new SubSocketAddress();
    474         try {
    475             this.channel1.connect(newTypeAddress);
    476             fail("Should throw an UnsupportedAddressTypeException here.");
    477         } catch (UnsupportedAddressTypeException e) {
    478             // OK.
    479         }
    480     }
    481 
    482     /**
    483      * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
    484      */
    485     public void testConnect_Unresolved() throws IOException {
    486         assertFalse(this.channel1.isConnected());
    487         InetSocketAddress unresolved = new InetSocketAddress(
    488                 "unresolved address", 1080);
    489         try {
    490             this.channel1.connect(unresolved);
    491             fail("Should throw an UnresolvedAddressException here."); //$NON-NLS-1$
    492         } catch (UnresolvedAddressException e) {
    493             // OK.
    494         }
    495     }
    496 
    497     public void testConnect_EmptyHost() throws Exception {
    498         assertFalse(this.channel1.isConnected());
    499 
    500         assertEquals(this.channel1, this.channel1
    501                 .connect(new InetSocketAddress("", 1081))); //$NON-NLS-1$
    502 
    503     }
    504 
    505     /**
    506      * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
    507      */
    508     public void testConnect_ClosedChannelException() throws IOException {
    509         assertFalse(this.channel1.isConnected());
    510         this.channel1.close();
    511         assertFalse(this.channel1.isOpen());
    512         try {
    513             this.channel1.connect(datagramSocket1Address);
    514             fail("Should throw ClosedChannelException."); //$NON-NLS-1$
    515         } catch (ClosedChannelException e) {
    516             // OK.
    517         }
    518     }
    519 
    520     /**
    521      * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
    522      */
    523     public void testConnect_IllegalStateException() throws IOException {
    524         assertFalse(this.channel1.isConnected());
    525         this.channel1.connect(datagramSocket1Address);
    526         assertTrue(this.channel1.isConnected());
    527         // connect after connected.
    528         try {
    529             this.channel1.connect(datagramSocket1Address);
    530             fail("Should throw IllegalStateException."); //$NON-NLS-1$
    531         } catch (IllegalStateException e) {
    532             // OK.
    533         }
    534     }
    535 
    536     /**
    537      * Test method for 'DatagramChannelImpl.connect(SocketAddress)'
    538      */
    539     public void testConnect_CheckOpenBeforeStatus() throws IOException {
    540         assertFalse(this.channel1.isConnected());
    541         this.channel1.connect(datagramSocket1Address);
    542         assertTrue(this.channel1.isConnected());
    543         // connect after connected.
    544         this.channel1.close();
    545         assertFalse(this.channel1.isOpen());
    546         // checking open is before checking status.
    547         try {
    548             this.channel1.connect(datagramSocket1Address);
    549             fail("Should throw ClosedChannelException."); //$NON-NLS-1$
    550         } catch (ClosedChannelException e) {
    551             // OK.
    552         }
    553     }
    554 
    555     private void disconnectAfterConnected() throws IOException {
    556         assertTrue(this.channel1.isConnected());
    557         this.channel1.disconnect();
    558         assertFalse(this.channel1.isConnected());
    559     }
    560 
    561     private void disconnectAfterClosed() throws IOException {
    562         assertFalse(this.channel1.isOpen());
    563         assertFalse(this.channel1.isConnected());
    564         this.channel1.disconnect();
    565         assertFalse(this.channel1.isConnected());
    566     }
    567 
    568     private void connectLocalServer() throws IOException {
    569         assertFalse(this.channel1.isConnected());
    570         assertTrue(this.datagramSocket1.isBound());
    571         assertSame(this.channel1, this.channel1.connect(datagramSocket1Address));
    572         assertTrue(this.channel1.isConnected());
    573     }
    574 
    575     private void connectWithoutServer() throws IOException {
    576         assertFalse(this.channel1.isConnected());
    577         this.datagramSocket1.close();
    578         assertTrue(this.datagramSocket1.isClosed());
    579         assertSame(this.channel1, this.channel1.connect(datagramSocket1Address));
    580         assertTrue(this.channel1.isConnected());
    581     }
    582 
    583     // -------------------------------------------------------------------
    584     // Test for disconnect()
    585     // -------------------------------------------------------------------
    586 
    587     /**
    588      * Test method for 'DatagramChannelImpl.disconnect()'
    589      */
    590     public void testDisconnect_BeforeConnect() throws IOException {
    591         assertFalse(this.channel1.isConnected());
    592         assertEquals(this.channel1, this.channel1.disconnect());
    593         assertFalse(this.channel1.isConnected());
    594     }
    595 
    596     /**
    597      * Test method for 'DatagramChannelImpl.disconnect()'
    598      */
    599     public void testDisconnect_UnconnectedClosed() throws IOException {
    600         assertFalse(this.channel1.isConnected());
    601         this.channel1.close();
    602         assertFalse(this.channel1.isOpen());
    603         assertEquals(this.channel1, this.channel1.disconnect());
    604         assertFalse(this.channel1.isConnected());
    605     }
    606 
    607     /**
    608      * Test method for 'DatagramChannelImpl.disconnect()'
    609      */
    610     public void testDisconnect_BlockWithServerChannelClosed()
    611             throws IOException {
    612         assertTrue(this.channel1.isBlocking());
    613         connectLocalServer();
    614         // disconnect after channel close
    615         this.channel1.close();
    616         disconnectAfterClosed();
    617     }
    618 
    619     /**
    620      * Test method for 'DatagramChannelImpl.disconnect()'
    621      */
    622     public void testDisconnect_NonBlockWithServerChannelClosed()
    623             throws IOException {
    624         this.channel1.configureBlocking(false);
    625         connectLocalServer();
    626         // disconnect after channel close
    627         this.channel1.close();
    628         disconnectAfterClosed();
    629     }
    630 
    631     /**
    632      * Test method for 'DatagramChannelImpl.disconnect()'
    633      */
    634     public void testDisconnect_BlockWithServerServerClosed() throws IOException {
    635         assertTrue(this.channel1.isBlocking());
    636         connectLocalServer();
    637         // disconnect after server close
    638         this.datagramSocket1.close();
    639         assertTrue(this.channel1.isOpen());
    640         assertTrue(this.channel1.isConnected());
    641         disconnectAfterConnected();
    642     }
    643 
    644     /**
    645      * Test method for 'DatagramChannelImpl.disconnect()'
    646      */
    647     public void testDisconnect_NonBlockWithServerServerClosed()
    648             throws IOException {
    649         this.channel1.configureBlocking(false);
    650         assertFalse(this.channel1.isBlocking());
    651         connectLocalServer();
    652         // disconnect after server close
    653         this.datagramSocket1.close();
    654         assertTrue(this.channel1.isOpen());
    655         assertTrue(this.channel1.isConnected());
    656         disconnectAfterConnected();
    657     }
    658 
    659     // -------------------------------------------------------------------
    660     // Test for receive(): Behavior Without Server.
    661     // -------------------------------------------------------------------
    662 
    663     /**
    664      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    665      */
    666     public void testReceive_UnconnectedNull() throws Exception {
    667         assertFalse(this.channel1.isConnected());
    668         try {
    669             this.channel1.receive(null);
    670             fail("Should throw a NPE here."); //$NON-NLS-1$
    671         } catch (NullPointerException e) {
    672             // OK.
    673         }
    674     }
    675 
    676     /**
    677      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    678      */
    679     public void testReceive_UnconnectedReadonly() throws Exception {
    680         assertFalse(this.channel1.isConnected());
    681         ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL)
    682                 .asReadOnlyBuffer();
    683         assertTrue(dst.isReadOnly());
    684         try {
    685             this.channel1.receive(dst);
    686             fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$
    687         } catch (IllegalArgumentException e) {
    688             // OK.
    689         }
    690     }
    691 
    692     /**
    693      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    694      */
    695     public void testReceive_UnconnectedBufEmpty() throws Exception {
    696         this.channel1.configureBlocking(false);
    697         assertFalse(this.channel1.isConnected());
    698         ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
    699         assertNull(this.channel1.receive(dst));
    700     }
    701 
    702     public void testReceive_UnboundBufZero() throws Exception {
    703         DatagramChannel dc = DatagramChannel.open();
    704 
    705         assertFalse(dc.isConnected());
    706         assertFalse(dc.socket().isBound());
    707         ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ZERO);
    708         assertNull(dc.receive(dst));
    709 
    710         dc.close();
    711     }
    712 
    713     public void testReceive_UnboundBufNotEmpty() throws Exception {
    714         DatagramChannel dc = DatagramChannel.open();
    715         assertFalse(dc.isConnected());
    716         assertFalse(dc.socket().isBound());
    717 
    718         ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
    719         // buf is not empty
    720         dst.put((byte) 88);
    721         assertEquals(dst.position() + CAPACITY_NORMAL - 1, dst.limit());
    722         assertNull(dc.receive(dst));
    723 
    724         dc.close();
    725     }
    726 
    727     public void testReceive_UnboundBufFull() throws Exception {
    728         DatagramChannel dc = DatagramChannel.open();
    729 
    730         assertFalse(dc.isConnected());
    731         assertFalse(dc.socket().isBound());
    732         ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ONE);
    733 
    734         // buf is full
    735         dst.put((byte) 88);
    736         assertEquals(dst.position(), dst.limit());
    737         assertNull(dc.receive(dst));
    738 
    739         dc.close();
    740     }
    741 
    742     /**
    743      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    744      */
    745     public void testReceive_UnconnectedClose() throws Exception {
    746         assertFalse(this.channel1.isConnected());
    747         ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
    748         this.channel1.close();
    749         assertFalse(this.channel1.isOpen());
    750         try {
    751             assertNull(this.channel1.receive(dst));
    752             fail("Should throw a ClosedChannelException here."); //$NON-NLS-1$
    753         } catch (ClosedChannelException e) {
    754             // OK.
    755         }
    756     }
    757 
    758     /**
    759      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    760      */
    761     public void testReceive_UnconnectedCloseNull() throws Exception {
    762         assertFalse(this.channel1.isConnected());
    763         this.channel1.close();
    764         assertFalse(this.channel1.isOpen());
    765         // checking buffer before checking open
    766         try {
    767             this.channel1.receive(null);
    768             fail("Should throw a NPE here."); //$NON-NLS-1$
    769         } catch (NullPointerException e) {
    770             // OK.
    771         }
    772     }
    773 
    774     /**
    775      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    776      */
    777     public void testReceive_UnconnectedCloseReadonly() throws Exception {
    778         assertFalse(this.channel1.isConnected());
    779         ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL)
    780                 .asReadOnlyBuffer();
    781         assertTrue(dst.isReadOnly());
    782         this.channel1.close();
    783         assertFalse(this.channel1.isOpen());
    784         try {
    785             this.channel1.receive(dst);
    786             fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$
    787         } catch (IllegalArgumentException e) {
    788             // OK.
    789         }
    790     }
    791 
    792     /**
    793      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    794      */
    795     public void testReceive_NonBlockNoServerBufEmpty() throws Exception {
    796         this.channel1.configureBlocking(false);
    797         receiveNonBlockNoServer(CAPACITY_NORMAL);
    798     }
    799 
    800     /**
    801      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    802      */
    803     public void testReceive_BlockNoServerNull() throws Exception {
    804         assertTrue(this.channel1.isBlocking());
    805         receiveNoServerNull();
    806     }
    807 
    808     /**
    809      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    810      */
    811     public void testReceive_NonBlockNoServerNull() throws Exception {
    812         this.channel1.configureBlocking(false);
    813         receiveNoServerNull();
    814     }
    815 
    816     /**
    817      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    818      */
    819     public void testReceive_BlockNoServerReadonly() throws Exception {
    820         assertTrue(this.channel1.isBlocking());
    821         receiveNoServerReadonly();
    822     }
    823 
    824     /**
    825      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    826      */
    827     public void testReceive_NonBlockNoServerReadonly() throws Exception {
    828         this.channel1.configureBlocking(false);
    829         receiveNoServerReadonly();
    830     }
    831 
    832     /**
    833      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    834      */
    835     public void testReceive_NonBlockNoServerBufZero() throws Exception {
    836         this.channel1.configureBlocking(false);
    837         receiveNonBlockNoServer(CAPACITY_ZERO);
    838     }
    839 
    840     /**
    841      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    842      */
    843     public void testReceive_NonBlockNoServerBufNotEmpty() throws Exception {
    844         this.channel1.configureBlocking(false);
    845         connectWithoutServer();
    846         ByteBuffer dst = allocateNonEmptyBuf();
    847         assertNull(this.channel1.receive(dst));
    848     }
    849 
    850 
    851     /**
    852      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    853      */
    854     public void testReceive_NonBlockNoServerBufFull() throws Exception {
    855         this.channel1.configureBlocking(false);
    856         connectWithoutServer();
    857         ByteBuffer dst = allocateFullBuf();
    858         assertNull(this.channel1.receive(dst));
    859     }
    860 
    861     /**
    862      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    863      */
    864     public void testReceive_BlockNoServerChannelClose() throws Exception {
    865         assertTrue(this.channel1.isBlocking());
    866         receiveNoServerChannelClose();
    867     }
    868 
    869     /**
    870      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    871      */
    872     public void testReceive_NonBlockNoServerChannelClose() throws Exception {
    873         this.channel1.configureBlocking(false);
    874         receiveNoServerChannelClose();
    875     }
    876 
    877     /**
    878      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    879      */
    880     public void testReceive_BlockNoServerCloseNull() throws Exception {
    881         assertTrue(this.channel1.isBlocking());
    882         receiveNoServerChannelCloseNull();
    883     }
    884 
    885     /**
    886      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    887      */
    888     public void testReceive_NonBlockNoServerCloseNull() throws Exception {
    889         this.channel1.configureBlocking(false);
    890         receiveNoServerChannelCloseNull();
    891     }
    892 
    893     /**
    894      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    895      */
    896     public void testReceive_NonBlockNoServerCloseReadonly() throws Exception {
    897         this.channel1.configureBlocking(false);
    898         receiveNoServerChannelCloseReadonly();
    899     }
    900 
    901     /**
    902      * Test method for 'DatagramChannelImpl.receive(ByteBuffer)'
    903      */
    904     public void testReceive_BlockNoServerCloseReadonly() throws Exception {
    905         assertTrue(this.channel1.isBlocking());
    906         receiveNoServerChannelCloseReadonly();
    907     }
    908 
    909     private void receiveNoServerNull() throws IOException {
    910         connectWithoutServer();
    911         try {
    912             this.channel1.receive(null);
    913             fail("Should throw a NPE here."); //$NON-NLS-1$
    914         } catch (NullPointerException e) {
    915             // OK.
    916         }
    917     }
    918 
    919     private void receiveNoServerReadonly() throws IOException {
    920         connectWithoutServer();
    921         ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL)
    922                 .asReadOnlyBuffer();
    923         assertTrue(dst.isReadOnly());
    924         try {
    925             this.channel1.receive(dst);
    926             fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$
    927         } catch (IllegalArgumentException e) {
    928             // OK.
    929         }
    930     }
    931 
    932     private void receiveNonBlockNoServer(int size) throws IOException {
    933         connectWithoutServer();
    934         ByteBuffer dst = ByteBuffer.allocateDirect(size);
    935         assertNull(this.channel1.receive(dst));
    936     }
    937 
    938     private void receiveNoServerChannelClose() throws IOException {
    939         connectWithoutServer();
    940         ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
    941         this.channel1.close();
    942         assertFalse(this.channel1.isOpen());
    943         try {
    944             assertNull(this.channel1.receive(dst));
    945             fail("Should throw a ClosedChannelException here."); //$NON-NLS-1$
    946         } catch (ClosedChannelException e) {
    947             // OK.
    948         }
    949     }
    950 
    951     private void receiveNoServerChannelCloseNull() throws IOException {
    952         connectWithoutServer();
    953         this.channel1.close();
    954         assertFalse(this.channel1.isOpen());
    955         try {
    956             this.channel1.receive(null);
    957             fail("Should throw a NPE here."); //$NON-NLS-1$
    958         } catch (NullPointerException e) {
    959             // OK.
    960         }
    961     }
    962 
    963     private void receiveNoServerChannelCloseReadonly() throws IOException {
    964         connectWithoutServer();
    965         this.channel1.close();
    966         assertFalse(this.channel1.isOpen());
    967         ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL)
    968                 .asReadOnlyBuffer();
    969         assertTrue(dst.isReadOnly());
    970         try {
    971             this.channel1.receive(dst);
    972             fail("Should throw an IllegalArgumentException here."); //$NON-NLS-1$
    973         } catch (IllegalArgumentException e) {
    974             // OK.
    975         }
    976     }
    977 
    978     private ByteBuffer allocateFullBuf() {
    979         ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_ONE);
    980         // buf is full
    981         dst.put((byte) 88);
    982         assertEquals(dst.position(), dst.limit());
    983         return dst;
    984     }
    985 
    986     private ByteBuffer allocateNonEmptyBuf() {
    987         ByteBuffer dst = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
    988         // buf is not empty
    989         dst.put((byte) 88);
    990         dst.put((byte) 99);
    991         assertEquals(dst.position() + CAPACITY_NORMAL - 2, dst.limit());
    992         return dst;
    993     }
    994 
    995     // -------------------------------------------------------------------
    996     // Test for send(): Behavior without server.
    997     // -------------------------------------------------------------------
    998 
    999     private void sendDataBlocking(InetSocketAddress addr, ByteBuffer writeBuf)
   1000             throws IOException {
   1001         InetSocketAddress ipAddr = addr;
   1002         assertEquals(CAPACITY_NORMAL, this.channel1.send(writeBuf, ipAddr));
   1003         assertTrue(this.channel1.isOpen());
   1004         assertTrue(this.channel1.isBlocking());
   1005         this.channel1.connect(ipAddr);
   1006         assertTrue(this.channel1.isConnected());
   1007     }
   1008 
   1009     private void sendDataNonBlocking(InetSocketAddress addr, ByteBuffer writeBuf)
   1010             throws IOException {
   1011         InetSocketAddress ipAddr = addr;
   1012         this.channel1.configureBlocking(false);
   1013         assertEquals(CAPACITY_NORMAL, this.channel1.send(writeBuf, ipAddr));
   1014         assertTrue(this.channel1.isOpen());
   1015         assertFalse(this.channel1.isBlocking());
   1016         this.channel1.connect(ipAddr);
   1017         assertTrue(this.channel1.isConnected());
   1018     }
   1019 
   1020     /*
   1021      * Test method for 'DatagramChannelImpl.send(ByteBuffer, SocketAddress)'
   1022      */
   1023     public void testSend_NoServerBlockingCommon() throws IOException {
   1024         ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1025         sendDataBlocking(datagramSocket1Address, writeBuf);
   1026     }
   1027 
   1028     public void testSend_NoServerNonblockingCommon() throws IOException {
   1029         ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1030         sendDataNonBlocking(datagramSocket1Address, writeBuf);
   1031     }
   1032 
   1033     public void testSend_NoServerTwice() throws IOException {
   1034         ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1035         sendDataBlocking(datagramSocket1Address, writeBuf);
   1036         // can not buffer twice!
   1037         assertEquals(0, this.channel1.send(writeBuf, datagramSocket1Address));
   1038         try {
   1039             channel1.send(writeBuf, datagramSocket2Address);
   1040             fail("Should throw IllegalArgumentException");
   1041         } catch (IllegalArgumentException e) {
   1042             // correct
   1043         }
   1044     }
   1045 
   1046     public void testSend_NoServerNonBlockingTwice() throws IOException {
   1047         ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1048         sendDataNonBlocking(datagramSocket1Address, writeBuf);
   1049         // can not buffer twice!
   1050         assertEquals(0, this.channel1.send(writeBuf, datagramSocket1Address));
   1051         try {
   1052             channel1.send(writeBuf, datagramSocket2Address);
   1053             fail("Should throw IllegalArgumentException");
   1054         } catch (IllegalArgumentException e) {
   1055             // correct
   1056         }
   1057     }
   1058 
   1059     public void testSend_NoServerBufNull() throws IOException {
   1060         try {
   1061             sendDataBlocking(datagramSocket1Address, null);
   1062             fail("Should throw a NPE here.");
   1063         } catch (NullPointerException e) {
   1064             // correct
   1065         }
   1066     }
   1067 
   1068     public void testSend_NoServerBufNullTwice() throws IOException {
   1069         ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1070         try {
   1071             sendDataBlocking(datagramSocket1Address, null);
   1072             fail("Should throw a NPE here.");
   1073         } catch (NullPointerException e) {
   1074             // correct
   1075         }
   1076         sendDataBlocking(datagramSocket1Address, writeBuf);
   1077         try {
   1078             channel1.send(null, datagramSocket2Address);
   1079             fail("Should throw NPE");
   1080         } catch (NullPointerException e) {
   1081             // correct
   1082         }
   1083     }
   1084 
   1085     public void testSend_NoServerAddrNull() throws IOException {
   1086         ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1087         try {
   1088             sendDataBlocking(null, writeBuf);
   1089             fail("Should throw a NPE here.");
   1090         } catch (NullPointerException e) {
   1091             // correct
   1092         }
   1093     }
   1094 
   1095     public void testSend_NoServerAddrNullTwice() throws IOException {
   1096         ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1097         try {
   1098             sendDataBlocking(null, writeBuf);
   1099             fail("Should throw a NPE here.");
   1100         } catch (NullPointerException e) {
   1101             // correct
   1102         }
   1103         sendDataBlocking(datagramSocket1Address, writeBuf);
   1104         try {
   1105             channel1.send(writeBuf, null);
   1106             fail("Should throw NPE");
   1107         } catch (NullPointerException e) {
   1108             // correct
   1109         }
   1110     }
   1111 
   1112     // -------------------------------------------------------------------
   1113     // Test for receive()and send(): Send and Receive with Real Data
   1114     // -------------------------------------------------------------------
   1115 
   1116     public void testReceiveSend_Block_Normal() throws Exception {
   1117         sendOnChannel2("some normal string in testReceiveSend_Normal",
   1118                 channel1Address);
   1119         receiveOnChannel1AndClose(CAPACITY_NORMAL, channel2Address,
   1120                 "some normal string in testReceiveSend_Normal");
   1121     }
   1122 
   1123     public void testReceiveSend_NonBlock_NotBound() throws Exception {
   1124         // not bound
   1125         this.channel1.configureBlocking(false);
   1126         this.channel2.configureBlocking(false);
   1127         sendOnChannel2("some normal string in testReceiveSend_Normal",
   1128                 datagramSocket2Address);
   1129         ByteBuffer buf = ByteBuffer.wrap(new byte[CAPACITY_NORMAL]);
   1130         assertNull(this.channel1.receive(buf));
   1131     }
   1132 
   1133     public void testReceiveSend_Block_Normal_S2C() throws Exception {
   1134         sendOnDatagramSocket1(
   1135                 "some normal string in testReceiveSend_Normal_S2C", channel1Address);
   1136         receiveOnChannel1AndClose(CAPACITY_NORMAL, datagramSocket1Address,
   1137                 "some normal string in testReceiveSend_Normal_S2C");
   1138     }
   1139 
   1140     public void testReceiveSend_Block_Normal_C2S() throws Exception {
   1141         String str1 = "some normal string in testReceiveSend_Normal_C2S";
   1142         sendOnChannel2(str1, datagramSocket1Address);
   1143         receiveOnDatagramSocket1(CAPACITY_NORMAL, str1);
   1144     }
   1145 
   1146     public void testReceiveSend_NonBlock_Normal_C2S() throws Exception {
   1147         this.channel1.configureBlocking(false);
   1148         this.channel2.configureBlocking(false);
   1149         String str1 = "some normal string in testReceiveSend_Normal_C2S";
   1150         sendOnChannel2(str1, datagramSocket1Address);
   1151         receiveOnDatagramSocket1(CAPACITY_NORMAL, str1);
   1152     }
   1153 
   1154     public void testReceiveSend_Normal_S2S() throws Exception {
   1155         String msg = "normal string in testReceiveSend_Normal_S2S";
   1156         DatagramPacket rdp = new DatagramPacket(msg.getBytes(), msg.length(),
   1157                 datagramSocket2Address);
   1158         this.datagramSocket1.send(rdp);
   1159         byte[] buf = new byte[CAPACITY_NORMAL];
   1160         this.datagramSocket2.setSoTimeout(TIME_UNIT);
   1161         rdp = new DatagramPacket(buf, buf.length);
   1162         this.datagramSocket2.receive(rdp);
   1163         assertEquals(new String(buf, 0, CAPACITY_NORMAL).trim(), msg);
   1164     }
   1165 
   1166     public void testReceiveSend_Block_Empty() throws Exception {
   1167         sendOnChannel2("", channel1Address);
   1168         receiveOnChannel1AndClose(CAPACITY_NORMAL, channel2Address, "");
   1169     }
   1170 
   1171     public void testReceiveSend_NonBlock_Empty() throws Exception {
   1172         this.channel1.configureBlocking(false);
   1173         this.channel2.configureBlocking(false);
   1174         sendOnChannel2("", channel1Address);
   1175         receiveOnChannel1AndClose(CAPACITY_NORMAL, channel2Address, "");
   1176     }
   1177 
   1178     public void testReceiveSend_Block_Empty_S2C() throws Exception {
   1179         sendOnDatagramSocket1("", channel1Address);
   1180         receiveOnChannel1AndClose(CAPACITY_NORMAL, datagramSocket1Address, "");
   1181     }
   1182 
   1183     public void testReceiveSend_NonBlock_Empty_S2C() throws Exception {
   1184         this.channel1.configureBlocking(false);
   1185         this.channel2.configureBlocking(false);
   1186         sendOnDatagramSocket1("", channel1Address);
   1187         receiveOnChannel1AndClose(CAPACITY_NORMAL, datagramSocket1Address, "");
   1188     }
   1189 
   1190     public void testReceiveSend_Block_Empty_C2S() throws Exception {
   1191         sendOnChannel2("", datagramSocket1Address);
   1192         receiveOnDatagramSocket1(CAPACITY_NORMAL, "");
   1193     }
   1194 
   1195     public void testReceiveSend_NonBlock_Empty_C2S() throws Exception {
   1196         this.channel1.configureBlocking(false);
   1197         this.channel2.configureBlocking(false);
   1198         sendOnChannel2("", datagramSocket1Address);
   1199         receiveOnDatagramSocket1(CAPACITY_NORMAL, "");
   1200     }
   1201 
   1202     public void testReceiveSend_Empty_S2S() throws Exception {
   1203         String msg = "";
   1204         DatagramPacket rdp = new DatagramPacket(msg.getBytes(), msg.length(),
   1205                 datagramSocket2Address);
   1206         this.datagramSocket1.send(rdp);
   1207         byte[] buf = new byte[CAPACITY_NORMAL];
   1208         this.datagramSocket2.setSoTimeout(TIME_UNIT);
   1209         rdp = new DatagramPacket(buf, buf.length);
   1210         this.datagramSocket2.receive(rdp);
   1211         assertEquals(new String(buf, 0, CAPACITY_NORMAL).trim(), msg);
   1212     }
   1213 
   1214     public void testReceiveSend_Block_Oversize() throws Exception {
   1215         sendOnChannel2("0123456789", channel1Address);
   1216         receiveOnChannel1AndClose(5, channel2Address, "01234");
   1217     }
   1218 
   1219     public void testReceiveSend_Block_Oversize_C2S() throws Exception {
   1220         sendOnChannel2("0123456789", datagramSocket1Address);
   1221         receiveOnDatagramSocket1(5, "01234");
   1222     }
   1223 
   1224     public void testReceiveSend_NonBlock_Oversize_C2S() throws Exception {
   1225         this.channel1.configureBlocking(false);
   1226         this.channel2.configureBlocking(false);
   1227         sendOnChannel2("0123456789", datagramSocket1Address);
   1228         receiveOnDatagramSocket1(5, "01234");
   1229     }
   1230 
   1231     public void testReceiveSend_Block_Oversize_S2C() throws Exception {
   1232         sendOnDatagramSocket1("0123456789", channel1Address);
   1233         receiveOnChannel1AndClose(5, datagramSocket1Address, "01234");
   1234     }
   1235 
   1236     public void testReceiveSend_8K() throws Exception {
   1237         StringBuffer str8k = new StringBuffer();
   1238         for (int i = 0; i < 8 * CAPACITY_1KB; i++) {
   1239             str8k.append('a');
   1240         }
   1241         String str = str8k.toString();
   1242 
   1243         sendOnChannel2(str, channel1Address);
   1244         receiveOnChannel1AndClose(8 * CAPACITY_1KB, channel2Address, str);
   1245     }
   1246 
   1247     public void testReceiveSend_64K() throws Exception {
   1248         StringBuffer str64k = new StringBuffer();
   1249         for (int i = 0; i < CAPACITY_64KB; i++) {
   1250             str64k.append('a');
   1251         }
   1252         String str = str64k.toString();
   1253         try {
   1254             Thread.sleep(TIME_UNIT);
   1255             channel2.send(ByteBuffer.wrap(str.getBytes()), datagramSocket1Address);
   1256             fail("Should throw SocketException!");
   1257         } catch (SocketException expected) {
   1258         }
   1259     }
   1260 
   1261     private void sendOnChannel2(String data, SocketAddress address)
   1262             throws IOException {
   1263         assertEquals(data.length(), channel2.send(ByteBuffer.wrap(data.getBytes()), address));
   1264     }
   1265 
   1266     private void sendOnDatagramSocket1(String data, InetSocketAddress address)
   1267             throws Exception {
   1268         DatagramPacket rdp = new DatagramPacket(data.getBytes(), data.length(), address);
   1269         this.datagramSocket1.send(rdp);
   1270     }
   1271 
   1272     private void receiveOnChannel1AndClose(int bufSize,
   1273             InetSocketAddress expectedAddress, String expectedString) throws IOException {
   1274         try {
   1275             ByteBuffer buf = ByteBuffer.wrap(new byte[bufSize]);
   1276             InetSocketAddress senderAddr;
   1277             long startTime = System.currentTimeMillis();
   1278             do {
   1279                 senderAddr = (InetSocketAddress) this.channel1.receive(buf);
   1280                 // continue loop when channel1 is non-blocking and no data was
   1281                 // received.
   1282                 if (channel1.isBlocking() || senderAddr != null) {
   1283                     break;
   1284                 }
   1285                 // avoid dead loop
   1286                 assertTimeout(startTime, 10000);
   1287             } while (true);
   1288 
   1289             assertEquals(senderAddr.getAddress(), Inet6Address.LOOPBACK);
   1290             assertEquals(expectedAddress.getPort(), senderAddr.getPort());
   1291             assertEquals(new String(buf.array(), 0, buf.position()), expectedString);
   1292         } finally {
   1293             this.channel1.close();
   1294         }
   1295     }
   1296 
   1297     /*
   1298      * Fails if the difference between current time and start time is greater
   1299      * than timeout.
   1300      */
   1301     private void assertTimeout(long startTime, long timeout) {
   1302         long currentTime = System.currentTimeMillis();
   1303         if ((currentTime - startTime) > timeout) {
   1304             fail("Timeout");
   1305         }
   1306     }
   1307 
   1308     private void receiveOnDatagramSocket1(int bufSize, String expectedString)
   1309             throws IOException {
   1310         byte[] buf = new byte[bufSize];
   1311         this.datagramSocket1.setSoTimeout(6000);
   1312         DatagramPacket rdp = new DatagramPacket(buf, buf.length);
   1313         this.datagramSocket1.receive(rdp);
   1314         assertEquals(new String(buf, 0, bufSize).trim(), expectedString);
   1315     }
   1316 
   1317     public void testRead_fromSend() throws Exception {
   1318         ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
   1319         String strHello = "hello";
   1320 
   1321         this.channel1.connect(channel2Address);
   1322         this.channel2.send(ByteBuffer.wrap(strHello.getBytes()), channel1Address);
   1323 
   1324         assertEquals(strHello.length(), this.channel1.read(buf));
   1325         assertAscii(buf, strHello);
   1326     }
   1327 
   1328     public void testReceive_Peek_NoSecurity_Nonblocking() throws Exception {
   1329         String strHello = "hello";
   1330 
   1331         sendOnChannel2(strHello, channel1Address);
   1332         this.channel1.configureBlocking(false);
   1333         // for accepted addr, no problem.
   1334         ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
   1335 
   1336         InetSocketAddress source = (InetSocketAddress) this.channel1.receive(buf);
   1337         assertEquals(channel2Address, source);
   1338         assertAscii(buf, strHello);
   1339     }
   1340 
   1341     private static void assertAscii(ByteBuffer b, String s) {
   1342         assertEquals(s.length(), b.position());
   1343         for (int i = 0; i < s.length(); ++i) {
   1344             assertEquals(s.charAt(i), b.get(i));
   1345         }
   1346     }
   1347 
   1348     // -------------------------------------------------------------------
   1349     // Test for write()
   1350     // -------------------------------------------------------------------
   1351 
   1352     private void connectWriteBuf(InetSocketAddress ipAddr, ByteBuffer buf)
   1353             throws IOException {
   1354         this.channel1.connect(ipAddr);
   1355         assertTrue(this.channel1.isConnected());
   1356         assertEquals(CAPACITY_NORMAL, this.channel1.write(buf));
   1357         assertEquals(0, this.channel1.write(buf));
   1358     }
   1359 
   1360     private void noconnectWrite(ByteBuffer buf) throws IOException {
   1361         try {
   1362             this.channel1.write(buf);
   1363             fail("should throw NotYetConnectedException");
   1364         } catch (NotYetConnectedException e) {
   1365             // correct
   1366         }
   1367     }
   1368 
   1369     /*
   1370      * Test method for 'DatagramChannelImpl.write(ByteBuffer)'
   1371      */
   1372     public void testWriteByteBuffer_Block() throws IOException {
   1373         ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1374         connectWriteBuf(datagramSocket1Address, writeBuf);
   1375     }
   1376 
   1377     public void testWriteByteBuffer_NonBlock() throws IOException {
   1378         ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1379         this.channel1.configureBlocking(false);
   1380         connectWriteBuf(datagramSocket1Address, writeBuf);
   1381     }
   1382 
   1383     public void testWriteByteBuffer_Block_closed() throws IOException {
   1384         ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1385         InetSocketAddress ipAddr = datagramSocket1Address;
   1386         noconnectWrite(writeBuf);
   1387         this.channel1.connect(ipAddr);
   1388         assertTrue(this.channel1.isConnected());
   1389         this.channel1.close();
   1390         try {
   1391             channel1.write(writeBuf);
   1392             fail("should throw ClosedChannelException");
   1393         } catch (ClosedChannelException e) {
   1394             // correct
   1395         }
   1396     }
   1397 
   1398     public void testWriteByteBuffer_NonBlock_closed() throws IOException {
   1399         ByteBuffer writeBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1400         InetSocketAddress ipAddr = datagramSocket1Address;
   1401         // non block mode
   1402         this.channel1.configureBlocking(false);
   1403         noconnectWrite(writeBuf);
   1404         this.channel1.connect(ipAddr);
   1405         assertTrue(this.channel1.isConnected());
   1406         this.channel1.close();
   1407         try {
   1408             channel1.write(writeBuf);
   1409             fail("should throw ClosedChannelException");
   1410         } catch (ClosedChannelException e) {
   1411             // correct
   1412         }
   1413     }
   1414 
   1415     public void testWriteByteBuffer_Block_BufNull() throws IOException {
   1416         ByteBuffer writeBuf = ByteBuffer.allocateDirect(0);
   1417         InetSocketAddress ipAddr = datagramSocket1Address;
   1418         try {
   1419             this.channel1.write((ByteBuffer) null);
   1420             fail("Should throw NPE.");
   1421         } catch (NullPointerException e) {
   1422             // correct
   1423         }
   1424         this.channel1.connect(ipAddr);
   1425         assertTrue(this.channel1.isConnected());
   1426         try {
   1427             this.channel1.write((ByteBuffer) null);
   1428             fail("Should throw NPE.");
   1429         } catch (NullPointerException e) {
   1430             // correct
   1431         }
   1432         assertEquals(0, this.channel1.write(writeBuf));
   1433         datagramSocket1.close();
   1434         try {
   1435             this.channel1.write((ByteBuffer) null);
   1436             fail("Should throw NPE.");
   1437         } catch (NullPointerException e) {
   1438             // correct
   1439         }
   1440     }
   1441 
   1442     public void testWriteByteBuffer_NonBlock_BufNull() throws IOException {
   1443         ByteBuffer writeBuf = ByteBuffer.allocateDirect(0);
   1444         InetSocketAddress ipAddr = datagramSocket1Address;
   1445 
   1446         // non block mode
   1447         this.channel1.configureBlocking(false);
   1448 
   1449         try {
   1450             this.channel1.write((ByteBuffer) null);
   1451             fail("Should throw NPE.");
   1452         } catch (NullPointerException e) {
   1453             // correct
   1454         }
   1455         this.channel1.connect(ipAddr);
   1456         assertTrue(this.channel1.isConnected());
   1457         try {
   1458             this.channel1.write((ByteBuffer) null);
   1459             fail("Should throw NPE.");
   1460         } catch (NullPointerException e) {
   1461             // correct
   1462         }
   1463         assertEquals(0, this.channel1.write(writeBuf));
   1464         datagramSocket1.close();
   1465         try {
   1466             this.channel1.write((ByteBuffer) null);
   1467             fail("Should throw NPE.");
   1468         } catch (NullPointerException e) {
   1469             // correct
   1470         }
   1471     }
   1472 
   1473     /*
   1474      * Test method for 'DatagramChannelImpl.write(ByteBuffer[], int, int)'
   1475      */
   1476     public void testWriteByteBufferArrayIntInt_Block() throws IOException {
   1477         ByteBuffer[] writeBuf = new ByteBuffer[2];
   1478         writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1479         writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1480         InetSocketAddress ipAddr = datagramSocket1Address;
   1481         try {
   1482             this.channel1.write(writeBuf, 0, 2);
   1483             fail("Should throw NotYetConnectedException.");
   1484         } catch (NotYetConnectedException e) {
   1485             // correct
   1486         }
   1487         this.channel1.connect(ipAddr);
   1488         assertTrue(this.channel1.isConnected());
   1489         assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2));
   1490         // cannot be buffered again!
   1491         assertEquals(0, this.channel1.write(writeBuf, 0, 1));
   1492 
   1493     }
   1494 
   1495     public void testWriteByteBufferArrayIntInt_NonBlock() throws IOException {
   1496         ByteBuffer[] writeBuf = new ByteBuffer[2];
   1497         writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1498         writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1499         InetSocketAddress ipAddr = datagramSocket1Address;
   1500         // non-block mode
   1501         this.channel1.configureBlocking(false);
   1502         try {
   1503             this.channel1.write(writeBuf, 0, 2);
   1504             fail("Should throw NotYetConnectedException.");
   1505         } catch (NotYetConnectedException e) {
   1506             // correct
   1507         }
   1508         this.channel1.connect(ipAddr);
   1509         assertTrue(this.channel1.isConnected());
   1510         assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2));
   1511         // cannot be buffered again!
   1512         assertEquals(0, this.channel1.write(writeBuf, 0, 1));
   1513 
   1514     }
   1515 
   1516     public void testWriteByteBufferArrayIntInt_NoConnectIndexBad()
   1517             throws IOException {
   1518         ByteBuffer[] writeBuf = new ByteBuffer[2];
   1519         writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1520         writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1521         InetSocketAddress ipAddr = datagramSocket1Address;
   1522         try {
   1523             this.channel1.write(writeBuf, -1, 2);
   1524             fail("should throw IndexOutOfBoundsException");
   1525         } catch (IndexOutOfBoundsException e) {
   1526             // correct
   1527         }
   1528         try {
   1529             this.channel1.write(writeBuf, 0, -1);
   1530             fail("should throw IndexOutOfBoundsException");
   1531         } catch (IndexOutOfBoundsException e) {
   1532             // correct
   1533         }
   1534         this.channel1.connect(ipAddr);
   1535         assertTrue(this.channel1.isConnected());
   1536         assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2));
   1537         // cannot be buffered again!
   1538         assertEquals(0, this.channel1.write(writeBuf, 0, 1));
   1539     }
   1540 
   1541     public void testWriteByteBufferArrayIntInt_ConnectedIndexBad()
   1542             throws IOException {
   1543         ByteBuffer[] writeBuf = new ByteBuffer[2];
   1544         writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1545         writeBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1546         InetSocketAddress ipAddr = datagramSocket1Address;
   1547         this.channel1.connect(ipAddr);
   1548         assertTrue(this.channel1.isConnected());
   1549         try {
   1550             this.channel1.write(writeBuf, -1, 2);
   1551             fail("should throw IndexOutOfBoundsException");
   1552         } catch (IndexOutOfBoundsException e) {
   1553             // correct
   1554         }
   1555         try {
   1556             this.channel1.write(writeBuf, 0, -1);
   1557             fail("should throw IndexOutOfBoundsException");
   1558         } catch (IndexOutOfBoundsException e) {
   1559             // correct
   1560         }
   1561     }
   1562 
   1563     public void testWriteByteBufferArrayIntInt_BufNullNoConnect()
   1564             throws IOException {
   1565         ByteBuffer[] writeBuf = new ByteBuffer[2];
   1566         writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1567         try {
   1568             this.channel1.write(null, 0, 2);
   1569             fail();
   1570         } catch (NullPointerException expected) {
   1571         }
   1572         try {
   1573             this.channel1.write(writeBuf, -1, 2);
   1574             fail();
   1575         } catch (IndexOutOfBoundsException expected) {
   1576         }
   1577         try {
   1578             this.channel1.write(writeBuf, 0, 3);
   1579             fail();
   1580         } catch (IndexOutOfBoundsException expected) {
   1581         }
   1582     }
   1583 
   1584     public void testWriteByteBufferArrayIntInt_BufNullConnect()
   1585             throws IOException {
   1586         ByteBuffer[] writeBuf = new ByteBuffer[2];
   1587         writeBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1588         InetSocketAddress ipAddr = datagramSocket1Address;
   1589         this.channel1.connect(ipAddr);
   1590         assertTrue(this.channel1.isConnected());
   1591         try {
   1592             this.channel1.write(null, 0, 2);
   1593             fail("should throw NPE");
   1594         } catch (NullPointerException e) {
   1595             // correct
   1596         }
   1597         try {
   1598             this.channel1.write(writeBuf, 0, 3);
   1599             fail("should throw IndexOutOfBoundsException");
   1600         } catch (IndexOutOfBoundsException e) {
   1601             // correct
   1602         }
   1603         datagramSocket1.close();
   1604         try {
   1605             this.channel1.write(null, 0, 2);
   1606             fail("should throw NPE");
   1607         } catch (NullPointerException e) {
   1608             // correct
   1609         }
   1610     }
   1611 
   1612     // -------------------------------------------------------------------
   1613     // Test for read()
   1614     // -------------------------------------------------------------------
   1615 
   1616     /*
   1617      * Test method for 'DatagramChannelImpl.read(ByteBuffer)'
   1618      */
   1619     public void testReadByteBuffer() throws IOException {
   1620         ByteBuffer readBuf = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1621         try {
   1622             this.channel1.read(readBuf);
   1623             fail("should throw NotYetConnectedException");
   1624         } catch (NotYetConnectedException e) {
   1625             // correct
   1626         }
   1627         this.channel1.connect(datagramSocket1Address);
   1628         assertTrue(this.channel1.isConnected());
   1629         this.channel1.configureBlocking(false);
   1630         // note : blocking-mode will make the read process endless!
   1631         assertEquals(0, this.channel1.read(readBuf));
   1632         this.channel1.close();
   1633         try {
   1634             this.channel1.read(readBuf);
   1635             fail("Should throw ClosedChannelException");
   1636         } catch (ClosedChannelException e) {
   1637             // OK.
   1638         }
   1639     }
   1640 
   1641     public void testReadByteBuffer_bufNull() throws IOException {
   1642         ByteBuffer readBuf = ByteBuffer.allocateDirect(0);
   1643         InetSocketAddress ipAddr = datagramSocket1Address;
   1644         try {
   1645             this.channel1.read(readBuf);
   1646             fail("should throw NotYetConnectedException");
   1647         } catch (NotYetConnectedException e) {
   1648             // correct
   1649         }
   1650         this.channel1.connect(ipAddr);
   1651         assertTrue(this.channel1.isConnected());
   1652         try {
   1653             channel1.read((ByteBuffer) null);
   1654             fail("should throw NPE");
   1655         } catch (NullPointerException e) {
   1656             // correct
   1657         }
   1658         this.channel1.configureBlocking(false);
   1659         // note : blocking-mode will make the read process endless!
   1660         assertEquals(0, this.channel1.read(readBuf));
   1661         datagramSocket1.close();
   1662     }
   1663 
   1664     /*
   1665      * Test method for 'DatagramChannelImpl.read(ByteBuffer[], int, int)'
   1666      */
   1667     public void testReadByteBufferArrayIntInt() throws IOException {
   1668         ByteBuffer[] readBuf = new ByteBuffer[2];
   1669         readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1670         readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1671         InetSocketAddress ipAddr = datagramSocket1Address;
   1672         try {
   1673             this.channel1.read(readBuf, 0, 2);
   1674             fail("should throw NotYetConnectedException");
   1675         } catch (NotYetConnectedException e) {
   1676             // correct
   1677         }
   1678         this.channel1.connect(ipAddr);
   1679         assertTrue(this.channel1.isConnected());
   1680         this.channel1.configureBlocking(false);
   1681         // note : blocking-mode will make the read process endless!
   1682         assertEquals(0, this.channel1.read(readBuf, 0, 1));
   1683         assertEquals(0, this.channel1.read(readBuf, 0, 2));
   1684         datagramSocket1.close();
   1685     }
   1686 
   1687     public void testReadByteBufferArrayIntInt_exceptions() throws IOException {
   1688         //regression test for HARMONY-932
   1689         try {
   1690             DatagramChannel.open().read(new ByteBuffer[] {}, 2, Integer.MAX_VALUE);
   1691             fail();
   1692         } catch (IndexOutOfBoundsException expected) {
   1693         }
   1694         try {
   1695             DatagramChannel.open().read(new ByteBuffer[] {}, -1, 0);
   1696             fail();
   1697         } catch (IndexOutOfBoundsException expected) {
   1698         }
   1699         try {
   1700             DatagramChannel.open().read((ByteBuffer[]) null, 0, 0);
   1701             fail();
   1702         } catch (NullPointerException expected) {
   1703         }
   1704     }
   1705 
   1706     public void testReadByteBufferArrayIntInt_BufNull() throws IOException {
   1707         ByteBuffer[] readBuf = new ByteBuffer[2];
   1708         readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   1709         InetSocketAddress ipAddr = datagramSocket1Address;
   1710         try {
   1711             this.channel1.read(null, 0, 0);
   1712             fail("should throw NPE");
   1713         } catch (NullPointerException e) {
   1714             // correct
   1715         }
   1716         this.channel1.connect(ipAddr);
   1717         assertTrue(this.channel1.isConnected());
   1718         this.channel1.configureBlocking(false);
   1719         // note : blocking-mode will make the read process endless!
   1720         try {
   1721             this.channel1.read(null, 0, 0);
   1722             fail("should throw NPE");
   1723         } catch (NullPointerException e) {
   1724             // correct
   1725         }
   1726         assertEquals(0, this.channel1.read(readBuf, 0, 1));
   1727         try {
   1728             this.channel1.read(readBuf, 0, 2);
   1729             fail("should throw NPE");
   1730         } catch (NullPointerException e) {
   1731             // correct
   1732         }
   1733         try {
   1734             this.channel1.read(readBuf, 0, 3);
   1735             fail("should throw IndexOutOfBoundsException");
   1736         } catch (IndexOutOfBoundsException e) {
   1737             // correct
   1738         }
   1739         datagramSocket1.close();
   1740     }
   1741 
   1742     // -------------------------------------------------------------------
   1743     // test read and write
   1744     // -------------------------------------------------------------------
   1745 
   1746     public static class A {
   1747         protected int z;
   1748     }
   1749 
   1750     public static class B extends A {
   1751         protected int z;
   1752 
   1753         void foo() {
   1754             super.z+=1;
   1755         }
   1756     }
   1757 
   1758 
   1759     public void testReadWrite_asyncClose() throws Exception {
   1760         byte[] targetArray = new byte[2];
   1761         ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
   1762 
   1763         channel2.connect(channel1Address);
   1764         channel1.connect(channel2Address);
   1765 
   1766         new Thread() {
   1767             public void run() {
   1768                 try {
   1769                     Thread.sleep(TIME_UNIT);
   1770                     channel1.close();
   1771                 } catch (Exception e) {
   1772                     //ignore
   1773                 }
   1774             }
   1775         }.start();
   1776 
   1777         try {
   1778             this.channel1.read(targetBuf);
   1779             fail("should throw AsynchronousCloseException");
   1780         } catch (AsynchronousCloseException e) {
   1781             // ok
   1782         }
   1783     }
   1784 
   1785     public void testReadWrite_Block_Zero() throws Exception {
   1786         byte[] sourceArray = new byte[0];
   1787         byte[] targetArray = new byte[0];
   1788 
   1789         channel1.connect(channel2Address);
   1790         channel2.connect(channel1Address);
   1791 
   1792         // write
   1793         ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   1794         assertEquals(0, this.channel1.write(sourceBuf));
   1795 
   1796         // read
   1797         ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
   1798         int readCount = this.channel2.read(targetBuf);
   1799 
   1800         assertEquals(0, readCount);
   1801     }
   1802 
   1803     public void testReadWrite_Block_Normal() throws Exception {
   1804         byte[] sourceArray = new byte[CAPACITY_NORMAL];
   1805         byte[] targetArray = new byte[CAPACITY_NORMAL];
   1806         for (int i = 0; i < sourceArray.length; i++) {
   1807             sourceArray[i] = (byte) i;
   1808         }
   1809 
   1810         channel1.connect(channel2Address);
   1811         channel2.connect(channel1Address);
   1812 
   1813         readWriteReadData(this.channel1, sourceArray, this.channel2,
   1814                 targetArray, CAPACITY_NORMAL, "testReadWrite_Block_Normal");
   1815     }
   1816 
   1817     public void testReadWrite_Block_Empty() throws Exception {
   1818         // empty buf
   1819         byte[] sourceArray = "".getBytes();
   1820         byte[] targetArray = new byte[CAPACITY_NORMAL];
   1821 
   1822         channel1.connect(channel2Address);
   1823         channel2.connect(channel1Address);
   1824 
   1825         // write
   1826         ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   1827         assertEquals(0, this.channel1.write(sourceBuf));
   1828 
   1829         // read
   1830         ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
   1831         // empty message let the reader blocked
   1832         closeBlockedReaderChannel2(targetBuf);
   1833     }
   1834 
   1835     public void testReadWrite_changeBlock_Empty() throws Exception {
   1836         // empty buf
   1837         byte[] sourceArray = "".getBytes();
   1838         byte[] targetArray = new byte[CAPACITY_NORMAL];
   1839 
   1840         channel1.connect(channel2Address);
   1841         channel2.connect(channel1Address);
   1842 
   1843         // write
   1844         ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   1845         assertEquals(0, this.channel1.write(sourceBuf));
   1846 
   1847         // read
   1848         ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
   1849         // empty message let the reader blocked
   1850         new Thread() {
   1851             public void run() {
   1852                 try {
   1853                     Thread.sleep(TIME_UNIT);
   1854                     channel2.configureBlocking(false);
   1855                     Thread.sleep(TIME_UNIT * 5);
   1856                     channel2.close();
   1857                 } catch (Exception e) {
   1858                     // do nothing
   1859                 }
   1860             }
   1861         }.start();
   1862         try {
   1863             assertTrue(this.channel2.isBlocking());
   1864             this.channel2.read(targetBuf);
   1865             fail("Should throw AsynchronousCloseException");
   1866         } catch (AsynchronousCloseException e) {
   1867             assertFalse(this.channel2.isBlocking());
   1868             // OK.
   1869         }
   1870     }
   1871 
   1872     public void testReadWrite_Block_8KB() throws Exception {
   1873         byte[] sourceArray = new byte[CAPACITY_1KB * 8];
   1874         byte[] targetArray = new byte[CAPACITY_1KB * 8];
   1875         for (int i = 0; i < sourceArray.length; i++) {
   1876             sourceArray[i] = (byte) i;
   1877         }
   1878 
   1879         channel1.connect(channel2Address);
   1880         channel2.connect(channel1Address);
   1881 
   1882         readWriteReadData(this.channel1, sourceArray, this.channel2,
   1883                 targetArray, 8 * CAPACITY_1KB, "testReadWrite_Block_8KB");
   1884     }
   1885 
   1886     /*
   1887      * sender write the sourceArray whose size is dataSize, and receiver read
   1888      * the data into targetArray
   1889      */
   1890     private void readWriteReadData(DatagramChannel sender, byte[] sourceArray,
   1891             DatagramChannel receiver, byte[] targetArray, int dataSize,
   1892             String methodName) throws IOException {
   1893         // write
   1894         ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   1895         assertEquals(dataSize, sender.write(sourceBuf));
   1896 
   1897         // read
   1898         ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
   1899 
   1900         int count = 0;
   1901         int total = 0;
   1902         long beginTime = System.currentTimeMillis();
   1903         while (total < dataSize && (count = receiver.read(targetBuf)) != -1) {
   1904             total = total + count;
   1905             // 3s timeout to avoid dead loop
   1906             if (System.currentTimeMillis() - beginTime > 3000){
   1907                 break;
   1908             }
   1909         }
   1910 
   1911         assertEquals(dataSize, total);
   1912         assertEquals(targetBuf.position(), total);
   1913         targetBuf.flip();
   1914         targetArray = targetBuf.array();
   1915         for (int i = 0; i < targetArray.length; i++) {
   1916             assertEquals(targetArray[i], (byte) i);
   1917         }
   1918     }
   1919 
   1920     public void testReadWrite_Block_64K() throws Exception {
   1921         byte[] sourceArray = new byte[CAPACITY_64KB];
   1922         for (int i = 0; i < sourceArray.length; i++) {
   1923             sourceArray[i] = (byte) i;
   1924         }
   1925 
   1926         channel1.connect(channel2Address);
   1927 
   1928         // write
   1929         ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   1930         try {
   1931             channel1.write(sourceBuf);
   1932             fail("Should throw IOException");
   1933         } catch (IOException expected) {
   1934             // too big
   1935         }
   1936     }
   1937 
   1938     public void testReadWrite_Block_DifferentAddr() throws Exception {
   1939         byte[] sourceArray = new byte[CAPACITY_NORMAL];
   1940         byte[] targetArray = new byte[CAPACITY_NORMAL];
   1941         for (int i = 0; i < sourceArray.length; i++) {
   1942             sourceArray[i] = (byte) i;
   1943         }
   1944 
   1945         this.channel1.connect(channel1.socket().getLocalSocketAddress());
   1946         this.channel2.connect(datagramSocket1Address); // the different addr
   1947 
   1948         // write
   1949         ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   1950         assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
   1951 
   1952         // read
   1953         ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
   1954         // the wrong connected addr will make the read blocked.
   1955         // we close the blocked channel
   1956         closeBlockedReaderChannel2(targetBuf);
   1957     }
   1958 
   1959     public void testReadWrite_Block_WriterNotBound() throws Exception {
   1960         byte[] sourceArray = new byte[CAPACITY_NORMAL];
   1961         byte[] targetArray = new byte[CAPACITY_NORMAL];
   1962         for (int i = 0; i < sourceArray.length; i++) {
   1963             sourceArray[i] = (byte) i;
   1964         }
   1965 
   1966         DatagramChannel dc = DatagramChannel.open();
   1967         // The writer isn't bound, but is connected.
   1968         dc.connect(channel1Address);
   1969 
   1970         // write
   1971         ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   1972         assertEquals(CAPACITY_NORMAL, dc.write(sourceBuf));
   1973 
   1974         // Connect channel2 after data has been written.
   1975         channel2.connect(dc.socket().getLocalSocketAddress());
   1976 
   1977         // read
   1978         ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
   1979         closeBlockedReaderChannel2(targetBuf);
   1980 
   1981         dc.close();
   1982     }
   1983 
   1984     // NOTE: The original harmony test tested that things still work
   1985     // if there's no socket bound at the the address we're connecting to.
   1986     //
   1987     // It isn't really feasible to implement that in a non-racy way.
   1988     public void testReadWrite_Block_WriterConnectLater() throws Exception {
   1989 
   1990         byte[] targetArray = new byte[CAPACITY_NORMAL];
   1991 
   1992         // The reader is bound & connected to channel1.
   1993         channel2.connect(channel1Address);
   1994 
   1995         // read
   1996         ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
   1997         new Thread() {
   1998             public void run() {
   1999                 try {
   2000                     Thread.sleep(TIME_UNIT);
   2001                     // bind later
   2002                     byte[] sourceArray = new byte[CAPACITY_NORMAL];
   2003                     for (int i = 0; i < sourceArray.length; i++) {
   2004                         sourceArray[i] = (byte) i;
   2005                     }
   2006 
   2007                     channel1.connect(channel2Address);
   2008                     // write later
   2009                     ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   2010                     assertEquals(CAPACITY_NORMAL, channel1.write(sourceBuf));
   2011                 } catch (Exception e) {
   2012                     // do nothing
   2013                 }
   2014             }
   2015         }.start();
   2016 
   2017         int count = 0;
   2018         int total = 0;
   2019         long beginTime = System.currentTimeMillis();
   2020 
   2021         while (total < CAPACITY_NORMAL && (count = channel2.read(targetBuf)) != -1) {
   2022             total = total + count;
   2023             // 3s timeout to avoid dead loop
   2024             if (System.currentTimeMillis() - beginTime > 3000){
   2025                 break;
   2026             }
   2027         }
   2028 
   2029         assertEquals(CAPACITY_NORMAL, total);
   2030         assertEquals(targetBuf.position(), total);
   2031         targetBuf.flip();
   2032         targetArray = targetBuf.array();
   2033         for (int i = 0; i < targetArray.length; i++) {
   2034             assertEquals(targetArray[i], (byte) i);
   2035         }
   2036     }
   2037 
   2038     // NOTE: The original harmony test tested that things still work
   2039     // if there's no socket bound at the the address we're connecting to.
   2040     //
   2041     // It isn't really feasible to implement that in a non-racy way.
   2042     public void testReadWrite_Block_ReaderNotConnected() throws Exception {
   2043         byte[] sourceArray = new byte[CAPACITY_NORMAL];
   2044         byte[] targetArray = new byte[CAPACITY_NORMAL];
   2045         for (int i = 0; i < sourceArray.length; i++) {
   2046             sourceArray[i] = (byte) i;
   2047         }
   2048 
   2049         // reader channel2 is not connected.
   2050         this.channel1.connect(channel2Address);
   2051 
   2052         // write
   2053         ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   2054         assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
   2055 
   2056         // read
   2057         ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
   2058         try {
   2059             this.channel2.read(targetBuf);
   2060             fail();
   2061         } catch (NotYetConnectedException expected) {
   2062         }
   2063     }
   2064 
   2065     private void closeBlockedReaderChannel2(ByteBuffer targetBuf)
   2066             throws IOException {
   2067         assertTrue(this.channel2.isBlocking());
   2068 
   2069         new Thread() {
   2070             public void run() {
   2071                 try {
   2072                     Thread.sleep(TIME_UNIT);
   2073                 } catch (InterruptedException ie) {
   2074                     fail();
   2075                 }
   2076                 IoUtils.closeQuietly(channel2);
   2077             }
   2078         }.start();
   2079 
   2080         try {
   2081             this.channel2.read(targetBuf);
   2082             fail("Should throw AsynchronousCloseException");
   2083         } catch (AsynchronousCloseException e) {
   2084             // OK.
   2085         }
   2086     }
   2087 
   2088     // -------------------------------------------------------------------
   2089     // Test read and write in non-block mode.
   2090     // -------------------------------------------------------------------
   2091     public void testReadWrite_NonBlock_Normal() throws Exception {
   2092         byte[] sourceArray = new byte[CAPACITY_NORMAL];
   2093         byte[] targetArray = new byte[CAPACITY_NORMAL];
   2094         for (int i = 0; i < sourceArray.length; i++) {
   2095             sourceArray[i] = (byte) i;
   2096         }
   2097 
   2098         this.channel1.configureBlocking(false);
   2099         this.channel2.configureBlocking(false);
   2100 
   2101         channel1.connect(channel2Address);
   2102         channel2.connect(channel1Address);
   2103 
   2104         readWriteReadData(this.channel1, sourceArray, this.channel2,
   2105                 targetArray, CAPACITY_NORMAL, "testReadWrite_NonBlock_Normal");
   2106     }
   2107 
   2108     public void testReadWrite_NonBlock_8KB() throws Exception {
   2109         byte[] sourceArray = new byte[CAPACITY_1KB * 8];
   2110         byte[] targetArray = new byte[CAPACITY_1KB * 8];
   2111         for (int i = 0; i < sourceArray.length; i++) {
   2112             sourceArray[i] = (byte) i;
   2113         }
   2114 
   2115         this.channel1.configureBlocking(false);
   2116         this.channel2.configureBlocking(false);
   2117 
   2118         // bind and connect
   2119         channel1.connect(channel2Address);
   2120         channel2.connect(channel1Address);
   2121 
   2122         readWriteReadData(this.channel1, sourceArray, this.channel2,
   2123                 targetArray, 8 * CAPACITY_1KB, "testReadWrite_NonBlock_8KB");
   2124     }
   2125 
   2126     public void testReadWrite_NonBlock_DifferentAddr() throws Exception {
   2127         byte[] sourceArray = new byte[CAPACITY_NORMAL];
   2128         byte[] targetArray = new byte[CAPACITY_NORMAL];
   2129         for (int i = 0; i < sourceArray.length; i++) {
   2130             sourceArray[i] = (byte) i;
   2131         }
   2132 
   2133         this.channel1.configureBlocking(false);
   2134         this.channel2.configureBlocking(false);
   2135 
   2136         channel1.connect(channel2Address);
   2137         channel2.connect(datagramSocket1Address);// the different addr
   2138 
   2139         // write
   2140         ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   2141         assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
   2142 
   2143         // read
   2144         ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
   2145         assertEquals(0, this.channel2.read(targetBuf));
   2146     }
   2147 
   2148 
   2149     public void testReadWrite_NonBlock_WriterNotBound() throws Exception {
   2150         byte[] sourceArray = new byte[CAPACITY_NORMAL];
   2151         byte[] targetArray = new byte[CAPACITY_NORMAL];
   2152         for (int i = 0; i < sourceArray.length; i++) {
   2153             sourceArray[i] = (byte) i;
   2154         }
   2155 
   2156         DatagramChannel dc = DatagramChannel.open();
   2157         // The writer isn't bound, but is connected.
   2158         dc.connect(channel1Address);
   2159         dc.configureBlocking(false);
   2160         channel2.configureBlocking(false);
   2161 
   2162         // write
   2163         ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   2164         assertEquals(CAPACITY_NORMAL, dc.write(sourceBuf));
   2165 
   2166         // Connect channel2 after data has been written.
   2167         channel2.connect(dc.socket().getLocalSocketAddress());
   2168 
   2169         // read
   2170         ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
   2171         assertEquals(0, this.channel2.read(targetBuf));
   2172 
   2173         dc.close();
   2174     }
   2175 
   2176     // NOTE: The original harmony test tested that things still work
   2177     // if there's no socket bound at the the address we're connecting to.
   2178     //
   2179     // It isn't really feasible to implement that in a non-racy way.
   2180     public void testReadWrite_NonBlock_ReaderNotConnected() throws Exception {
   2181         byte[] sourceArray = new byte[CAPACITY_NORMAL];
   2182         byte[] targetArray = new byte[CAPACITY_NORMAL];
   2183         for (int i = 0; i < sourceArray.length; i++) {
   2184             sourceArray[i] = (byte) i;
   2185         }
   2186 
   2187         this.channel1.configureBlocking(false);
   2188         this.channel2.configureBlocking(false);
   2189 
   2190         channel1.connect(channel2Address);
   2191 
   2192         // write
   2193         ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   2194         assertEquals(CAPACITY_NORMAL, this.channel1.write(sourceBuf));
   2195 
   2196         // read
   2197         ByteBuffer targetBuf = ByteBuffer.wrap(targetArray);
   2198 
   2199         try {
   2200             assertEquals(0, this.channel2.read(targetBuf));
   2201             fail();
   2202         } catch (NotYetConnectedException expected) {
   2203         }
   2204     }
   2205 
   2206     public void test_write_LBuffer_positioned() throws Exception {
   2207         // Regression test for Harmony-683
   2208         int position = 16;
   2209         DatagramChannel dc = DatagramChannel.open();
   2210         byte[] sourceArray = new byte[CAPACITY_NORMAL];
   2211         dc.connect(datagramSocket1Address);
   2212         // write
   2213         ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   2214         sourceBuf.position(position);
   2215         assertEquals(CAPACITY_NORMAL - position, dc.write(sourceBuf));
   2216     }
   2217 
   2218     public void test_send_LBuffer_LSocketAddress_PositionNotZero()
   2219             throws Exception {
   2220         // regression test for Harmony-701
   2221         int CAPACITY_NORMAL = 256;
   2222         int position = 16;
   2223         DatagramChannel dc = DatagramChannel.open();
   2224         byte[] sourceArray = new byte[CAPACITY_NORMAL];
   2225         // send ByteBuffer whose position is not zero
   2226         ByteBuffer sourceBuf = ByteBuffer.wrap(sourceArray);
   2227         sourceBuf.position(position);
   2228         int ret = dc.send(sourceBuf, datagramSocket1Address);
   2229         // assert send (256 - 16) bytes
   2230         assertEquals(CAPACITY_NORMAL - position, ret);
   2231         // assert the position of ByteBuffer has been set
   2232         assertEquals(CAPACITY_NORMAL, sourceBuf.position());
   2233     }
   2234 
   2235     /**
   2236      * @tests DatagramChannel#read(ByteBuffer[])
   2237      */
   2238     public void test_read_$LByteBuffer() throws Exception {
   2239         channel1.connect(channel2Address);
   2240         channel2.connect(channel1Address);
   2241 
   2242         // regression test for Harmony-754
   2243         channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL));
   2244 
   2245         ByteBuffer[] readBuf = new ByteBuffer[2];
   2246         readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   2247         readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   2248 
   2249         channel1.configureBlocking(true);
   2250         assertEquals(CAPACITY_NORMAL, channel1.read(readBuf));
   2251     }
   2252 
   2253     /**
   2254      * @tests DatagramChannel#read(ByteBuffer[],int,int)
   2255      */
   2256     public void test_read_$LByteBufferII() throws Exception {
   2257         channel1.connect(channel2Address);
   2258         channel2.connect(channel1Address);
   2259 
   2260         // regression test for Harmony-754
   2261         channel2.write(ByteBuffer.allocate(CAPACITY_NORMAL));
   2262 
   2263         ByteBuffer[] readBuf = new ByteBuffer[2];
   2264         readBuf[0] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   2265         readBuf[1] = ByteBuffer.allocateDirect(CAPACITY_NORMAL);
   2266 
   2267         channel1.configureBlocking(true);
   2268         assertEquals(CAPACITY_NORMAL, channel1.read(readBuf, 0, 2));
   2269     }
   2270 
   2271     /**
   2272      * @tests DatagramChannel#read(ByteBuffer)
   2273      */
   2274     public void test_read_LByteBuffer_closed_nullBuf() throws Exception {
   2275         // regression test for Harmony-754
   2276         ByteBuffer c = null;
   2277         DatagramChannel channel = DatagramChannel.open();
   2278         channel.close();
   2279         try{
   2280             channel.read(c);
   2281             fail("Should throw NullPointerException");
   2282         } catch (NullPointerException e){
   2283             // expected
   2284         }
   2285     }
   2286 
   2287     /**
   2288      * @tests DatagramChannel#read(ByteBuffer)
   2289      */
   2290     public void test_read_LByteBuffer_NotConnected_nullBuf() throws Exception {
   2291         // regression test for Harmony-754
   2292         ByteBuffer c = null;
   2293         DatagramChannel channel = DatagramChannel.open();
   2294         try{
   2295             channel.read(c);
   2296             fail("Should throw NullPointerException");
   2297         } catch (NullPointerException e){
   2298             // expected
   2299         }
   2300     }
   2301 
   2302     /**
   2303      * @tests DatagramChannel#read(ByteBuffer)
   2304      */
   2305     public void test_read_LByteBuffer_readOnlyBuf() throws Exception {
   2306         // regression test for Harmony-754
   2307         ByteBuffer c = ByteBuffer.allocate(1);
   2308         DatagramChannel channel = DatagramChannel.open();
   2309         try{
   2310             channel.read(c.asReadOnlyBuffer());
   2311             fail("Should throw NotYetConnectedException");
   2312         } catch (NotYetConnectedException e){
   2313         } catch (IllegalArgumentException e){
   2314             // expected
   2315         }
   2316         channel.connect(datagramSocket1Address);
   2317         try{
   2318             channel.read(c.asReadOnlyBuffer());
   2319             fail("Should throw IllegalArgumentException");
   2320         } catch (IllegalArgumentException e){
   2321             // expected
   2322         }
   2323     }
   2324 
   2325     /**
   2326      * @tests DatagramChannel#send(ByteBuffer, SocketAddress)
   2327      */
   2328     public void test_send_LByteBuffer_LSocketAddress_closed() throws IOException{
   2329         // regression test for Harmony-913
   2330         channel1.close();
   2331         ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
   2332         try {
   2333             channel1.send(buf, datagramSocket1Address);
   2334             fail("Should throw ClosedChannelException");
   2335         } catch (ClosedChannelException e) {
   2336             //pass
   2337         }
   2338         try {
   2339             channel1.send(null, datagramSocket1Address);
   2340             fail("Should throw NullPointerException");
   2341         } catch (NullPointerException e) {
   2342             //pass
   2343         }
   2344         try {
   2345             channel1.send(buf, null);
   2346             fail("Should throw ClosedChannelException");
   2347         } catch (ClosedChannelException e) {
   2348             //pass
   2349         }
   2350         try {
   2351             channel1.send(null, null);
   2352             fail("Should throw NullPointerException");
   2353         } catch (NullPointerException e) {
   2354             //pass
   2355         }
   2356     }
   2357 
   2358     /**
   2359      * @tests DatagramChannel#socket()
   2360      */
   2361     public void test_socket_IllegalBlockingModeException() throws Exception {
   2362         // regression test for Harmony-1036
   2363         DatagramChannel channel = DatagramChannel.open();
   2364         channel.configureBlocking(false);
   2365         DatagramSocket socket = channel.socket();
   2366         try {
   2367             socket.send(null);
   2368             fail("should throw IllegalBlockingModeException");
   2369         } catch (IllegalBlockingModeException e) {
   2370             // expected
   2371         }
   2372         try {
   2373             socket.receive(null);
   2374             fail("should throw IllegalBlockingModeException");
   2375         } catch (IllegalBlockingModeException e) {
   2376             // expected
   2377         }
   2378 
   2379         channel.close();
   2380     }
   2381 
   2382     public void test_bounded_harmony6493() throws IOException {
   2383         DatagramChannel server = DatagramChannel.open();
   2384         InetSocketAddress addr = new InetSocketAddress("localhost", 0);
   2385         server.socket().bind(addr);
   2386         SocketAddress boundedAddress = server.socket().getLocalSocketAddress();
   2387 
   2388         DatagramChannel client = DatagramChannel.open();
   2389         ByteBuffer sent = ByteBuffer.allocate(1024);
   2390         sent.put("test".getBytes());
   2391         sent.flip();
   2392         client.send(sent, boundedAddress);
   2393         assertTrue(client.socket().isBound());
   2394 
   2395         server.close();
   2396         client.close();
   2397     }
   2398 
   2399     public void test_bind_null() throws Exception {
   2400         DatagramChannel dc = DatagramChannel.open();
   2401         try {
   2402             assertNull(dc.socket().getLocalSocketAddress());
   2403 
   2404             dc.socket().bind(null);
   2405 
   2406             InetSocketAddress localAddress = (InetSocketAddress) dc.socket().getLocalSocketAddress();
   2407             assertTrue(localAddress.getAddress().isAnyLocalAddress());
   2408             assertTrue(localAddress.getPort() > 0);
   2409         } finally {
   2410             dc.close();
   2411         }
   2412     }
   2413 
   2414     public void test_bind_failure() throws Exception {
   2415         DatagramChannel dc = DatagramChannel.open();
   2416         try {
   2417             // Bind to a local address that is in use
   2418             dc.socket().bind(channel1Address);
   2419             fail();
   2420         } catch (IOException expected) {
   2421         } finally {
   2422             dc.close();
   2423         }
   2424     }
   2425 
   2426     public void test_bind_closed() throws Exception {
   2427         DatagramChannel dc = DatagramChannel.open();
   2428         dc.close();
   2429 
   2430         try {
   2431             dc.socket().bind(null);
   2432             fail();
   2433         } catch (IOException expected) {
   2434         } finally {
   2435             dc.close();
   2436         }
   2437     }
   2438 
   2439     public void test_bind_explicitPort() throws Exception {
   2440         InetSocketAddress address = (InetSocketAddress) channel1.socket().getLocalSocketAddress();
   2441         assertTrue(address.getPort() > 0);
   2442 
   2443         DatagramChannel dc = DatagramChannel.open();
   2444         // Allow the socket to bind to a port we know is already in use.
   2445         dc.socket().setReuseAddress(true);
   2446         InetSocketAddress bindAddress = new InetSocketAddress("localhost", address.getPort());
   2447         dc.socket().bind(bindAddress);
   2448 
   2449         InetSocketAddress boundAddress = (InetSocketAddress) dc.socket().getLocalSocketAddress();
   2450         assertEquals(bindAddress.getHostName(), boundAddress.getHostName());
   2451         assertEquals(bindAddress.getPort(), boundAddress.getPort());
   2452 
   2453         dc.close();
   2454         channel1.close();
   2455     }
   2456 
   2457     /** Checks that the SocketChannel and associated Socket agree on the socket state. */
   2458     public void test_bind_socketSync() throws IOException {
   2459         DatagramChannel dc = DatagramChannel.open();
   2460         assertNull(dc.socket().getLocalSocketAddress());
   2461 
   2462         DatagramSocket socket = dc.socket();
   2463         assertNull(socket.getLocalSocketAddress());
   2464         assertFalse(socket.isBound());
   2465 
   2466         InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
   2467         dc.socket().bind(bindAddr);
   2468 
   2469         InetSocketAddress actualAddr = (InetSocketAddress) dc.socket().getLocalSocketAddress();
   2470         assertEquals(actualAddr, socket.getLocalSocketAddress());
   2471         assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
   2472         assertTrue(socket.isBound());
   2473         assertFalse(socket.isConnected());
   2474         assertFalse(socket.isClosed());
   2475 
   2476         dc.close();
   2477 
   2478         assertFalse(dc.isOpen());
   2479         assertTrue(socket.isClosed());
   2480     }
   2481 
   2482     /**
   2483      * Checks that the SocketChannel and associated Socket agree on the socket state, even if
   2484      * the Socket object is requested/created after bind().
   2485      */
   2486     public void test_bind_socketSyncAfterBind() throws IOException {
   2487         DatagramChannel dc = DatagramChannel.open();
   2488         assertNull(dc.socket().getLocalSocketAddress());
   2489 
   2490         InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
   2491         dc.socket().bind(bindAddr);
   2492 
   2493         // Socket creation after bind().
   2494         DatagramSocket socket = dc.socket();
   2495         InetSocketAddress actualAddr = (InetSocketAddress) dc.socket().getLocalSocketAddress();
   2496         assertEquals(actualAddr, socket.getLocalSocketAddress());
   2497         assertEquals(bindAddr.getHostName(), actualAddr.getHostName());
   2498         assertTrue(socket.isBound());
   2499         assertFalse(socket.isConnected());
   2500         assertFalse(socket.isClosed());
   2501 
   2502         dc.close();
   2503 
   2504         assertFalse(dc.isOpen());
   2505         assertTrue(socket.isClosed());
   2506     }
   2507 
   2508     public void test_getLocalSocketAddress_afterClose() throws IOException {
   2509         DatagramChannel dc = DatagramChannel.open();
   2510         assertNull(dc.socket().getLocalSocketAddress());
   2511 
   2512         InetSocketAddress bindAddr = new InetSocketAddress("localhost", 0);
   2513         dc.socket().bind(bindAddr);
   2514 
   2515         assertNotNull(dc.socket().getLocalSocketAddress());
   2516 
   2517         dc.close();
   2518 
   2519         assertFalse(dc.isOpen());
   2520 
   2521         dc.socket().getLocalSocketAddress();
   2522     }
   2523 }
   2524