List of usage examples for java.io PrintStream close
public void close()
From source file:net.rim.ejde.internal.packaging.PackagingManager.java
private void flushToFile(File file) throws IOException { FileOutputStream fout = null; PrintStream indirect = null; try {// w ww. jav a 2 s. c om ByteArrayOutputStream bout = new ByteArrayOutputStream(); indirect = new PrintStream(bout, false, "UTF-8"); for (int i = 0; i < _rapcCommands.size(); i++) { indirect.println(_rapcCommands.get(i)); } indirect.close(); byte[] newBytes = bout.toByteArray(); // either old file doesn't exist or it isn't the same // write out the new data fout = new FileOutputStream(file); fout.write(newBytes); fout.close(); } finally { if (indirect != null) { indirect.close(); } if (fout != null) { fout.close(); } } }
From source file:hu.sztaki.ilab.bigdata.common.tools.hbase.PerformanceEvaluation.java
private Path writeInputFile(final Configuration c) throws IOException { FileSystem fs = FileSystem.get(c); if (!fs.exists(PERF_EVAL_DIR)) { fs.mkdirs(PERF_EVAL_DIR);/* www . jav a 2 s . c o m*/ } SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); Path subdir = new Path(PERF_EVAL_DIR, formatter.format(new Date())); fs.mkdirs(subdir); Path inputFile = new Path(subdir, "input.txt"); PrintStream out = new PrintStream(fs.create(inputFile)); // Make input random. Map<Integer, String> m = new TreeMap<Integer, String>(); Hash h = MurmurHash.getInstance(); int perClientRows = (R / N); try { for (int i = 0; i < 10; i++) { for (int j = 0; j < N; j++) { String s = "startRow=" + ((j * perClientRows) + (i * (perClientRows / 10))) + ", perClientRunRows=" + (perClientRows / 10) + ", totalRows=" + R + ", clients=" + N + ", rowsPerPut=" + B; int hash = h.hash(Bytes.toBytes(s)); m.put(hash, s); } } for (Map.Entry<Integer, String> e : m.entrySet()) { out.println(e.getValue()); } } finally { out.close(); } return subdir; }
From source file:com.bluexml.side.util.dependencies.MavenUtil.java
@SuppressWarnings("unchecked") private MavenExecutionResult doMavenGoalUsingMavenCli(File baseDir, List<String> goals, Map<String, String> parameters, List<String> profiles, Boolean offline) throws Exception { // save the current classloader ... maven play with thread classloader Grrr ClassLoader cl = Thread.currentThread().getContextClassLoader(); // Instantiate MavenClient MavenCli mci = new MavenCli(); String workingDirectory = baseDir.getAbsolutePath(); // build arguments list List<String> argsL = new ArrayList<String>(); argsL.addAll(goals);/*from ww w. ja va2s . c o m*/ // Additional parameters // disable interactive mode argsL.add("-B"); //$NON-NLS-1$ // display stacktrace if error occur argsL.add("-e"); //$NON-NLS-1$ // argsL.add("-X"); //$NON-NLS-1$ if (offline == null) { offline = false; } // offline mode activated if (offline) { argsL.add("-o"); //$NON-NLS-1$ } // active profile parameter if (profiles != null && profiles.size() > 0) { String profileParam = ""; //$NON-NLS-1$ Iterator<String> iterator = profiles.iterator(); while (iterator.hasNext()) { profileParam += iterator.next(); if (iterator.hasNext()) { profileParam += ","; //$NON-NLS-1$ } } argsL.add("-P " + profileParam); //$NON-NLS-1$ } // user Properties if (parameters != null) { for (Map.Entry<String, String> entry : parameters.entrySet()) { argsL.add("-D" + entry.getKey() + "=" + entry.getValue()); //$NON-NLS-1$ //$NON-NLS-2$ } } // define streams // TODO use PrintStreamLogger to implement maven logging and error detection File mvOutFile = new File(baseDir, "log.txt"); //$NON-NLS-1$ PrintStream stdout = new PrintStream(mvOutFile); File mvOutErrFile = new File(baseDir, "log-err.txt"); //$NON-NLS-1$ PrintStream stderr = new PrintStream(mvOutErrFile); stdout.println("MavenUtil execute maven request :"); //$NON-NLS-1$ String commandFromMavenExecutionArgs = getCommandFromMavenExecutionArgs(argsL); stdout.println("** args :" + commandFromMavenExecutionArgs); //$NON-NLS-1$ stdout.println("** working directory :" + workingDirectory); //$NON-NLS-1$ System.out.println("MavenUtil.doMavenGoalUsingMavenCli() dir :" + workingDirectory); System.out.println("MavenUtil.doMavenGoalUsingMavenCli() > " + commandFromMavenExecutionArgs); String[] args = argsL.toArray(new String[argsL.size()]); // execute maven request mci.doMain(args, workingDirectory, stdout, stderr); // build a MavenEcecutionResult DefaultMavenExecutionResult defaultMavenExecutionResult = new DefaultMavenExecutionResult(); // restore classloader Thread.currentThread().setContextClassLoader(cl); // search in output for errors Iterator<String> it = FileUtils.lineIterator(mvOutFile); List<String> errorLines = new ArrayList<String>(); String errors = ""; //$NON-NLS-1$ while (it.hasNext()) { String line = it.next(); if (line.startsWith("[ERROR]")) { //$NON-NLS-1$ errorLines.add(line); errors += line; errors += "\n"; //$NON-NLS-1$ } } if (errorLines.size() > 0) { defaultMavenExecutionResult.addException(new Exception(errors)); } // close output streams stdout.close(); stderr.close(); return defaultMavenExecutionResult; }
From source file:org.apache.hadoop.hbase.stargate.PerformanceEvaluation.java
private Path writeInputFile(final Configuration c) throws IOException { FileSystem fs = FileSystem.get(c); if (!fs.exists(PERF_EVAL_DIR)) { fs.mkdirs(PERF_EVAL_DIR);// w ww. j av a 2 s . co m } SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); Path subdir = new Path(PERF_EVAL_DIR, formatter.format(new Date())); fs.mkdirs(subdir); Path inputFile = new Path(subdir, "input.txt"); PrintStream out = new PrintStream(fs.create(inputFile)); // Make input random. Map<Integer, String> m = new TreeMap<Integer, String>(); Hash h = MurmurHash.getInstance(); int perClientRows = (this.R / this.N); try { for (int i = 0; i < 10; i++) { for (int j = 0; j < N; j++) { String s = "startRow=" + ((j * perClientRows) + (i * (perClientRows / 10))) + ", perClientRunRows=" + (perClientRows / 10) + ", totalRows=" + this.R + ", clients=" + this.N + ", rowsPerPut=" + this.B; int hash = h.hash(Bytes.toBytes(s)); m.put(hash, s); } } for (Map.Entry<Integer, String> e : m.entrySet()) { out.println(e.getValue()); } } finally { out.close(); } return subdir; }
From source file:com.basistech.lucene.tools.LuceneQueryTool.java
void runScript(String scriptPath) throws IOException, ParseException { try (BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(scriptPath), Charsets.UTF_8))) { int lineno = 0; String line;/* w w w.j ava 2 s . c om*/ while ((line = in.readLine()) != null) { lineno++; if (line.trim().isEmpty()) { continue; } // This is Ant's Commandline class. We need it because commons-cli // only has an interface from String[], where it expects the shell // has handled the quoting to give you this array. But here we lines // in a script file and no shell to help us. Commandline cl = new Commandline(line); PrintStream out = defaultOut; String query = null; String[] args = cl.getCommandline(); int i = 0; while (i < args.length) { String arg = args[i]; if ("-o".equals(arg) || "-output".equals(arg) || "--output".equals(arg)) { i++; out = new PrintStream(new FileOutputStream(new File(args[i])), true); } else if ("-q".equals(arg) || "-query".equals(arg) || "--query".equals(arg)) { i++; query = args[i]; if (query.startsWith("%")) { throw new RuntimeException( String.format("%s:%d: script does not support %% queries", scriptPath, lineno)); } } else { throw new RuntimeException( String.format("%s:%d: script supports only -q and -o", scriptPath, lineno)); } i++; } if (query == null || query.startsWith("%")) { throw new RuntimeException(String.format("%s:%d: script line requires -q", scriptPath, lineno)); } runQuery(query, out); if (out != defaultOut) { out.close(); } } } }
From source file:net.sourceforge.dita4publishers.tools.mapreporter.MapBosReporter.java
/** * @throws Exception //from w w w . j a va2 s. co m * */ private void run() throws Exception { String mapFilepath = commandLine.getOptionValue("i"); File mapFile = new File(mapFilepath); checkExistsAndCanReadSystemExit(mapFile); System.err.println("Processing map \"" + mapFile.getAbsolutePath() + "\"..."); PrintStream outStream = System.out; if (commandLine.hasOption(OUTPUT_OPTION_ONE_CHAR)) { String outputFilepath = commandLine.getOptionValue("o"); File outputFile = new File(outputFilepath); if (!outputFile.getParentFile().canWrite()) { throw new RuntimeException("File " + outputFile.getAbsolutePath() + " cannot be written to."); } outStream = new PrintStream(outputFile); } DitaBosReporter bosReporter = getBosReporter(outStream); KeySpaceReporter keyreporter = getKeyspaceReporter(outStream); Document rootMap = null; BosConstructionOptions bosOptions = new BosConstructionOptions(log, new HashMap<URI, Document>()); if (commandLine.hasOption(MAPTREE_OPTION_ONE_CHAR)) { bosOptions.setMapTreeOnly(true); System.err.println("MapBosReporter: Calculating map tree..."); } else { System.err.println("MapBosReporter: Calculating full map BOS..."); } setupCatalogs(bosOptions); try { URL rootMapUrl = mapFile.toURI().toURL(); rootMap = DomUtil.getDomForUri(new URI(rootMapUrl.toExternalForm()), bosOptions); Date startTime = TimingUtils.getNowTime(); DitaBoundedObjectSet mapBos = DitaBosHelper.calculateMapBos(bosOptions, log, rootMap); System.err.println("Map BOS construction took " + TimingUtils.reportElapsedTime(startTime)); BosReportOptions bosReportOptions = new BosReportOptions(); bosReporter.report(mapBos, bosReportOptions); DitaKeySpace keySpace = mapBos.getKeySpace(); KeyReportOptions reportOptions = new KeyReportOptions(); reportOptions.setAllKeys(true); keyreporter.report(new KeyAccessOptions(), keySpace, reportOptions); } catch (Exception e) { e.printStackTrace(); } finally { outStream.close(); } }
From source file:josejamilena.pfc.servidor.chartserver.ClientHandler.java
/** * Mtodo que ejecuta el Thread.//from w ww. ja v a2 s.co m */ @Override public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(miSocketServidor.getInputStream())); PrintStream out = new PrintStream(new BufferedOutputStream(miSocketServidor.getOutputStream())); String s = in.readLine(); // System.out.println(s); // Salida para el Log // Atiende a servir archivos. String filename = ""; StringTokenizer st = new StringTokenizer(s); try { // Parsea la peticin desde el comando GET if (st.hasMoreElements() && st.nextToken().equalsIgnoreCase("GET") && st.hasMoreElements()) { filename = st.nextToken(); } else { throw new FileNotFoundException(); } // Aade "/" with "index.html" if (filename.endsWith("/")) { filename += nombreFichero; } // Quita / del nombre del archivo while (filename.indexOf("/") == 0) { filename = filename.substring(1); } // Reemplaza "/" por "\" en el path para servidores en Win32 filename = filename.replace('/', File.separator.charAt(0)); /* Comprueba caracteres no permitidos, para impedir acceder a directorios superiores */ if ((filename.indexOf("..") >= 0) || (filename.indexOf(':') >= 0) || (filename.indexOf('|') >= 0)) { throw new FileNotFoundException(); } // Si la peticin de acceso a un directorio no tiene "/", // envia al cliente un respuesta HTTP if (new File(filename).isDirectory()) { filename = filename.replace('\\', '/'); out.print( "HTTP/1.0 301 Movido permantemente \r\n" + "Albergado en: /" + filename + "/\r\n\r\n"); out.close(); return; } // Abriendo el archivo (puede lanzar FileNotFoundException) InputStream f = new FileInputStream(filename); // Determina el tipe MIME e imprime la cabecera HTTP String mimeType = "text/plain"; if (filename.endsWith(".html") || filename.endsWith(".htm")) { mimeType = "text/html"; } else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) { mimeType = "image/jpeg"; } else if (filename.endsWith(".gif")) { mimeType = "image/gif"; } else if (filename.endsWith(".class")) { mimeType = "application/octet-stream"; } else if (filename.endsWith(".jnlp")) { mimeType = "application/x-java-jnlp-file"; } out.print("HTTP/1.0 200 OK\r\n" + "Server: josejamilena_Torito-Chart-Server\r\n" + "Content-type: " + mimeType + "\r\n\r\n"); // Envia el fichero ala cliente, y cierra la conexin byte[] a = new byte[bufferSize]; int n; while ((n = f.read(a)) > 0) { out.write(a, 0, n); } f.close(); out.close(); } catch (FileNotFoundException x) { out.println("HTTP/1.0 404 No encontrado.\r\n" + "Server: josejamilena_Torito-Chart-Server\r\n" + "Content-type: text/html\r\n\r\n" + "<html><head></head><body>" + "El fichero " + filename + " no ha sido encontrado.</body></html>\n"); out.close(); } } catch (IOException x) { System.out.println(x); } finally { File aborrar = new File(nombreFichero); org.apache.commons.io.FileUtils.deleteQuietly(aborrar); } }
From source file:fr.certu.chouette.command.ExchangeCommand.java
/** * @param beans//from w w w . ja va 2 s .c om * @param manager * @param parameters * @throws ChouetteException */ public void executeValidate(List<NeptuneIdentifiedObject> beans, INeptuneManager<NeptuneIdentifiedObject> manager, Map<String, List<String>> parameters) throws ChouetteException { String fileName = getSimpleString(parameters, "file", ""); boolean append = getBoolean(parameters, "append"); JSONObject validationParameters; try { String json = FileUtils.readFileToString(new File("parameterset.json")); validationParameters = new JSONObject(json); } catch (IOException e1) { System.err.println("cannot open file :parameterset.json"); e1.printStackTrace(); return; } PhaseReportItem valReport = new PhaseReportItem(PhaseReportItem.PHASE.THREE); manager.validate(null, beans, validationParameters, valReport, null, true); PrintStream stream = System.out; if (!fileName.isEmpty()) { try { stream = new PrintStream(new FileOutputStream(new File(fileName), append)); } catch (FileNotFoundException e) { System.err.println("cannot open file :" + fileName); fileName = ""; } } stream.println(valReport.getLocalizedMessage()); printItems(stream, "", valReport.getItems()); int nbUNCHECK = 0; int nbOK = 0; int nbWARN = 0; int nbERROR = 0; int nbFATAL = 0; for (ReportItem item1 : valReport.getItems()) // Categorie { if (item1.getItems() != null) for (ReportItem item2 : item1.getItems()) // fiche { STATE status = item2.getStatus(); switch (status) { case UNCHECK: nbUNCHECK++; break; case OK: nbOK++; break; case WARNING: nbWARN++; break; case ERROR: nbERROR++; break; case FATAL: nbFATAL++; break; } } } stream.println("Bilan : " + nbOK + " tests ok, " + nbWARN + " warnings, " + nbERROR + " erreurs, " + nbUNCHECK + " non effectus, " + nbFATAL + " fatals"); if (!fileName.isEmpty()) { stream.close(); } }
From source file:PerformanceEvaluation.java
private Path writeInputFile(final Configuration c) throws IOException { FileSystem fs = FileSystem.get(c); if (!fs.exists(PERF_EVAL_DIR)) { fs.mkdirs(PERF_EVAL_DIR);// w w w. j av a2s . co m } SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); Path subdir = new Path(PERF_EVAL_DIR, formatter.format(new Date())); fs.mkdirs(subdir); Path inputFile = new Path(subdir, "input.txt"); PrintStream out = new PrintStream(fs.create(inputFile)); // Make input random. Map<Integer, String> m = new TreeMap<Integer, String>(); Hash h = MurmurHash.getInstance(); int perClientRows = (this.R / this.N); try { for (int i = 0; i < 10; i++) { for (int j = 0; j < N; j++) { String s = "startRow=" + ((j * perClientRows) + (i * (perClientRows / 10))) + ", perClientRunRows=" + (perClientRows / 10) + ", totalRows=" + this.R + ", clients=" + this.N + ", flushCommits=" + this.flushCommits + ", writeToWAL=" + this.writeToWAL + ", scanCache=" + this.S; int hash = h.hash(Bytes.toBytes(s)); m.put(hash, s); } } for (Map.Entry<Integer, String> e : m.entrySet()) { out.println(e.getValue()); } } finally { out.close(); } return subdir; }