List of usage examples for java.lang ProcessBuilder redirectOutput
public ProcessBuilder redirectOutput(File file)
From source file:uk.ac.sanger.cgp.wwdocker.actions.Local.java
public static int execCommand(String command, Map envs, boolean shellCmd) { ProcessBuilder pb; if (shellCmd) { pb = new ProcessBuilder("/bin/sh", "-c", command); } else {//from w w w . j ava2 s. c o m pb = new ProcessBuilder(command.split(" ")); } Map<String, String> pEnv = pb.environment(); pEnv.putAll(envs); logger.info("Executing: " + command); int exitCode = -1; Process p = null; File tempOut = null; File tempErr = null; try { tempOut = File.createTempFile("wwdExec", ".out"); tempErr = File.createTempFile("wwdExec", ".err"); pb.redirectOutput(tempOut); pb.redirectError(tempErr); p = pb.start(); exitCode = p.waitFor(); } catch (InterruptedException | IOException e) { logger.error(e.getMessage(), e); } finally { if (tempOut != null && tempErr != null) { try { logger.info(IOUtils.toString(new FileInputStream(tempOut))); logger.error(IOUtils.toString(new FileInputStream(tempErr))); tempOut.delete(); tempErr.delete(); } catch (IOException e) { logger.error("Failed to get output from log files"); } } if (p != null) { p.destroy(); exitCode = p.exitValue(); } } logger.trace("Exit code: " + exitCode); return exitCode; }
From source file:jeplus.RadianceWinTools.java
/** * Call Rtrace to run the simulation/*from ww w.j a v a 2 s . c om*/ * @param config Radiance Configuration * @param WorkDir The working directory where the input files are stored and the output files to be generated * @param args * @param model * @param in * @param out * @param err * @param process * @return the result code represents the state of execution steps. >=0 means successful */ public static int runRtrace(RadianceConfig config, String WorkDir, String args, String model, String in, String out, String err, ProcessWrapper process) { int ExitValue = -99; try { StringBuilder buf = new StringBuilder(config.getResolvedRadianceBinDir()); buf.append(File.separator).append("rtrace"); List<String> command = new ArrayList<>(); command.add(buf.toString()); String[] arglist = args.split("\\s+"); command.addAll(Arrays.asList(arglist)); command.add(model); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedRadianceLibDir()); builder.redirectError(new File(WorkDir + File.separator + err)); builder.redirectOutput(new File(WorkDir + File.separator + out)); builder.redirectInput(new File(WorkDir + File.separator + in)); Process proc = builder.start(); if (process != null) { process.setWrappedProc(proc); } ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing Rtrace", ex); } // Return Radiance exit value return ExitValue; }
From source file:uk.ac.sanger.cgp.wwdocker.actions.Local.java
public static Map<String, String> execCapture(String command, Map envs, boolean shellCmd) { Map<String, String> result = new HashMap(); ProcessBuilder pb; if (shellCmd) { pb = new ProcessBuilder("/bin/sh", "-c", command); } else {/*ww w . j a v a 2 s .c o m*/ pb = new ProcessBuilder(command.split(" ")); } Map<String, String> pEnv = pb.environment(); if (envs != null) { pEnv.putAll(envs); } logger.info("Executing: " + command); int exitCode = -1; Process p = null; File tempOut = null; File tempErr = null; try { tempOut = File.createTempFile("wwdExec", ".out"); tempErr = File.createTempFile("wwdExec", ".err"); pb.redirectOutput(tempOut); pb.redirectError(tempErr); p = pb.start(); exitCode = p.waitFor(); } catch (InterruptedException | IOException e) { logger.error(e.getMessage(), e); } finally { if (tempOut != null && tempErr != null) { try { result.put("stdout", StringUtils.chomp(IOUtils.toString(new FileInputStream(tempOut)))); result.put("stderr", StringUtils.chomp(IOUtils.toString(new FileInputStream(tempErr)))); tempOut.delete(); tempErr.delete(); logger.info(result.get("stdout")); logger.error(result.get("stderr")); } catch (IOException e) { logger.error("Failed to get output from log files"); } } if (p != null) { p.destroy(); exitCode = p.exitValue(); } } result.put("exitCode", Integer.toString(exitCode)); return result; }
From source file:jeplus.RadianceWinTools.java
/** * Call a sequence of DaySim programs to run the simulation * @param config Radiance Configuration//from w ww. j a v a 2s.c om * @param WorkDir The working directory where the input files are stored and the output files to be generated * @param model * @param in * @param out * @param err * @param process * @return the result code represents the state of execution steps. >=0 means successful */ public static int runDaySim(RadianceConfig config, String WorkDir, String model, String in, String out, String err, ProcessWrapper process) { int ExitValue = -99; // Manipulate header file HashMap<String, String> props = new HashMap<>(); // props.put("project_name", ""); props.put("project_directory", "./"); props.put("bin_directory", config.getResolvedDaySimBinDir()); props.put("tmp_directory", "./"); props.put("Template_File", config.getResolvedDaySimBinDir() + "../template/DefaultTemplate.htm"); props.put("sensor_file", in); try { FileUtils.moveFile(new File(WorkDir + File.separator + model), new File(WorkDir + File.separator + model + ".ori")); } catch (IOException ex) { logger.error("Error renaming header file to " + WorkDir + File.separator + model + ".ori", ex); } DaySimModel.updateHeaderFile(WorkDir + File.separator + model + ".ori", WorkDir + File.separator + model, props); // Run gen_dc command try { StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir()); buf.append(File.separator).append("gen_dc"); List<String> command = new ArrayList<>(); command.add(buf.toString()); command.add(model); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir()); builder.redirectError(new File(WorkDir + File.separator + err)); builder.redirectOutput(new File(WorkDir + File.separator + out)); if (in != null) { builder.redirectInput(new File(WorkDir + File.separator + in)); } Process proc = builder.start(); if (process != null) { process.setWrappedProc(proc); } ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing gen_dc", ex); } // Run ds_illum command try { StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir()); buf.append(File.separator).append("ds_illum"); List<String> command = new ArrayList<>(); command.add(buf.toString()); command.add(model); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir()); builder.redirectError(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + err))); builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + out))); if (in != null) { builder.redirectInput(new File(WorkDir + File.separator + in)); } Process proc = builder.start(); if (process != null) { process.setWrappedProc(proc); } ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing ds_illum", ex); } // Run ds_el_lighting command try { StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir()); buf.append(File.separator).append("ds_el_lighting"); List<String> command = new ArrayList<>(); command.add(buf.toString()); command.add(model); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir()); builder.redirectError(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + err))); builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + out))); if (in != null) { builder.redirectInput(new File(WorkDir + File.separator + in)); } Process proc = builder.start(); ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing ds_el_lighting", ex); } // Return Radiance exit value return ExitValue; }
From source file:jeplus.RadianceWinTools.java
/** * Call Rpict to run the simulation// w ww. j a va2 s. c om * @param config Radiance Configuration * @param WorkDir The working directory where the input files are stored and the output files to be generated * @param args * @param model * @param in * @param out * @param err * @param png Switch for converting scene to jpg or not * @param process * @return the result code represents the state of execution steps. >=0 means successful */ public static int runRpict(RadianceConfig config, String WorkDir, String args, String model, String in, String out, String err, boolean png, ProcessWrapper process) { int ExitValue = -99; // Call rpict StringBuilder buf = new StringBuilder(config.getResolvedRadianceBinDir()); buf.append(File.separator).append("rpict"); List<String> command = new ArrayList<>(); command.add(buf.toString()); String[] arglist = args.split("\\s+"); command.addAll(Arrays.asList(arglist)); command.add(model); try { ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedRadianceLibDir()); builder.redirectError(new File(WorkDir + File.separator + err)); builder.redirectOutput(new File(WorkDir + File.separator + out)); if (in != null) { builder.redirectInput(new File(WorkDir + File.separator + in)); } Process proc = builder.start(); if (process != null) { process.setWrappedProc(proc); } ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing Rpict", ex); } if (png) { // Sweep everything with the same extension as out. This is for handling // -o option in rpict String ext = FilenameUtils.getExtension(out); File[] files = new File(WorkDir).listFiles((FileFilter) new WildcardFileFilter("*." + ext)); for (File file : files) { String outname = file.getName(); // Filter scene try { buf = new StringBuilder(config.getResolvedRadianceBinDir()); buf.append(File.separator).append("pfilt"); command = new ArrayList<>(); command.add(buf.toString()); // String [] arglist = "-1 -e -3".split("\\s+"); // command.addAll(Arrays.asList(arglist)); command.add(outname); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedRadianceLibDir()); builder.redirectError(new File(WorkDir + File.separator + err)); builder.redirectOutput(new File(WorkDir + File.separator + outname + ".flt")); Process proc = builder.start(); ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing pfilt", ex); } // Convert to bmp try { buf = new StringBuilder(config.getResolvedRadianceBinDir()); buf.append(File.separator).append("ra_bmp"); command = new ArrayList<>(); command.add(buf.toString()); //String [] arglist = "-g 1.0".split("\\s+"); //command.addAll(Arrays.asList(arglist)); command.add(outname + ".flt"); command.add(outname + ".bmp"); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedRadianceLibDir()); builder.redirectError( ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + err))); Process proc = builder.start(); ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing ra_bmp", ex); } // Convert to png BufferedImage input_image = null; try { input_image = ImageIO.read(new File(WorkDir + File.separator + outname + ".bmp")); //read bmp into input_image object File outputfile = new File(WorkDir + File.separator + outname + ".png"); //create new outputfile object ImageIO.write(input_image, "png", outputfile); //write PNG output to file } catch (Exception ex) { logger.error("Error converting bmp to png.", ex); } // Remove flt and bmp new File(WorkDir + File.separator + outname + ".flt").delete(); new File(WorkDir + File.separator + outname + ".bmp").delete(); } } // Return Radiance exit value return ExitValue; }
From source file:hyperheuristics.main.comparisons.CompareHypervolumes.java
private static void hypervolumeComparison(String[] problems, String[] heuristicFunctions, int numberOfObjectives) throws InterruptedException, IOException { for (String heuristicFunction : heuristicFunctions) { String path = outpath;/* w ww. j a v a2 s. c o m*/ String outputDirectory = path + numberOfObjectives + "objectives/" + heuristicFunction + "/"; try (FileWriter fileWriter = new FileWriter(outputDirectory + "HYPERVOLUMES.txt")) { int hyperheuristicBest = 0; int mecbaBest = 0; int tied = 0; int hyperheuristicBestMean = 0; int mecbaBestMean = 0; int tiedMean = 0; int equivalent = 0; for (String problem : problems) { fileWriter.append("Hypervolume comparison for " + problem + ":\n"); fileWriter.append("\n"); HypervolumeHandler hypervolumeHandler = new HypervolumeHandler(); String hyperheuristicDirectory = outputDirectory + problem + "/"; String mecbaDirectory = "resultado/nsgaii/" + problem + "_Comb_" + numberOfObjectives + "obj/"; //Best hypervolume for PFknown hypervolumeHandler.addParetoFront(hyperheuristicDirectory + "FUN.txt"); hypervolumeHandler.addParetoFront(mecbaDirectory + "All_FUN_nsgaii-" + problem); double mecbaHypervolume = hypervolumeHandler .calculateHypervolume(mecbaDirectory + "All_FUN_nsgaii-" + problem, numberOfObjectives); double hyperheuristicHypervolume = hypervolumeHandler .calculateHypervolume(hyperheuristicDirectory + "FUN.txt", numberOfObjectives); fileWriter.append("MECBA PFknown: " + mecbaHypervolume + "\n"); fileWriter.append(heuristicFunction + " PFknown: " + hyperheuristicHypervolume + "\n"); if (mecbaHypervolume == hyperheuristicHypervolume) { fileWriter.append("Best PFknown: Tied!\n"); tied++; } else { if (mecbaHypervolume > hyperheuristicHypervolume) { fileWriter.append("Best PFknown: MECBA\n"); mecbaBest++; } else { fileWriter.append("Best PFknown: " + heuristicFunction + "\n"); hyperheuristicBest++; } } //Best mean hypervolume fileWriter.append("\n"); hypervolumeHandler.clear(); for (int i = 0; i < EXECUTIONS; i++) { hypervolumeHandler.addParetoFront(hyperheuristicDirectory + "EXECUTION_" + i + "/FUN.txt"); hypervolumeHandler.addParetoFront( mecbaDirectory + "FUN_nsgaii-" + problem + "-" + i + ".NaoDominadas"); } double[] mecbaHypervolumes = new double[EXECUTIONS]; double[] hyperheuristicHypervolumes = new double[EXECUTIONS]; mecbaHypervolume = 0; hyperheuristicHypervolume = 0; for (int i = 0; i < EXECUTIONS; i++) { mecbaHypervolumes[i] = hypervolumeHandler.calculateHypervolume( mecbaDirectory + "FUN_nsgaii-" + problem + "-" + i + ".NaoDominadas", numberOfObjectives); mecbaHypervolume += mecbaHypervolumes[i]; hyperheuristicHypervolumes[i] = hypervolumeHandler.calculateHypervolume( hyperheuristicDirectory + "EXECUTION_" + i + "/FUN.txt", numberOfObjectives); hyperheuristicHypervolume += hyperheuristicHypervolumes[i]; } mecbaHypervolume /= (double) EXECUTIONS; hyperheuristicHypervolume /= (double) EXECUTIONS; fileWriter.append("MECBA (Mean): " + mecbaHypervolume + "\n"); fileWriter.append(heuristicFunction + " (Mean): " + hyperheuristicHypervolume + "\n"); if (mecbaHypervolume == hyperheuristicHypervolume) { fileWriter.append("Best (Mean): Tied!\n"); tiedMean++; } else { if (mecbaHypervolume > hyperheuristicHypervolume) { fileWriter.append("Best (Mean): MECBA\n"); mecbaBestMean++; } else { fileWriter.append("Best (Mean): " + heuristicFunction + "\n"); hyperheuristicBestMean++; } String script = ""; script += "MECBA <- c("; for (double value : mecbaHypervolumes) { script += value + ","; } script = script.substring(0, script.lastIndexOf(",")) + ")"; script += "\n"; script += "MECBA_Hyp <- c("; for (double value : hyperheuristicHypervolumes) { script += value + ","; } script = script.substring(0, script.lastIndexOf(",")) + ")"; script += "\n"; script += "require(pgirmess)\n"; script += "AR1 <- cbind(MECBA, MECBA_Hyp)\n"; script += "result <- friedman.test(AR1)\n"; script += "m <- data.frame(result$statistic,result$p.value)\n"; script += "pos_teste <- friedmanmc(AR1)\n"; script += "print(pos_teste)"; try (FileWriter scriptWriter = new FileWriter(hyperheuristicDirectory + "temp_input.txt")) { scriptWriter.append(script); } ProcessBuilder processBuilder = new ProcessBuilder("R", "--no-save"); File tempOutput = new File(hyperheuristicDirectory + "temp_output.txt"); processBuilder.redirectOutput(tempOutput); File tempInput = new File(hyperheuristicDirectory + "temp_input.txt"); processBuilder.redirectInput(tempInput); Process process = processBuilder.start(); process.waitFor(); Scanner scanner = new Scanner(tempOutput); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("FALSE")) { equivalent++; fileWriter.append("Statistical Equivalents (Friedman 5%)\n"); break; } } tempInput.delete(); tempOutput.delete(); } fileWriter.append("\n"); fileWriter.append("----------\n"); fileWriter.append("\n"); } fileWriter.append("Problems: " + problems.length + "\n"); fileWriter.append("\n"); fileWriter.append("Tied PFknown: " + tied + "\n"); fileWriter.append("MECBA PFknown: " + mecbaBest + "\n"); fileWriter.append(heuristicFunction + " PFknown: " + hyperheuristicBest + "\n"); fileWriter.append("\n"); fileWriter.append("Tied (Mean): " + tiedMean + "\n"); fileWriter.append("MECBA (Mean): " + mecbaBestMean + "\n"); fileWriter.append(heuristicFunction + " (Mean): " + hyperheuristicBestMean + "\n"); fileWriter.append("Statistically Equivalent: " + equivalent + "\n"); } } }
From source file:se.trixon.toolbox.alphatrans.cmd.CmdIconv.java
public String convert(File source, File dest, String fromCharset, String toCharset, boolean omit) { String result = null;//from ww w. j a v a 2 s. co m ArrayList<String> cmdElements = new ArrayList<>(); cmdElements.add(mCommand); cmdElements.add("-f"); cmdElements.add(fromCharset); cmdElements.add("-t"); cmdElements.add(toCharset); if (omit) { cmdElements.add("-c"); } cmdElements.add(source.getAbsolutePath()); String[] cmd = cmdElements.toArray(new String[cmdElements.size()]); Xlog.v(AlphatransController.LOG_TAG, StringUtils.join(cmd, " ")); ProcessBuilder processBuilder = new ProcessBuilder(cmd); processBuilder.redirectOutput(dest); try { Process process = processBuilder.start(); process.waitFor(); result = IOUtils.toString(process.getErrorStream()); if (result.length() == 0) { result = null; } } catch (IOException | InterruptedException ex) { Exceptions.printStackTrace(ex); } return result; }
From source file:org.apache.hyracks.control.nc.service.NCService.java
/** * Attempts to launch the "real" NCDriver, based on the configuration * information gathered so far./* w ww. j a v a 2 s.c om*/ * @return true if the process was successfully launched and has now * exited with a 0 (normal) exit code. false if some configuration error * prevented the process from being launched or the process returned * a non-0 (abnormal) exit code. */ private static boolean launchNCProcess() { try { ProcessBuilder pb = new ProcessBuilder(buildCommand()); configEnvironment(pb.environment()); // QQQ inheriting probably isn't right pb.inheritIO(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("Launching NCDriver process"); } // Logfile if (!"-".equals(config.logdir)) { pb.redirectErrorStream(true); File log = new File(config.logdir); if (!log.mkdirs()) { if (!log.isDirectory()) { throw new IOException(config.logdir + ": cannot create"); } // If the directory IS there, all is well } File logfile = new File(config.logdir, "nc-" + ncId + ".log"); // Don't care if this succeeds or fails: logfile.delete(); pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logfile)); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("Logging to " + logfile.getCanonicalPath()); } } proc = pb.start(); boolean waiting = true; int retval = 0; while (waiting) { try { retval = proc.waitFor(); waiting = false; } catch (InterruptedException ignored) { } } LOGGER.info("NCDriver exited with return value " + retval); if (retval == 99) { LOGGER.info("Terminating NCService based on return value from NCDriver"); exit(0); } return retval == 0; } catch (Exception e) { if (LOGGER.isLoggable(Level.SEVERE)) { LOGGER.log(Level.SEVERE, "Configuration from CC broken", e); } return false; } }
From source file:com.orange.clara.cloud.servicedbdumper.dbdumper.core.AbstractCoreDbAction.java
protected Process runCommandLine(String[] commandLine, boolean inInheritOutput) throws IOException, InterruptedException { ProcessBuilder pb = this.generateProcessBuilder(commandLine); if (inInheritOutput) { pb.redirectOutput(ProcessBuilder.Redirect.INHERIT); } else {// w ww . jav a2s .co m pb.redirectOutput(ProcessBuilder.Redirect.PIPE); } pb.redirectErrorStream(true); Process process = pb.start(); return process; }
From source file:org.fiware.cybercaptor.server.api.InformationSystemManagement.java
/** * Execute the python script that builds MulVAL inputs * * @return boolean true if the execution was right *//*from ww w. ja va 2s .co m*/ public static boolean prepareMulVALInputs() { try { //Load python script properties String pythonPath = ProjectProperties.getProperty("python-path"); String mulvalInputScriptFolder = ProjectProperties.getProperty("mulval-input-script-folder"); String mulvalInputScriptPath = mulvalInputScriptFolder + "main.py"; String hostInterfacePath = ProjectProperties.getProperty("host-interfaces-path"); String vlansPath = ProjectProperties.getProperty("vlans-path"); String routingPath = ProjectProperties.getProperty("routing-path"); String flowMatrixPath = ProjectProperties.getProperty("flow-matrix-path"); String vulnerabilityScanPath = ProjectProperties.getProperty("vulnerability-scan-path"); String mulvalInputPath = ProjectProperties.getProperty("mulval-input"); String topologyPath = ProjectProperties.getProperty("topology-path"); File mulvalInputFile = new File(mulvalInputPath); if (mulvalInputFile.exists()) { mulvalInputFile.delete(); } Logger.getAnonymousLogger().log(Level.INFO, "Genering MulVAL inputs"); //TODO: use parameter nessus-files-path rather than vulnerability-scan-path, in order to manage when // mutliple nessus files are provided. ProcessBuilder processBuilder = new ProcessBuilder(pythonPath, mulvalInputScriptPath, "--hosts-interfaces-file", hostInterfacePath, "--vlans-file", vlansPath, "--flow-matrix-file", flowMatrixPath, "--vulnerability-scan", vulnerabilityScanPath, "--routing-file", routingPath, "--mulval-output-file", mulvalInputFile.getAbsolutePath(), "--to-fiware-xml-topology", topologyPath); processBuilder.directory(new File(mulvalInputScriptFolder)); StringBuilder command = new StringBuilder(); for (String str : processBuilder.command()) command.append(str + " "); Logger.getAnonymousLogger().log(Level.INFO, "Launch generation of MulVAL inputs with command : \n" + command.toString()); processBuilder.redirectOutput( new File(ProjectProperties.getProperty("output-path") + "/input-generation.log")); processBuilder.redirectError( new File(ProjectProperties.getProperty("output-path") + "/input-generation.log")); Process process = processBuilder.start(); process.waitFor(); if (!mulvalInputFile.exists()) { Logger.getAnonymousLogger().log(Level.WARNING, "A problem happened in the generation of mulval inputs"); return false; } return true; } catch (Exception e) { e.printStackTrace(); } return false; }