Java Code Examples for java.nio.channels.Pipe#open()

The following examples show how to use java.nio.channels.Pipe#open() . 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: PackageUtilTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testPackageUploadEventuallySucceeds() throws Exception {
  Pipe pipe = Pipe.open();
  File tmpFile = makeFileWithContents("file.txt", "This is a test!");
  when(mockGcsUtil.getObjects(anyListOf(GcsPath.class)))
      .thenReturn(
          ImmutableList.of(
              StorageObjectOrIOException.create(new FileNotFoundException("some/path"))));
  when(mockGcsUtil.create(any(GcsPath.class), anyString()))
      .thenThrow(new IOException("Fake Exception: 410 Gone")) // First attempt fails
      .thenReturn(pipe.sink()); // second attempt succeeds

  try (PackageUtil directPackageUtil =
      PackageUtil.withExecutorService(MoreExecutors.newDirectExecutorService())) {
    directPackageUtil.stageClasspathElements(
        ImmutableList.of(makeStagedFile(tmpFile.getAbsolutePath())),
        STAGING_PATH,
        fastNanoClockAndSleeper,
        createOptions);
  } finally {
    verify(mockGcsUtil).getObjects(anyListOf(GcsPath.class));
    verify(mockGcsUtil, times(2)).create(any(GcsPath.class), anyString());
    verifyNoMoreInteractions(mockGcsUtil);
  }
}
 
Example 2
Source File: SelectorTest.java    From cava with Apache License 2.0 6 votes vote down vote up
@Test
void selectorRemovesKeysOnChannelCloseWhenSelecting() throws Exception {
  Pipe pipe = Pipe.open();

  Selector selector = Selector.open();
  SelectableChannel source = pipe.source();
  source.configureBlocking(false);

  SelectionKey key = source.register(selector, OP_READ);
  assertTrue(selector.keys().contains(key));

  source.close();
  assertTrue(selector.keys().contains(key));

  selector.selectNow();
  assertFalse(selector.keys().contains(key));
}
 
Example 3
Source File: PipeInterrupt.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public void test() throws Exception {

        Thread tester = new Thread("PipeTester") {
            private Pipe testPipe = null;

            @Override
            public void run() {
                for (;;) {
                    boolean interrupted = this.isInterrupted();
                    try {
                        testPipe = Pipe.open();
                        close();
                        if (interrupted) {
                            if (!this.isInterrupted())
                               exc = new RuntimeException("interrupt status reset");
                            break;
                        }
                    } catch (IOException ioe) {
                        exc = ioe;
                    }
                }
            }

            private void close() throws IOException {
                if (testPipe != null) {
                    testPipe.sink().close();
                    testPipe.source().close();
                }
            }
        };

        tester.start();
        Thread.sleep(200);
        tester.interrupt();
        tester.join();

        if (exc != null)
            throw exc;
    }
 
Example 4
Source File: WindowsSelectorImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
WindowsSelectorImpl(SelectorProvider sp) throws IOException {
    super(sp);
    pollWrapper = new PollArrayWrapper(INIT_CAP);
    wakeupPipe = Pipe.open();
    wakeupSourceFd = ((SelChImpl)wakeupPipe.source()).getFDVal();

    // Disable the Nagle algorithm so that the wakeup is more immediate
    SinkChannelImpl sink = (SinkChannelImpl)wakeupPipe.sink();
    (sink.sc).socket().setTcpNoDelay(true);
    wakeupSinkFd = ((SelChImpl)sink).getFDVal();

    pollWrapper.addWakeupSocket(wakeupSourceFd, 0);
}
 
