List of usage examples for java.lang ProcessBuilder start
public Process start() throws IOException
From source file:ai.h2o.servicebuilder.Util.java
/** * Run command cmd in separate process in directory * * @param directory run in this directory * @param cmd command to run//from ww w . j ava2 s . co m * @param errorMessage error message if process didn't finish with exit value 0 * @return stdout combined with stderr * @throws Exception */ public static String runCmd(File directory, List<String> cmd, String errorMessage) throws Exception { ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(directory); pb.redirectErrorStream(true); // error sent to output stream Process p = pb.start(); // get output stream to string String s; StringBuilder sb = new StringBuilder(); BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((s = stdout.readLine()) != null) { logger.info(s); sb.append(s); sb.append('\n'); } String sbs = sb.toString(); int exitValue = p.waitFor(); if (exitValue != 0) throw new Exception(errorMessage + " exit value " + exitValue + " " + sbs); return sbs; }
From source file:com.microsoft.alm.plugin.external.utils.ProcessHelper.java
public static Process startProcess(final String workingDirectory, final List<String> arguments) throws IOException { final ProcessBuilder pb = new ProcessBuilder(arguments); // Disable any telemetry that the tool may initiate pb.environment().put("tf_notelemetry", "TRUE"); pb.environment().put("TF_ADDITIONAL_JAVA_ARGS", "-Duser.country=US -Duser.language=en"); if (StringUtils.isNotEmpty(workingDirectory)) { pb.directory(new File(workingDirectory)); }//from w ww . j a v a2s .c om return pb.start(); }
From source file:net.pms.util.ProcessUtil.java
public static String run(int[] expectedExitCodes, String... cmd) { try {// w w w. j a va 2 s. co m ProcessBuilder pb = new ProcessBuilder(cmd); pb.redirectErrorStream(true); Process p = pb.start(); StringBuilder output; try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String line; output = new StringBuilder(); while ((line = br.readLine()) != null) { output.append(line).append("\n"); } } p.waitFor(); boolean expected = false; if (expectedExitCodes != null) { for (int expectedCode : expectedExitCodes) { if (expectedCode == p.exitValue()) { expected = true; break; } } } if (!expected) { LOGGER.debug("Warning: command {} returned {}", Arrays.toString(cmd), p.exitValue()); } return output.toString(); } catch (Exception e) { LOGGER.error("Error running command " + Arrays.toString(cmd), e); } return ""; }
From source file:abs.backend.erlang.ErlangTestDriver.java
public static boolean checkErlang() { if (SemanticTests.checkProg("erl")) { // http://stackoverflow.com/a/9561398/60462 ProcessBuilder pb = new ProcessBuilder("erl", "-eval", "erlang:display(erlang:system_info(otp_release)), halt().", "-noshell"); try {/*from ww w. j a v a2 s.com*/ Process p = pb.start(); InputStreamReader r = new InputStreamReader(p.getInputStream()); BufferedReader b = new BufferedReader(r); Assert.assertEquals(0, p.waitFor()); String version = b.readLine(); java.util.regex.Pattern pat = java.util.regex.Pattern.compile("\"(\\d*).*"); Matcher m = pat.matcher(version); Assert.assertTrue("Could not identify Erlang version: " + version, m.matches()); String v = m.group(1); Assume.assumeTrue("Need Erlang R17 or better.", Integer.parseInt(v) >= 17); } catch (IOException e) { return false; } catch (InterruptedException e) { return false; } } return true; }
From source file:com.diffplug.gradle.CmdLine.java
/** Runs the given command in the given directory with the given echo setting. */ public static Result runCmd(File directory, String cmd, boolean echoCmd, boolean echoOutput) throws IOException { // set the cmds List<String> cmds = getPlatformCmds(cmd); ProcessBuilder builder = new ProcessBuilder(cmds); // set the working directory builder.directory(directory);/*w ww . j a va 2 s. c o m*/ // execute the command Process process = builder.start(); // wrap the process' input and output try (BufferedReader stdInput = new BufferedReader( new InputStreamReader(process.getInputStream(), Charset.defaultCharset())); BufferedReader stdError = new BufferedReader( new InputStreamReader(process.getErrorStream(), Charset.defaultCharset()));) { if (echoCmd) { System.out.println("cmd>" + cmd); } // dump the output ImmutableList.Builder<String> output = ImmutableList.builder(); ImmutableList.Builder<String> error = ImmutableList.builder(); String line = null; while ((line = stdInput.readLine()) != null) { output.add(line); if (echoOutput) { System.out.println(line); } } // dump the input while ((line = stdError.readLine()) != null) { error.add(line); if (echoOutput) { System.err.println(line); } } // check that the process exited correctly int exitValue = process.waitFor(); if (exitValue != EXIT_VALUE_SUCCESS) { throw new RuntimeException("'" + cmd + "' exited with " + exitValue); } // returns the result of this successful execution return new Result(directory, cmd, output.build(), error.build()); } catch (InterruptedException e) { // this isn't expected, but it's possible throw new RuntimeException(e); } }
From source file:pieShareAppITs.helper.ITUtil.java
public static Process startProcess(Class mainClazz, String cloudName, String password) throws IOException { String separator = System.getProperty("file.separator"); String classpath = System.getProperty("java.class.path"); String path = System.getProperty("java.home") + separator + "bin" + separator + "java"; ProcessBuilder processBuilder = new ProcessBuilder(path, "-Xdebug", "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005", "-cp", classpath, mainClazz.getName(), cloudName, password); return processBuilder.start(); }
From source file:functionaltests.RestFuncTHelper.java
public static void startRestfulSchedulerWebapp(int nbNodes) throws Exception { // Kill all children processes on exit org.apache.log4j.BasicConfigurator.configure(new org.apache.log4j.varia.NullAppender()); CookieBasedProcessTreeKiller.registerKillChildProcessesOnShutdown("rest_tests"); List<String> cmd = new ArrayList<>(); String javaPath = RestFuncTUtils.getJavaPathFromSystemProperties(); cmd.add(javaPath);//from w w w . j ava2 s.com cmd.add("-Djava.security.manager"); cmd.add(CentralPAPropertyRepository.JAVA_SECURITY_POLICY.getCmdLine() + toPath(serverJavaPolicy)); cmd.add(CentralPAPropertyRepository.PA_HOME.getCmdLine() + getSchedHome()); cmd.add(PASchedulerProperties.SCHEDULER_HOME.getCmdLine() + getSchedHome()); cmd.add(PAResourceManagerProperties.RM_HOME.getCmdLine() + getRmHome()); cmd.add(PAResourceManagerProperties.RM_DB_HIBERNATE_DROPDB.getCmdLine() + System.getProperty("rm.deploy.dropDB", "true")); cmd.add(PAResourceManagerProperties.RM_DB_HIBERNATE_CONFIG.getCmdLine() + toPath(rmHibernateConfig)); cmd.add(PASchedulerProperties.SCHEDULER_DB_HIBERNATE_DROPDB.getCmdLine() + System.getProperty("scheduler.deploy.dropDB", "true")); cmd.add(PASchedulerProperties.SCHEDULER_DB_HIBERNATE_CONFIG.getCmdLine() + toPath(schedHibernateConfig)); cmd.add(CentralPAPropertyRepository.PA_COMMUNICATION_PROTOCOL.getCmdLine() + "pnp"); cmd.add(PNPConfig.PA_PNP_PORT.getCmdLine() + "1200"); cmd.add("-cp"); cmd.add(getClassPath()); cmd.add(SchedulerStarter.class.getName()); cmd.add("-ln"); cmd.add("" + nbNodes); ProcessBuilder processBuilder = new ProcessBuilder(cmd); processBuilder.redirectErrorStream(true); schedProcess = processBuilder.start(); ProcessStreamReader out = new ProcessStreamReader("scheduler-output: ", schedProcess.getInputStream()); out.start(); // RM and scheduler are on the same url String port = "1200"; String url = "pnp://localhost:" + port + "/"; // Connect a scheduler client SchedulerAuthenticationInterface schedAuth = SchedulerConnection.waitAndJoin(url, TimeUnit.SECONDS.toMillis(60)); schedulerPublicKey = schedAuth.getPublicKey(); Credentials schedCred = RestFuncTUtils.createCredentials("admin", "admin", schedulerPublicKey); scheduler = schedAuth.login(schedCred); // Connect a rm client RMAuthentication rmAuth = RMConnection.waitAndJoin(url, TimeUnit.SECONDS.toMillis(60)); Credentials rmCredentials = getRmCredentials(); rm = rmAuth.login(rmCredentials); restServerUrl = "http://localhost:8080/rest/"; restfulSchedulerUrl = restServerUrl + "scheduler"; await().atMost(Duration.FIVE_MINUTES).until(restIsStarted()); }
From source file:com.cprassoc.solr.auth.SolrAuthActionController.java
public static String doPushConfigToSolrAction(SecurityJson json) { String result = ""; try {/*from ww w .ja v a2 s . c om*/ String mime = "sh"; if (Utils.isWindows()) { mime = "bat"; } String pathToScript = System.getProperty("user.dir") + File.separator + "solrAuth." + mime; String jsonstr = json.export(); String filePath = SolrAuthManager.getProperties().getProperty("solr.install.path") + File.separator + "security.json"; File backup = new File("backup"); if (!backup.exists()) { backup.mkdirs(); } File file = new File(filePath); if (file.exists()) { // String newFilePath = SolrAuthManager.getProperties().getProperty("solr.install.path") + File.separator + System.currentTimeMillis() + "_security.json"; // File newFile = new File(newFilePath); // file.renameTo(newFile); FileUtils.copyFileToDirectory(file, backup); } FileUtils.writeByteArrayToFile(file, jsonstr.getBytes()); Thread.sleep(500); ProcessBuilder pb = new ProcessBuilder(pathToScript); Log.log("Run PUSH command"); Process process = pb.start(); if (process.waitFor() == 0) { result = ""; } else { result = Utils.streamToString(process.getErrorStream()); result += "\n" + Utils.streamToString(process.getInputStream()); Log.log(result); } } catch (Exception e) { e.printStackTrace(); result = e.getLocalizedMessage(); } return result; }
From source file:com.ikanow.aleph2.data_model.utils.ProcessUtils.java
/** * Finds all a processes children, kills the process then recursively calls this on the children. * /* ww w. j av a 2s .c o m*/ * @param pid * @param kill_signal * @return * @throws IOException */ private static boolean killProcessAndChildren(final String pid, final Optional<Integer> kill_signal) throws IOException { //first find any children via pgrep -P pid final ProcessBuilder pb_children = new ProcessBuilder("pgrep", "-P", pid.toString()); final BufferedReader br = new BufferedReader(new InputStreamReader(pb_children.start().getInputStream())); final Set<String> child_pids = new HashSet<String>(); String line; while ((line = br.readLine()) != null) { child_pids.add(line); } logger.debug("children of pid: " + pid + " are: " + child_pids.toString()); //kill pid w/ signal killProcess(pid, kill_signal); //if still alive kill with -9, give it 5s to try and die the old way for (int i = 0; i < 5; i++) { try { Thread.sleep(1000L); } catch (Exception e) { } if (!isProcessRunning(pid)) { break; } } if (isProcessRunning(pid)) { killProcess(pid, Optional.of(9)); } //call this on all children return !child_pids.stream().filter(child_pid -> { try { return killProcessAndChildren(child_pid, kill_signal); } catch (Exception ex) { return false; } }).anyMatch(result -> false); }
From source file:de.teamgrit.grit.preprocess.fetch.SvnFetcher.java
/** * runSVNCommand runs an svn command in the specified directory. * * @param connection//from ww w. jav a 2 s .c o m * the connection storing the connection infos for the remote * @param svnCommand * is the command to be executed. Each part of the command must * be a string element. For example: "svn" "checkout" * "file://some/path" * @param workingDir * where the svn command should be executed (must be a * repository). * @return A list of all output lines. * @throws IOException * Thrown when process can't be started or an error occurs * while reading its output */ private static SVNResultData runSVNCommand(Connection connection, List<String> svnCommand, Path workingDir) throws IOException { // add boilerplate to command svnCommand.add("--non-interactive"); svnCommand.add("--no-auth-cache"); svnCommand.add("--force"); if ((connection.getUsername() != null) && !connection.getUsername().isEmpty()) { svnCommand.add("--username"); svnCommand.add(connection.getUsername()); } if ((connection.getPassword() != null) && !connection.getPassword().isEmpty()) { svnCommand.add("--password"); svnCommand.add(connection.getPassword()); } // build process: construct command and set working directory. Process svnProcess = null; ProcessBuilder svnProcessBuilder = new ProcessBuilder(svnCommand); svnProcessBuilder.directory(workingDir.toFile()); svnProcess = svnProcessBuilder.start(); try { svnProcess.waitFor(); } catch (InterruptedException e) { LOGGER.severe("Interrupted while waiting for SVN. " + "Cannot guarantee clean command run!"); return null; } InputStream svnOutputStream = svnProcess.getInputStream(); InputStreamReader svnStreamReader = new InputStreamReader(svnOutputStream); BufferedReader svnOutputBuffer = new BufferedReader(svnStreamReader); String line; List<String> svnOutputLines = new LinkedList<>(); while ((line = svnOutputBuffer.readLine()) != null) { svnOutputLines.add(line); } return new SVNResultData(svnProcess.exitValue(), svnOutputLines); }