List of usage examples for java.io PrintStream close
public void close()
From source file:at.ac.tuwien.big.moea.print.SolutionWriter.java
@Override public String write(final S solution) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream ps = new PrintStream(baos); write(ps, solution);//from w w w .ja v a2 s .co m ps.close(); try { return baos.toString("UTF-8"); } catch (final UnsupportedEncodingException e) { return e.getMessage(); } }
From source file:playground.dgrether.analysis.categoryhistogram.CategoryHistogramWriter.java
public void writeCsv(CategoryHistogram histo, String filename) { PrintStream stream; try {// ww w . j a va2 s .c om stream = new PrintStream(new File(filename + ".csv")); } catch (FileNotFoundException e) { throw new IllegalArgumentException("Filename " + filename + " is not found", e); } write(histo, stream); stream.close(); }
From source file:cc.wikitools.lucene.hadoop.ScoreWikipediaArticleHdfs.java
@SuppressWarnings("static-access") @Override//from www .j ava2s .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("num").hasArg().withDescription("id").create(ID_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("title").create(TITLE_OPTION)); options.addOption( OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION)); 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(ID_OPTION) || cmdline.hasOption(TITLE_OPTION)) || !cmdline.hasOption(INDEX_OPTION) || !cmdline.hasOption(QUERY_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(ScoreWikipediaArticleHdfs.class.getName(), options); System.exit(-1); } String indexLocation = cmdline.getOptionValue(INDEX_OPTION); String queryText = cmdline.getOptionValue(QUERY_OPTION); HdfsWikipediaSearcher searcher = new HdfsWikipediaSearcher(new Path(indexLocation), getConf()); PrintStream out = new PrintStream(System.out, true, "UTF-8"); if (cmdline.hasOption(ID_OPTION)) { out.println("score: " + searcher.scoreArticle(queryText, Integer.parseInt(cmdline.getOptionValue(ID_OPTION)))); } else { out.println("score: " + searcher.scoreArticle(queryText, cmdline.getOptionValue(TITLE_OPTION))); } searcher.close(); out.close(); return 0; }
From source file:com.indeed.imhotep.web.QueryServlet.java
static void handleError(HttpServletResponse resp, boolean json, Throwable e, boolean status500, boolean isEventStream) throws IOException { if (!(e instanceof Exception || e instanceof OutOfMemoryError)) { throw Throwables.propagate(e); }//from w w w . j a v a 2 s. co m // output parse/execute error if (!json) { final ServletOutputStream outputStream = resp.getOutputStream(); final PrintStream printStream = new PrintStream(outputStream); if (isEventStream) { resp.setContentType("text/event-stream"); final String[] stackTrace = Throwables.getStackTraceAsString(e).split("\\n"); printStream.println("event: servererror"); for (String s : stackTrace) { printStream.println("data: " + s); } printStream.println(); } else { resp.setStatus(500); e.printStackTrace(printStream); printStream.close(); } } else { if (status500) { resp.setStatus(500); } // construct a parsed error object to be JSON serialized String clause = ""; int offset = -1; if (e instanceof IQLParseException) { final IQLParseException IQLParseException = (IQLParseException) e; clause = IQLParseException.getClause(); offset = IQLParseException.getOffsetInClause(); } final String stackTrace = Throwables.getStackTraceAsString(Throwables.getRootCause(e)); final ErrorResult error = new ErrorResult(e.getClass().getSimpleName(), e.getMessage(), stackTrace, clause, offset); resp.setContentType("application/json"); final ObjectMapper jsonMapper = new ObjectMapper(); final ServletOutputStream outputStream = resp.getOutputStream(); jsonMapper.defaultPrettyPrintingWriter().writeValue(outputStream, error); outputStream.close(); } }
From source file:edu.umn.cs.spatialHadoop.operations.KNN.java
private static <S extends Shape> long knnLocal(Path inFile, Path outPath, OperationsParams params) throws IOException, InterruptedException { int iterations = 0; FileSystem fs = inFile.getFileSystem(params); Point queryPoint = (Point) OperationsParams.getShape(params, "point"); int k = params.getInt("k", 1); // Top-k objects are retained in this object PriorityQueue<ShapeWithDistance<S>> knn = new KNNObjects<ShapeWithDistance<S>>(k); SpatialInputFormat3<Rectangle, Shape> inputFormat = new SpatialInputFormat3<Rectangle, Shape>(); final GlobalIndex<Partition> gIndex = SpatialSite.getGlobalIndex(fs, inFile); double kthDistance = Double.MAX_VALUE; if (gIndex != null) { // There is a global index, use it PriorityQueue<ShapeWithDistance<Partition>> partitionsToProcess = new PriorityQueue<KNN.ShapeWithDistance<Partition>>() { {/*from w w w .ja v a2 s.co m*/ initialize(gIndex.size()); } @Override protected boolean lessThan(Object a, Object b) { return ((ShapeWithDistance<Partition>) a).distance < ((ShapeWithDistance<Partition>) b).distance; } }; for (Partition p : gIndex) { double distance = p.getMinDistanceTo(queryPoint.x, queryPoint.y); partitionsToProcess.insert(new ShapeWithDistance<Partition>(p.clone(), distance)); } while (partitionsToProcess.size() > 0 && partitionsToProcess.top().distance <= kthDistance) { ShapeWithDistance<Partition> partitionToProcess = partitionsToProcess.pop(); // Process this partition Path partitionPath = new Path(inFile, partitionToProcess.shape.filename); long length = fs.getFileStatus(partitionPath).getLen(); FileSplit fsplit = new FileSplit(partitionPath, 0, length, new String[0]); RecordReader<Rectangle, Iterable<Shape>> 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"); } iterations++; while (reader.nextKeyValue()) { Iterable<Shape> shapes = reader.getCurrentValue(); for (Shape shape : shapes) { double distance = shape.distanceTo(queryPoint.x, queryPoint.y); if (distance <= kthDistance) knn.insert(new ShapeWithDistance<S>((S) shape.clone(), distance)); } } reader.close(); if (knn.size() >= k) kthDistance = knn.top().distance; } } else { // No global index, have to scan the whole file Job job = new Job(params); SpatialInputFormat3.addInputPath(job, inFile); List<InputSplit> splits = inputFormat.getSplits(job); for (InputSplit split : splits) { RecordReader<Rectangle, Iterable<Shape>> reader = inputFormat.createRecordReader(split, null); if (reader instanceof SpatialRecordReader3) { ((SpatialRecordReader3) reader).initialize(split, params); } else if (reader instanceof RTreeRecordReader3) { ((RTreeRecordReader3) reader).initialize(split, params); } else if (reader instanceof HDFRecordReader) { ((HDFRecordReader) reader).initialize(split, params); } else { throw new RuntimeException("Unknown record reader"); } iterations++; while (reader.nextKeyValue()) { Iterable<Shape> shapes = reader.getCurrentValue(); for (Shape shape : shapes) { double distance = shape.distanceTo(queryPoint.x, queryPoint.y); knn.insert(new ShapeWithDistance<S>((S) shape.clone(), distance)); } } reader.close(); } if (knn.size() >= k) kthDistance = knn.top().distance; } long resultCount = knn.size(); if (outPath != null && params.getBoolean("output", true)) { FileSystem outFS = outPath.getFileSystem(params); PrintStream ps = new PrintStream(outFS.create(outPath)); Vector<ShapeWithDistance<S>> resultsOrdered = new Vector<ShapeWithDistance<S>>((int) resultCount); resultsOrdered.setSize((int) resultCount); while (knn.size() > 0) { ShapeWithDistance<S> nextAnswer = knn.pop(); resultsOrdered.set(knn.size(), nextAnswer); } Text text = new Text(); for (ShapeWithDistance<S> answer : resultsOrdered) { text.clear(); TextSerializerHelper.serializeDouble(answer.distance, text, ','); answer.shape.toText(text); ps.println(text); } ps.close(); } TotalIterations.addAndGet(iterations); return resultCount; }
From source file:uk.ac.ebi.intact.editor.controller.misc.ErrorController.java
public String createExceptionMessage() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); ps.println("ViewId: " + viewId); ps.println("Referer: " + referer); ps.println("---------------------------------------------"); if (throwable != null) throwable.printStackTrace(ps);/* w ww . ja va 2 s . c o m*/ ps.close(); return baos.toString(); }
From source file:edu.emory.mathcs.nlp.zzz.CSVSentiment.java
public void toTXT(String inputFile) throws Exception { CSVParser parser = new CSVParser(IOUtils.createBufferedReader(inputFile), CSVFormat.DEFAULT); PrintStream fout = IOUtils.createBufferedPrintStream(inputFile + ".txt"); List<CSVRecord> records = parser.getRecords(); CSVRecord record;// w ww . j ava2 s .c o m System.out.println(inputFile); for (int i = 0; i < records.size(); i++) { if (i == 0) continue; record = records.get(i); fout.println(record.get(6)); } fout.close(); parser.close(); }
From source file:edu.stanford.muse.lens.LensPrefs.java
private void savePrefs() { try {//from w ww. java 2 s. c o m FileOutputStream fos = new FileOutputStream(pathToPrefsFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(prefs); oos.flush(); oos.close(); PrintStream ps = new PrintStream(new FileOutputStream(pathToPrefsFile + ".txt")); for (String term : prefs.keySet()) { Map<String, Float> map = prefs.get(term); for (String url : map.keySet()) ps.println(term + "\t" + url + "\t" + map.get(url)); } ps.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.kylin.tool.KylinConfigCLITest.java
@Test public void testGetPrefix() throws IOException { PrintStream o = System.out; File f = File.createTempFile("cfg", ".tmp"); PrintStream tmpOut = new PrintStream(new FileOutputStream(f)); System.setOut(tmpOut);/*from w ww .ja v a2 s.com*/ KylinConfigCLI.main(new String[] { "kylin.cube.engine." }); String val = FileUtils.readFileToString(f, Charset.defaultCharset()).trim(); assertEquals("2=org.apache.kylin.engine.mr.MRBatchCubingEngine2" + System.lineSeparator() + "0=org.apache.kylin.engine.mr.MRBatchCubingEngine", val); tmpOut.close(); FileUtils.forceDelete(f); System.setOut(o); }
From source file:com.algollabs.rgx.java
private void showSupportedFlags(Request request, Response response, PrintStream stream) { stream.println(supported_flags_.serialize()); stream.close(); }