Example 5
Source File: SelectorTest.java    From cava with Apache License 2.0 5 votes vote down vote up
@Test
void selectorRemovesKeysOnCancelWhileSelecting() throws Exception {
  Pipe pipe = Pipe.open();

  Selector selector = Selector.open();
  SelectableChannel source = pipe.source();
  source.configureBlocking(false);

  SelectionKey key = source.register(selector, OP_READ);
  assertTrue(selector.keys().contains(key));

  CountDownLatch latch = new CountDownLatch(1);
  Future<?> job = executor.submit(() -> {
    latch.countDown();
    try {
      selector.select();
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
  });

  latch.await();
  Thread.sleep(100);

  key.cancel();
  assertTrue(selector.keys().contains(key));
  assertSame(key, source.keyFor(selector));

  selector.wakeup();
  job.get();
  assertFalse(selector.keys().contains(key));
  assertNull(source.keyFor(selector));
}
 
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: WindowsSelectorImpl.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
WindowsSelectorImpl(SelectorProvider sp) throws IOException {
    super(sp);
    pollWrapper = new PollArrayWrapper(INIT_CAP);
    wakeupPipe = Pipe.open();
    wakeupSourceFd = ((SelChImpl)wakeupPipe.source()).getFDVal();

    // Disable the Nagle algorithm so that the wakeup is more immediate
    SinkChannelImpl sink = (SinkChannelImpl)wakeupPipe.sink();
    (sink.sc).socket().setTcpNoDelay(true);
    wakeupSinkFd = ((SelChImpl)sink).getFDVal();

    pollWrapper.addWakeupSocket(wakeupSourceFd, 0);
}
 
Example 8
Source File: FileChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long)
 */
public void test_transferFromLReadableByteChannelJJ_Pipe() throws Exception {
    // inits data in file.
    writeDataToFile(fileOfWriteOnlyFileChannel);

    // inits pipe.
    pipe = Pipe.open();

    // writes content to pipe.
    ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
    pipe.sink().write(writeBuffer);

    // transfers data from pipe to fileChannel.
    final int OFFSET = 2;
    final int LENGTH = 4;
    long result = writeOnlyFileChannel.transferFrom(pipe.source(), OFFSET,
            LENGTH);
    assertEquals(LENGTH, result);
    writeOnlyFileChannel.close();

    // gets content from file.
    fis = new FileInputStream(fileOfWriteOnlyFileChannel);
    byte[] resultBytes = new byte[OFFSET + LENGTH];
    fis.read(resultBytes);

    // compares content.
    byte[] expectedBytes = new byte[OFFSET + LENGTH];
    System.arraycopy(CONTENT_AS_BYTES, 0, expectedBytes, 0, OFFSET);
    System.arraycopy(CONTENT_AS_BYTES, 0, expectedBytes, OFFSET, LENGTH);

    assertTrue(Arrays.equals(expectedBytes, resultBytes));
}
 
