Java Code Examples for java.nio.channels.Pipe#SourceChannel

The following examples show how to use java.nio.channels.Pipe#SourceChannel . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestPipe.java    From code with Apache License 2.0 6 votes vote down vote up
@Test
public void test1() throws IOException {
    //1.获取管道
    Pipe pipe = Pipe.open();
    //2.将缓冲区数据写入管道
    ByteBuffer buf = ByteBuffer.allocate(1024);

    Pipe.SinkChannel sinkChannel = pipe.sink();
    buf.put("通过单向管道发送数据".getBytes());
    buf.flip();
    sinkChannel.write(buf);

    //3.读取缓冲区中的数据
    Pipe.SourceChannel sourceChannel = pipe.source();
    buf.flip();
    int len = sourceChannel.read(buf);
    System.out.println(new String(buf.array(), 0, len));

    sourceChannel.close();
    sinkChannel.close();

}
 
Example 2
Source File: TestPipe.java    From cs-summary-reflection with Apache License 2.0 6 votes vote down vote up
@Test
public void test1() throws IOException {
    // 1. 获取管道
    Pipe pipe = Pipe.open();

    // 2. 将缓冲区中的数据写入管道
    ByteBuffer buf = ByteBuffer.allocate(1024);

    Pipe.SinkChannel sinkChannel = pipe.sink();
    buf.put("通过单向管道发送数据".getBytes());
    buf.flip();
    sinkChannel.write(buf);

    // 3. 读取缓冲区中的数据
    Pipe.SourceChannel sourceChannel = pipe.source();
    buf.flip();
    int len = sourceChannel.read(buf);
    System.out.println(new String(buf.array(), 0, len));

    sourceChannel.close();
    sinkChannel.close();
}
 
Example 3
Source File: SingleInputExpect.java    From ExpectIt with Apache License 2.0 6 votes vote down vote up
protected SingleInputExpect(
        final Pipe.SourceChannel source,
        final Pipe.SinkChannel sink,
        final InputStream input,
        final Charset charset,
        final Appendable echoInput,
        final Filter filter,
        final int bufferSize,
        final boolean autoFlushEcho) throws IOException {
    this.input = input;
    this.charset = charset;
    this.echoInput = echoInput;
    this.filter = filter;
    this.bufferSize = bufferSize;
    this.autoFlushEcho = autoFlushEcho;
    this.source = source;
    this.sink = sink;
    source.configureBlocking(false);
    buffer = new StringBuilder();
}
 
Example 4
Source File: ChannelsTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testStreamNonBlocking() throws IOException {
    Pipe.SourceChannel sourceChannel = createNonBlockingChannel("abc".getBytes("UTF-8"));
    try {
        Channels.newInputStream(sourceChannel).read();
        fail();
    } catch (IllegalBlockingModeException expected) {
    }
}
 
Example 5
Source File: ChannelsTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * This fails on the RI which violates its own promise to throw when
 * read in non-blocking mode.
 */
public void testReaderNonBlocking() throws IOException {
    Pipe.SourceChannel sourceChannel = createNonBlockingChannel("abc".getBytes("UTF-8"));
    try {
        Channels.newReader(sourceChannel, "UTF-8").read();
        fail();
    } catch (IllegalBlockingModeException expected) {
    }
}
 
Example 6
Source File: ChannelsTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private Pipe.SourceChannel createNonBlockingChannel(byte[] content) throws IOException {
    Pipe pipe = Pipe.open();
    WritableByteChannel sinkChannel = pipe.sink();
    sinkChannel.write(ByteBuffer.wrap(content));
    Pipe.SourceChannel sourceChannel = pipe.source();
    sourceChannel.configureBlocking(false);
    return sourceChannel;
}
 
Example 7
Source File: NBCircularIOStream.java    From imhotep with Apache License 2.0 5 votes vote down vote up
public NBCircularIOStream() throws IOException {
    final Pipe pipe = Pipe.open();
    sink = new BufferedWritableSelectableChannel(new PipeSinkWritableSelectableChannel(pipe.sink()));
    final Pipe.SourceChannel source = pipe.source();
    sink.configureBlocking(false);
    source.configureBlocking(true);
    in = Channels.newInputStream(source);
}
 
