Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/java/nio/channels/AsynchronousSocketChannel/Basic.java
38828 views
/*1* Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/* @test24* @bug 4607272 6842687 6878369 6944810 702340325* @summary Unit test for AsynchronousSocketChannel26* @run main Basic -skipSlowConnectTest27* @key randomness28*/2930import java.nio.ByteBuffer;31import java.nio.channels.*;32import java.net.*;33import java.util.Arrays;34import java.util.Random;35import java.util.Set;36import java.util.List;37import java.util.concurrent.*;38import java.util.concurrent.atomic.*;39import java.io.Closeable;40import java.io.IOException;41import static java.net.StandardSocketOptions.*;42import static jdk.net.ExtendedSocketOptions.*;4344public class Basic {45static final Random rand = new Random();4647static boolean skipSlowConnectTest = false;4849public static void main(String[] args) throws Exception {50for (String arg: args) {51switch (arg) {52case "-skipSlowConnectTest" :53skipSlowConnectTest = true;54break;55default:56throw new RuntimeException("Unrecognized argument: " + arg);57}58}5960testBind();61testSocketOptions();62testConnect();63testCloseWhenPending();64testCancel();65testRead1();66testRead2();67testRead3();68testWrite1();69testWrite2();70// skip timeout tests until 7052549 is fixed71if (!System.getProperty("os.name").startsWith("Windows"))72testTimeout();73testShutdown();74}7576static class Server implements Closeable {77private final ServerSocketChannel ssc;78private final InetSocketAddress address;7980Server() throws IOException {81ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0));8283InetAddress lh = InetAddress.getLocalHost();84int port = ((InetSocketAddress)(ssc.getLocalAddress())).getPort();85address = new InetSocketAddress(lh, port);86}8788InetSocketAddress address() {89return address;90}9192SocketChannel accept() throws IOException {93return ssc.accept();94}9596public void close() throws IOException {97ssc.close();98}99100}101102static void testBind() throws Exception {103System.out.println("-- bind --");104105try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {106if (ch.getLocalAddress() != null)107throw new RuntimeException("Local address should be 'null'");108ch.bind(new InetSocketAddress(0));109110// check local address after binding111InetSocketAddress local = (InetSocketAddress)ch.getLocalAddress();112if (local.getPort() == 0)113throw new RuntimeException("Unexpected port");114if (!local.getAddress().isAnyLocalAddress())115throw new RuntimeException("Not bound to a wildcard address");116117// try to re-bind118try {119ch.bind(new InetSocketAddress(0));120throw new RuntimeException("AlreadyBoundException expected");121} catch (AlreadyBoundException x) {122}123}124125// check ClosedChannelException126AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();127ch.close();128try {129ch.bind(new InetSocketAddress(0));130throw new RuntimeException("ClosedChannelException expected");131} catch (ClosedChannelException x) {132}133}134135static void testSocketOptions() throws Exception {136System.out.println("-- socket options --");137138try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {139ch.setOption(SO_RCVBUF, 128*1024)140.setOption(SO_SNDBUF, 128*1024)141.setOption(SO_REUSEADDR, true);142143// check SO_SNDBUF/SO_RCVBUF limits144int before, after;145before = ch.getOption(SO_SNDBUF);146after = ch.setOption(SO_SNDBUF, Integer.MAX_VALUE).getOption(SO_SNDBUF);147if (after < before)148throw new RuntimeException("setOption caused SO_SNDBUF to decrease");149before = ch.getOption(SO_RCVBUF);150after = ch.setOption(SO_RCVBUF, Integer.MAX_VALUE).getOption(SO_RCVBUF);151if (after < before)152throw new RuntimeException("setOption caused SO_RCVBUF to decrease");153154ch.bind(new InetSocketAddress(0));155156// default values157if (ch.getOption(SO_KEEPALIVE))158throw new RuntimeException("Default of SO_KEEPALIVE should be 'false'");159if (ch.getOption(TCP_NODELAY))160throw new RuntimeException("Default of TCP_NODELAY should be 'false'");161162// set and check163if (!ch.setOption(SO_KEEPALIVE, true).getOption(SO_KEEPALIVE))164throw new RuntimeException("SO_KEEPALIVE did not change");165if (!ch.setOption(TCP_NODELAY, true).getOption(TCP_NODELAY))166throw new RuntimeException("SO_KEEPALIVE did not change");167168// read others (can't check as actual value is implementation dependent)169ch.getOption(SO_RCVBUF);170ch.getOption(SO_SNDBUF);171Set<SocketOption<?>> options = ch.supportedOptions();172List<SocketOption<?>> extOptions = Arrays.asList(TCP_KEEPCOUNT,173TCP_KEEPIDLE, TCP_KEEPINTERVAL);174if (options.containsAll(extOptions)) {175ch.setOption(TCP_KEEPIDLE, 1234);176checkOption(ch, TCP_KEEPIDLE, 1234);177ch.setOption(TCP_KEEPINTERVAL, 123);178checkOption(ch, TCP_KEEPINTERVAL, 123);179ch.setOption(TCP_KEEPCOUNT, 7);180checkOption(ch, TCP_KEEPCOUNT, 7);181}182}183}184185static void checkOption(AsynchronousSocketChannel sc, SocketOption name, Object expectedValue)186throws IOException {187Object value = sc.getOption(name);188if (!value.equals(expectedValue)) {189throw new RuntimeException("value not as expected");190}191}192193static void testConnect() throws Exception {194System.out.println("-- connect --");195196SocketAddress address;197198try (Server server = new Server()) {199address = server.address();200201// connect to server and check local/remote addresses202try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {203ch.connect(address).get();204// check local address205if (ch.getLocalAddress() == null)206throw new RuntimeException("Not bound to local address");207208// check remote address209InetSocketAddress remote = (InetSocketAddress)ch.getRemoteAddress();210if (remote.getPort() != server.address().getPort())211throw new RuntimeException("Connected to unexpected port");212if (!remote.getAddress().equals(server.address().getAddress()))213throw new RuntimeException("Connected to unexpected address");214215// try to connect again216try {217ch.connect(server.address()).get();218throw new RuntimeException("AlreadyConnectedException expected");219} catch (AlreadyConnectedException x) {220}221222// clean-up223server.accept().close();224}225226// check that connect fails with ClosedChannelException227AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();228ch.close();229try {230ch.connect(server.address()).get();231throw new RuntimeException("ExecutionException expected");232} catch (ExecutionException x) {233if (!(x.getCause() instanceof ClosedChannelException))234throw new RuntimeException("Cause of ClosedChannelException expected");235}236final AtomicReference<Throwable> connectException = new AtomicReference<>();237ch.connect(server.address(), (Void)null, new CompletionHandler<Void,Void>() {238public void completed(Void result, Void att) {239}240public void failed(Throwable exc, Void att) {241connectException.set(exc);242}243});244while (connectException.get() == null) {245Thread.sleep(100);246}247if (!(connectException.get() instanceof ClosedChannelException))248throw new RuntimeException("ClosedChannelException expected");249}250251// test that failure to connect closes the channel252try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {253try {254ch.connect(address).get();255} catch (ExecutionException x) {256// failed to establish connection257if (ch.isOpen())258throw new RuntimeException("Channel should be closed");259}260}261262// repeat test by connecting to a (probably) non-existent host. This263// improves the chance that the connect will not fail immediately.264if (!skipSlowConnectTest) {265try (AsynchronousSocketChannel ch = AsynchronousSocketChannel.open()) {266try {267ch.connect(genSocketAddress()).get();268} catch (ExecutionException x) {269// failed to establish connection270if (ch.isOpen())271throw new RuntimeException("Channel should be closed");272}273}274}275}276277static void testCloseWhenPending() throws Exception {278System.out.println("-- asynchronous close when connecting --");279280AsynchronousSocketChannel ch;281282// asynchronous close while connecting283ch = AsynchronousSocketChannel.open();284Future<Void> connectResult = ch.connect(genSocketAddress());285286// give time to initiate the connect (SYN)287Thread.sleep(50);288289// close290ch.close();291292// check that exception is thrown in timely manner293try {294connectResult.get(5, TimeUnit.SECONDS);295} catch (TimeoutException x) {296throw new RuntimeException("AsynchronousCloseException not thrown");297} catch (ExecutionException x) {298// expected299}300301System.out.println("-- asynchronous close when reading --");302303try (Server server = new Server()) {304ch = AsynchronousSocketChannel.open();305ch.connect(server.address()).get();306307ByteBuffer dst = ByteBuffer.allocateDirect(100);308Future<Integer> result = ch.read(dst);309310// attempt a second read - should fail with ReadPendingException311ByteBuffer buf = ByteBuffer.allocateDirect(100);312try {313ch.read(buf);314throw new RuntimeException("ReadPendingException expected");315} catch (ReadPendingException x) {316}317318// close channel (should cause initial read to complete)319ch.close();320server.accept().close();321322// check that AsynchronousCloseException is thrown323try {324result.get();325throw new RuntimeException("Should not read");326} catch (ExecutionException x) {327if (!(x.getCause() instanceof AsynchronousCloseException))328throw new RuntimeException(x);329}330331System.out.println("-- asynchronous close when writing --");332333ch = AsynchronousSocketChannel.open();334ch.connect(server.address()).get();335336final AtomicReference<Throwable> writeException =337new AtomicReference<Throwable>();338339// write bytes to fill socket buffer340ch.write(genBuffer(), ch, new CompletionHandler<Integer,AsynchronousSocketChannel>() {341public void completed(Integer result, AsynchronousSocketChannel ch) {342ch.write(genBuffer(), ch, this);343}344public void failed(Throwable x, AsynchronousSocketChannel ch) {345writeException.set(x);346}347});348349// give time for socket buffer to fill up.350Thread.sleep(5*1000);351352// attempt a concurrent write - should fail with WritePendingException353try {354ch.write(genBuffer());355throw new RuntimeException("WritePendingException expected");356} catch (WritePendingException x) {357}358359// close channel - should cause initial write to complete360ch.close();361server.accept().close();362363// wait for exception364while (writeException.get() == null) {365Thread.sleep(100);366}367if (!(writeException.get() instanceof AsynchronousCloseException))368throw new RuntimeException("AsynchronousCloseException expected");369}370}371372static void testCancel() throws Exception {373System.out.println("-- cancel --");374375try (Server server = new Server()) {376for (int i=0; i<2; i++) {377boolean mayInterruptIfRunning = (i == 0) ? false : true;378379// establish loopback connection380AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();381ch.connect(server.address()).get();382SocketChannel peer = server.accept();383384// start read operation385ByteBuffer buf = ByteBuffer.allocate(1);386Future<Integer> res = ch.read(buf);387388// cancel operation389boolean cancelled = res.cancel(mayInterruptIfRunning);390391// check post-conditions392if (!res.isDone())393throw new RuntimeException("isDone should return true");394if (res.isCancelled() != cancelled)395throw new RuntimeException("isCancelled not consistent");396try {397res.get();398throw new RuntimeException("CancellationException expected");399} catch (CancellationException x) {400}401try {402res.get(1, TimeUnit.SECONDS);403throw new RuntimeException("CancellationException expected");404} catch (CancellationException x) {405}406407// check that the cancel doesn't impact writing to the channel408if (!mayInterruptIfRunning) {409buf = ByteBuffer.wrap("a".getBytes());410ch.write(buf).get();411}412413ch.close();414peer.close();415}416}417}418419static void testRead1() throws Exception {420System.out.println("-- read (1) --");421422try (Server server = new Server()) {423final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();424ch.connect(server.address()).get();425426// read with 0 bytes remaining should complete immediately427ByteBuffer buf = ByteBuffer.allocate(1);428buf.put((byte)0);429int n = ch.read(buf).get();430if (n != 0)431throw new RuntimeException("0 expected");432433// write bytes and close connection434ByteBuffer src = genBuffer();435try (SocketChannel sc = server.accept()) {436sc.setOption(SO_SNDBUF, src.remaining());437while (src.hasRemaining())438sc.write(src);439}440441// reads should complete immediately442final ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity() + 100);443final CountDownLatch latch = new CountDownLatch(1);444ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() {445public void completed(Integer result, Void att) {446int n = result;447if (n > 0) {448ch.read(dst, (Void)null, this);449} else {450latch.countDown();451}452}453public void failed(Throwable exc, Void att) {454}455});456457latch.await();458459// check buffers460src.flip();461dst.flip();462if (!src.equals(dst)) {463throw new RuntimeException("Contents differ");464}465466// close channel467ch.close();468469// check read fails with ClosedChannelException470try {471ch.read(dst).get();472throw new RuntimeException("ExecutionException expected");473} catch (ExecutionException x) {474if (!(x.getCause() instanceof ClosedChannelException))475throw new RuntimeException("Cause of ClosedChannelException expected");476}477}478}479480static void testRead2() throws Exception {481System.out.println("-- read (2) --");482483try (Server server = new Server()) {484final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();485ch.connect(server.address()).get();486SocketChannel sc = server.accept();487488ByteBuffer src = genBuffer();489490// read until the buffer is full491final ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity());492final CountDownLatch latch = new CountDownLatch(1);493ch.read(dst, (Void)null, new CompletionHandler<Integer,Void>() {494public void completed(Integer result, Void att) {495if (dst.hasRemaining()) {496ch.read(dst, (Void)null, this);497} else {498latch.countDown();499}500}501public void failed(Throwable exc, Void att) {502}503});504505// trickle the writing506do {507int rem = src.remaining();508int size = (rem <= 100) ? rem : 50 + rand.nextInt(rem - 100);509ByteBuffer buf = ByteBuffer.allocate(size);510for (int i=0; i<size; i++)511buf.put(src.get());512buf.flip();513Thread.sleep(50 + rand.nextInt(1500));514while (buf.hasRemaining())515sc.write(buf);516} while (src.hasRemaining());517518// wait until ascynrhonous reading has completed519latch.await();520521// check buffers522src.flip();523dst.flip();524if (!src.equals(dst)) {525throw new RuntimeException("Contents differ");526}527528sc.close();529ch.close();530}531}532533// exercise scattering read534static void testRead3() throws Exception {535System.out.println("-- read (3) --");536537try (Server server = new Server()) {538final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();539ch.connect(server.address()).get();540SocketChannel sc = server.accept();541542ByteBuffer[] dsts = new ByteBuffer[3];543for (int i=0; i<dsts.length; i++) {544dsts[i] = ByteBuffer.allocateDirect(100);545}546547// scattering read that completes ascynhronously548final CountDownLatch l1 = new CountDownLatch(1);549ch.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, (Void)null,550new CompletionHandler<Long,Void>() {551public void completed(Long result, Void att) {552long n = result;553if (n <= 0)554throw new RuntimeException("No bytes read");555l1.countDown();556}557public void failed(Throwable exc, Void att) {558}559});560561// write some bytes562sc.write(genBuffer());563564// read should now complete565l1.await();566567// write more bytes568sc.write(genBuffer());569570// read should complete immediately571for (int i=0; i<dsts.length; i++) {572dsts[i].rewind();573}574575final CountDownLatch l2 = new CountDownLatch(1);576ch.read(dsts, 0, dsts.length, 0L, TimeUnit.SECONDS, (Void)null,577new CompletionHandler<Long,Void>() {578public void completed(Long result, Void att) {579long n = result;580if (n <= 0)581throw new RuntimeException("No bytes read");582l2.countDown();583}584public void failed(Throwable exc, Void att) {585}586});587l2.await();588589ch.close();590sc.close();591}592}593594static void testWrite1() throws Exception {595System.out.println("-- write (1) --");596597try (Server server = new Server()) {598final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();599ch.connect(server.address()).get();600SocketChannel sc = server.accept();601602// write with 0 bytes remaining should complete immediately603ByteBuffer buf = ByteBuffer.allocate(1);604buf.put((byte)0);605int n = ch.write(buf).get();606if (n != 0)607throw new RuntimeException("0 expected");608609// write all bytes and close connection when done610final ByteBuffer src = genBuffer();611ch.write(src, (Void)null, new CompletionHandler<Integer,Void>() {612public void completed(Integer result, Void att) {613if (src.hasRemaining()) {614ch.write(src, (Void)null, this);615} else {616try {617ch.close();618} catch (IOException ignore) { }619}620}621public void failed(Throwable exc, Void att) {622}623});624625// read to EOF or buffer full626ByteBuffer dst = ByteBuffer.allocateDirect(src.capacity() + 100);627do {628n = sc.read(dst);629} while (n > 0);630sc.close();631632// check buffers633src.flip();634dst.flip();635if (!src.equals(dst)) {636throw new RuntimeException("Contents differ");637}638639// check write fails with ClosedChannelException640try {641ch.read(dst).get();642throw new RuntimeException("ExecutionException expected");643} catch (ExecutionException x) {644if (!(x.getCause() instanceof ClosedChannelException))645throw new RuntimeException("Cause of ClosedChannelException expected");646}647}648}649650// exercise gathering write651static void testWrite2() throws Exception {652System.out.println("-- write (2) --");653654try (Server server = new Server()) {655final AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();656ch.connect(server.address()).get();657SocketChannel sc = server.accept();658659// number of bytes written660final AtomicLong bytesWritten = new AtomicLong(0);661662// write buffers (should complete immediately)663ByteBuffer[] srcs = genBuffers(1);664final CountDownLatch l1 = new CountDownLatch(1);665ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, (Void)null,666new CompletionHandler<Long,Void>() {667public void completed(Long result, Void att) {668long n = result;669if (n <= 0)670throw new RuntimeException("No bytes read");671bytesWritten.addAndGet(n);672l1.countDown();673}674public void failed(Throwable exc, Void att) {675}676});677l1.await();678679// set to true to signal that no more buffers should be written680final AtomicBoolean continueWriting = new AtomicBoolean(true);681682// write until socket buffer is full so as to create the conditions683// for when a write does not complete immediately684srcs = genBuffers(1);685ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS, (Void)null,686new CompletionHandler<Long,Void>() {687public void completed(Long result, Void att) {688long n = result;689if (n <= 0)690throw new RuntimeException("No bytes written");691bytesWritten.addAndGet(n);692if (continueWriting.get()) {693ByteBuffer[] srcs = genBuffers(8);694ch.write(srcs, 0, srcs.length, 0L, TimeUnit.SECONDS,695(Void)null, this);696}697}698public void failed(Throwable exc, Void att) {699}700});701702// give time for socket buffer to fill up.703Thread.sleep(5*1000);704705// signal handler to stop further writing706continueWriting.set(false);707708// read until done709ByteBuffer buf = ByteBuffer.allocateDirect(4096);710long total = 0L;711do {712int n = sc.read(buf);713if (n <= 0)714throw new RuntimeException("No bytes read");715buf.rewind();716total += n;717} while (total < bytesWritten.get());718719ch.close();720sc.close();721}722}723724static void testShutdown() throws Exception {725System.out.println("-- shutdown--");726727try (Server server = new Server();728AsynchronousSocketChannel ch = AsynchronousSocketChannel.open())729{730ch.connect(server.address()).get();731try (SocketChannel peer = server.accept()) {732ByteBuffer buf = ByteBuffer.allocateDirect(1000);733int n;734735// check read736ch.shutdownInput();737n = ch.read(buf).get();738if (n != -1)739throw new RuntimeException("-1 expected");740// check full with full buffer741buf.put(new byte[100]);742n = ch.read(buf).get();743if (n != -1)744throw new RuntimeException("-1 expected");745746// check write747ch.shutdownOutput();748try {749ch.write(buf).get();750throw new RuntimeException("ClosedChannelException expected");751} catch (ExecutionException x) {752if (!(x.getCause() instanceof ClosedChannelException))753throw new RuntimeException("ClosedChannelException expected");754}755}756}757}758759static void testTimeout() throws Exception {760System.out.println("-- timeouts --");761testTimeout(Integer.MIN_VALUE, TimeUnit.SECONDS);762testTimeout(-1L, TimeUnit.SECONDS);763testTimeout(0L, TimeUnit.SECONDS);764testTimeout(2L, TimeUnit.SECONDS);765}766767static void testTimeout(final long timeout, final TimeUnit unit) throws Exception {768try (Server server = new Server()) {769AsynchronousSocketChannel ch = AsynchronousSocketChannel.open();770ch.connect(server.address()).get();771772ByteBuffer dst = ByteBuffer.allocate(512);773774final AtomicReference<Throwable> readException = new AtomicReference<Throwable>();775776// this read should timeout if value is > 0777ch.read(dst, timeout, unit, null, new CompletionHandler<Integer,Void>() {778public void completed(Integer result, Void att) {779readException.set(new RuntimeException("Should not complete"));780}781public void failed(Throwable exc, Void att) {782readException.set(exc);783}784});785if (timeout > 0L) {786// wait for exception787while (readException.get() == null) {788Thread.sleep(100);789}790if (!(readException.get() instanceof InterruptedByTimeoutException))791throw new RuntimeException("InterruptedByTimeoutException expected");792793// after a timeout then further reading should throw unspecified runtime exception794boolean exceptionThrown = false;795try {796ch.read(dst);797} catch (RuntimeException x) {798exceptionThrown = true;799}800if (!exceptionThrown)801throw new RuntimeException("RuntimeException expected after timeout.");802} else {803Thread.sleep(1000);804Throwable exc = readException.get();805if (exc != null)806throw new RuntimeException(exc);807}808809final AtomicReference<Throwable> writeException = new AtomicReference<Throwable>();810811// write bytes to fill socket buffer812ch.write(genBuffer(), timeout, unit, ch,813new CompletionHandler<Integer,AsynchronousSocketChannel>()814{815public void completed(Integer result, AsynchronousSocketChannel ch) {816ch.write(genBuffer(), timeout, unit, ch, this);817}818public void failed(Throwable exc, AsynchronousSocketChannel ch) {819writeException.set(exc);820}821});822if (timeout > 0) {823// wait for exception824while (writeException.get() == null) {825Thread.sleep(100);826}827if (!(writeException.get() instanceof InterruptedByTimeoutException))828throw new RuntimeException("InterruptedByTimeoutException expected");829830// after a timeout then further writing should throw unspecified runtime exception831boolean exceptionThrown = false;832try {833ch.write(genBuffer());834} catch (RuntimeException x) {835exceptionThrown = true;836}837if (!exceptionThrown)838throw new RuntimeException("RuntimeException expected after timeout.");839} else {840Thread.sleep(1000);841Throwable exc = writeException.get();842if (exc != null)843throw new RuntimeException(exc);844}845846// clean-up847server.accept().close();848ch.close();849}850}851852// returns ByteBuffer with random bytes853static ByteBuffer genBuffer() {854int size = 1024 + rand.nextInt(16000);855byte[] buf = new byte[size];856rand.nextBytes(buf);857boolean useDirect = rand.nextBoolean();858if (useDirect) {859ByteBuffer bb = ByteBuffer.allocateDirect(buf.length);860bb.put(buf);861bb.flip();862return bb;863} else {864return ByteBuffer.wrap(buf);865}866}867868// return ByteBuffer[] with random bytes869static ByteBuffer[] genBuffers(int max) {870int len = 1;871if (max > 1)872len += rand.nextInt(max);873ByteBuffer[] bufs = new ByteBuffer[len];874for (int i=0; i<len; i++)875bufs[i] = genBuffer();876return bufs;877}878879// return random SocketAddress880static SocketAddress genSocketAddress() {881StringBuilder sb = new StringBuilder("10.");882sb.append(rand.nextInt(256));883sb.append('.');884sb.append(rand.nextInt(256));885sb.append('.');886sb.append(rand.nextInt(256));887InetAddress rh;888try {889rh = InetAddress.getByName(sb.toString());890} catch (UnknownHostException x) {891throw new InternalError("Should not happen");892}893return new InetSocketAddress(rh, rand.nextInt(65535)+1);894}895}896897898