Example 9
Source File: RsyncClient.java    From yajsync with GNU General Public License v3.0 5 votes vote down vote up
private static Pipe[] pipePair()
{
    try {
        return new Pipe[] { Pipe.open(), Pipe.open() };
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
Source File: PipeInterrupt.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void test() throws Exception {

        Thread tester = new Thread("PipeTester") {
            private Pipe testPipe = null;

            @Override
            public void run() {
                for (;;) {
                    boolean interrupted = this.isInterrupted();
                    try {
                        testPipe = Pipe.open();
                        close();
                        if (interrupted) {
                            if (!this.isInterrupted())
                               exc = new RuntimeException("interrupt status reset");
                            break;
                        }
                    } catch (IOException ioe) {
                        exc = ioe;
                    }
                }
            }

            private void close() throws IOException {
                if (testPipe != null) {
                    testPipe.sink().close();
                    testPipe.source().close();
                }
            }
        };

        tester.start();
        Thread.sleep(200);
        tester.interrupt();
        tester.join();

        if (exc != null)
            throw exc;
    }
 
Example 11
Source File: WindowsSelectorImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
WindowsSelectorImpl(SelectorProvider sp) throws IOException {
    super(sp);
    pollWrapper = new PollArrayWrapper(INIT_CAP);
    wakeupPipe = Pipe.open();
    wakeupSourceFd = ((SelChImpl)wakeupPipe.source()).getFDVal();

    // Disable the Nagle algorithm so that the wakeup is more immediate
    SinkChannelImpl sink = (SinkChannelImpl)wakeupPipe.sink();
    (sink.sc).socket().setTcpNoDelay(true);
    wakeupSinkFd = ((SelChImpl)sink).getFDVal();

    pollWrapper.addWakeupSocket(wakeupSourceFd, 0);
}
 
Example 12
Source File: PackageUtilTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
public void testPackageUploadWithFileSucceeds() throws Exception {
  Pipe pipe = Pipe.open();
  String contents = "This is a test!";
  File tmpFile = makeFileWithContents("file.txt", contents);
  when(mockGcsUtil.getObjects(anyListOf(GcsPath.class)))
      .thenReturn(
          ImmutableList.of(
              StorageObjectOrIOException.create(new FileNotFoundException("some/path"))));

  when(mockGcsUtil.create(any(GcsPath.class), anyString())).thenReturn(pipe.sink());

  List<DataflowPackage> targets =
      defaultPackageUtil.stageClasspathElements(
          ImmutableList.of(makeStagedFile(tmpFile.getAbsolutePath())),
          STAGING_PATH,
          createOptions);
  DataflowPackage target = Iterables.getOnlyElement(targets);

  verify(mockGcsUtil).getObjects(anyListOf(GcsPath.class));
  verify(mockGcsUtil).create(any(GcsPath.class), anyString());
  verifyNoMoreInteractions(mockGcsUtil);

  assertThat(target.getName(), endsWith(".txt"));
  assertThat(target.getLocation(), equalTo(STAGING_PATH + target.getName()));
  assertThat(
      new LineReader(Channels.newReader(pipe.source(), StandardCharsets.UTF_8.name())).readLine(),
      equalTo(contents));
}
 
Example 13
Source File: WindowsSelectorImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
WindowsSelectorImpl(SelectorProvider sp) throws IOException {
    super(sp);
    pollWrapper = new PollArrayWrapper(INIT_CAP);
    wakeupPipe = Pipe.open();
    wakeupSourceFd = ((SelChImpl)wakeupPipe.source()).getFDVal();

    // Disable the Nagle algorithm so that the wakeup is more immediate
    SinkChannelImpl sink = (SinkChannelImpl)wakeupPipe.sink();
    (sink.sc).socket().setTcpNoDelay(true);
    wakeupSinkFd = ((SelChImpl)sink).getFDVal();

    pollWrapper.addWakeupSocket(wakeupSourceFd, 0);
}
 
Example 14
Source File: PipeInterrupt.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void test() throws Exception {

        Thread tester = new Thread("PipeTester") {
            private Pipe testPipe = null;

            @Override
            public void run() {
                for (;;) {
                    boolean interrupted = this.isInterrupted();
                    try {
                        testPipe = Pipe.open();
                        close();
                        if (interrupted) {
                            if (!this.isInterrupted())
                               exc = new RuntimeException("interrupt status reset");
                            break;
                        }
                    } catch (IOException ioe) {
                        exc = ioe;
                    }
                }
            }

            private void close() throws IOException {
                if (testPipe != null) {
                    testPipe.sink().close();
                    testPipe.source().close();
                }
            }
        };

        tester.start();
        Thread.sleep(200);
        tester.interrupt();
        tester.join();

        if (exc != null)
            throw exc;
    }
 
Example 15
Source File: WindowsSelectorImpl.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
WindowsSelectorImpl(SelectorProvider sp) throws IOException {
    super(sp);
    pollWrapper = new PollArrayWrapper(INIT_CAP);
    wakeupPipe = Pipe.open();
    wakeupSourceFd = ((SelChImpl)wakeupPipe.source()).getFDVal();

    // Disable the Nagle algorithm so that the wakeup is more immediate
    SinkChannelImpl sink = (SinkChannelImpl)wakeupPipe.sink();
    (sink.sc).socket().setTcpNoDelay(true);
    wakeupSinkFd = ((SelChImpl)sink).getFDVal();

    pollWrapper.addWakeupSocket(wakeupSourceFd, 0);
}
 
Example 16
Source File: SourceChannelTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
protected void setUp() throws Exception {
	super.setUp();
	pipe = Pipe.open();
	sink = pipe.sink();
	source = pipe.source();
	buffer = ByteBuffer.wrap("bytes".getBytes(ISO8859_1));
	positionedBuffer = ByteBuffer.wrap("12345bytes".getBytes(ISO8859_1));
	positionedBuffer.position(BUFFER_SIZE);
}
 
Example 17
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 18
Source File: SourceChannelTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer[], int, int)
 */
public void test_read_$LByteBufferII() throws IOException {
    ByteBuffer[] bufArray = { buffer, positionedBuffer };
    boolean[] sinkBlockingMode = { true, true, false, false };
    boolean[] sourceBlockingMode = { true, false, true, false };
    for (int i = 0; i < sinkBlockingMode.length; ++i) {
        Pipe pipe = Pipe.open();
        sink = pipe.sink();
        source = pipe.source();

        sink.configureBlocking(sinkBlockingMode[i]);
        source.configureBlocking(sourceBlockingMode[i]);

        buffer.position(0);
        positionedBuffer.position(BUFFER_SIZE);
        try {
            sink.write(bufArray);
            // invoke close to ensure all data will be sent out
            sink.close();
            // read until EOF is meet or readBufArray is full.
            ByteBuffer[] readBufArray = { ByteBuffer.allocate(BUFFER_SIZE),
                    ByteBuffer.allocate(BUFFER_SIZE) };
            long totalCount = 0;
            do {
                long count = source.read(readBufArray, 0, 2);
                if (count < 0) {
                    break;
                }
                if (0 == count && BUFFER_SIZE == readBufArray[1].position()) {
                    // source.read returns 0 because readBufArray is full
                    break;
                }
                totalCount += count;
            } while (totalCount != 10);

            // assert read result
            for (ByteBuffer readBuf : readBufArray) {
                // RI may fail because of its bug implementation
                assertEquals(BUFFER_SIZE, readBuf.position());
                assertEquals("bytes",
                        new String(readBuf.array(), ISO8859_1));
            }
        } finally {
            sink.close();
            source.close();
        }
    }
}
 
Example 19
Source File: SourceChannelTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer[])
 */
