Java Code Examples for java.io.PipedOutputStream#write()

The following examples show how to use java.io.PipedOutputStream#write() . 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: StreamReaderTest.java    From Ardulink-2 with Apache License 2.0 6 votes vote down vote up
@Test
public void canHandleDataNotAlreadyPresentSeparatedByComma()
		throws Exception {
	List<String> expected = Arrays.asList("a", "b", "c");

	PipedOutputStream os = new PipedOutputStream();
	PipedInputStream is = new PipedInputStream(os);

	StreamReader reader = process(is, ",", expected);

	TimeUnit.SECONDS.sleep(2);
	os.write("a,b,c,".getBytes());

	waitUntil(expected.size());
	assertThat(received, is(expected));
	reader.close();
}
 
Example 2
Source File: ContainerLogWatchTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testLimitInputStreamBytes() throws IOException {
  PipedInputStream inputStream = new PipedInputStream();
  PipedOutputStream outputStream = new PipedOutputStream(inputStream);
  outputStream.write("This is long message that won't fit into the limit.".getBytes());
  outputStream.close();
  logWatch.setInputStream(inputStream);

  ContainerLogWatch clw =
      new ContainerLogWatch(
          client, eventsPublisher, namespace, podname, container, podLogHandler, TIMEOUTS, 4);
  clw.run();

  ArgumentCaptor<String> messageCaptor = ArgumentCaptor.forClass(String.class);
  ArgumentCaptor<String> containerCaptor = ArgumentCaptor.forClass(String.class);
  verify(podLogHandler, times(1)).handle(messageCaptor.capture(), containerCaptor.capture());
  assertEquals(messageCaptor.getValue(), "This");
  assertEquals(containerCaptor.getValue(), container);
  assertTrue(logWatch.isClosed);

  // verify events were properly fired
  verify(eventsPublisher, times(1)).sendWatchLogStartedEvent(any(String.class));
  verify(eventsPublisher, times(1)).sendWatchLogStoppedEvent(any(String.class));
}
 
Example 3
Source File: TestTerminalConnection.java    From aesh-readline with Apache License 2.0 6 votes vote down vote up
@Test
public void testSignal() throws IOException, InterruptedException {
    PipedOutputStream outputStream = new PipedOutputStream();
    PipedInputStream pipedInputStream = new PipedInputStream(outputStream);
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    TerminalConnection connection = new TerminalConnection(Charset.defaultCharset(), pipedInputStream, out);
    Attributes attributes = new Attributes();
    attributes.setLocalFlag(Attributes.LocalFlag.ECHOCTL, true);
    connection.setAttributes(attributes);

    Readline readline = new Readline();
    readline.readline(connection, new Prompt(""), s -> {  });

    connection.openNonBlocking();
    outputStream.write(("FOO").getBytes());
    outputStream.flush();
    Thread.sleep(100);
    connection.getTerminal().raise(Signal.INT);
    connection.close();

    Assert.assertEquals("FOO^C"+ Config.getLineSeparator(), new String(out.toByteArray()));
}
 
Example 4
Source File: StreamPumperTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test public void shouldKnowIfPumperExpired() throws Exception {
    PipedOutputStream output = new PipedOutputStream();
    InputStream inputStream = new PipedInputStream(output);
    try {
        TestingClock clock = new TestingClock();
        StreamPumper pumper = new StreamPumper(inputStream, new TestConsumer(), "", "utf-8", clock);
        new Thread(pumper).start();

        output.write("line1\n".getBytes());
        output.flush();

        long timeoutDuration = 2L;
        assertThat(pumper.didTimeout(timeoutDuration, TimeUnit.SECONDS), is(false));
        clock.addSeconds(5);
        assertThat(pumper.didTimeout(timeoutDuration, TimeUnit.SECONDS), is(true));
    } finally {
        output.close();
    }
}
 
Example 5
Source File: AnyProcessTest.java    From ipc-eventbus with Apache License 2.0 6 votes vote down vote up
@Test
public void pipe_stdin() throws InterruptedException, TimeoutException, ExecutionException, IOException {
  PipedInputStream in = new PipedInputStream();
  PipedOutputStream out = new PipedOutputStream(in);
  AnyProcess proc = AnyProcess.newBuilder()
      .command("bash", "-c", "read input && echo $input")
      .pipeStdout()
      .pipeStderr()
      .pipeStdin(in)
      .recordStderr()
      .recordStdout()
      .build();
  out.write("Hello World!\n".getBytes());
  out.close();
  assertEquals(0, proc.waitFor());
  assertEquals("Hello World!\n", proc.getRecordedStdoutText());
}
 