Example 8
Source File: Transfer.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testReadableByteChannel() throws Exception {
    int[] testSizes = { 0, 10, 1023, 1024, 1025, 2047, 2048, 2049 };

    for (int size : testSizes) {
        SelectorProvider sp = SelectorProvider.provider();
        Pipe p = sp.openPipe();
        Pipe.SinkChannel sink = p.sink();
        Pipe.SourceChannel source = p.source();
        sink.configureBlocking(false);

        ByteBuffer outgoingdata = ByteBuffer.allocateDirect(size + 10);
        byte[] someBytes = new byte[size + 10];
        generator.nextBytes(someBytes);
        outgoingdata.put(someBytes);
        outgoingdata.flip();

        int totalWritten = 0;
        while (totalWritten < size + 10) {
            int written = sink.write(outgoingdata);
            if (written < 0)
                throw new Exception("Write failed");
            totalWritten += written;
        }

        File f = File.createTempFile("blah"+size, null);
        f.deleteOnExit();
        RandomAccessFile raf = new RandomAccessFile(f, "rw");
        FileChannel fc = raf.getChannel();
        long oldPosition = fc.position();

        long bytesWritten = fc.transferFrom(source, 0, size);
        fc.force(true);
        if (bytesWritten != size)
            throw new RuntimeException("Transfer failed");

        if (fc.position() != oldPosition)
            throw new RuntimeException("Position changed");

        if (fc.size() != size)
            throw new RuntimeException("Unexpected sink size "+ fc.size());

        fc.close();
        sink.close();
        source.close();

        f.delete();
    }
}
 
Example 9
Source File: TestSocketIOWithTimeout.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test
public void testSocketIOWithTimeout() throws Exception {
  
  // first open pipe:
  Pipe pipe = Pipe.open();
  Pipe.SourceChannel source = pipe.source();
  Pipe.SinkChannel sink = pipe.sink();
  
  try {
    final InputStream in = new SocketInputStream(source, TIMEOUT);
    OutputStream out = new SocketOutputStream(sink, TIMEOUT);
    
    byte[] writeBytes = TEST_STRING.getBytes();
    byte[] readBytes = new byte[writeBytes.length];
    byte byteWithHighBit = (byte)0x80;
    
    out.write(writeBytes);
    out.write(byteWithHighBit);
    doIO(null, out, TIMEOUT);
    
    in.read(readBytes);
    assertTrue(Arrays.equals(writeBytes, readBytes));
    assertEquals(byteWithHighBit & 0xff, in.read());
    doIO(in, null, TIMEOUT);
    
    // Change timeout on the read side.
    ((SocketInputStream)in).setTimeout(TIMEOUT * 2);
    doIO(in, null, TIMEOUT * 2);
    
    
    /*
     * Verify that it handles interrupted threads properly.
     * Use a large timeout and expect the thread to return quickly
     * upon interruption.
     */
    ((SocketInputStream)in).setTimeout(0);
    TestingThread thread = new TestingThread(ctx) {
      @Override
      public void doWork() throws Exception {
        try {
          in.read();
          fail("Did not fail with interrupt");
        } catch (InterruptedIOException ste) {
          LOG.info("Got expection while reading as expected : " + 
              ste.getMessage());
        }
      }
    };
    ctx.addThread(thread);
    ctx.startThreads();
    // If the thread is interrupted before it calls read()
    // then it throws ClosedByInterruptException due to
    // some Java quirk. Waiting for it to call read()
    // gets it into select(), so we get the expected
    // InterruptedIOException.
    Thread.sleep(1000);
    thread.interrupt();
    ctx.stop();

    //make sure the channels are still open
    assertTrue(source.isOpen());
    assertTrue(sink.isOpen());
    
    // Nevertheless, the output stream is closed, because
    // a partial write may have succeeded (see comment in
    // SocketOutputStream#write(byte[]), int, int)
    // This portion of the test cannot pass on Windows due to differences in
    // behavior of partial writes.  Windows appears to buffer large amounts of
    // written data and send it all atomically, thus making it impossible to
    // simulate a partial write scenario.  Attempts were made to switch the
    // test from using a pipe to a network socket and also to use larger and
    // larger buffers in doIO.  Nothing helped the situation though.
    if (!Shell.WINDOWS) {
      try {
        out.write(1);
        fail("Did not throw");
      } catch (IOException ioe) {
        GenericTestUtils.assertExceptionContains(
            "stream is closed", ioe);
      }
    }
    
    out.close();
    assertFalse(sink.isOpen());
    
    // close sink and expect -1 from source.read()
    assertEquals(-1, in.read());
    
    // make sure close() closes the underlying channel.
    in.close();
    assertFalse(source.isOpen());
    
  } finally {
    if (source != null) {
      source.close();
    }
    if (sink != null) {
      sink.close();
    }
  }
}
 
