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.io.IOException;
20import java.nio.ByteBuffer;
21import java.nio.channels.Channels;
22import java.nio.channels.IllegalBlockingModeException;
23import java.nio.channels.Pipe;
24import java.nio.channels.WritableByteChannel;
25import junit.framework.TestCase;
26
27public final class ChannelsTest extends TestCase {
28
29    public void testStreamNonBlocking() throws IOException {
30        Pipe.SourceChannel sourceChannel = createNonBlockingChannel("abc".getBytes("UTF-8"));
31        try {
32            Channels.newInputStream(sourceChannel).read();
33            fail();
34        } catch (IllegalBlockingModeException expected) {
35        }
36    }
37
38    /**
39     * This fails on the RI which violates its own promise to throw when
40     * read in non-blocking mode.
41     */
42    public void testReaderNonBlocking() throws IOException {
43        Pipe.SourceChannel sourceChannel = createNonBlockingChannel("abc".getBytes("UTF-8"));
44        try {
45            Channels.newReader(sourceChannel, "UTF-8").read();
46            fail();
47        } catch (IllegalBlockingModeException expected) {
48        }
49    }
50
51    private Pipe.SourceChannel createNonBlockingChannel(byte[] content) throws IOException {
52        Pipe pipe = Pipe.open();
53        WritableByteChannel sinkChannel = pipe.sink();
54        sinkChannel.write(ByteBuffer.wrap(content));
55        Pipe.SourceChannel sourceChannel = pipe.source();
56        sourceChannel.configureBlocking(false);
57        return sourceChannel;
58    }
59}
60
61