Example 6
Source File: ChangeLoader.java    From bireme with Apache License 2.0 6 votes vote down vote up
private void tupleWriter(PipedOutputStream pipeOut, Set<String> tuples) throws BiremeException {
  byte[] data = null;

  try {
    Iterator<String> iterator = tuples.iterator();

    while (iterator.hasNext() && !cxt.stop) {
      data = iterator.next().getBytes("UTF-8");
      pipeOut.write(data);
    }

    pipeOut.flush();
  } catch (IOException e) {
    throw new BiremeException("I/O error occurs while write to pipe.", e);
  } finally {
    try {
      pipeOut.close();
    } catch (IOException ignore) {
    }
  }
}
 
Example 7
Source File: StreamReaderTest.java    From Ardulink-2 with Apache License 2.0 6 votes vote down vote up
@Test
public void canHandleDataNotAlreadyPresentSeparatedByNewline()
		throws Exception {
	List<String> expected = Arrays.asList("a", "b", "c");

	PipedOutputStream os = new PipedOutputStream();
	PipedInputStream is = new PipedInputStream(os);

	StreamReader reader = process(is, "\n", expected);

	TimeUnit.SECONDS.sleep(2);
	os.write("a\nb\nc\n".getBytes());

	waitUntil(expected.size());
	assertThat(received, is(expected));
	reader.close();
}
 
Example 8
Source File: TestYarnWatchdog.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testParentWatcher() throws Exception {
  final PipedOutputStream pOut = new PipedOutputStream();
  final PipedInputStream pIn = new PipedInputStream(pOut);
  final YarnWatchdog.ParentWatcher pw = new YarnWatchdog.ParentWatcher(pIn);
  Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
      pw.watchInput();
      logger.info("Parent watcher thread exited");
    }
  });
  t.start();

  t.join(1);
  assertTrue(t.isAlive());

  pOut.write(15);
  t.join(1);
  assertTrue(t.isAlive());

  pOut.close();
  t.join();
  assertFalse(t.isAlive());
}
 
Example 9
Source File: ProcessExecutorInputStreamTest.java    From zt-exec with Apache License 2.0 6 votes vote down vote up
@Test
 public void testDataIsFlushedToProcessWithANonEndingInputStream() throws Exception {
String str = "Tere Minu Uus vihik " + System.nanoTime();

// Setup InputStream that will block on a read()
   PipedOutputStream pos = new PipedOutputStream();
   PipedInputStream pis = new PipedInputStream(pos);
   ByteArrayOutputStream baos = new ByteArrayOutputStream();

   ProcessExecutor exec = new ProcessExecutor("java", "-cp", "target/test-classes", PrintInputToOutput.class.getName());
   exec.redirectInput(pis).redirectOutput(baos);
   StartedProcess startedProcess = exec.start();
   pos.write(str.getBytes());
   pos.write("\n\n\n".getBytes()); // PrintInputToOutput processes at most 3 lines
   
   // Assert that we don't get a TimeoutException
   startedProcess.getFuture().get(5, TimeUnit.SECONDS);
   Assert.assertEquals(str, baos.toString());
 }
 
Example 10
Source File: DownloadSchema.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@ApiResponses({@ApiResponse(code = 200, response = File.class, message = "")})
@GetMapping(path = "/slowInputStream")
public ResponseEntity<InputStream> slowInputStream() throws IOException {
  PipedInputStream in = new PipedInputStream();
  PipedOutputStream out = new PipedOutputStream();
  in.connect(out);

  slowInputStreamThread = new Thread(() -> {
    Thread.currentThread().setName("download thread");
    byte[] bytes = "1".getBytes();
    for (; ; ) {
      try {
        out.write(bytes);
        out.flush();
        Thread.sleep(1000);
      } catch (Throwable e) {
        break;
      }
    }
    try {
      out.close();
    } catch (final IOException ioe) {
      // ignore
    }
  });
  slowInputStreamThread.start();

  ResponseEntity<InputStream> responseEntity = ResponseEntity
      .ok()
      .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE)
      .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=slowInputStream.txt")
      .body(in);
  return responseEntity;
}
 
Example 11
Source File: StreamPumperTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test public void shouldNotHaveExpiredTimeoutWhenCompleted() throws Exception {
    PipedOutputStream output = new PipedOutputStream();
    InputStream inputStream = new PipedInputStream(output);
    TestingClock clock = new TestingClock();
    StreamPumper pumper = new StreamPumper(inputStream, new TestConsumer(), "", "utf-8", clock);
    new Thread(pumper).start();

    output.write("line1\n".getBytes());
    output.flush();
    output.close();
    pumper.readToEnd();
    clock.addSeconds(2);
    assertThat(pumper.didTimeout(1L, TimeUnit.SECONDS), is(false));
}
 