Example 10
Source File: TestSocketIOWithTimeout.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Test
public void testSocketIOWithTimeout() throws Exception {
  
  // first open pipe:
  Pipe pipe = Pipe.open();
  Pipe.SourceChannel source = pipe.source();
  Pipe.SinkChannel sink = pipe.sink();
  
  try {
    final InputStream in = new SocketInputStream(source, TIMEOUT);
    OutputStream out = new SocketOutputStream(sink, TIMEOUT);
    
    byte[] writeBytes = TEST_STRING.getBytes();
    byte[] readBytes = new byte[writeBytes.length];
    byte byteWithHighBit = (byte)0x80;
    
    out.write(writeBytes);
    out.write(byteWithHighBit);
    doIO(null, out, TIMEOUT);
    
    in.read(readBytes);
    assertTrue(Arrays.equals(writeBytes, readBytes));
    assertEquals(byteWithHighBit & 0xff, in.read());
    doIO(in, null, TIMEOUT);
    
    // Change timeout on the read side.
    ((SocketInputStream)in).setTimeout(TIMEOUT * 2);
    doIO(in, null, TIMEOUT * 2);
    
    
    /*
     * Verify that it handles interrupted threads properly.
     * Use a large timeout and expect the thread to return quickly
     * upon interruption.
     */
    ((SocketInputStream)in).setTimeout(0);
    TestingThread thread = new TestingThread(ctx) {
      @Override
      public void doWork() throws Exception {
        try {
          in.read();
          fail("Did not fail with interrupt");
        } catch (InterruptedIOException ste) {
          LOG.info("Got expection while reading as expected : " + 
              ste.getMessage());
        }
      }
    };
    ctx.addThread(thread);
    ctx.startThreads();
    // If the thread is interrupted before it calls read()
    // then it throws ClosedByInterruptException due to
    // some Java quirk. Waiting for it to call read()
    // gets it into select(), so we get the expected
    // InterruptedIOException.
    Thread.sleep(1000);
    thread.interrupt();
    ctx.stop();

    //make sure the channels are still open
    assertTrue(source.isOpen());
    assertTrue(sink.isOpen());
    
    // Nevertheless, the output stream is closed, because
    // a partial write may have succeeded (see comment in
    // SocketOutputStream#write(byte[]), int, int)
    // This portion of the test cannot pass on Windows due to differences in
    // behavior of partial writes.  Windows appears to buffer large amounts of
    // written data and send it all atomically, thus making it impossible to
    // simulate a partial write scenario.  Attempts were made to switch the
    // test from using a pipe to a network socket and also to use larger and
    // larger buffers in doIO.  Nothing helped the situation though.
    if (!Shell.WINDOWS) {
      try {
        out.write(1);
        fail("Did not throw");
      } catch (IOException ioe) {
        GenericTestUtils.assertExceptionContains(
            "stream is closed", ioe);
      }
    }
    
    out.close();
    assertFalse(sink.isOpen());
    
    // close sink and expect -1 from source.read()
    assertEquals(-1, in.read());
    
    // make sure close() closes the underlying channel.
    in.close();
    assertFalse(source.isOpen());
    
  } finally {
    if (source != null) {
      source.close();
    }
    if (sink != null) {
      sink.close();
    }
  }
}
 
