List of usage examples for java.io PipedOutputStream write
public void write(int b) throws IOException
byte
to the piped output stream. From source file:Main.java
public static void main(String[] args) throws Exception { PipedOutputStream out = new PipedOutputStream(); PipedInputStream in = new PipedInputStream(); // connect input and output in.connect(out);//from ww w. j a v a 2 s . c o m // write something out.write(70); out.write(71); // print how many bytes are available System.out.println(in.available()); // read what we wrote for (int i = 0; i < 2; i++) { System.out.println("" + (char) in.read()); } in.close(); }
From source file:Main.java
public static void produceData(PipedOutputStream pos) { try {//from w w w .java 2 s . c o m for (int i = 1; i <= 50; i++) { pos.write((byte) i); pos.flush(); System.out.println("Writing: " + i); Thread.sleep(500); } pos.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.xebialabs.overthere.cifs.telnet.CifsTelnetConnection.java
private static void handleReceivedLine(final ByteArrayOutputStream outputBuf, final String outputBufStr, final PipedOutputStream toCallersStdout) throws IOException { if (!outputBufStr.contains(DETECTABLE_WINDOWS_PROMPT)) { toCallersStdout.write(outputBuf.toByteArray()); toCallersStdout.flush();/*from w w w. j av a2 s .c o m*/ } outputBuf.reset(); }
From source file:com.github.vatbub.awsvpnlauncher.Main.java
/** * Copies {@code System.in} to new {@code InputStream}. Filters {@code CrLf}s ({@code \r\n} in Java) out and replaces them with a single {@code \n} ({@code \n} in Java) * * @return The {@code InputStream} to which the filtered contents are forwarded to. * @throws IOException If {@code System.in} cannot be read for any reason *//*from w w w .j a v a2 s . c o m*/ private static InputStream copyAndFilterInputStream() throws IOException { PipedOutputStream forwardTo = new PipedOutputStream(); PipedInputStream res = new PipedInputStream(forwardTo); Thread pipeThread = new Thread(() -> { while (true) { try { char ch = (char) System.in.read(); if (ch != '\r' && !SystemUtils.IS_OS_MAC) { forwardTo.write((int) ch); } } catch (IOException e) { FOKLogger.log(Main.class.getName(), Level.SEVERE, "Stopped forwarding System in due to an exception", e); break; } } }); pipeThread.setName("pipeThread"); pipeThread.start(); return res; }
From source file:de.resol.vbus.LiveInputStreamTest.java
@Test public void testReadHeader() throws Exception { byte[] refPacketBuffer1 = Hex.decodeHex( "aa362335331034430d2a0004080c00671014181c00272024282c00673034383c00274044484c00675054585c00276064686c00677074787c00270004080c0f581014181c0f182024282c0f583034383c0f184044484c0f58" .toCharArray());//from w w w. j a v a2 s. co m byte[] refDgramBuffer1 = Hex.decodeHex("aa362335332034433353300332630851".toCharArray()); byte[] refTgramBuffer1 = Hex .decodeHex("aa2211443330772e000c1824303c48000354606c7804101c70472834404c5864707f6c".toCharArray()); byte[] refZeroBuffer1 = Hex.decodeHex("00000000000000000000000000000000".toCharArray()); byte[] refMsbBuffer1 = Hex.decodeHex("80808080808080808080808080808080".toCharArray()); String refPacketId1 = "13_2336_3335_10_4334"; String refDgramId1 = "13_2336_3335_20_4334_0000"; String refTgramId1 = "13_1122_3344_30_77"; PipedInputStream refIs1 = new PipedInputStream(2048); PipedOutputStream refOs1 = new PipedOutputStream(refIs1); int refChannel1 = 0x13; LiveInputStream testIs = new LiveInputStream(refIs1, refChannel1); refOs1.write(refPacketBuffer1); assertEquals(refPacketId1, testIs.readHeader().getId()); refOs1.write(refDgramBuffer1); refOs1.write(refTgramBuffer1); assertEquals(refDgramId1, testIs.readHeader().getId()); assertEquals(refTgramId1, testIs.readHeader().getId()); // write a partial header (before protocol version) refOs1.write(refTgramBuffer1); refOs1.write(refDgramBuffer1, 0, 5); assertEquals(refTgramId1, testIs.readHeader().getId()); refOs1.write(refDgramBuffer1, 5, 11); assertEquals(refDgramId1, testIs.readHeader().getId()); // write a broken header (without sync byte) refOs1.write(refDgramBuffer1, 1, 15); refOs1.write(refTgramBuffer1); assertEquals(refTgramId1, testIs.readHeader().getId()); // write unknown version refOs1.write(refDgramBuffer1, 0, 5); refOs1.write(0x05); refOs1.write(refTgramBuffer1); assertEquals(refTgramId1, testIs.readHeader().getId()); // write partial packet (incomplete header) refOs1.write(refDgramBuffer1); refOs1.write(refPacketBuffer1, 0, 9); assertEquals(refDgramId1, testIs.readHeader().getId()); refOs1.write(refPacketBuffer1, 9, refPacketBuffer1.length - 9); assertEquals(refPacketId1, testIs.readHeader().getId()); // write defect packet (header msb) refOs1.write(refPacketBuffer1, 0, 9); refOs1.write(refMsbBuffer1, 0, 1); refOs1.write(refDgramBuffer1); assertEquals(refDgramId1, testIs.readHeader().getId()); // write defect packet (header checksum) refOs1.write(refPacketBuffer1, 0, 9); refOs1.write(refZeroBuffer1, 0, 1); refOs1.write(refDgramBuffer1); assertEquals(refDgramId1, testIs.readHeader().getId()); // write partial packet (incomplete frame data) refOs1.write(refDgramBuffer1); refOs1.write(refPacketBuffer1, 0, 15); assertEquals(refDgramId1, testIs.readHeader().getId()); refOs1.write(refPacketBuffer1, 15, refPacketBuffer1.length - 15); assertEquals(refPacketId1, testIs.readHeader().getId()); // write defect packet (frame data msb) refOs1.write(refPacketBuffer1, 0, refPacketBuffer1.length - 1); refOs1.write(refMsbBuffer1, 0, 1); refOs1.write(refDgramBuffer1); assertEquals(refDgramId1, testIs.readHeader().getId()); // write partial datagram refOs1.write(refTgramBuffer1); refOs1.write(refDgramBuffer1, 0, 15); assertEquals(refTgramId1, testIs.readHeader().getId()); refOs1.write(refDgramBuffer1, 15, refDgramBuffer1.length - 15); assertEquals(refDgramId1, testIs.readHeader().getId()); // write defect datagram refOs1.write(refDgramBuffer1, 0, 15); refOs1.write(refMsbBuffer1, 0, 1); refOs1.write(refTgramBuffer1); assertEquals(refTgramId1, testIs.readHeader().getId()); // write partial telegram (incomplete header) refOs1.write(refDgramBuffer1); refOs1.write(refTgramBuffer1, 0, 7); assertEquals(refDgramId1, testIs.readHeader().getId()); refOs1.write(refTgramBuffer1, 7, refTgramBuffer1.length - 7); assertEquals(refTgramId1, testIs.readHeader().getId()); // write defect telegram (header msb) refOs1.write(refTgramBuffer1, 0, 7); refOs1.write(refMsbBuffer1, 0, 1); refOs1.write(refDgramBuffer1); assertEquals(refDgramId1, testIs.readHeader().getId()); // write defect telegram (header checksum) refOs1.write(refTgramBuffer1, 0, 7); refOs1.write(refZeroBuffer1, 0, 1); refOs1.write(refDgramBuffer1); assertEquals(refDgramId1, testIs.readHeader().getId()); // write partial telegram (incomplete frame data) refOs1.write(refDgramBuffer1); refOs1.write(refTgramBuffer1, 0, 15); assertEquals(refDgramId1, testIs.readHeader().getId()); refOs1.write(refTgramBuffer1, 15, refTgramBuffer1.length - 15); assertEquals(refTgramId1, testIs.readHeader().getId()); // write defect telegram (frame data msb) refOs1.write(refTgramBuffer1, 0, refTgramBuffer1.length - 1); refOs1.write(refMsbBuffer1, 0, 1); refOs1.write(refDgramBuffer1); assertEquals(refDgramId1, testIs.readHeader().getId()); // close pipe refOs1.close(); assertEquals(null, testIs.readHeader()); }
From source file:edu.umn.msi.tropix.common.io.impl.AsyncStreamCopierImplTest.java
@Test(groups = "unit", timeOut = 1000, invocationCount = 10) public void close() throws IOException, InterruptedException { final AsyncStreamCopierImpl copier = new AsyncStreamCopierImpl(); final Reference<Thread> threadReference = new Reference<Thread>(); final Reference<Throwable> throwableReference = new Reference<Throwable>(); copier.setExecutor(new Executor() { public void execute(final Runnable runnable) { final Thread thread = new Thread(runnable); threadReference.set(thread); thread.start();/*from w w w .j ava 2 s . com*/ thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(final Thread arg0, final Throwable throwable) { throwableReference.set(throwable); } }); } }); final PipedOutputStream pipedOutputStream = new PipedOutputStream(); final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream); final ByteArrayOutputStream copiedStream = new ByteArrayOutputStream(); copier.copy(pipedInputStream, copiedStream, true); Thread.sleep(3); assert new String(copiedStream.toByteArray()).equals(""); pipedOutputStream.write("Hello ".getBytes()); pipedOutputStream.flush(); while (!new String(copiedStream.toByteArray()).equals("Hello ")) { Thread.sleep(1); } pipedOutputStream.write("World!".getBytes()); pipedOutputStream.flush(); while (!new String(copiedStream.toByteArray()).equals("Hello World!")) { Thread.sleep(1); } assert threadReference.get().isAlive(); pipedOutputStream.close(); while (threadReference.get().isAlive()) { Thread.sleep(1); } assert throwableReference.get() == null; }
From source file:org.onebusaway.nyc.webapp.actions.admin.ReportingAction.java
public String submit() throws Exception { Session session = null;//from w w w . ja v a 2 s . co m Connection connection = null; Statement statement = null; ResultSet rs = null; try { session = sessionFactory.openSession(); connection = getConnectionFromSession(session); connection.setReadOnly(true); statement = connection.createStatement(); rs = statement.executeQuery(query); } catch (Exception e) { // make sure everything is closed if an exception was thrown try { rs.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } try { session.close(); } catch (Exception ex) { } reportError = e.getMessage(); // not really "success", but we'll use the same template with the error displayed return SUCCESS; } // final so the output generator thread can close it final Session finalSession = session; final Connection finalConnection = connection; final Statement finalStatement = statement; final ResultSet finalRS = rs; final PipedInputStream pipedInputStream = new PipedInputStream(); final PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream); executorService.execute(new Runnable() { @Override public void run() { try { // column labels ResultSetMetaData metaData = finalRS.getMetaData(); int columnCount = metaData.getColumnCount(); for (int i = 0; i < columnCount; i++) { String columnName = metaData.getColumnName(i + 1); byte[] bytes = columnName.getBytes(); if (i > 0) pipedOutputStream.write(columnDelimiter); pipedOutputStream.write(bytes); } pipedOutputStream.write(newline); // column values while (finalRS.next()) { for (int i = 0; i < columnCount; i++) { String value = finalRS.getString(i + 1); if (value == null) value = "null"; else { // remove returns value = value.replaceAll("\n|\r", ""); } byte[] valueBytes = value.getBytes(); if (i > 0) pipedOutputStream.write(columnDelimiter); pipedOutputStream.write(valueBytes); } pipedOutputStream.write(newline); } } catch (Exception e) { } finally { try { pipedOutputStream.close(); } catch (IOException e) { } try { finalRS.close(); } catch (SQLException e) { } try { finalStatement.close(); } catch (SQLException e) { } try { finalConnection.close(); } catch (SQLException e) { } try { finalSession.close(); } catch (Exception e) { } } } }); // the input stream will get populated by the piped output stream inputStream = pipedInputStream; return "download"; }
From source file:gov.vha.isaac.rf2.filter.RF2Filter.java
private void handleFile(Path inputFile, Path outputFile) throws IOException { boolean justCopy = true; boolean justSkip = false; if (inputFile.toFile().getName().toLowerCase().endsWith(".txt")) { justCopy = false;//from www .j av a2s . c o m //Filter the file BufferedReader fileReader = new BufferedReader( new InputStreamReader(new BOMInputStream(new FileInputStream(inputFile.toFile())), "UTF-8")); BufferedWriter fileWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outputFile.toFile()), "UTF-8")); PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(pos); CSVReader csvReader = new CSVReader(new InputStreamReader(pis), '\t', CSVParser.NULL_CHARACTER); //don't look for quotes, the data is bad, and has floating instances of '"' all by itself boolean firstLine = true; String line = null; long kept = 0; long skipped = 0; long total = 0; int moduleColumn = -1; while ((line = fileReader.readLine()) != null) { total++; //Write this line into the CSV parser pos.write(line.getBytes()); pos.write("\r\n".getBytes()); pos.flush(); String[] fields = csvReader.readNext(); boolean correctModule = false; for (String ms : moduleStrings_) { if (moduleColumn >= 0 && fields[moduleColumn].equals(ms)) { correctModule = true; break; } } if (firstLine || correctModule) { kept++; fileWriter.write(line); fileWriter.write("\r\n"); } else { //don't write line skipped++; } if (firstLine) { log("Filtering file " + inputDirectory.toPath().relativize(inputFile).toString()); firstLine = false; if (fields.length < 2) { log("txt file doesn't look like a data file - abort and just copy."); justCopy = true; break; } for (int i = 0; i < fields.length; i++) { if (fields[i].equals("moduleId")) { moduleColumn = i; break; } } if (moduleColumn < 0) { log("No moduleId column found - skipping file"); justSkip = true; break; } } } fileReader.close(); csvReader.close(); fileWriter.close(); if (!justCopy) { log("Kept " + kept + " Skipped " + skipped + " out of " + total + " lines in " + inputDirectory.toPath().relativize(inputFile).toString()); } } if (justCopy) { //Just copy the file Files.copy(inputFile, outputFile, StandardCopyOption.REPLACE_EXISTING); log("Copied file " + inputDirectory.toPath().relativize(inputFile).toString()); } if (justSkip) { Files.delete(outputFile); log("Skipped file " + inputDirectory.toPath().relativize(inputFile).toString() + " because it doesn't contain a moduleId"); } }
From source file:ch.cyberduck.core.cryptomator.features.CryptoChecksumCompute.java
protected Checksum compute(final InputStream in, final long offset, final ByteBuffer header, final NonceGenerator nonces) throws ChecksumException { if (log.isDebugEnabled()) { log.debug(String.format("Calculate checksum with header %s", header)); }//w ww . j a v a 2 s . co m try { final PipedOutputStream source = new PipedOutputStream(); final CryptoOutputStream<Void> out = new CryptoOutputStream<Void>(new VoidStatusOutputStream(source), cryptomator.getCryptor(), cryptomator.getCryptor().fileHeaderCryptor().decryptHeader(header), nonces, cryptomator.numberOfChunks(offset)); final PipedInputStream sink = new PipedInputStream(source, PreferencesFactory.get().getInteger("connection.chunksize")); final ThreadPool pool = ThreadPoolFactory.get("checksum", 1); try { final Future execute = pool.execute(new Callable<TransferStatus>() { @Override public TransferStatus call() throws Exception { if (offset == 0) { source.write(header.array()); } final TransferStatus status = new TransferStatus(); new StreamCopier(status, status).transfer(in, out); return status; } }); try { return delegate.compute(sink, new TransferStatus()); } finally { try { execute.get(); } catch (InterruptedException e) { throw new ChecksumException(LocaleFactory.localizedString("Checksum failure", "Error"), e.getMessage(), e); } catch (ExecutionException e) { if (e.getCause() instanceof BackgroundException) { throw (BackgroundException) e.getCause(); } throw new DefaultExceptionMappingService().map(e.getCause()); } } } finally { pool.shutdown(true); } } catch (ChecksumException e) { throw e; } catch (IOException | BackgroundException e) { throw new ChecksumException(LocaleFactory.localizedString("Checksum failure", "Error"), e.getMessage(), e); } }
From source file:org.apache.tajo.cli.tsql.TestTajoCli.java
License:asdf
@Test public void testRunWhenError() throws Exception { Thread t = new Thread() { public void run() { try { PipedOutputStream po = new PipedOutputStream(); InputStream is = new PipedInputStream(po); ByteArrayOutputStream out = new ByteArrayOutputStream(); TajoConf tajoConf = new TajoConf(); setVar(tajoCli, SessionVars.CLI_FORMATTER_CLASS, TajoCliOutputTestFormatter.class.getName()); Properties connParams = new Properties(); connParams.setProperty(ClientParameters.RETRY, "3"); TajoCli tc = new TajoCli(tajoConf, new String[] {}, connParams, is, out, err); tc.executeMetaCommand("\\set ON_ERROR_STOP false"); assertSessionVar(tc, SessionVars.ON_ERROR_STOP.keyname(), "false"); po.write(new String("asdf;\nqwe;\nzxcv;\n").getBytes()); tc.runShell();//from ww w . j a va 2s . co m } catch (Exception e) { throw new RuntimeException("Cannot run thread in testRunWhenError", e); } } }; t.start(); Thread.sleep(1000); if (!t.isAlive()) { fail("TSQL should be alive"); } else { t.interrupt(); t.join(); } }