Example 12
Source File: OldPipedOutputStreamTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_flush() throws Exception {
    out = new PipedOutputStream();
    rt = new Thread(reader = new PReader(out));
    rt.start();
    out.write(testString.getBytes(), 0, 10);
    assertTrue("Test 1: Bytes have been written before flush.", reader.available() != 0);
    out.flush();
    assertEquals("Test 2: Flush failed. ",
            testString.substring(0, 10), reader.read(10));
}
 
Example 13
Source File: ClientConnectionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private PipedOutputStream createPipedConnection(final boolean[] success,
                                                final ClientConnection.Listener listener)
                                                throws IOException {
    final boolean[] closed = new boolean[] { false };
    PipedOutputStream pos = new PipedOutputStream() {
        @Override public void close() throws IOException {
            closed[0] = true;
            super.close();
        }
    };
    PipedInputStream pis = new PipedInputStream(pos);
    OutputStream dummyOS = new OutputStream() {
        @Override
        public void write(int b) throws IOException {}
    };
    final ClientConnection cc = new ClientConnection(pis, dummyOS);
    Thread t = new Thread() {
        @Override public void run() {
            try {
                cc.runEventLoop(listener);
            } catch (IOException ex) {
                if (!closed[0]) {
                    ex.printStackTrace();
                    success[0] = false;
                }
            }
        }
    };
    t.start();
    pos.write("Protocol-Version: 1\r\n".getBytes());
    return pos;
}
 
Example 14
Source File: ContainerLogWatchTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testCloseOfOutputStream() throws IOException, InterruptedException {
  PipedInputStream inputStream = new PipedInputStream();
  PipedOutputStream outputStream = new PipedOutputStream(inputStream);
  outputStream.write("message\n".getBytes());
  logWatch.setInputStream(inputStream);

  CountDownLatch messageHandleLatch = new CountDownLatch(1);
  doAnswer(
          (a) -> {
            messageHandleLatch.countDown();
            return null;
          })
      .when(podLogHandler)
      .handle("message", container);

  ContainerLogWatch clw =
      new ContainerLogWatch(
          client,
          eventsPublisher,
          namespace,
          podname,
          container,
          podLogHandler,
          TIMEOUTS,
          LOG_LIMIT_BYTES);
  new Thread(clw).start();

  messageHandleLatch.await(1, TimeUnit.SECONDS);
  outputStream.close();

  CountDownLatch closeLatch = new CountDownLatch(1);
  logWatch.setLatch(closeLatch);
  closeLatch.await(1, TimeUnit.SECONDS);
  assertTrue(logWatch.isClosed);

  // verify events were properly fired
  verify(eventsPublisher, times(1)).sendWatchLogStartedEvent(any(String.class));
  verify(eventsPublisher, timeout(1000).times(1)).sendWatchLogStoppedEvent(any(String.class));
}
 
Example 15
Source File: ContainerLogWatchTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testSuccessfulFinishedContainerLogWatch() throws IOException {
  PipedInputStream inputStream = new PipedInputStream();
  PipedOutputStream outputStream = new PipedOutputStream(inputStream);
  outputStream.write("first\nsecond".getBytes());
  outputStream.write("\nthird".getBytes());
  outputStream.close();
  logWatch.setInputStream(inputStream);

  ContainerLogWatch clw =
      new ContainerLogWatch(
          client,
          eventsPublisher,
          namespace,
          podname,
          container,
          podLogHandler,
          TIMEOUTS,
          LOG_LIMIT_BYTES);
  clw.run();

  verify(podLogHandler).handle("first", container);
  verify(podLogHandler).handle("second", container);
  verify(podLogHandler).handle("third", container);
  assertTrue(logWatch.isClosed);

  // verify events were properly fired
  verify(eventsPublisher, times(1)).sendWatchLogStartedEvent(any(String.class));
  verify(eventsPublisher, times(1)).sendWatchLogStoppedEvent(any(String.class));
}
 
