1/*
2 * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/* @test
25 * @bug 4607272
26 * @summary Test Channels methods for interoperability between streams and
27 *     asynchronous byte channels
28 * @key randomness
29 */
30
31import java.net.*;
32import java.io.*;
33import java.nio.channels.*;
34import java.util.Random;
35
36public class Basic2 {
37
38    static final Random rand = new Random();
39
40    public static void main(String[] args) throws Exception {
41        // establish loopback connection
42        AsynchronousServerSocketChannel listener =
43            AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(0));
44        int port = ((InetSocketAddress)(listener.getLocalAddress())).getPort();
45        InetSocketAddress isa =
46            new InetSocketAddress(InetAddress.getLocalHost(), port);
47        AsynchronousSocketChannel ch1 = AsynchronousSocketChannel.open();
48        ch1.connect(isa).get();
49        AsynchronousSocketChannel ch2 = listener.accept().get();
50
51        // start thread to write to stream
52        Writer writer = new Writer(Channels.newOutputStream(ch1));
53        Thread writerThread = new Thread(writer);
54        writerThread.start();
55
56        // start thread to read from stream
57        Reader reader = new Reader(Channels.newInputStream(ch2));
58        Thread readerThread = new Thread(reader);
59        readerThread.start();
60
61        // wait for threads to complete
62        writerThread.join();
63        readerThread.join();
64
65        // shutdown listener
66        listener.close();
67
68        // check that reader received what we expected
69        if (reader.total() != writer.total())
70            throw new RuntimeException("Unexpected number of bytes read");
71        if (reader.hash() != writer.hash())
72            throw new RuntimeException("Hash incorrect for bytes read");
73
74        // channels should be closed
75        if (ch1.isOpen() || ch2.isOpen())
76            throw new RuntimeException("Channels should be closed");
77    }
78
79    static class Reader implements Runnable {
80        private final InputStream in;
81        private volatile int total;
82        private volatile int hash;
83
84        Reader(InputStream in) {
85            this.in = in;
86        }
87
88        public void run() {
89            try {
90                int n;
91                do {
92                    // random offset/len
93                    byte[] buf = new byte[128 + rand.nextInt(128)];
94                    int len, off;
95                    if (rand.nextBoolean()) {
96                        len = buf.length;
97                        off = 0;
98                        n = in.read(buf);
99                    } else {
100                        len = 1 + rand.nextInt(64);
101                        off = rand.nextInt(64);
102                        n = in.read(buf, off, len);
103                    }
104                    if (n > len)
105                        throw new RuntimeException("Too many bytes read");
106                    if (n > 0) {
107                        total += n;
108                        for (int i=0; i<n; i++) {
109                            int value = buf[off + i];
110                            hash = hash ^ value;
111                        }
112                    }
113                } while (n > 0);
114                in.close();
115
116            } catch (IOException x) {
117                x.printStackTrace();
118            }
119        }
120
121        int total() { return total; }
122        int hash() { return hash; }
123    }
124
125    static class Writer implements Runnable {
126        private final OutputStream out;
127        private final int total;
128        private volatile int hash;
129
130        Writer(OutputStream out) {
131            this.out = out;
132            this.total = 50*1000 + rand.nextInt(50*1000);
133        }
134
135        public void run() {
136            hash = 0;
137            int rem = total;
138            try {
139                do {
140                    byte[] buf = new byte[1 + rand.nextInt(rem)];
141                    int off, len;
142
143                    // write random bytes
144                    if (rand.nextBoolean()) {
145                        off = 0;
146                        len = buf.length;
147                    } else {
148                        off = rand.nextInt(buf.length);
149                        int r = buf.length - off;
150                        len = (r <= 1) ? 1 : (1 + rand.nextInt(r));
151                    }
152                    for (int i=0; i<len; i++) {
153                        byte value = (byte)rand.nextInt(256);
154                        buf[off + i] = value;
155                        hash = hash ^ value;
156                    }
157                    if ((off == 0) && (len == buf.length)) {
158                        out.write(buf);
159                    } else {
160                        out.write(buf, off, len);
161                    }
162                    rem -= len;
163                } while (rem > 0);
164
165                // close stream when done
166                out.close();
167
168            } catch (IOException x) {
169                x.printStackTrace();
170            }
171        }
172
173        int total() { return total; }
174        int hash() { return hash; }
175    }
176}
177