List of usage examples for java.lang Process waitFor
public abstract int waitFor() throws InterruptedException;
From source file:com.jsystem.j2autoit.AutoItAgent.java
private static String extractLocation(String regkey) throws Exception { String cmd = "reg query " + regkey + " /ve"; Process child = Runtime.getRuntime().exec(cmd); child.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(child.getInputStream())); StringBuffer sb = new StringBuffer(""); String line = null;// ww w .j a v a 2s . co m while ((line = br.readLine()) != null) { sb.append(line).append(NEW_LINE); } Matcher mat = PATTERN_EXTRACTING_AUTOIT_LOCATION.matcher(sb.toString()); if (mat.find()) { return mat.group(mat.groupCount()).trim(); } else { throw new Exception("Unable to find AutoIt Location"); } }
From source file:edu.ucsd.sbrg.escher.EscherConverter.java
/** * Extracts CoBRA from {@link SBMLDocument} if it is FBC compliant. cobrapy must be present for * this./*from w w w . j a va2 s . co m*/ * * @param file Input file. * @return Result of extraction. * @throws IOException Thrown if there are problems in reading the {@code input} file(s). * @throws XMLStreamException Thrown if there are problems in parsing XML file(s). */ public static boolean extractCobraModel(File file) throws IOException, XMLStreamException { if (false) { logger.warning(format(bundle.getString("SBMLFBCNotAvailable"), file.getName())); return false; } else { logger.info(format(bundle.getString("SBMLFBCInit"), file.getName())); // Execute: py3 -c "from cobra import io; // io.save_json_model(model=io.read_sbml_model('FILENAME'), file_name='FILENAME')" String[] command; command = new String[] { "python3", "-c", "\"print('yo');from cobra import io;" + "io.save_json_model(model=io.read_sbml_model('" + file.getAbsolutePath() + "'), file_name='" + file.getAbsolutePath() + ".json" + "');print('yo')\"", "> /temp/log" }; // command = new String[] {"/usr/local/bin/python3", "-c", "\"print('yo')\""}; command = new String[] { "python3" }; Process p; try { // p = new ProcessBuilder(command).redirectErrorStream(true).start(); p = Runtime.getRuntime().exec(command); p.waitFor(); if (p.exitValue() == 0) { logger.info(format(bundle.getString("SBMLFBCExtractionSuccessful"), file.getAbsolutePath(), file.getAbsolutePath())); InputStream is = p.getErrorStream(); is = p.getInputStream(); OutputStream os = p.getOutputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String cobrapy_output = ""; cobrapy_output = reader.readLine(); while (cobrapy_output != null) { logger.warning(cobrapy_output); cobrapy_output = reader.readLine(); } return true; } else { logger.info(format(bundle.getString("SBMLFBCExtractionFailed"))); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String cobrapy_output = ""; cobrapy_output = reader.readLine(); while (cobrapy_output != null) { logger.warning(cobrapy_output); cobrapy_output = reader.readLine(); } return false; } } catch (InterruptedException e) { e.printStackTrace(); return false; } } }
From source file:com.ikon.util.ExecutionUtils.java
/** * Execute command line: implementation//from w w w . java2 s. c om */ private static ExecutionResult runCmdImpl(final String cmd[], final long timeout) throws SecurityException, InterruptedException, IOException { log.debug("runCmdImpl({}, {})", Arrays.toString(cmd), timeout); ExecutionResult ret = new ExecutionResult(); long start = System.currentTimeMillis(); final ProcessBuilder pb = new ProcessBuilder(cmd); final Process process = pb.start(); Timer t = new Timer("Process Execution Timeout"); t.schedule(new TimerTask() { @Override public void run() { process.destroy(); log.warn("Process killed due to timeout."); log.warn("CommandLine: {}", Arrays.toString(cmd)); } }, timeout); try { ret.setStdout(IOUtils.toString(process.getInputStream())); ret.setStderr(IOUtils.toString(process.getErrorStream())); } catch (IOException e) { // Ignore } process.waitFor(); t.cancel(); ret.setExitValue(process.exitValue()); // Check return code if (ret.getExitValue() != 0) { log.warn("Abnormal program termination: {}", ret.getExitValue()); log.warn("CommandLine: {}", Arrays.toString(cmd)); log.warn("STDERR: {}", ret.getStderr()); } else { log.debug("Normal program termination"); } process.destroy(); log.debug("Elapse time: {}", FormatUtil.formatSeconds(System.currentTimeMillis() - start)); return ret; }
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 w w .j a v a2 s . c om*/ 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:Main.java
private static List<Integer> getAllRelatedPids(final int pid) { List<Integer> result = new ArrayList<Integer>(Arrays.asList(pid)); // use 'ps' to get this pid and all pids that are related to it (e.g. // spawned by it) try {/*w ww . ja v a2 s. c om*/ final Process suProcess = Runtime.getRuntime().exec("su"); new Thread(new Runnable() { @Override public void run() { PrintStream outputStream = null; try { outputStream = new PrintStream(new BufferedOutputStream(suProcess.getOutputStream(), 8192)); outputStream.println("ps"); outputStream.println("exit"); outputStream.flush(); } finally { if (outputStream != null) { outputStream.close(); } } } }).run(); if (suProcess != null) { try { suProcess.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } } BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new InputStreamReader(suProcess.getInputStream()), 8192); while (bufferedReader.ready()) { String[] line = SPACES_PATTERN.split(bufferedReader.readLine()); if (line.length >= 3) { try { if (pid == Integer.parseInt(line[2])) { result.add(Integer.parseInt(line[1])); } } catch (NumberFormatException ignore) { } } } } finally { if (bufferedReader != null) { bufferedReader.close(); } } } catch (IOException e1) { e1.printStackTrace(); } return result; }
From source file:com.cloudera.sqoop.manager.MySQLTestUtils.java
/** @return the current username. */ public static String getCurrentUser() { // First, check the $USER environment variable. String envUser = System.getenv("USER"); if (null != envUser) { return envUser; }/*from w ww . ja v a 2 s . c o m*/ // Try `whoami` String[] whoamiArgs = new String[1]; whoamiArgs[0] = "whoami"; Process p = null; BufferedReader r = null; try { p = Runtime.getRuntime().exec(whoamiArgs); InputStream is = p.getInputStream(); r = new BufferedReader(new InputStreamReader(is)); return r.readLine(); } catch (IOException ioe) { LOG.error("IOException reading from `whoami`: " + ioe.toString()); return null; } finally { // close our stream. if (null != r) { try { r.close(); } catch (IOException ioe) { LOG.warn("IOException closing input stream from `whoami`: " + ioe.toString()); } } // wait for whoami to exit. while (p != null) { try { int ret = p.waitFor(); if (0 != ret) { LOG.error("whoami exited with error status " + ret); // suppress original return value from this method. return null; } } catch (InterruptedException ie) { continue; // loop around. } } } }
From source file:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java
public static boolean deleteStudy(String studyUID) { InputStream is = null;//from w w w .ja va 2 s . c o m InputStreamReader isr = null; BufferedReader br = null; boolean success = false; try { log.info("Deleting study " + studyUID + " files - command: ./dcmdeleteStudy " + studyUID); String[] command = { "./dcmdeleteStudy", studyUID }; ProcessBuilder pb = new ProcessBuilder(command); String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/"; File script = new File(dicomScriptsDir, "dcmdeleteStudy"); if (!script.exists()) dicomScriptsDir = EPADConfig.getEPADWebServerMyScriptsDir(); script = new File(dicomScriptsDir, "dcmdeleteStudy"); // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath()); script.setExecutable(true); pb.directory(new File(dicomScriptsDir)); Process process = pb.start(); process.getOutputStream(); is = process.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { log.info("./dcmdeleteStudy: " + line); sb.append(line).append("\n"); } try { int exitValue = process.waitFor(); log.info("DICOM delete study exit value is: " + exitValue); if (exitValue == 0) success = true; } catch (Exception e) { log.warning("Failed to delete DICOM study " + studyUID, e); } String cmdLineOutput = sb.toString(); if (cmdLineOutput.toLowerCase().contains("error")) { throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput)); } } catch (Exception e) { log.warning("Failed to delete DICOM study " + studyUID, e); } return success; }
From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java
/** * Run a command and wait// w w w . j ava 2 s .c o m * * @param cmd The command to run * @param workingDir The folder where the command is run * @param executeFrom For logging message to the center of where to execute the command. * @return */ public static String executeCommandGetOutput(String cmd, String workingDir, String executeFrom) { logger.debug("Execute command: " + cmd); if (workingDir == null) { workingDir = "/tmp"; } try { String[] splitStr = cmd.split("\\s+"); ProcessBuilder pb = new ProcessBuilder(splitStr); pb.directory(new File(workingDir)); pb = pb.redirectErrorStream(true); // this is important to redirect the error stream to output stream, prevent blocking with long output Map<String, String> env = pb.environment(); String path = env.get("PATH"); path = path + File.pathSeparator + "/usr/bin:/usr/sbin"; logger.debug("PATH to execute command: " + pb.environment().get("PATH")); env.put("PATH", path); Process p = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; StringBuffer output = new StringBuffer(); int lineCount = 0; while ((line = reader.readLine()) != null) { if (lineCount < 10) { // only get 10 lines to prevent the overflow output.append(line); } lineCount += 1; logger.debug(line); } if (lineCount >= 10) { logger.debug("... there are alot of more output here which is not shown ! ..."); } p.waitFor(); System.out.println("Execute Commang output: " + output.toString().trim()); if (p.exitValue() == 0) { logger.debug("Command exit 0, result: " + output.toString().trim()); return output.toString().trim(); } else { logger.debug("Command return non zero code: " + p.exitValue()); return null; } } catch (InterruptedException | IOException e1) { logger.error("Error when execute command. Error: " + e1); } return null; }
From source file:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java
public static boolean dcmsnd(File inputDirFile, boolean throwException) throws Exception { InputStream is = null;//from ww w.j a v a2 s .c om InputStreamReader isr = null; BufferedReader br = null; FileWriter tagFileWriter = null; boolean success = false; try { String aeTitle = EPADConfig.aeTitle; String dicomServerIP = EPADConfig.dicomServerIP; String dicomServerPort = EPADConfig.dicomServerPort; String dicomServerTitleAndPort = aeTitle + "@" + dicomServerIP + ":" + dicomServerPort; dicomServerTitleAndPort = dicomServerTitleAndPort.trim(); String dirPath = inputDirFile.getAbsolutePath(); if (pathContainsSpaces(dirPath)) dirPath = escapeSpacesInDirPath(dirPath); File dir = new File(dirPath); int nbFiles = -1; if (dir != null) { String[] filePaths = dir.list(); if (filePaths != null) nbFiles = filePaths.length; } log.info("./dcmsnd: sending " + nbFiles + " file(s) - command: ./dcmsnd " + dicomServerTitleAndPort + " " + dirPath); String[] command = { "./dcmsnd", dicomServerTitleAndPort, dirPath }; ProcessBuilder processBuilder = new ProcessBuilder(command); String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/"; File script = new File(dicomScriptsDir, "dcmsnd"); if (!script.exists()) dicomScriptsDir = EPADConfig.getEPADWebServerDICOMBinDir(); script = new File(dicomScriptsDir, "dcmsnd"); if (!script.exists()) throw new Exception("No script found:" + script.getAbsolutePath()); // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath()); script.setExecutable(true); processBuilder.directory(new File(dicomScriptsDir)); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); is = process.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); log.info("./dcmsend output: " + line); } try { int exitValue = process.waitFor(); log.info("DICOM send exit value is: " + exitValue); if (exitValue == 0) success = true; } catch (InterruptedException e) { log.warning("Didn't send DICOM files in: " + inputDirFile.getAbsolutePath(), e); } String cmdLineOutput = sb.toString(); if (cmdLineOutput.toLowerCase().contains("error")) throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput)); return success; } catch (Exception e) { log.warning("DicomSendTask failed to send DICOM files", e); if (e instanceof IllegalStateException && throwException) { throw e; } if (throwException) { throw new IllegalStateException("DicomSendTask failed to send DICOM files", e); } return success; } catch (OutOfMemoryError oome) { log.warning("DicomSendTask out of memory: ", oome); if (throwException) { throw new IllegalStateException("DicomSendTask out of memory: ", oome); } return success; } finally { IOUtils.closeQuietly(tagFileWriter); IOUtils.closeQuietly(br); IOUtils.closeQuietly(isr); IOUtils.closeQuietly(is); } }
From source file:org.cloudifysource.azure.CliAzureDeploymentTest.java
public static String runCliCommands(File cliExecutablePath, List<List<String>> commands, boolean isDebug) throws IOException, InterruptedException { if (!cliExecutablePath.isFile()) { throw new IllegalArgumentException(cliExecutablePath + " is not a file"); }//w ww . j av a 2 s . c o m File workingDirectory = cliExecutablePath.getAbsoluteFile().getParentFile(); if (!workingDirectory.isDirectory()) { throw new IllegalArgumentException(workingDirectory + " is not a directory"); } int argsCount = 0; for (List<String> command : commands) { argsCount += command.size(); } // needed to properly intercept error return code String[] cmd = new String[(argsCount == 0 ? 0 : 1) + 4 /* cmd /c call cloudify.bat ["args"] */]; int i = 0; cmd[i] = "cmd"; i++; cmd[i] = "/c"; i++; cmd[i] = "call"; i++; cmd[i] = cliExecutablePath.getAbsolutePath(); i++; if (argsCount > 0) { cmd[i] = "\""; //TODO: Use StringBuilder for (List<String> command : commands) { if (command.size() > 0) { for (String arg : command) { if (cmd[i].length() > 0) { cmd[i] += " "; } cmd[i] += arg; } cmd[i] += ";"; } } cmd[i] += "\""; } final ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(workingDirectory); pb.redirectErrorStream(true); String extCloudifyJavaOptions = ""; if (isDebug) { extCloudifyJavaOptions += "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9000 -Xnoagent -Djava.compiler=NONE"; } pb.environment().put("EXT_CLOUDIFY_JAVA_OPTIONS", extCloudifyJavaOptions); final StringBuilder sb = new StringBuilder(); logger.info("running: " + cliExecutablePath + " " + Arrays.toString(cmd)); // log std output and redirected std error Process p = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = reader.readLine(); while (line != null) { sb.append(line).append("\n"); line = reader.readLine(); logger.info(line); } final String readResult = sb.toString(); final int exitValue = p.waitFor(); logger.info("Exit value = " + exitValue); if (exitValue != 0) { Assert.fail("Cli ended with error code: " + exitValue); } return readResult; }