Path: blob/master/test/jdk/java/nio/channels/Pipe/PipeChannel.java
41152 views
/*1* Copyright (c) 2000, 2001, 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* @summary Test reading and writing from Pipes25* @key randomness26*/2728import java.io.*;29import java.nio.ByteBuffer;30import java.nio.channels.*;31import java.nio.channels.spi.SelectorProvider;32import java.util.Random;333435/**36* Testing PipeChannel37*/38public class PipeChannel {3940private static Random generator = new Random();4142public static void main(String[] args) throws Exception {43for (int x=0; x<100; x++) {44SelectorProvider sp = SelectorProvider.provider();45Pipe p = sp.openPipe();46Pipe.SinkChannel sink = p.sink();47Pipe.SourceChannel source = p.source();4849ByteBuffer outgoingdata = ByteBuffer.allocateDirect(10);50byte[] someBytes = new byte[10];51generator.nextBytes(someBytes);52outgoingdata.put(someBytes);53outgoingdata.flip();5455int totalWritten = 0;56while (totalWritten < 10) {57int written = sink.write(outgoingdata);58if (written < 0)59throw new Exception("Write failed");60totalWritten += written;61}6263ByteBuffer incomingdata = ByteBuffer.allocateDirect(10);64int totalRead = 0;65do {66int bytesRead = source.read(incomingdata);67if (bytesRead > 0)68totalRead += bytesRead;69} while(totalRead < 10);7071for(int i=0; i<10; i++)72if (outgoingdata.get(i) != incomingdata.get(i))73throw new Exception("Pipe failed");74sink.close();75source.close();76}77}78}798081