1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package libcore.java.nio.channels;
18
19import java.net.ConnectException;
20import java.net.InetAddress;
21import java.net.InetSocketAddress;
22import java.net.ServerSocket;
23import java.nio.ByteBuffer;
24import java.nio.channels.ClosedChannelException;
25import java.nio.channels.Selector;
26import java.nio.channels.SelectionKey;
27import java.nio.channels.SocketChannel;
28import tests.io.MockOs;
29import static libcore.io.OsConstants.*;
30
31public class SocketChannelTest extends junit.framework.TestCase {
32  private final MockOs mockOs = new MockOs();
33
34  @Override public void setUp() throws Exception {
35    mockOs.install();
36  }
37
38  @Override protected void tearDown() throws Exception {
39    mockOs.uninstall();
40  }
41
42  public void test_read_intoReadOnlyByteArrays() throws Exception {
43    ByteBuffer readOnly = ByteBuffer.allocate(1).asReadOnlyBuffer();
44    ServerSocket ss = new ServerSocket(0);
45    ss.setReuseAddress(true);
46    SocketChannel sc = SocketChannel.open(ss.getLocalSocketAddress());
47    try {
48      sc.read(readOnly);
49      fail();
50    } catch (IllegalArgumentException expected) {
51    }
52    try {
53      sc.read(new ByteBuffer[] { readOnly });
54      fail();
55    } catch (IllegalArgumentException expected) {
56    }
57    try {
58      sc.read(new ByteBuffer[] { readOnly }, 0, 1);
59      fail();
60    } catch (IllegalArgumentException expected) {
61    }
62  }
63
64  public void test_56684() throws Exception {
65    mockOs.enqueueFault("connect", ENETUNREACH);
66
67    SocketChannel sc = SocketChannel.open();
68    sc.configureBlocking(false);
69
70    Selector selector = Selector.open();
71    SelectionKey selectionKey = sc.register(selector, SelectionKey.OP_CONNECT);
72
73    try {
74      sc.connect(new InetSocketAddress(InetAddress.getByAddress(new byte[] { 0, 0, 0, 0 }), 0));
75      fail();
76    } catch (ConnectException ex) {
77    }
78
79    try {
80      sc.finishConnect();
81    } catch (ClosedChannelException expected) {
82    }
83  }
84}
85