List of usage examples for java.io PipedOutputStream close
public void close() throws IOException
From source file:org.apache.oozie.cli.TestCLIParser.java
private String readCommandOutput(CLIParser parser, CLIParser.Command c) throws IOException { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); PipedOutputStream pipeOut = new PipedOutputStream(); PipedInputStream pipeIn = new PipedInputStream(pipeOut, 1024 * 10); System.setOut(new PrintStream(pipeOut)); parser.showHelp(c.getCommandLine()); pipeOut.close(); ByteStreams.copy(pipeIn, outBytes);//w ww .jav a 2 s . co m pipeIn.close(); return new String(outBytes.toByteArray()); }
From source file:org.duracloud.audit.reader.impl.AuditLogReaderImpl.java
@Override public InputStream getAuditLog(final String account, final String storeId, final String spaceId) throws AuditLogReaderException { checkEnabled();/*from w w w . j a v a 2 s . c o m*/ this.storageProvider = getStorageProvider(); final String auditBucket = auditConfig.getAuditLogSpaceId(); String prefix = MessageFormat.format("{0}/{1}/{2}/", account, storeId, spaceId); final PipedInputStream is = new PipedInputStream(10 * 1024); final PipedOutputStream os; try { os = new PipedOutputStream(is); } catch (IOException e) { throw new AuditLogReaderException(e); } try { final Iterator<String> it = this.storageProvider.getSpaceContents(auditBucket, prefix); if (!it.hasNext()) { os.write((AuditLogUtil.getHeader() + "\n").getBytes()); os.close(); } new Thread(new Runnable() { @Override public void run() { try { int count = 0; while (it.hasNext()) { String contentId = it.next(); writeToOutputStream(auditBucket, storageProvider, os, count, contentId); count++; } os.close(); } catch (ContentStoreException | IOException ex) { log.error(MessageFormat.format("failed to complete audit log read routine " + "for space: storeId={0}, spaceId={1}", storeId, spaceId), ex); } } }).start(); } catch (StorageException | IOException e) { throw new AuditLogReaderException(e); } return is; }
From source file:org.duracloud.manifest.impl.ManifestGeneratorImpl.java
@Override public InputStream getManifest(String account, String storeId, String spaceId, ManifestFormat format) throws ManifestArgumentException, ManifestNotFoundException { log.info("retrieving manifest for account:{}, storeId:{}, spaceId:{}, format:{}", account, storeId, spaceId, format);// w w w .j av a 2 s.co m try { storeId = validateStoreId(storeId); validateSpaceId(storeId, spaceId); PipedInputStream is = new PipedInputStream(10 * 1024); final PipedOutputStream os = new PipedOutputStream(is); final Iterator<ManifestItem> it = this.manifestStore.getItems(account, storeId, spaceId); final ManifestFormatter formatter = getFormatter(format); if (!it.hasNext()) { formatter.writeManifestItemToOutput(null, os); os.close(); return is; } else { new Thread(new Runnable() { @Override public void run() { try { while (it.hasNext()) { formatter.writeManifestItemToOutput(it.next(), os); } try { os.close(); } catch (IOException e) { log.error("failed to close piped output stream : " + e.getMessage(), e); } } catch (Exception e) { log.error("error writing to piped output stream : " + e.getMessage(), e); } } }).start(); } return is; } catch (IOException | RuntimeException ex) { log.error("failed to retrieve manifest: " + ex.getMessage(), ex); throw new ManifestGeneratorException(ex.getMessage()); } }
From source file:org.eclipse.lyo.oslc.v3.sample.ETag.java
/** * Create an ETag value from a Jena model. * * @param m the model that represents the HTTP response body * @param lang the serialization language * @param base the base URI//from www .j ava2 s . c o m * @return an ETag value * @throws IOException on I/O errors * * @see <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.19">HTTP 1.1: Section 14.19 - ETag</a> */ public static String generate(final Model m, final String lang, final String base) throws IOException { final PipedInputStream in = new PipedInputStream(); final PipedOutputStream out = new PipedOutputStream(in); new Thread(new Runnable() { public void run() { m.write(out, lang, base); try { out.close(); } catch (IOException e) { logger.error("Error creating MD5 hash of Model", e); } } }).start(); return generate(in); }
From source file:org.eclipse.lyo.oslc.v3.sample.ETag.java
public static String generate(final JsonObject object) throws IOException { final PipedInputStream in = new PipedInputStream(); final PipedOutputStream out = new PipedOutputStream(in); new Thread(new Runnable() { public void run() { object.output(new IndentedWriter(out)); try { out.close(); } catch (IOException e) { logger.error("Error creating MD5 hash of JSON", e); }// w ww .j a va 2 s.c o m } }).start(); return generate(in); }
From source file:org.fedoraproject.eclipse.packager.SourcesFile.java
/** * Saves the sources file to the underlying file. * @throws CoreException/*from ww w .j av a 2 s. co m*/ */ public void save() throws CoreException { final PipedInputStream in = new PipedInputStream(); // create an OutputStream with the InputStream from above as input PipedOutputStream out = null; try { out = new PipedOutputStream(in); PrintWriter pw = new PrintWriter(out); for (Map.Entry<String, String> entry : sources.entrySet()) { pw.println(entry.getValue() + " " + entry.getKey()); //$NON-NLS-1$ } pw.close(); out.close(); final IFile file = sourcesFile; Job job = new Job(FedoraPackagerText.SourcesFile_saveJob) { @Override public IStatus run(IProgressMonitor monitor) { try { // Potentially long running so do as job. file.setContents(in, false, true, monitor); file.getParent().refreshLocal(IResource.DEPTH_ONE, null); } catch (CoreException e) { e.printStackTrace(); } return Status.OK_STATUS; } }; job.schedule(); try { job.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, PackagerPlugin.PLUGIN_ID, MessageFormat.format(FedoraPackagerText.SourcesFile_saveFailedMsg, sourcesFile.getName()))); } finally { if (out != null) { try { out.close(); } catch (IOException e) { // Nothing to do } } } }
From source file:org.geoserver.wfs.xslt.XSLTOutputFormat.java
@Override protected void write(final FeatureCollectionResponse featureCollection, OutputStream output, Operation operation) throws IOException, ServiceException { // get the transformation we need TransformInfo info = locateTransformation(featureCollection, operation); Transformer transformer = repository.getTransformer(info); // force Xalan to indent the output if (transformer.getOutputProperties() != null && "yes".equals(transformer.getOutputProperties().getProperty("indent"))) { try {/*from w w w. ja v a 2 s . c o m*/ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } catch (IllegalArgumentException e) { LOGGER.log(Level.FINE, "Could not set indent amount", e); // in case it's not Xalan } } // prepare the fake operation we're providing to the source output format final Operation sourceOperation = buildSourceOperation(operation, info); // lookup the operation we are going to use final Response sourceResponse = findSourceResponse(sourceOperation, info); if (sourceResponse == null) { throw new WFSException("Could not locate a response that can generate the desired source format '" + info.getSourceFormat() + "' for transformation '" + info.getName() + "'"); } // prepare the stream connections, so that we can do the transformation on the fly PipedInputStream pis = new PipedInputStream(); final PipedOutputStream pos = new PipedOutputStream(pis); // submit the source output format execution, tracking exceptions Future<Void> future = executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { try { sourceResponse.write(featureCollection, pos, sourceOperation); } finally { // close the stream to make sure the transformation won't keep on waiting pos.close(); } return null; } }); // run the transformation TransformerException transformerException = null; try { transformer.transform(new StreamSource(pis), new StreamResult(output)); } catch (TransformerException e) { transformerException = e; } finally { pis.close(); } // now handle exceptions, starting from the source try { future.get(); } catch (Exception e) { throw new WFSException( "Failed to run the output format generating the source for the XSTL transformation", e); } if (transformerException != null) { throw new WFSException("Failed to run the the XSTL transformation", transformerException); } }
From source file:org.gradle.launcher.daemon.server.exec.ForwardClientInput.java
public void execute(final DaemonCommandExecution execution) { final PipedOutputStream inputSource = new PipedOutputStream(); final PipedInputStream replacementStdin; try {/*from w ww . j av a 2 s. co m*/ replacementStdin = new PipedInputStream(inputSource); } catch (IOException e) { throw UncheckedException.throwAsUncheckedException(e); } execution.getConnection().onStdin(new StdinHandler() { public void onInput(ForwardInput input) { LOGGER.debug("Writing forwarded input on daemon's stdin."); try { inputSource.write(input.getBytes()); } catch (IOException e) { LOGGER.warn("Received exception trying to forward client input.", e); } } public void onEndOfInput() { LOGGER.info("Closing daemon's stdin at end of input."); try { inputSource.close(); } catch (IOException e) { LOGGER.warn("Problem closing output stream connected to replacement stdin", e); } finally { LOGGER.info("The daemon will no longer process any standard input."); } } }); try { try { new StdinSwapper().swap(replacementStdin, new Callable<Void>() { public Void call() { execution.proceed(); return null; } }); } finally { execution.getConnection().onStdin(null); IOUtils.closeQuietly(replacementStdin); IOUtils.closeQuietly(inputSource); } } catch (Exception e) { throw UncheckedException.throwAsUncheckedException(e); } }
From source file:org.guvnor.ala.build.maven.executor.MavenCliOutputTest.java
@Test public void buildAppAndWaitForMavenOutputTest() throws IOException { final GitHub gitHub = new GitHub(); gitHub.getRepository("salaboy/drools-workshop", new HashMap<String, String>() { {//from w w w . j av a2s.c o m put("out-dir", tempPath.getAbsolutePath()); } }); final Optional<Source> _source = new GitConfigExecutor(new InMemorySourceRegistry()) .apply(new GitConfigImpl(tempPath.getAbsolutePath(), "master", "https://github.com/salaboy/drools-workshop", "drools-workshop", "true")); assertTrue(_source.isPresent()); final Source source = _source.get(); boolean buildProcessReady = false; Throwable error = null; PipedOutputStream baosOut = new PipedOutputStream(); PipedOutputStream baosErr = new PipedOutputStream(); final PrintStream out = new PrintStream(baosOut, true); final PrintStream err = new PrintStream(baosErr, true); //Build the project in a different thread new Thread(() -> { buildMavenProject(source, out, err); }).start(); // Use the PipeOutputStream to read the execution output and validate that the application was built. StringBuilder sb = new StringBuilder(); BufferedReader bufferedReader; bufferedReader = new BufferedReader(new InputStreamReader(new PipedInputStream(baosOut))); String line; while (!(buildProcessReady || error != null)) { if ((line = bufferedReader.readLine()) != null) { sb.append(line).append("\n"); if (line.contains("Building war:")) { buildProcessReady = true; out.close(); err.close(); baosOut.close(); baosErr.close(); } } } assertTrue(sb.toString().contains("Building war:")); assertTrue(buildProcessReady); assertTrue(error == null); }
From source file:org.lamport.tla.toolbox.jcloud.PayloadHelper.java
public static Payload appendModel2Jar(final Path modelPath, String mainClass, Properties properties, IProgressMonitor monitor) throws IOException { /*/* w w w . j ava 2 s . c o m*/ * Get the standard tla2tools.jar from the classpath as a blueprint. * It's located in the org.lamport.tla.toolbox.jclouds bundle in the * files/ directory. It uses OSGi functionality to read files/tla2tools.jar * from the .jclouds bundle. * The copy of the blueprint will contain the spec & model and * additional metadata (properties, amended manifest). */ final Bundle bundle = FrameworkUtil.getBundle(PayloadHelper.class); final URL toolsURL = bundle.getEntry("files/tla2tools.jar"); if (toolsURL == null) { throw new RuntimeException("No tlatools.jar and/or spec to deploy"); } /* * Copy the tla2tools.jar blueprint to a temporary location on * disk to append model files below. */ final File tempFile = File.createTempFile("tla2tools", ".jar"); tempFile.deleteOnExit(); try (FileOutputStream out = new FileOutputStream(tempFile)) { IOUtils.copy(toolsURL.openStream(), out); } /* * Create a virtual filesystem in jar format. */ final Map<String, String> env = new HashMap<>(); env.put("create", "true"); final URI uri = URI.create("jar:" + tempFile.toURI()); try (FileSystem fs = FileSystems.newFileSystem(uri, env)) { /* * Copy the spec and model into the jar's model/ folder. * Also copy any module override (.class file) into the jar. */ try (DirectoryStream<Path> modelDirectoryStream = Files.newDirectoryStream(modelPath, "*.{cfg,tla,class}")) { for (final Path file : modelDirectoryStream) { final Path to = fs.getPath("/model/" + file.getFileName()); Files.copy(file, to, StandardCopyOption.REPLACE_EXISTING); } } /* * Add given class as Main-Class statement to jar's manifest. This * causes Java to launch this class when no other Main class is * given on the command line. Thus, it shortens the command line * for us. */ final Path manifestPath = fs.getPath("/META-INF/", "MANIFEST.MF"); final Manifest manifest = new Manifest(Files.newInputStream(manifestPath)); manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, mainClass); final PipedOutputStream ps = new PipedOutputStream(); final PipedInputStream is = new PipedInputStream(ps); manifest.write(ps); ps.close(); Files.copy(is, manifestPath, StandardCopyOption.REPLACE_EXISTING); /* * Add properties file to archive. The property file contains the * result email address... from where TLC eventually reads it. */ // On Windows 7 and above the file has to be created in the system's // temp folder. Otherwise except file creation to fail with a // AccessDeniedException final File f = File.createTempFile("generated", "properties"); OutputStream out = new FileOutputStream(f); // Append all entries in "properties" to the temp file f properties.store(out, "This is an optional header comment string"); // Copy the temp file f into the jar with path /model/generated.properties. final Path to = fs.getPath("/model/generated.properties"); Files.copy(f.toPath(), to, StandardCopyOption.REPLACE_EXISTING); } catch (final IOException e1) { throw new RuntimeException("No model directory found to deploy", e1); } /* * Compress archive with pack200 to achieve a much higher compression rate. We * are going to send the file on the wire after all: * * effort: take more time choosing codings for better compression segment: use * largest-possible archive segments (>10% better compression) mod time: smear * modification times to a single value deflate: ignore all JAR deflation hints * in original archive */ final Packer packer = Pack200.newPacker(); final Map<String, String> p = packer.properties(); p.put(Packer.EFFORT, "9"); p.put(Packer.SEGMENT_LIMIT, "-1"); p.put(Packer.MODIFICATION_TIME, Packer.LATEST); p.put(Packer.DEFLATE_HINT, Packer.FALSE); // Do not reorder which changes package names. Pkg name changes e.g. break // SimpleFilenameToStream. p.put(Packer.KEEP_FILE_ORDER, Packer.TRUE); // Throw an error if any of the above attributes is unrecognized. p.put(Packer.UNKNOWN_ATTRIBUTE, Packer.ERROR); final File packTempFile = File.createTempFile("tla2tools", ".pack.gz"); try (final JarFile jarFile = new JarFile(tempFile); final GZIPOutputStream fos = new GZIPOutputStream(new FileOutputStream(packTempFile));) { packer.pack(jarFile, fos); } catch (IOException ioe) { throw new RuntimeException("Failed to pack200 the tla2tools.jar file", ioe); } /* * Convert the customized tla2tools.jar into a jClouds payload object. This is * the format it will be transfered on the wire. This is handled by jClouds * though. */ Payload jarPayLoad = null; try { final InputStream openStream = new FileInputStream(packTempFile); jarPayLoad = Payloads.newInputStreamPayload(openStream); // manually set length of content to prevent a NPE bug jarPayLoad.getContentMetadata().setContentLength(Long.valueOf(openStream.available())); } catch (final IOException e1) { throw new RuntimeException("No tlatools.jar to deploy", e1); } finally { monitor.worked(5); } return jarPayLoad; }