Example 11
Source File: ReadPipe.java    From jlibs with Apache License 2.0 4 votes vote down vote up
public ReadPipe(Pipe.SourceChannel selectable) throws IOException{
    super(selectable, null);
}
 
Example 12
Source File: TestSocketIOWithTimeout.java    From RDFS with Apache License 2.0 4 votes vote down vote up
public void testSocketIOWithTimeout() throws IOException {
  
  // first open pipe:
  Pipe pipe = Pipe.open();
  Pipe.SourceChannel source = pipe.source();
  Pipe.SinkChannel sink = pipe.sink();
  
  try {
    InputStream in = new SocketInputStream(source, TIMEOUT);
    OutputStream out = new SocketOutputStream(sink, TIMEOUT);
    
    byte[] writeBytes = TEST_STRING.getBytes();
    byte[] readBytes = new byte[writeBytes.length];
    
    out.write(writeBytes);
    doIO(null, out);
    
    in.read(readBytes);
    assertTrue(Arrays.equals(writeBytes, readBytes));
    doIO(in, null);
    
    /*
     * Verify that it handles interrupted threads properly.
     * Use a large timeout and expect the thread to return quickly.
     */
    in = new SocketInputStream(source, 0);
    Thread thread = new Thread(new ReadRunnable(in));
    thread.start();
    
    try {
      Thread.sleep(1000);
    } catch (InterruptedException ignored) {}
    
    thread.interrupt();
    
    try {
      thread.join();
    } catch (InterruptedException e) {
      throw new IOException("Unexpected InterruptedException : " + e);
    }
    
    //make sure the channels are still open
    assertTrue(source.isOpen());
    assertTrue(sink.isOpen());

    out.close();
    assertFalse(sink.isOpen());
    
    // close sink and expect -1 from source.read()
    assertEquals(-1, in.read());
    
    // make sure close() closes the underlying channel.
    in.close();
    assertFalse(source.isOpen());
    
  } finally {
    if (source != null) {
      source.close();
    }
    if (sink != null) {
      sink.close();
    }
  }
}
 
Example 13
Source File: TestSocketIOWithTimeout.java    From hadoop-gpu with Apache License 2.0 4 votes vote down vote up
public void testSocketIOWithTimeout() throws IOException {
  
  // first open pipe:
  Pipe pipe = Pipe.open();
  Pipe.SourceChannel source = pipe.source();
  Pipe.SinkChannel sink = pipe.sink();
  
  try {
    InputStream in = new SocketInputStream(source, TIMEOUT);
    OutputStream out = new SocketOutputStream(sink, TIMEOUT);
    
    byte[] writeBytes = TEST_STRING.getBytes();
    byte[] readBytes = new byte[writeBytes.length];
    
    out.write(writeBytes);
    doIO(null, out);
    
    in.read(readBytes);
    assertTrue(Arrays.equals(writeBytes, readBytes));
    doIO(in, null);
    
    /*
     * Verify that it handles interrupted threads properly.
     * Use a large timeout and expect the thread to return quickly.
     */
    in = new SocketInputStream(source, 0);
    Thread thread = new Thread(new ReadRunnable(in));
    thread.start();
    
    try {
      Thread.sleep(1000);
    } catch (InterruptedException ignored) {}
    
    thread.interrupt();
    
    try {
      thread.join();
    } catch (InterruptedException e) {
      throw new IOException("Unexpected InterruptedException : " + e);
    }
    
    //make sure the channels are still open
    assertTrue(source.isOpen());
    assertTrue(sink.isOpen());

    out.close();
    assertFalse(sink.isOpen());
    
    // close sink and expect -1 from source.read()
    assertEquals(-1, in.read());
    
    // make sure close() closes the underlying channel.
    in.close();
    assertFalse(source.isOpen());
    
  } finally {
    if (source != null) {
      source.close();
    }
    if (sink != null) {
      sink.close();
    }
  }
}