Example 16
Source File: OldAndroidPipedStreamTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testC() throws Exception {
    final PipedInputStream in = new PipedInputStream();
    final PipedOutputStream out = new PipedOutputStream(in);
    final byte readBytes[] = new byte[1024 * 2];

    assertEquals(0, in.available());

    TestThread reader, writer;

    reader = new TestThread() {
        @Override
        public void runTest() throws Exception {
            int ret;

            for (; ;) {
                int nread = 0;
                while (nread < readBytes.length) {
                    ret = in.read(readBytes, nread, readBytes.length - nread);

                    if (ret == -1) {
                        return;
                    }
                    nread += ret;
                }
            }
        }
    };

    reader.start();

    writer = new TestThread() {
        Fibonacci fib = new Fibonacci();

        @Override
        public void runTest() throws Exception {
            byte writeBytes[] = new byte[1024 * 2];
            for (int i = 0; i < (writeBytes.length - 4); i += 4) {
                int toWrite = fib.next();
                writeBytes[i    ] = (byte) (toWrite >> 24);
                writeBytes[i + 1] = (byte) (toWrite >> 16);
                writeBytes[i + 2] = (byte) (toWrite >> 8);
                writeBytes[i + 3] = (byte) (toWrite);
            }
            out.write(writeBytes, 0, writeBytes.length);
            out.close();
        }
    };

    writer.start();


    for (; ;) {
        try {
            reader.join(60 * 1000);
            writer.join(1000);
            break;
        } catch (InterruptedException ex) {
        }
    }

    if (reader.exception != null) {
        throw new Exception(reader.exception);
    }
    if (writer.exception != null) {
        throw new Exception(writer.exception);
    }

    Fibonacci fib = new Fibonacci();
    for (int i = 0; i < (readBytes.length - 4); i += 4) {
        int readInt = (((int) readBytes[i] & 0xff) << 24)
                | (((int) readBytes[i + 1] & 0xff) << 16)
                | (((int) readBytes[i + 2] & 0xff) << 8)
                | (((int) readBytes[i + 3] & 0xff));

        assertEquals("Error at " + i, readInt, fib.next());
    }
}
 
Example 17
Source File: TarGenerator.java    From evosql with Apache License 2.0 4 votes vote down vote up
/**
 * After instantiating a TarEntrySupplicant, the user must either invoke
 * write() or close(), to release system resources on the input
 * File/Stream.
 * <P>
 * <B>WARNING:</B>
 * Do not use this method unless the quantity of available RAM is
 * sufficient to accommodate the specified maxBytes all at one time.
 * This constructor loads all input from the specified InputStream into
 * RAM before anything is written to disk.
 * </P>
 *
 * @param maxBytes This method will fail if more than maxBytes bytes
 *                 are supplied on the specified InputStream.
 *                 As the type of this parameter enforces, the max
 *                 size you can request is 2GB.
 */
public TarEntrySupplicant(String path, InputStream origStream,
                          int maxBytes, char typeFlag,
                          TarFileOutputStream tarStream)
        throws IOException, TarMalformatException {

    /*
     * If you modify this, make sure to not intermix reading/writing of
     * the PipedInputStream and the PipedOutputStream, or you could
     * cause dead-lock.  Everything is safe if you close the
     * PipedOutputStream before reading the PipedInputStream.
     */
    this(path, typeFlag, tarStream, 0100000000000L);

    if (maxBytes < 1) {
        throw new IllegalArgumentException(RB.read_lt_1.getString());
    }

    int               i;
    PipedOutputStream outPipe = new PipedOutputStream();

    /*
     *  This constructor not available until Java 1.6:
     * inputStream = new PipedInputStream(outPipe, maxBytes);
     */
    try {
        inputStream =
            new InputStreamWrapper(new PipedInputStream(outPipe));

        while ((i =
                origStream.read(tarStream.writeBuffer, 0,
                                tarStream.writeBuffer.length)) > 0) {
            outPipe.write(tarStream.writeBuffer, 0, i);
        }

        outPipe.flush();    // Do any good on a pipe?
        dataSize = inputStream.available();

        if (TarFileOutputStream.debug) {
            System.out.println(
                RB.stream_buffer_report.getString(
                    Long.toString(dataSize)));
        }
    } catch (IOException ioe) {
        close();

        throw ioe;
    } finally {
        try {
            outPipe.close();
        } finally {
            outPipe = null;    // Encourage buffer GC
        }
    }

    modTime = new java.util.Date().getTime() / 1000L;
}
 
