List of usage examples for java.lang ProcessBuilder directory
File directory
To view the source code for java.lang ProcessBuilder directory.
Click Source Link
From source file:com.atlassian.labs.bamboo.git.edu.nyu.cs.javagit.client.cli.ProcessUtilities.java
/** * Runs the command specified in the command line with the specified working directory. The * IParser is used to parse the response given by the command line. * * @param workingDirectory// w w w .j av a 2 s . com * The working directory in with which to start the process. * @param commandLine * The command line to run. * @param parser * The parser to use to parse the command line's response. * @return The command response from the <code>IParser</code>. * @throws IOException * Thrown if there are problems with the subprocess. * @throws JavaGitException */ public static CommandResponse runCommand(File workingDirectory, List<String> commandLine, IParser parser) throws IOException, JavaGitException { ProcessBuilder pb = new ProcessBuilder(commandLine); LOG.debug("Command:" + commandLine); if (workingDirectory != null) { pb.directory(workingDirectory); } pb.redirectErrorStream(true); Process p = startProcess(pb); getProcessOutput(p, parser); waitForAndDestroyProcess(p, parser); return parser.getResponse(); }
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 w w w .ja v a 2 s. com*/ * @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:edu.uci.ics.asterix.installer.test.AsterixClusterLifeCycleIT.java
private static Process remoteInvoke(String cmd) throws Exception { ProcessBuilder pb = new ProcessBuilder("vagrant", "ssh", "cc", "-c", "MANAGIX_HOME=/tmp/asterix/ " + cmd); File cwd = new File(asterixProjectDir.toString() + "/" + CLUSTER_BASE); pb.directory(cwd); pb.redirectErrorStream(true);/*from w w w .j ava 2 s . com*/ Process p = pb.start(); return p; }
From source file:org.zanata.workflow.ClientWorkFlow.java
private static synchronized Process invokeClient(File projectDir, List<String> command) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder(command).redirectErrorStream(true); // Map<String, String> env = processBuilder.environment(); // log.debug("env: {}", env); processBuilder.directory(projectDir); return processBuilder.start(); }
From source file:org.apache.storm.daemon.supervisor.ClientSupervisorUtils.java
/** * Launch a new process as per {@link ProcessBuilder} with a given * callback.//from w w w .ja va 2 s . c o m * @param command the command to be executed in the new process * @param environment the environment to be applied to the process. Can be * null. * @param logPrefix a prefix for log entries from the output of the process. * Can be null. * @param exitCodeCallback code to be called passing the exit code value * when the process completes * @param dir the working directory of the new process * @return the new process * @throws IOException * @see ProcessBuilder */ public static Process launchProcess(List<String> command, Map<String, String> environment, final String logPrefix, final ExitCodeCallback exitCodeCallback, File dir) throws IOException { ProcessBuilder builder = new ProcessBuilder(command); Map<String, String> procEnv = builder.environment(); if (dir != null) { builder.directory(dir); } builder.redirectErrorStream(true); if (environment != null) { procEnv.putAll(environment); } final Process process = builder.start(); if (logPrefix != null || exitCodeCallback != null) { Utils.asyncLoop(new Callable<Object>() { public Object call() { if (logPrefix != null) { Utils.readAndLogStream(logPrefix, process.getInputStream()); } if (exitCodeCallback != null) { try { process.waitFor(); exitCodeCallback.call(process.exitValue()); } catch (InterruptedException ie) { LOG.info("{} interrupted", logPrefix); exitCodeCallback.call(-1); } } return null; // Run only once. } }); } return process; }
From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java
/** * Run a command and wait/*from ww w . j av a2 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 Process executeCommandAndForget(String cmd, String workingDir, String executeFrom) { logger.debug("Execute command: " + cmd); if (workingDir == null) { workingDir = "/tmp"; } 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 pb.redirectOutput(new File("/tmp/salsa.conductor.log")); 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; try { p = pb.start(); return p; } catch (IOException ex) { logger.debug("Cannot run the command: " + cmd); return null; } }
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); // 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); }// w ww . ja v a 2 s . c o m // 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:org.wso2.security.tools.scanner.dependency.js.preprocessor.ReactFileDownloader.java
/** * Install npm modules which are referenced in package.json files. * * @param path Directory where the package.json file is placed. * @throws DownloaderException exception occurred while downloading NPM Modules. *///from w w w.ja v a2 s. c om private static void installNPMModules(String path) throws DownloaderException { Process process = null; try { ProcessBuilder processBuilder = new ProcessBuilder(JSScannerConstants.NPM, JSScannerConstants.INSTALL); processBuilder.directory(new File(path)); process = processBuilder.start(); process.waitFor(); } catch (IOException | InterruptedException e) { throw new DownloaderException("Error occurred while downloading NPM modules due to : ", e); } finally { if (process != null) { process.destroyForcibly(); } } }
From source file:com.ikanow.aleph2.harvest.script.utils.ScriptUtils.java
/** * Creates a processbuilder pointed at the given script path and adds the working dir and environment vars for you. * Just runs a process that does "sh <script_file_path>" * @param script_file_path/*from www. ja v a2 s .c om*/ * @param working_dir * @return * @throws JsonProcessingException * @throws ExecutionException * @throws InterruptedException */ public static ProcessBuilder createProcessBuilderForScriptFile(final String script_file_path, final String working_dir, final Optional<Long> test_requested_num_objects, final Optional<Long> test_max_runtime_s, final Map<String, String> user_args, final IHarvestContext context, final DataBucketBean bucket, final String aleph_global_root_path) throws JsonProcessingException, InterruptedException, ExecutionException { _logger.debug("create pb for script file: " + script_file_path); ArrayList<String> args = new ArrayList<String>(); args.add("sh"); args.add(script_file_path); final ProcessBuilder pb = new ProcessBuilder(args); pb.directory(new File(working_dir)).redirectErrorStream(true); pb.environment().put("JAVA_OPTS", ""); if (test_requested_num_objects.isPresent()) pb.environment().put(ENV_TEST_NUM_OBJ, test_requested_num_objects.get().toString()); if (test_max_runtime_s.isPresent()) pb.environment().put(ENV_TEST_MAX_RUNTIME_S, test_max_runtime_s.get().toString()); //add in default env vars final String classpath = Stream .concat(context.getHarvestContextLibraries(Optional.empty()).stream(), context.getHarvestLibraries(Optional.of(bucket)).get().values().stream()) .collect(Collectors.joining(":")); pb.environment().put(ENV_MODULE_PATH, context.getHarvestContextLibraries(Optional.empty()).stream().collect(Collectors.joining(":"))); pb.environment().put(ENV_LIBRARY_PATH, context.getHarvestLibraries(Optional.of(bucket)).get().values() .stream().collect(Collectors.joining(":"))); pb.environment().put(ENV_CLASS_PATH, classpath); pb.environment().put(ENV_BUCKET_HDFS_PATH, aleph_global_root_path + "/data" + bucket.full_name()); pb.environment().put(ENV_BUCKET_SIGNATURE, BucketUtils.getUniqueSignature(bucket.full_name(), Optional.empty())); pb.environment().put(ENV_BUCKET_PATH, bucket.full_name()); pb.environment().put(ENV_BUCKET_STR, BeanTemplateUtils.toJson(bucket).toString()); //add user args as env vars user_args.forEach((k, val) -> pb.environment().put(k, val)); return pb; }
From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java
public static int executeCommandGetReturnCode(String cmd, String workingDir, String executeFrom) { if (workingDir == null) { workingDir = "/tmp"; }//w w w .j a va 2 s. c o m logger.debug("Execute command: " + cmd + ". Working dir: " + workingDir); 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; while ((line = reader.readLine()) != null) { logger.debug(line); } p.waitFor(); int returnCode = p.exitValue(); logger.debug("Execute command done: " + cmd + ". Get return code: " + returnCode); return returnCode; } catch (InterruptedException | IOException e1) { logger.error("Error when execute command. Error: " + e1); } return -1; }