List of usage examples for java.io PrintStream close
public void close()
From source file:hudson.plugins.clearcase.ClearCaseChangeLogSet.java
/** * Stores the history objects to the output stream as xml * /*from w ww . ja v a 2 s .c o m*/ * @param outputStream the stream to write to * @param history the history objects to store * @throws IOException */ public static void saveToChangeLog(OutputStream outputStream, List<ClearCaseChangeLogEntry> history) throws IOException { PrintStream stream = new PrintStream(outputStream, false, "UTF-8"); int tagcount = ClearCaseChangeLogSet.TAGS.length; stream.println("<?xml version='1.0' encoding='UTF-8'?>"); stream.println("<history>"); for (ClearCaseChangeLogEntry entry : history) { stream.println("\t<entry>"); String[] strings = getEntryAsStrings(entry); for (int tag = 0; tag < tagcount; tag++) { stream.print("\t\t<"); stream.print(ClearCaseChangeLogSet.TAGS[tag]); stream.print('>'); stream.print(escapeForXml(strings[tag])); stream.print("</"); stream.print(ClearCaseChangeLogSet.TAGS[tag]); stream.println('>'); } for (ClearCaseChangeLogEntry.FileElement file : entry.getElements()) { stream.println("\t\t<element>"); stream.println("\t\t\t<file>"); stream.println(escapeForXml(file.getFile())); stream.println("\t\t\t</file>"); stream.println("\t\t\t<action>"); stream.println(escapeForXml(file.getAction())); stream.println("\t\t\t</action>"); stream.println("\t\t\t<version>"); stream.println(escapeForXml(file.getVersion())); stream.println("\t\t\t</version>"); stream.println("\t\t\t<operation>"); stream.println(escapeForXml(file.getOperation())); stream.println("\t\t\t</operation>"); stream.println("\t\t</element>"); } stream.println("\t</entry>"); } stream.println("</history>"); stream.close(); }
From source file:org.apache.pig.test.TestInfixArithmetic.java
private void generateInput(PrintStream ps, boolean withNulls) { if (withNulls) { // inject nulls randomly for (int i = 1; i < LOOP_COUNT; i++) { int rand = new Random().nextInt(LOOP_COUNT); if (rand <= (0.2 * LOOP_COUNT)) { ps.println(":" + i); } else if (rand > (0.2 * LOOP_COUNT) && rand <= (0.4 * LOOP_COUNT)) { ps.println(i + ":"); } else if (rand > (0.2 * LOOP_COUNT) && rand <= (0.4 * LOOP_COUNT)) { ps.println(":"); } else { ps.println(i + ":" + i); }//from w w w .j a v a 2s .c o m } } else { for (int i = 1; i < LOOP_COUNT; i++) { ps.println(i + ":" + i); } } ps.close(); }
From source file:org.apache.phoenix.hive.HiveTestUtil.java
private static int executeCmd(String[] args, String outFile, String errFile) throws Exception { LOG.info("Running: " + org.apache.commons.lang.StringUtils.join(args, ' ')); PrintStream out = outFile == null ? SessionState.getConsole().getChildOutStream() : new PrintStream(new FileOutputStream(outFile), true); PrintStream err = errFile == null ? SessionState.getConsole().getChildErrStream() : new PrintStream(new FileOutputStream(errFile), true); Process executor = Runtime.getRuntime().exec(args); StreamPrinter errPrinter = new StreamPrinter(executor.getErrorStream(), null, err); StreamPrinter outPrinter = new StreamPrinter(executor.getInputStream(), null, out); outPrinter.start();// w ww . j a va 2 s . c om errPrinter.start(); int result = executor.waitFor(); outPrinter.join(); errPrinter.join(); if (outFile != null) { out.close(); } if (errFile != null) { err.close(); } return result; }
From source file:info.mikaelsvensson.devtools.analysis.db2eventlog.Db2EventLogReportGenerator.java
@Override public void generateReport(File outputFile, ReportPrinter reportPrinter) throws IOException { PrintStream stream = new PrintStream(outputFile); printHeader(stream,// w ww . j ava2 s . c o m "Report for " + _report.getStartTime().toString() + " to " + _report.getStopTime().toString() + " (" + (_report.getStopTime().getTime() - _report.getStartTime().getTime()) / (1000 * 60) + " minutes)"); List<QueryStatistics> values = new ArrayList<QueryStatistics>(_report.getRecords().values()); printHeader(stream, "Queries Sorted by Total Execution Time (only top 10 queries shown)"); sortQueryDataByTime(values); printQueryData(values.subList(0, Math.min(10, values.size())), stream); printHeader(stream, "Queries Sorted by Total Number of Calls (all queries shown)"); sortQueryDataBySamples(values); printQueryData(values, stream); stream.close(); }
From source file:com.ibm.jaql.JaqlBaseTestCase.java
private void execute(String inputFileName, String outputFilename, int type) throws FileNotFoundException, IOException { // Initialize input, output streams // TODO: switch jaql output to PrintWriter instead of PrintStream FileWriter writer = new FileWriter(outputFilename); FastPrintWriter oStr = new FastPrintWriter(writer); Reader reader = new InputStreamReader(new FileInputStream(inputFileName), "UTF-8"); reader = new EchoedReader(reader, writer); // TeeInputStream teeInput = new TeeInputStream(input, oStr); // Initialize parser JaqlLexer lexer = new JaqlLexer(reader); JaqlParser parser = new JaqlParser(lexer); Context context = new Context(); // Begin to loop all sentences boolean parsing = false; int qNum = 0; while (true) { try {//from w ww . j a va2 s . co m parser.env.reset(); parsing = true; Expr expr = parser.parse(); parsing = false; System.err.println("\n\nParsing query at " + inputFileName + ":" + lexer.getLine()); writer.flush(); if (parser.done) { break; } if (expr == null) { continue; } VarTagger.tag(expr); captures.clear(); System.err.println("\nDecompiled query:"); FastPrintBuffer exprText = new FastPrintBuffer(); expr.decompile(exprText, captures); exprText.writeTo(System.err); System.err.println("\n;\nEnd decompiled query\n"); if (type == PLAIN) { System.err.println("\nrunning formatResult"); formatResult(qNum, expr, context, oStr); } else if (type == DECOMPLIE) { System.err.println("\nrunning formatDecompileResult"); formatDecompileResult(expr, context, oStr); } else if (type == REWRITE) { System.err.println("\nrunning formatRewriteResult"); formatRewriteResult(expr, context, oStr); } oStr.flush(); context.reset(); qNum++; } catch (Exception ex) { LOG.error(ex); ex.printStackTrace(System.err); formatFailure(qNum, oStr); oStr.flush(); if (parsing) { BitSet bs = new BitSet(); bs.add(JaqlParser.EOF); bs.add(JaqlParser.SEMI); try { parser.consumeUntil(bs); } catch (TokenStreamException tse) { queryFailure(tse); } } } } if (this.runRewriteResult & this.runCountResult && exprTypeCounter != null) { PrintStream cStr = new PrintStream(new FileOutputStream(this.m_countName)); // Print out all concerned expression occurrences java.util.Iterator<String> i = exprTypeCounter.keySet().iterator(); while (i.hasNext()) { String tem = i.next(); cStr.println(tem + "\t" + exprTypeCounter.get(tem)); } cStr.flush(); cStr.close(); // clear type counter exprTypeCounter.clear(); } // Close all streams context.reset(); oStr.close(); reader.close(); }
From source file:cc.wikitools.lucene.hadoop.SearchWikipediaHdfs.java
@SuppressWarnings("static-access") @Override//from w w w . j a v a 2 s .c o m public int run(String[] args) throws Exception { Options options = new Options(); options.addOption( OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION)); options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return") .create(NUM_RESULTS_OPTION)); options.addOption(new Option(VERBOSE_OPTION, "print out complete document")); options.addOption(new Option(TITLE_OPTION, "search title")); options.addOption(new Option(ARTICLE_OPTION, "search article")); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(QUERY_OPTION) || !cmdline.hasOption(INDEX_OPTION) || !cmdline.hasOption(QUERY_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(SearchWikipediaHdfs.class.getName(), options); System.exit(-1); } String indexLocation = cmdline.getOptionValue(INDEX_OPTION); String queryText = cmdline.getOptionValue(QUERY_OPTION); int numResults = cmdline.hasOption(NUM_RESULTS_OPTION) ? Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION)) : DEFAULT_NUM_RESULTS; boolean verbose = cmdline.hasOption(VERBOSE_OPTION); boolean searchArticle = !cmdline.hasOption(TITLE_OPTION); PrintStream out = new PrintStream(System.out, true, "UTF-8"); HdfsWikipediaSearcher searcher = new HdfsWikipediaSearcher(new Path(indexLocation), getConf()); TopDocs rs = null; if (searchArticle) { rs = searcher.searchArticle(queryText, numResults); } else { rs = searcher.searchTitle(queryText, numResults); } int i = 1; for (ScoreDoc scoreDoc : rs.scoreDocs) { Document hit = searcher.doc(scoreDoc.doc); out.println(String.format("%d. %s (id = %s) %f", i, hit.getField(IndexField.TITLE.name).stringValue(), hit.getField(IndexField.ID.name).stringValue(), scoreDoc.score)); if (verbose) { out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " ")); } i++; } searcher.close(); out.close(); return 0; }
From source file:edu.msu.cme.rdp.kmer.cli.KmerCoverage.java
/** * This is for JUNIT test/* w w w. ja v a 2 s .c o m*/ * @param kmerSize * @param contigReader * @param readsReader * @param match_reads_out * @throws IOException */ public KmerCoverage(int kmerSize, SequenceReader contigReader, SeqReaderCore readsReader, PrintStream outStream) throws IOException { kmerMaps[0] = new ConcurrentHashMap<Kmer, KmerAbund>(); // kmer map for the forward direction kmerMaps[1] = new ConcurrentHashMap<Kmer, KmerAbund>(); // kmer map for the reverse direction this.kmerSize = kmerSize; processContigFile(contigReader); Sequence seq; while ((seq = readsReader.readNextSequence()) != null) { if (seq.getSeqString().length() < kmerSize) { continue; } processReads(seq, outStream); } readsReader.close(); if (outStream != null) { outStream.close(); } }
From source file:org.apache.cocoon.bean.CocoonBean.java
/** * Generate a <code>resourceUnavailable</code> message. * * @param target being unavailable/*from w w w . ja va 2 s .co m*/ * @exception IOException if an error occurs */ private void resourceUnavailable(Target target) throws IOException, ProcessingException { if (brokenLinkGenerate) { //Why decode this URI now? //String brokenFile = NetUtils.decodePath(destinationURI); if (brokenLinkExtension != null) { target.setExtraExtension(brokenLinkExtension); } SimpleNotifyingBean n = new SimpleNotifyingBean(this); n.setType("resource-not-found"); n.setTitle("Resource not Found"); n.setSource("Cocoon commandline (Main.java)"); n.setMessage("Page Not Available."); n.setDescription("The requested resource couldn't be found."); n.addExtraDescription(Notifying.EXTRA_REQUESTURI, target.getSourceURI()); n.addExtraDescription("missing-file", target.getSourceURI()); ModifiableSource source = getSource(target); OutputStream stream = null; PrintStream out = null; try { stream = source.getOutputStream(); out = new PrintStream(stream); Notifier.notify(n, out, "text/html"); } finally { if (out != null) out.close(); if (stream != null) stream.close(); releaseSource(source); } } }
From source file:org.apache.hadoop.yarn.server.nodemanager.DockerExecutor.java
public void writeLaunchEnv(OutputStream out, Map<String, String> environment, Map<Path, List<String>> resources, List<String> command) throws IOException { ContainerLaunch.ShellScriptBuilder sb = ContainerLaunch.ShellScriptBuilder.create(); Set<String> exclusionSet = new HashSet<String>(); exclusionSet.add(YarnConfiguration.NM_DOCKER_CONTAINER_EXECUTOR_IMAGE_NAME); exclusionSet.add(DOCKER_CMD);// w ww . java2 s .c o m exclusionSet.add(USE_DOCKER_EXECUTOR); exclusionSet.add(ApplicationConstants.Environment.HADOOP_YARN_HOME.name()); exclusionSet.add(ApplicationConstants.Environment.HADOOP_COMMON_HOME.name()); exclusionSet.add(ApplicationConstants.Environment.HADOOP_HDFS_HOME.name()); exclusionSet.add(ApplicationConstants.Environment.HADOOP_CONF_DIR.name()); exclusionSet.add(ApplicationConstants.Environment.JAVA_HOME.name()); if (environment != null) { for (Map.Entry<String, String> env : environment.entrySet()) { if (!exclusionSet.contains(env.getKey())) { sb.env(env.getKey().toString(), env.getValue().toString()); } } } if (resources != null) { for (Map.Entry<Path, List<String>> entry : resources.entrySet()) { for (String linkName : entry.getValue()) { sb.symlink(entry.getKey(), new Path(linkName)); } } } sb.command(command); PrintStream pout = null; PrintStream ps = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { pout = new PrintStream(out, false, "UTF-8"); if (LOG.isDebugEnabled()) { ps = new PrintStream(baos, false, "UTF-8"); sb.write(ps); } sb.write(pout); } finally { if (out != null) { out.close(); } if (ps != null) { ps.close(); } } if (LOG.isDebugEnabled()) { LOG.debug("Script: " + baos.toString("UTF-8")); } }
From source file:at.ofai.music.util.WormFileParseException.java
public void writeLabelFile(String fileName) throws Exception { PrintStream out = new PrintStream(new File(fileName)); out.printf("###Created automatically\n"); for (Event ev : l) out.printf("%5.3f\t%s\n", ev.keyDown, ((WormEvent) ev).label); out.close(); }