List of usage examples for java.io PipedOutputStream close
public void close() throws IOException
From source file:org.liveSense.service.email.EmailServiceImpl.java
/** * {@inheritDoc}/* w w w . jav a 2 s . c om*/ */ @Override public void sendEmail(Session session, final MimeMessage message) throws Exception { boolean haveSession = false; try { if (session != null && session.isLive()) { haveSession = true; } else { session = repository.loginAdministrative(null); } // Store mail to Spool folder Node mailNode = session.getRootNode().getNode(spoolFolder).addNode(UUID.randomUUID().toString(), nodeType); mailNode = mailNode.addNode(propertyName, "nt:resource"); PipedInputStream in = new PipedInputStream(); final PipedOutputStream out = new PipedOutputStream(in); new Thread(new Runnable() { @Override public void run() { try { message.writeTo(out); out.close(); } catch (IOException e) { log.error("Could not write mail message stream", e); } catch (MessagingException e) { log.error("Could not write mail message stream", e); } } }).start(); BinaryValue bv = null; try { bv = new BinaryValue(in); } catch (IllegalArgumentException e) { // The jackrabbit closes the PipedInputStream, thats incorrect } if (bv != null) { mailNode.setProperty("jcr:data", bv); } mailNode.setProperty("jcr:lastModified", Calendar.getInstance()); mailNode.setProperty("jcr:mimeType", "message/rfc822"); } catch (Exception ex) { log.error("Cannot create mail: ", ex); throw ex; } finally { if (!haveSession && session != null) { if (session.hasPendingChanges()) try { session.save(); } catch (Throwable th) { } session.logout(); } } }
From source file:org.lockss.util.TestStreamUtil.java
public void testReadBufShortRead() throws Exception { byte[] snd1 = { '0', '1', 0, '3' }; final int len = 12; final byte[] buf = new byte[len]; PipedOutputStream outs = new PipedOutputStream(); final InputStream ins = new PipedInputStream(outs); final Exception[] ex = { null }; final int[] res = { 0 }; Thread th = new Thread() { public void run() { try { res[0] = StreamUtil.readBytes(ins, buf, len); StreamUtil.readBytes(ins, buf, len); } catch (IOException e) { ex[0] = e;/*from w w w . jav a2 s . c o m*/ } } }; th.start(); outs.write(snd1); outs.close(); th.join(); assertEquals(snd1.length, res[0]); assertEquals(null, ex[0]); }
From source file:org.lockss.util.TestStreamUtil.java
public void testReadBufMultipleRead() throws Exception { byte[] snd1 = { '0', '1', 0, '3' }; byte[] snd2 = { '4', '5', '6', '7', '8', '9', 'a', 'b' }; byte[] exp = { '0', '1', 0, '3', '4', '5', '6', '7', '8', '9', 'a', 'b' }; final int len = exp.length; final byte[] buf = new byte[len]; PipedOutputStream outs = new PipedOutputStream(); final InputStream ins = new PipedInputStream(outs); final Exception[] ex = { null }; final int[] res = { 0 }; Thread th = new Thread() { public void run() { try { res[0] = StreamUtil.readBytes(ins, buf, len); } catch (IOException e) { ex[0] = e;/*w ww .ja va 2 s. c o m*/ } } }; th.start(); outs.write(snd1); TimerUtil.guaranteedSleep(100); outs.write(snd2); outs.flush(); th.join(); assertEquals(exp, buf); assertEquals(len, res[0]); assertNull(ex[0]); outs.close(); }
From source file:org.rhq.enterprise.server.plugins.alertCli.CliSender.java
private static InputStream getPackageBits(int packageId, int repoId) throws IOException { final ContentSourceManagerLocal csm = LookupUtil.getContentSourceManager(); RepoManagerLocal rm = LookupUtil.getRepoManagerLocal(); final PackageVersion versionToUse = rm.getLatestPackageVersion(LookupUtil.getSubjectManager().getOverlord(), packageId, repoId);// ww w .jav a2 s .c o m if (versionToUse == null) { throw new IllegalArgumentException("The package with id " + packageId + " either doesn't exist at all or doesn't have any version. Can't execute a CLI script without a script to run."); } PipedInputStream ret = new PipedInputStream(); final PipedOutputStream out = new PipedOutputStream(ret); Thread reader = new Thread(new Runnable() { public void run() { try { csm.outputPackageVersionBits(versionToUse, out); } catch (RuntimeException e) { LOG.warn("The thread for reading the bits of package version [" + versionToUse + "] failed with exception.", e); throw e; } finally { try { out.close(); } catch (IOException e) { //doesn't happen in piped output stream LOG.error( "Failed to close the piped output stream receiving the package bits of package version " + versionToUse + ". This should never happen.", e); } } } }); reader.setName("CLI Alert download thread for package version " + versionToUse); reader.setDaemon(true); reader.start(); return ret; }
From source file:org.sonar.scanner.report.ReportPublisherTest.java
@Test public void test_ws_parameters() throws Exception { ReportPublisher underTest = new ReportPublisher(settings, wsClient, server, contextPublisher, reactor, mode, mock(TempFolder.class), new ReportPublisherStep[0]); settings.setProperty(CoreProperties.PROJECT_ORGANIZATION_PROPERTY, "MyOrg"); WsResponse response = mock(WsResponse.class); PipedOutputStream out = new PipedOutputStream(); PipedInputStream in = new PipedInputStream(out); WsCe.SubmitResponse.newBuilder().build().writeTo(out); out.close(); when(response.failIfNotSuccessful()).thenReturn(response); when(response.contentStream()).thenReturn(in); when(wsClient.call(any(WsRequest.class))).thenReturn(response); underTest.upload(temp.newFile());//from w w w.j a v a 2 s. c o m ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class); verify(wsClient).call(capture.capture()); WsRequest wsRequest = capture.getValue(); assertThat(wsRequest.getParams()).containsOnly(entry("organization", "MyOrg"), entry("projectKey", "struts")); }
From source file:org.springframework.integration.ip.tcp.connection.TcpNetConnectionTests.java
@Test public void transferHeaders() throws Exception { Socket inSocket = mock(Socket.class); PipedInputStream pipe = new PipedInputStream(); when(inSocket.getInputStream()).thenReturn(pipe); TcpConnectionSupport inboundConnection = new TcpNetConnection(inSocket, true, false, nullPublisher, null); inboundConnection.setDeserializer(new MapJsonSerializer()); MapMessageConverter inConverter = new MapMessageConverter(); MessageConvertingTcpMessageMapper inMapper = new MessageConvertingTcpMessageMapper(inConverter); inboundConnection.setMapper(inMapper); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Socket outSocket = mock(Socket.class); TcpNetConnection outboundConnection = new TcpNetConnection(outSocket, true, false, nullPublisher, null); when(outSocket.getOutputStream()).thenReturn(baos); MapMessageConverter outConverter = new MapMessageConverter(); outConverter.setHeaderNames("bar"); MessageConvertingTcpMessageMapper outMapper = new MessageConvertingTcpMessageMapper(outConverter); outboundConnection.setMapper(outMapper); outboundConnection.setSerializer(new MapJsonSerializer()); Message<String> message = MessageBuilder.withPayload("foo").setHeader("bar", "baz").build(); outboundConnection.send(message);/*from w w w .j av a2 s.c om*/ PipedOutputStream out = new PipedOutputStream(pipe); out.write(baos.toByteArray()); out.close(); final AtomicReference<Message<?>> inboundMessage = new AtomicReference<Message<?>>(); TcpListener listener = new TcpListener() { public boolean onMessage(Message<?> message) { if (!(message instanceof ErrorMessage)) { inboundMessage.set(message); } return false; } }; inboundConnection.registerListener(listener); inboundConnection.run(); assertNotNull(inboundMessage.get()); assertEquals("foo", inboundMessage.get().getPayload()); assertEquals("baz", inboundMessage.get().getHeaders().get("bar")); }
From source file:org.springframework.integration.sftp.outbound.SftpServerOutboundTests.java
@Test public void testInt3047ConcurrentSharedSession() throws Exception { final Session<?> session1 = this.sessionFactory.getSession(); final Session<?> session2 = this.sessionFactory.getSession(); final PipedInputStream pipe1 = new PipedInputStream(); PipedOutputStream out1 = new PipedOutputStream(pipe1); final PipedInputStream pipe2 = new PipedInputStream(); PipedOutputStream out2 = new PipedOutputStream(pipe2); final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); Executors.newSingleThreadExecutor().execute(() -> { try {/*from w w w . j a v a 2s . c o m*/ session1.write(pipe1, "foo.txt"); } catch (IOException e) { e.printStackTrace(); } latch1.countDown(); }); Executors.newSingleThreadExecutor().execute(() -> { try { session2.write(pipe2, "bar.txt"); } catch (IOException e) { e.printStackTrace(); } latch2.countDown(); }); out1.write('a'); out2.write('b'); out1.write('c'); out2.write('d'); out1.write('e'); out2.write('f'); out1.close(); out2.close(); assertTrue(latch1.await(10, TimeUnit.SECONDS)); assertTrue(latch2.await(10, TimeUnit.SECONDS)); ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); session1.read("foo.txt", bos1); session2.read("bar.txt", bos2); assertEquals("ace", new String(bos1.toByteArray())); assertEquals("bdf", new String(bos2.toByteArray())); session1.remove("foo.txt"); session2.remove("bar.txt"); session1.close(); session2.close(); }
From source file:org.talend.dataprep.schema.csv.CSVSerializer.java
@Override public InputStream serialize(InputStream rawContent, DataSetMetadata metadata, long limit) { try {/*www .j a v a 2 s .co m*/ PipedInputStream pipe = new PipedInputStream(); PipedOutputStream jsonOutput = new PipedOutputStream(pipe); // Serialize asynchronously for better performance (especially if caller doesn't consume all, see sampling). Runnable r = () -> { final Map<String, String> parameters = metadata.getContent().getParameters(); final String separator = parameters.get(CSVFormatFamily.SEPARATOR_PARAMETER); try (CSVReader reader = new CSVReader(new InputStreamReader(rawContent, metadata.getEncoding()), separator.charAt(0), '\"', '\0')) { JsonGenerator generator = new JsonFactory().createGenerator(jsonOutput); int i = 0; while (i++ < metadata.getContent().getNbLinesInHeader()) { reader.readNext(); // Skip all header lines } generator.writeStartArray(); writeLineContent(reader, metadata, generator, separator, limit); generator.writeEndArray(); generator.flush(); } catch (Exception e) { // Consumer may very well interrupt consumption of stream (in case of limit(n) use for sampling). // This is not an issue as consumer is allowed to partially consumes results, it's up to the // consumer to ensure data it consumed is consistent. LOGGER.debug("Unable to continue serialization for {}. Skipping remaining content.", metadata.getId(), e); } finally { try { jsonOutput.close(); } catch (IOException e) { LOGGER.error("Unable to close output", e); } } }; executor.execute(r); return pipe; } catch (IOException e) { throw new TDPException(CommonErrorCodes.UNABLE_TO_SERIALIZE_TO_JSON, e); } }
From source file:org.waarp.openr66.context.task.ExecMoveTask.java
@Override public void run() { /*// w ww. j av a 2s . c o m * First apply all replacements and format to argRule from context and argTransfer. Will * call exec (from first element of resulting string) with arguments as the following value * from the replacements. Return 0 if OK, else 1 for a warning else as an error. The last * line of stdout will be the new name given to the R66File in case of status 0. The * previous file should be deleted by the script or will be deleted in case of status 0. If * the status is 1, no change is made to the file. */ logger.info("ExecMove with " + argRule + ":" + argTransfer + " and {}", session); String finalname = argRule; finalname = getReplacedValue(finalname, argTransfer.split(" ")); // Force the WaitForValidation waitForValidation = true; if (Configuration.configuration.isUseLocalExec() && useLocalExec) { LocalExecClient localExecClient = new LocalExecClient(); if (localExecClient.connect()) { localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion); LocalExecResult result = localExecClient.getLocalExecResult(); move(result.getStatus(), result.getResult(), finalname); localExecClient.disconnect(); return; } // else continue } String[] args = finalname.split(" "); File exec = new File(args[0]); if (exec.isAbsolute()) { if (!exec.canExecute()) { logger.error("Exec command is not executable: " + finalname); R66Result result = new R66Result(session, false, ErrorCode.CommandNotFound, session.getRunner()); futureCompletion.setResult(result); futureCompletion.cancel(); return; } } CommandLine commandLine = new CommandLine(args[0]); for (int i = 1; i < args.length; i++) { commandLine.addArgument(args[i]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); PipedInputStream inputStream = new PipedInputStream(); PipedOutputStream outputStream = null; try { outputStream = new PipedOutputStream(inputStream); } catch (IOException e1) { try { inputStream.close(); } catch (IOException e) { } logger.error("Exception: " + e1.getMessage() + " Exec in error with " + commandLine.toString(), e1); futureCompletion.setFailure(e1); return; } PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, null); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); ExecuteWatchdog watchdog = null; if (delay > 0) { watchdog = new ExecuteWatchdog(delay); defaultExecutor.setWatchdog(watchdog); } LastLineReader lastLineReader = new LastLineReader(inputStream); Thread thread = new Thread(lastLineReader, "ExecRename" + session.getRunner().getSpecialId()); thread.setDaemon(true); Configuration.configuration.getExecutorService().execute(thread); int status = -1; try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(Configuration.RETRYINMS); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e1) { try { outputStream.close(); } catch (IOException e2) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e2) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("ExecuteException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } catch (IOException e1) { try { outputStream.close(); } catch (IOException e2) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e2) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error( "IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } } else { try { outputStream.close(); } catch (IOException e1) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e1) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error( "ExecuteException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } } catch (IOException e) { try { outputStream.close(); } catch (IOException e1) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e1) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } try { outputStream.flush(); } catch (IOException e) { } try { outputStream.close(); } catch (IOException e) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } try { if (delay > 0) { thread.join(delay); } else { thread.join(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } try { inputStream.close(); } catch (IOException e1) { } String newname = null; if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) status = -1; newname = "TimeOut"; } else { newname = lastLineReader.getLastLine(); if (status == 0 && (newname == null || newname.isEmpty())) { status = 1; } } move(status, newname, commandLine.toString()); }
From source file:org.waarp.openr66.context.task.ExecOutputTask.java
@Override public void run() { /*//ww w . ja v a 2 s . c om * First apply all replacements and format to argRule from context and argTransfer. Will * call exec (from first element of resulting string) with arguments as the following value * from the replacements. Return 0 if OK, else 1 for a warning else as an error. In case of * an error (> 0), all the line from output will be send back to the partner with the Error * code. No change is made to the file. */ logger.info("ExecOutput with " + argRule + ":" + argTransfer + " and {}", session); String finalname = argRule; finalname = getReplacedValue(finalname, argTransfer.split(" ")); // Force the WaitForValidation waitForValidation = true; if (Configuration.configuration.isUseLocalExec() && useLocalExec) { LocalExecClient localExecClient = new LocalExecClient(); if (localExecClient.connect()) { localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion); LocalExecResult result = localExecClient.getLocalExecResult(); finalize(result.getStatus(), result.getResult(), finalname); localExecClient.disconnect(); return; } // else continue } String[] args = finalname.split(" "); File exec = new File(args[0]); if (exec.isAbsolute()) { if (!exec.canExecute()) { logger.error("Exec command is not executable: " + finalname); R66Result result = new R66Result(session, false, ErrorCode.CommandNotFound, session.getRunner()); futureCompletion.setResult(result); futureCompletion.cancel(); return; } } CommandLine commandLine = new CommandLine(args[0]); for (int i = 1; i < args.length; i++) { commandLine.addArgument(args[i]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); PipedInputStream inputStream = new PipedInputStream(); PipedOutputStream outputStream = null; try { outputStream = new PipedOutputStream(inputStream); } catch (IOException e1) { try { inputStream.close(); } catch (IOException e) { } logger.error("Exception: " + e1.getMessage() + " Exec in error with " + commandLine.toString(), e1); futureCompletion.setFailure(e1); return; } PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, null); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); ExecuteWatchdog watchdog = null; if (delay > 0) { watchdog = new ExecuteWatchdog(delay); defaultExecutor.setWatchdog(watchdog); } AllLineReader allLineReader = new AllLineReader(inputStream); Thread thread = new Thread(allLineReader, "ExecRename" + session.getRunner().getSpecialId()); thread.setDaemon(true); Configuration.configuration.getExecutorService().execute(thread); int status = -1; try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(Configuration.RETRYINMS); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e1) { finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status, commandLine); return; } catch (IOException e1) { try { outputStream.flush(); } catch (IOException e2) { } try { outputStream.close(); } catch (IOException e2) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e2) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error( "IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } } else { finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status, commandLine); return; } } catch (IOException e) { try { outputStream.close(); } catch (IOException e1) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e1) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } try { outputStream.flush(); } catch (IOException e) { } try { outputStream.close(); } catch (IOException e) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } try { if (delay > 0) { thread.join(delay); } else { thread.join(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } try { inputStream.close(); } catch (IOException e1) { } String newname = null; if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) status = -1; newname = "TimeOut"; } else { newname = allLineReader.getLastLine().toString(); } finalize(status, newname, commandLine.toString()); }