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:org.mskcc.cbio.importer.util.Shell.java
/** * Executes the given command via java ProcessBuilder. * * @param command List<String>// w ww . ja va 2 s . co m * @param workingDirectory String * @return boolean */ public static boolean exec(List<String> command, String workingDirectory) { if (LOG.isInfoEnabled()) { LOG.info("exec():, command: " + command); LOG.info("exec():, workingDirectory: " + workingDirectory); } try { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(new File(workingDirectory)); Process process = processBuilder.start(); StreamSink stdoutSink = new StreamSink(process.getInputStream()); StreamSink stderrSink = new StreamSink(process.getErrorStream()); stdoutSink.start(); stderrSink.start(); process.waitFor(); return process.exitValue() == 0; } catch (Exception e) { if (LOG.isInfoEnabled()) { LOG.info(e.toString() + " thrown during shell command: " + command); } return false; } }
From source file:com.sap.prd.mobile.ios.mios.Forker.java
static int forkProcess(final PrintStream out, final File executionDirectory, final String... args) throws IOException { if (out == null) throw new IllegalArgumentException("Print stream for log handling was not provided."); if (args == null || args.length == 0) throw new IllegalArgumentException("No arguments has been provided."); for (final String arg : args) if (arg == null || arg.isEmpty()) throw new IllegalArgumentException( "Invalid argument '" + arg + "' provided with arguments '" + Arrays.asList(args) + "'."); final ProcessBuilder builder = new ProcessBuilder(args); if (executionDirectory != null) builder.directory(executionDirectory); builder.redirectErrorStream(true);//w ww .j a v a 2s. c o m InputStream is = null; // // TODO: check if there is any support for forking processes in // maven/plexus // try { final Process process = builder.start(); is = process.getInputStream(); handleLog(is, out); return process.waitFor(); } catch (InterruptedException e) { throw new RuntimeException(e.getClass().getName() + " caught during while waiting for a forked process. This exception is not expected to be caught at that time.", e); } finally { // // Exception raised during close operation below are not reported. // That is actually bad. // We do not have any logging facility here and we cannot throw the // exception since this would swallow any // other exception raised in the try block. // May be we should revisit that ... // IOUtils.closeQuietly(is); } }
From source file:pl.edu.icm.coansys.commons.shell.JavaShellRunner.java
private static ProcessBuilder buildProcess(String[] args) { ProcessBuilder pb = new ProcessBuilder(args[0]); Map<String, String> env = pb.environment(); for (int i = 3; i < args.length; i = i + 2) { env.put(args[i], args[i + 1]);//ww w . jav a 2 s .co m } pb.directory(new File(args[1])); return pb; }
From source file:org.janusgraph.pkgtest.AbstractJanusGraphAssemblyIT.java
protected static void command(File dir, String... command) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder(command); pb.directory(dir); // pb.redirectInput(Redirect.PIPE); /*//w w w . j ava2 s . co m * Using Redirect.INHERIT with expect breaks maven-failsafe-plugin when * failsafe is configured to fork. The parent and child normally * communicate over stdout/stderr in fork mode. But after executing * expect, this failsafe communication starts appearing on the terminal. * The parent never sees it and assumes no tests ran. expect is probably * doing something nasty to its file descriptors and neglecting to clean * up after itself. Invoking unzip does not break failsafe+forks in this * way. So expect must be doing something unusual with its file * descriptors. * * Redirect.INHERIT works fine if failsafe is configured to never fork. */ // pb.redirectOutput(Redirect.INHERIT); // pb.redirectError(Redirect.INHERIT); // pb.redirectOutput(Redirect.PIPE); // pb.redirectError(Redirect.PIPE); final Process p = pb.start(); // Sense of "input" and "output" are reversed between ProcessBuilder and Process p.getOutputStream().close(); // Child process sees EOF on stdin (if it reads stdin at all) Thread outPrinter = new Thread(new SubprocessPipePrinter(p.getInputStream(), System.out)); Thread errPrinter = new Thread(new SubprocessPipePrinter(p.getErrorStream(), System.out)); outPrinter.start(); errPrinter.start(); int stat = p.waitFor(); outPrinter.join(); errPrinter.join(); assertEquals(0, stat); }
From source file:org.wso2.appserver.integration.common.utils.PasswordEncryptionUtil.java
/** * By using run.sh running the ciphertool.sh and give the password as input * * @param carbonHome - carbon server installation location * @param cmdArray - commands to be executed. * @return - boolean shell script ran successfully or not * @throws IOException - Error when reading the InputStream when running shell script *//*w w w . java 2s . c o m*/ public static boolean runCipherToolScriptAndCheckStatus(String carbonHome, String[] cmdArray) throws PasswordEncryptionIntegrationTestException { boolean foundTheMessage = false; BufferedReader br = null; Process process = null; try { log.info("Running the ciphertool.sh .."); File commandDir = new File(carbonHome + "/bin"); ProcessBuilder processBuilder = new ProcessBuilder(cmdArray); processBuilder.directory(commandDir); process = processBuilder.start(); br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; while ((line = br.readLine()) != null) { log.info(line); if (line.contains("Encryption is done Successfully")) { foundTheMessage = true; } } return foundTheMessage; } catch (IOException ex) { log.error("Error when reading the InputStream when running shell script ", ex); throw new PasswordEncryptionIntegrationTestException( "Error when reading the InputStream when running shell script ", ex); } finally { if (br != null) { try { br.close(); } catch (IOException e) { log.warn("error while closing the buffered reader"); } } if (process != null) { process.destroy(); } } }
From source file:org.apache.tajo.plan.function.stream.StreamingUtil.java
/** * Set up the run-time environment of the managed process. * * @param pb {@link ProcessBuilder} used to exec the process *//*ww w. j a va 2 s .co m*/ private static void setupEnvironment(ProcessBuilder pb) { String separator = ":"; Map<String, String> env = pb.environment(); // Add the current-working-directory to the $PATH File dir = pb.directory(); String cwd = (dir != null) ? dir.getAbsolutePath() : System.getProperty("user.dir"); String envPath = env.get(PATH); if (envPath == null) { envPath = cwd; } else { envPath = envPath + separator + cwd; } env.put(PATH, envPath); }
From source file:io.jmnarloch.cd.go.plugin.gradle.GradleTaskExecutor.java
/** * Builds the Gradle process for later execution, it configures all the build properties based on the current * task configuration. It also takes into account the current task execution context. * * @param config the task configuration//from ww w.j av a2 s. c o m * @param environment the task execution environment * @return the created Gradle build process */ private static ProcessBuilder buildGradleProcess(ExecutionConfiguration config, ExecutionContext environment) { final Map<String, String> env = environment.getEnvironmentVariables(); String workingDirectory = unifyPath(environment.getWorkingDirectory()); workingDirectory = workingDirectory.endsWith(File.separator) ? workingDirectory : workingDirectory + File.separator; String relativePath = config.getProperty(GradleTaskConfig.RELATIVE_PATH.getName()); workingDirectory = StringUtils.isBlank(relativePath) ? workingDirectory : unifyPath(workingDirectory + relativePath); final List<String> command = parse(config, env, workingDirectory); logger.debug("Executing command: " + command); final ProcessBuilder builder = new ProcessBuilder(command); builder.environment().putAll(env); builder.directory(new File(workingDirectory)); return builder; }
From source file:functionaltests2.SchedulerCommandLine.java
/** * Start a Scheduler and Resource Manager. *//*from w w w . j a v a 2s . c om*/ public static void startSchedulerCmdLine(boolean restart, File proactiveConf) throws Exception { File schedHome = new File(System.getProperty("pa.scheduler.home")).getCanonicalFile(); File rmHome = new File(System.getProperty("pa.rm.home")).getCanonicalFile(); if (proactiveConf != null) { FileUtils.copyFile(proactiveConf, new File(schedHome, "config" + fs + "proactive" + fs + "ProActiveConfiguration.xml")); } System.out.println(schedHome); p = null; ProcessBuilder pb = new ProcessBuilder(); if (OperatingSystem.getOperatingSystem().equals(OperatingSystem.unix)) { pb.directory(new File(schedHome + fs + "bin" + fs + "unix")); pb.command("/bin/bash", restart ? "scheduler-start" : "scheduler-start-clean", "-Dproactive.communication.protocol=pnp", "-Dproactive.pnp.port=9999"); pb.environment().put("SchedulerTStarter", "SchedulerTStarter"); p = pb.start(); } else { pb.directory(new File(schedHome + fs + "bin" + fs + "windows")); pb.command("cmd.exe", "/c", restart ? "scheduler-start.bat" : "scheduler-start-clean.bat", "-Dproactive.communication.protocol=pnp", "-Dproactive.pnp.port=9999"); pb.environment().put("SchedulerTStarter", "SchedulerTStarter"); p = pb.start(); } IOTools.LoggingThread lt1 = new IOTools.LoggingThread(p.getInputStream(), "[SchedulerTStarter]", System.out); Thread t1 = new Thread(lt1, "SchedulerTStarter"); t1.setDaemon(true); t1.start(); // waiting the initialization RMAuthentication rmAuth = RMConnection.waitAndJoin("pnp://localhost:9999"); System.out.println("RM successfully joined."); SchedulerConnection.waitAndJoin("pnp://localhost:9999"); System.out.println("Scheduler successfully joined."); }
From source file:org.jsweet.util.ProcessUtil.java
public static void runCmd(File directory, Consumer<String> stdoutConsumer, String... cmd) { System.out.println("run command: " + StringUtils.join(cmd, " ")); String[] args;//from ww w . j a v a 2 s.co m if (System.getProperty("os.name").startsWith("Windows")) { args = new String[] { "cmd", "/c" }; } else { args = new String[0]; } args = ArrayUtils.addAll(args, cmd); System.out.println("run command: '" + StringUtils.join(args, " ") + "' in directory " + directory); // logger.fine("run command: " + StringUtils.join(args, " ")); int code = -1; try { ProcessBuilder processBuilder = new ProcessBuilder(args); processBuilder.redirectErrorStream(true); if (directory != null) { processBuilder.directory(directory); } if (!StringUtils.isBlank(EXTRA_PATH)) { processBuilder.environment().put("PATH", processBuilder.environment().get("PATH") + File.pathSeparator + EXTRA_PATH); } Process process = processBuilder.start(); try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while ((line = in.readLine()) != null) { if (stdoutConsumer != null) { stdoutConsumer.accept(line); } else { logger.info("OUT:" + line); } } } code = process.waitFor(); if (code != 0) { throw new RuntimeException( "error while exectuting: " + StringUtils.join(args, " ") + ", error code: " + code); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:io.mesosphere.mesos.frameworks.cassandra.executor.ProdObjectFactory.java
@NotNull private static String processBuilderToString(@NotNull final ProcessBuilder builder) { return "ProcessBuilder{\n" + "directory() = " + builder.directory() + ",\n" + "command() = " + Joiner.on(" ").join(builder.command()) + ",\n" + "environment() = " + Joiner.on("\n").withKeyValueSeparator("->").join(builder.environment()) + "\n}"; }