public void test_read_$LByteBuffer() throws IOException {
    ByteBuffer[] bufArray = { buffer, positionedBuffer };
    boolean[] sinkBlockingMode = { true, true, false, false };
    boolean[] sourceBlockingMode = { true, false, true, false };
    for (int i = 0; i < sinkBlockingMode.length; ++i) {
        // open new pipe everytime, will be closed in finally block
        pipe = Pipe.open();
        sink = pipe.sink();
        source = pipe.source();
        sink.configureBlocking(sinkBlockingMode[i]);
        source.configureBlocking(sourceBlockingMode[i]);
        buffer.position(0);
        positionedBuffer.position(BUFFER_SIZE);
        try {
            long writeCount = sink.write(bufArray);
            assertEquals(10, writeCount);
            // invoke close to ensure all data will be sent out
            sink.close();
            // read until EOF is meet or readBufArray is full.
            ByteBuffer[] readBufArray = { ByteBuffer.allocate(BUFFER_SIZE),
                    ByteBuffer.allocate(BUFFER_SIZE) };
            long totalCount = 0;
            do {
                long count = source.read(readBufArray);
                if (count < 0) {
                    break;
                }
                if (0 == count && BUFFER_SIZE == readBufArray[1].position()) {
                    // source.read returns 0 because readBufArray is full
                    break;
                }
                totalCount += count;
            } while (totalCount <= 10);
            // assert read result
            for (ByteBuffer readBuf : readBufArray) {
                // RI may fail because of its bug implementation
                assertEquals(BUFFER_SIZE, readBuf.position());
                assertEquals("bytes",
                        new String(readBuf.array(), ISO8859_1));
            }
        } finally {
            // close pipe everytime
            sink.close();
            source.close();
        }
    }
}
 
Example 20
Source File: Basic.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Pipe p = Pipe.open();
    p.source().close();
    p.sink().close();
}