List of usage examples for java.lang Process waitFor
public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException
From source file:mcnutty.music.get.MusicGet.java
public static void main(String[] args) throws Exception { //print out music-get System.out.println(" _ _ "); System.out.println(" _ __ ___ _ _ ___(_) ___ __ _ ___| |_ "); System.out.println("| '_ ` _ \\| | | / __| |/ __|____ / _` |/ _ \\ __|"); System.out.println("| | | | | | |_| \\__ \\ | (_|_____| (_| | __/ |_ "); System.out.println("|_| |_| |_|\\__,_|___/_|\\___| \\__, |\\___|\\__|"); System.out.println(" |___/ \n"); //these will always be initialised later (but the compiler doesn't know that) String directory = ""; Properties prop = new Properties(); try (InputStream input = new FileInputStream("config.properties")) { prop.load(input);//www.jav a2 s. c o m if (prop.getProperty("directory") != null) { directory = prop.getProperty("directory"); } else { System.out.println( "Error reading config property 'directory' - using default value of /tmp/musicserver/\n"); directory = "/tmp/musicserver/"; } if (prop.getProperty("password") == null) { System.out.println("Error reading config property 'password' - no default value, exiting\n"); System.exit(1); } } catch (IOException e) { System.out.println("Error reading config file"); System.exit(1); } //create a queue object ProcessQueue process_queue = new ProcessQueue(); try { if (args.length > 0 && args[0].equals("clean")) { Files.delete(Paths.get("queue.json")); } //load an existing queue if possible String raw_queue = Files.readAllLines(Paths.get("queue.json")).toString(); JSONArray queue_state = new JSONArray(raw_queue); ConcurrentLinkedQueue<QueueItem> loaded_queue = new ConcurrentLinkedQueue<>(); JSONArray queue = queue_state.getJSONArray(0); for (int i = 0; i < queue.length(); i++) { JSONObject item = ((JSONObject) queue.get(i)); QueueItem loaded_item = new QueueItem(); loaded_item.ip = item.getString("ip"); loaded_item.real_name = item.getString("name"); loaded_item.disk_name = item.getString("guid"); loaded_queue.add(loaded_item); } process_queue.bucket_queue = loaded_queue; System.out.println("Loaded queue from disk\n"); } catch (Exception ex) { //otherwise clean out the music directory and start a new queue try { Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } }); Files.delete(Paths.get(directory)); } catch (Exception e) { e.printStackTrace(); } Files.createDirectory(Paths.get(directory)); System.out.println("Created a new queue\n"); } //start the web server StartServer start_server = new StartServer(process_queue, directory); new Thread(start_server).start(); //wit for the web server to spool up Thread.sleep(1000); //read items from the queue and play them while (true) { QueueItem next_item = process_queue.next_item(); if (!next_item.equals(new QueueItem())) { //Check the timeout int timeout = 547; try (FileInputStream input = new FileInputStream("config.properties")) { prop.load(input); timeout = Integer.parseInt(prop.getProperty("timeout", "547")); } catch (Exception e) { e.printStackTrace(); } System.out.println("Playing " + next_item.real_name); process_queue.set_played(next_item); process_queue.save_queue(); Process p = Runtime.getRuntime().exec("timeout " + timeout + "s mplayer -fs -quiet -af volnorm=2:0.25 " + directory + next_item.disk_name); try { p.waitFor(timeout, TimeUnit.SECONDS); Files.delete(Paths.get(directory + next_item.disk_name)); } catch (Exception e) { e.printStackTrace(); } } else { process_queue.bucket_played.clear(); } Thread.sleep(1000); } }
From source file:Main.java
public static void runOSCommand(String command) { ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", command); try {//from w w w .ja v a2 s .c o m Process p = builder.start(); p.waitFor(5000, TimeUnit.MILLISECONDS); } catch (IOException | InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:de.uni_freiburg.informatik.ultimate.licence_manager.authors.SvnAuthorProvider.java
private static boolean isSvnAvailable() { final ProcessBuilder pbuilder = new ProcessBuilder("svn", "--version"); try {/*from w ww . j av a 2 s . c o m*/ final Process process = pbuilder.start(); if (process.waitFor(1000, TimeUnit.MILLISECONDS)) { final List<String> lines = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset()); if (lines == null || lines.isEmpty()) { return false; } sSvnVersion = lines.get(0); return true; } } catch (IOException | InterruptedException e) { System.err.println("Could not find 'svn' executable, disabling author provider"); return false; } return false; }
From source file:com.thinkbiganalytics.spark.shell.SparkClientUtil.java
/** * Gets the Spark version string by executing {@code spark-submit}. * * @throws IOException if the version string cannot be obtained *//*from w w w .j av a 2s. com*/ private static String getVersion() throws IOException { // Build spark-submit process final String sparkSubmitCommand = new StringJoiner(File.separator).add(getSparkHome()).add("bin") .add("spark-submit").toString(); final Process process = new ProcessBuilder().command(sparkSubmitCommand, "--version") .redirectErrorStream(true).start(); // Wait for process to complete boolean exited; try { exited = process.waitFor(10, TimeUnit.SECONDS); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); exited = !process.isAlive(); } if (!exited) { throw new IOException("Timeout waiting for Spark version"); } // Read stdout final byte[] bytes = new byte[1024]; final int length = process.getInputStream().read(bytes); final String output = new String(bytes, 0, length, "UTF-8"); final Matcher matcher = Pattern.compile("version ([\\d+.]+)").matcher(output); if (matcher.find()) { return matcher.group(1); } else { throw new IllegalStateException("Unable to determine version from Spark Submit"); } }
From source file:de.micromata.mgc.application.webserver.config.KeyTool.java
public static void generateKey(ValContext ctx, File keyFile, String storePass, String keyAlias) { String[] args = { "keytool", "-genkey", "-alias", keyAlias, "-keyalg", "RSA", "-keystore", keyFile.getAbsolutePath(), "-keysize", "2048", "-keypass", storePass, "-storepass", storePass, "-dname", "cn=Launcher, ou=MGC, o=Microamta, c=DE" }; StringBuilder oksb = new StringBuilder(); oksb.append("Execute: " + StringUtils.join(args, " ")); try {/*from www . j a v a2 s .co m*/ ProcessBuilder pb = new ProcessBuilder(args); pb.redirectErrorStream(true); Process process = pb.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { oksb.append(line); } boolean success = process.waitFor(5, TimeUnit.SECONDS); if (success == false) { ctx.directError(null, "Fail to wait for keytool"); } else { int exitValue = process.exitValue(); if (exitValue == 0) { oksb.append("\nSuccess"); ctx.directInfo(null, oksb.toString()); } else { ctx.directError(null, oksb.toString()); ctx.directError(null, "Failure executing keytool. ReturnCode: " + exitValue); } } } catch (Exception ex) { ctx.directError(null, "Failure executing keytool: " + ex.getMessage(), ex); } }
From source file:com.act.utils.ProcessRunner.java
/** * Run's a child process using the specified command and arguments, timing out after a specified number of seconds * if the process does not terminate on its own in that time. * @param command The process to run./*ww w . j a va 2 s . c o m*/ * @param args The arguments to pass to that process. * @param timeoutInSeconds A timeout to impose on the child process; an InterruptedException is likely to occur * when the child process times out. * @return The exit code of the child process. * @throws InterruptedException * @throws IOException */ public static int runProcess(String command, List<String> args, Long timeoutInSeconds) throws InterruptedException, IOException { /* The ProcessBuilder doesn't differentiate the command from its arguments, but we do in our API to ensure the user * doesn't just pass us a single string command, which invokes the shell and can cause all sorts of bugs and * security issues. */ List<String> commandAndArgs = new ArrayList<String>(args.size() + 1) { { add(command); addAll(args); } }; ProcessBuilder processBuilder = new ProcessBuilder(commandAndArgs); LOGGER.info("Running child process: %s", StringUtils.join(commandAndArgs, " ")); Process p = processBuilder.start(); // Log whatever the child writes. new StreamLogger(p.getInputStream(), l -> LOGGER.info("[child STDOUT]: %s", l)).run(); new StreamLogger(p.getErrorStream(), l -> LOGGER.warn("[child STDERR]: %s", l)).run(); // Wait for the child process to exit, timing out if it takes to long to finish. if (timeoutInSeconds != null) { p.waitFor(timeoutInSeconds, TimeUnit.SECONDS); } else { p.waitFor(); } // 0 is the default success exit code in *nix land. if (p.exitValue() != 0) { LOGGER.error("Child process exited with non-zero status code: %d", p.exitValue()); } return p.exitValue(); }
From source file:docs.AbstractGemFireIntegrationTests.java
protected static int waitForProcessToStop(Process process, File directory, long duration) { final long timeout = (System.currentTimeMillis() + duration); try {//from w w w .j av a 2s . c o m while (process.isAlive() && System.currentTimeMillis() < timeout) { if (process.waitFor(DEFAULT_WAIT_INTERVAL, TimeUnit.MILLISECONDS)) { return process.exitValue(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return (process.isAlive() ? -1 : process.exitValue()); }
From source file:gov.nist.appvet.tool.sigverifier.Service.java
private static boolean execute(String command, StringBuffer output) { List<String> commandArgs = Arrays.asList(command.split("\\s+")); ProcessBuilder pb = new ProcessBuilder(commandArgs); Process process = null; IOThreadHandler outputHandler = null; IOThreadHandler errorHandler = null; int exitValue = -1; try {/*from ww w . j a v a2 s . com*/ if (command == null || command.isEmpty()) { log.error("Command is null or empty"); return false; } log.debug("Executing " + command); process = pb.start(); outputHandler = new IOThreadHandler(process.getInputStream()); outputHandler.start(); errorHandler = new IOThreadHandler(process.getErrorStream()); errorHandler.start(); if (process.waitFor(Properties.commandTimeout, TimeUnit.MILLISECONDS)) { // Process has waited and exited within the timeout exitValue = process.exitValue(); if (exitValue == 0) { log.debug("Command terminated normally: \n" + outputHandler.getOutput() + "\nErrors: " + errorHandler.getOutput()); StringBuffer resultOut = outputHandler.getOutput(); output.append(resultOut); return true; } else { log.error("Command terminated abnormally: \n" + outputHandler.getOutput() + "\nErrors: " + errorHandler.getOutput()); StringBuffer resultError = errorHandler.getOutput(); output.append(resultError); return false; } } else { // Process exceed timeout or was interrupted log.error("Command timed-out or was interrupted: \n" + outputHandler.getOutput() + "\nErrors: " + errorHandler.getOutput()); StringBuffer resultOutput = outputHandler.getOutput(); StringBuffer resultError = errorHandler.getOutput(); if (resultOutput != null) { output.append(resultOutput); return false; } else if (resultError != null) { output.append(resultError); } else { output.append(Properties.toolName + " timed-out"); } return false; } } catch (IOException e) { e.printStackTrace(); return false; } catch (InterruptedException e) { e.printStackTrace(); return false; } finally { if (outputHandler.isAlive()) { try { outputHandler.inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (errorHandler.isAlive()) { try { errorHandler.inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (process.isAlive()) { process.destroy(); } } }
From source file:com.blackducksoftware.integration.hub.docker.executor.Executor.java
public String[] executeCommand(final String commandString) throws IOException, InterruptedException, HubIntegrationException { final List<String> commandStringList = Arrays.asList(commandString.split(" ")); final ProcessBuilder builder = new ProcessBuilder(); builder.command(commandStringList.toArray(new String[commandStringList.size()])); builder.directory(new File(".")); final Process process = builder.start(); final boolean finished = process.waitFor(this.commandTimeout, TimeUnit.MILLISECONDS); if (!finished) { throw new HubIntegrationException(String.format( "Execution of command %s timed out (timeout: %d milliseconds)", commandString, commandTimeout)); }//from w w w .j a v a 2 s . co m final int errCode = process.exitValue(); if (errCode == 0) { logger.debug(String.format("Execution of command: %s: Succeeded", commandString)); } else { throw new HubIntegrationException( String.format("Execution of command: %s: Error code: %d", commandString, errCode)); } final InputStream inputStream = process.getInputStream(); final String outputString = IOUtils.toString(inputStream, StandardCharsets.UTF_8); logger.debug(String.format("Command output:/n%s", outputString)); return outputString.split(System.lineSeparator()); }
From source file:com.diversityarrays.kdxplore.trialdesign.JobRunningTask.java
@Override public Either<String, AlgorithmRunResult> generateResult(Closure<Void> arg0) throws Exception { AlgorithmRunResult result = new AlgorithmRunResult(algorithmName, algorithmFolder); ProcessBuilder pb = new ProcessBuilder(command); File tempAlgorithmOutputFile = new File(algorithmFolder, "stdout.txt"); File tempAlgorithmErrorFile = new File(algorithmFolder, "stderr.txt"); //pb.redirectErrorStream(true); tempAlgorithmErrorFile.createNewFile(); tempAlgorithmOutputFile.createNewFile(); pb.redirectOutput(tempAlgorithmOutputFile); pb.redirectError(tempAlgorithmErrorFile); Process process = pb.start(); while (!process.waitFor(1000, TimeUnit.MILLISECONDS)) { if (backgroundRunner.isCancelRequested()) { process.destroy();//from w ww . ja v a2s. co m throw new CancellationException(); } } int exitCode = process.exitValue(); if (exitCode != 0) { String errtxt = Algorithms.readContent("Error Output: (code=" + exitCode + ")", new FileInputStream(tempAlgorithmErrorFile)); return Either.left(errtxt); } if (!kdxploreOutputFile.exists()) { return Either.left("Missing output file: " + kdxploreOutputFile.getPath()); } result.addTrialEntries(kdxploreOutputFile, userTrialEntries); return Either.right(result); }