List of usage examples for java.io PrintStream close
public void close()
From source file:com.runwaysdk.dataaccess.database.general.ProcessReader.java
/** * Consumes the output of the process in a separate thread. * // ww w .j a v a 2 s .com * @param inputStream * @param stream */ private void consumeOutput(final InputStream inputStream, final PrintStream stream) { final BufferedReader out = new BufferedReader(new InputStreamReader(inputStream)); Thread t = new Thread(new Runnable() { @Override public void run() { try { String line = new String(); while ((line = out.readLine()) != null) { stream.println(line); } stream.close(); } catch (Throwable t) { String msg = "Error when consuming the process output."; throw new ProgrammingErrorException(msg, t); } } }, OUTPUT_THREAD); t.setUncaughtExceptionHandler(this); t.setDaemon(true); t.start(); }
From source file:edu.umn.cs.spatialHadoop.operations.Union.java
private static <S extends OGCJTSShape> void unionLocal(Path inPath, Path outPath, final OperationsParams params) throws IOException, InterruptedException, ClassNotFoundException { // 1- Split the input path/file to get splits that can be processed independently final SpatialInputFormat3<Rectangle, S> inputFormat = new SpatialInputFormat3<Rectangle, S>(); Job job = Job.getInstance(params);/*from w w w .j a v a2 s.co m*/ SpatialInputFormat3.setInputPaths(job, inPath); final List<InputSplit> splits = inputFormat.getSplits(job); int parallelism = params.getInt("parallel", Runtime.getRuntime().availableProcessors()); // 2- Process splits in parallel final List<Float> progresses = new Vector<Float>(); final IntWritable overallProgress = new IntWritable(0); List<List<Geometry>> results = Parallel.forEach(splits.size(), new RunnableRange<List<Geometry>>() { @Override public List<Geometry> run(final int i1, final int i2) { final int pi; final IntWritable splitsProgress = new IntWritable(); synchronized (progresses) { pi = progresses.size(); progresses.add(0f); } final float progressRatio = (i2 - i1) / (float) splits.size(); Progressable progress = new Progressable.NullProgressable() { @Override public void progress(float p) { progresses.set(pi, p * ((splitsProgress.get() - i1) / (float) (i2 - i1)) * progressRatio); float sum = 0; for (float f : progresses) sum += f; int newProgress = (int) (sum * 100); if (newProgress > overallProgress.get()) { overallProgress.set(newProgress); LOG.info("Local union progress " + newProgress + "%"); } } }; final List<Geometry> localUnion = new ArrayList<Geometry>(); ResultCollector<Geometry> output = new ResultCollector<Geometry>() { @Override public void collect(Geometry r) { localUnion.add(r); } }; final int MaxBatchSize = 100000; Geometry[] batch = new Geometry[MaxBatchSize]; int batchSize = 0; for (int i = i1; i < i2; i++) { splitsProgress.set(i); try { FileSplit fsplit = (FileSplit) splits.get(i); final RecordReader<Rectangle, Iterable<S>> reader = inputFormat.createRecordReader(fsplit, null); if (reader instanceof SpatialRecordReader3) { ((SpatialRecordReader3) reader).initialize(fsplit, params); } else if (reader instanceof RTreeRecordReader3) { ((RTreeRecordReader3) reader).initialize(fsplit, params); } else if (reader instanceof HDFRecordReader) { ((HDFRecordReader) reader).initialize(fsplit, params); } else { throw new RuntimeException("Unknown record reader"); } while (reader.nextKeyValue()) { Iterable<S> shapes = reader.getCurrentValue(); for (S s : shapes) { if (s.geom == null) continue; batch[batchSize++] = s.geom; if (batchSize >= MaxBatchSize) { SpatialAlgorithms.multiUnion(batch, progress, output); batchSize = 0; } } } reader.close(); } catch (IOException e) { LOG.error("Error processing split " + splits.get(i), e); } catch (InterruptedException e) { LOG.error("Error processing split " + splits.get(i), e); } } // Union all remaining geometries try { Geometry[] finalBatch = new Geometry[batchSize]; System.arraycopy(batch, 0, finalBatch, 0, batchSize); SpatialAlgorithms.multiUnion(finalBatch, progress, output); return localUnion; } catch (IOException e) { // Should never happen as the context is passed as null throw new RuntimeException("Error in local union", e); } } }, parallelism); // Write result to output LOG.info("Merge the results of all splits"); int totalNumGeometries = 0; for (List<Geometry> result : results) totalNumGeometries += result.size(); List<Geometry> allInOne = new ArrayList<Geometry>(totalNumGeometries); for (List<Geometry> result : results) allInOne.addAll(result); final S outShape = (S) params.getShape("shape"); final PrintStream out; if (outPath == null || !params.getBoolean("output", true)) { // Skip writing the output out = new PrintStream(new NullOutputStream()); } else { FileSystem outFS = outPath.getFileSystem(params); out = new PrintStream(outFS.create(outPath)); } SpatialAlgorithms.multiUnion(allInOne.toArray(new Geometry[allInOne.size()]), new Progressable.NullProgressable() { int lastProgress = 0; public void progress(float p) { int newProgresss = (int) (p * 100); if (newProgresss > lastProgress) { LOG.info("Global union progress " + (lastProgress = newProgresss) + "%"); } } }, new ResultCollector<Geometry>() { Text line = new Text2(); @Override public void collect(Geometry r) { outShape.geom = r; outShape.toText(line); out.println(line); } }); out.close(); }
From source file:net.rim.ejde.internal.packaging.RAPCFile.java
/** * Collects a resource file content (like .rapc) * * @param relativeTo/*from w ww . j a va 2s .c o m*/ * @return * @throws IDEError */ private byte[] collectResourceInformation() throws IDEError { ByteArrayOutputStream bout = new ByteArrayOutputStream(); PrintStream out; try { out = new PrintStream(bout, false, "UTF-8"); } catch (UnsupportedEncodingException uee) { out = new PrintStream(bout); } for (int i = 0; i < _rapcContents.size(); ++i) { out.println(_rapcContents.elementAt(i)); } out.close(); return bout.toByteArray(); }
From source file:com.ning.billing.beatrix.osgi.SetupBundleWithAssertion.java
private void createConfigFile(final PluginJavaConfig pluginConfig) throws IOException { PrintStream printStream = null; try {/*from ww w .j a va2s. c o m*/ final File configFile = new File(pluginConfig.getPluginVersionRoot(), config.getOSGIKillbillPropertyName()); configFile.createNewFile(); printStream = new PrintStream(new FileOutputStream(configFile)); printStream.print("pluginType=" + PluginType.NOTIFICATION); } finally { if (printStream != null) { printStream.close(); } } }
From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.logging.LoggerDestinationFastTest.java
@Test public void stdoutLoggerDestination() throws IOException, LoggerDestination.LoggerException { PrintStream outStream = null; try {/*from w ww . j av a 2s . c o m*/ // redirect stdout to a file String outfile = OUTPUT_PATH + "stdout.txt"; //noinspection IOResourceOpenedButNotSafelyClosed outStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(outfile))); System.setOut(outStream); // send message to logger destination StdoutLoggerDestination dest = new StdoutLoggerDestination(); dest.setMinLevel(Level.DEBUG); String message = "THIS IS AN ERROR MESSAGE"; dest.logToDestination(Level.ERROR, message); outStream.close(); // read in output file and compare to expected assertEquals(message, readFirstLine(outfile)); new File(outfile).deleteOnExit(); } finally { IOUtils.closeQuietly(outStream); } }
From source file:fr.gouv.culture.vitam.droid.DroidHandler.java
/** * Check one InputStream/*from w w w . j ava2 s .c om*/ * * @param in * @param argument * @return a List of DroidFileFOrmat * @throws CommandExecutionException */ public List<DroidFileFormat> checkFileFormat(InputStream in, VitamArgument argument) throws CommandExecutionException { String path = ""; String slash = File.separator; String slash1 = slash; path = ""; ResultPrinter resultPrinter = new ResultPrinter(vitamBinarySignatureIdentifier, containerSignatureDefinitions, path, slash, slash1, argument.archive, argument.checkSubFormat); // change System.out PrintStream oldOut = System.out; DroidFileFormatOutputStream out = new DroidFileFormatOutputStream( vitamBinarySignatureIdentifier.getSigFile(), argument); PrintStream newOut = new PrintStream(out, true); try { System.setOut(newOut); realCheck(in, resultPrinter); } finally { // reset System.out System.setOut(oldOut); newOut.close(); newOut = null; } return out.getResult(); }
From source file:de.uni_koblenz.jgralab.utilities.tg2dot.Tg2Dot.java
public InputStream convertToGraphVizStream(GraphVizProgram prog) throws IOException { String executionString = String.format("%s%s -T%s", prog.path, prog.layouter, prog.outputFormat); final Process process = Runtime.getRuntime().exec(executionString); InputStream inputStream = new BufferedInputStream(process.getInputStream()); new Thread() { @Override/*w w w . j a va2 s .co m*/ public void run() { PrintStream ps = new PrintStream(process.getOutputStream()); convert(ps); ps.flush(); ps.close(); }; }.start(); return inputStream; }
From source file:com.taobao.adfs.util.Utilities.java
public static String getThrowableStackTrace(Throwable t) { PrintStream printStream = null; try {/* www . java 2 s. c o m*/ OutputStream outputStream = null; outputStream = new ByteArrayOutputStream(1024); printStream = new PrintStream(outputStream); t.printStackTrace(printStream); printStream.flush(); return outputStream.toString(); } catch (Exception e) { return "unknow"; } finally { if (printStream != null) printStream.close(); } }
From source file:fr.gouv.culture.vitam.droid.DroidHandler.java
/** * Check one file//w w w . j a v a2 s . c o m * * @param file * @param argument * @return a List of DroidFileFOrmat * @throws CommandExecutionException */ public List<DroidFileFormat> checkFileFormat(File file, VitamArgument argument) throws CommandExecutionException { Collection<File> matchedFiles = new ArrayList<File>(1); String path = file.getAbsolutePath(); String slash = path.contains(FORWARD_SLASH) ? FORWARD_SLASH : BACKWARD_SLASH; String slash1 = slash; matchedFiles.add(file); path = ""; ResultPrinter resultPrinter = new ResultPrinter(vitamBinarySignatureIdentifier, containerSignatureDefinitions, path, slash, slash1, argument.archive, argument.checkSubFormat); // change System.out PrintStream oldOut = System.out; DroidFileFormatOutputStream out = new DroidFileFormatOutputStream( vitamBinarySignatureIdentifier.getSigFile(), argument); PrintStream newOut = new PrintStream(out, true); try { System.setOut(newOut); realCheck(file, resultPrinter); } finally { // reset System.out System.setOut(oldOut); newOut.close(); newOut = null; } return out.getResult(); }
From source file:dynamicrefactoring.interfaz.dynamic.DynamicExamplesTab.java
/** * Genera htmls mediante java2html para visualizar los ejemplos de la * refactorizacin en un navegador html.//from w w w. j a v a 2s .c o m */ private void generarHTMLS() { // directorio de la refactorizacion String dirRefactoring = new File(refactoringDefinition.getExamplesAbsolutePath().get(0).getAfter()) .getParent(); // Cambiamos de extensin los ficheros .txt por .java para que puedan // ser interpretados // por java2HTML copyExampleFilesWithOtherExtension(".java"); try { // redirijo la consola a un fichero .txt para que no salga las // trazas de la // biblioteca java2html. PrintStream out = new PrintStream( new FileOutputStream(dirRefactoring + File.separator + "consola.txt")); System.setOut(out); Java2HTML java2html = new Java2HTML(); String[] dir = new String[1]; dir[0] = dirRefactoring; java2html.setJavaDirectorySource(dir); java2html.setDestination(dirRefactoring); java2html.buildJava2HTML(); out.close(); } catch (Exception e) { e.printStackTrace(); } }