Example 18
Source File: ContainerLogWatchTest.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void shouldRetryWhenOutputIsNullFirst() throws IOException, InterruptedException {
  logWatch.setInputStream(null);

  LogWatchMock logWatchRegularMessage = new LogWatchMock();
  // prepare regular message logwatch
  PipedInputStream inputStream = new PipedInputStream();
  PipedOutputStream outputStream = new PipedOutputStream(inputStream);
  outputStream.write("message\n".getBytes());
  outputStream.close();
  logWatchRegularMessage.setInputStream(inputStream);
  CountDownLatch messageHandleLatch = new CountDownLatch(2);
  logWatchRegularMessage.setLatch(messageHandleLatch);
  doAnswer(
          (a) -> {
            messageHandleLatch.countDown();
            return null;
          })
      .when(podLogHandler)
      .handle("message", container);

  // return null stream first and regular message stream on second call
  when(pods.watchLog()).thenReturn(logWatch).thenReturn(logWatchRegularMessage);

  ContainerLogWatch clw =
      new ContainerLogWatch(
          client,
          eventsPublisher,
          namespace,
          podname,
          container,
          podLogHandler,
          TIMEOUTS,
          LOG_LIMIT_BYTES);
  new Thread(clw).start();

  // wait for logwatch close, it means that error message was processed
  CountDownLatch closeLatch = new CountDownLatch(1);
  logWatch.setLatch(closeLatch);
  closeLatch.await(1, TimeUnit.SECONDS);
  assertTrue(logWatch.isClosed);

  // wait for regular message
  messageHandleLatch.await(1, TimeUnit.SECONDS);

  // message was processed
  verify(podLogHandler).handle("message", container);
  assertTrue(logWatchRegularMessage.isClosed);

  // verify events were properly fired
  verify(eventsPublisher, times(2)).sendWatchLogStartedEvent(any(String.class));
  verify(eventsPublisher, timeout(1000).times(2)).sendWatchLogStoppedEvent(any(String.class));
}
 
Example 19
Source File: OldAndroidPipedStreamTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testA() throws Exception {

        final PipedInputStream in = new PipedInputStream();
        final PipedOutputStream out = new PipedOutputStream(in);

        assertEquals(0, in.available());

        TestThread reader, writer;

        reader = new TestThread() {
            Fibonacci fib = new Fibonacci();

            @Override
            public void runTest() throws Exception {
                int readInt;
                byte readByte;

                for (; ;) {
                    readInt = in.read();

                    if (readInt == -1) {
                        return;
                    }

                    readByte = (byte) readInt;
                    assertEquals(readByte, (byte) fib.next());
                    countRead++;
                }
            }
        };

        reader.start();

        writer = new TestThread() {
            Fibonacci fib = new Fibonacci();

            @Override
            public void runTest() throws Exception {
                for (int i = 0; i < 2000; i++) {
                    int toWrite = fib.next();
                    out.write(toWrite);
                }
                out.close();
            }
        };

        writer.start();


        for (; ;) {
            try {
                reader.join(60 * 1000);
                writer.join(1000);
                break;
            } catch (InterruptedException ex) {
            }
        }

        assertEquals(2000, reader.countRead);

        if (writer.exception != null) {
            throw new Exception(writer.exception);
        }
        if (reader.exception != null) {
            throw new Exception(reader.exception);
        }
    }
 
Example 20
Source File: SpeechToTextTest.java    From java-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Test closing input stream closes web socket.
 *
 * @throws Exception the exception
 */
@Test
public void testClosingInputStreamClosesWebSocket() throws Exception {
  TestRecognizeCallback callback = new TestRecognizeCallback();
  WebSocketRecorder webSocketRecorder = new WebSocketRecorder("server");
  PipedOutputStream outputStream = new PipedOutputStream();
  InputStream inputStream = new PipedInputStream(outputStream);

  server.enqueue(new MockResponse().withWebSocketUpgrade(webSocketRecorder));

  String customizationId = "id";
  String version = "version";
  Double customizationWeight = 0.1;
  RecognizeOptions options =
      new RecognizeOptions.Builder()
          .audio(inputStream)
          .contentType(HttpMediaType.createAudioRaw(44000))
          .customizationId(customizationId)
          .baseModelVersion(version)
          .customizationWeight(customizationWeight)
          .build();
  service.recognizeUsingWebSocket(options, callback);

  WebSocket serverSocket = webSocketRecorder.assertOpen();
  serverSocket.send("{\"state\": {}}");

  outputStream.write(ByteString.encodeUtf8("test").toByteArray());
  outputStream.close();

  webSocketRecorder.assertTextMessage(
      "{\"content-type\":\"audio/l16; rate=44000\","
          + "\"customization_weight\":0.1,\"action\":\"start\"}");
  webSocketRecorder.assertBinaryMessage(ByteString.encodeUtf8("test"));
  webSocketRecorder.assertTextMessage("{\"action\":\"stop\"}");
  webSocketRecorder.assertExhausted();

  serverSocket.close(1000, null);

  callback.assertConnected();
  callback.assertDisconnected();
  callback.assertNoErrors();
  callback.assertOnTranscriptionComplete();
}