Example usage for java.lang ProcessBuilder directory

List of usage examples for java.lang ProcessBuilder directory

Introduction

In this page you can find the example usage for java.lang ProcessBuilder directory.

Prototype

File directory

To view the source code for java.lang ProcessBuilder directory.

Click Source Link

Usage

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 ww w .  ja  v a2 s .c om*/
    return pb.start();
}

From source file:org.openengsb.openengsbplugin.tools.Tools.java

public static int executeProcess(List<String> command, File targetDirectory)
        throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.directory(targetDirectory);
    if (targetDirectory != null) {
        LOG.trace(//  ww  w  .j a  va2 s  . c om
                String.format("processBuilder.directory().exists(): %s", processBuilder.directory().exists()));
    }
    Process p = processBuilder.start();

    BufferedReader br = null;
    try {
        br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            LOG.debug(line);
        }
    } finally {
        IOUtils.closeQuietly(br);
    }

    p.waitFor();
    return p.exitValue();
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java

/**
 * Run a command and wait/*from  ww  w . ja v  a  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:org.apache.karaf.kittests.Helper.java

public static Process launchScript(File homeDir, String script, String args) throws IOException {
    ProcessBuilder builder = new ProcessBuilder();
    builder.directory(homeDir);
    if (isWindowsOs()) {
        builder.command("cmd.exe", "/c", new File(homeDir, "bin\\" + script + ".bat").getAbsolutePath(), args);
    } else {//from  w ww. j a  v a  2  s.c  o m
        builder.command("/bin/sh", new File(homeDir, "bin/" + script).getAbsolutePath(), args);
    }
    builder.redirectErrorStream(true);
    Process process = builder.start();
    PumpStreamHandler pump = new PumpStreamHandler(System.in, System.out, System.err);
    pump.attach(process);
    pump.start();
    return process;
}

From source file:org.openo.nfvo.jujuvnfmadapter.common.LocalComandUtils.java

/**
 * execute local command/*from ww  w. j  a v  a 2 s.  c  o m*/
 * <br/>
 * 
 * @param dir the command path
 * @param command
 * @param timeout  millis
 * @return response msg
 * @since NFVO 0.5
 */
public static ExeRes execute(String dir, List<String> command, long timeout) {
    ExeRes er = new ExeRes();
    StringBuilder sb = new StringBuilder();
    try {
        if (SwitchController.isDebugModel()) {
            command.set(0, "juju.bat");
        }
        ProcessBuilder pb = new ProcessBuilder(command);
        if (StringUtils.isNotBlank(dir)) {
            pb.directory(new File(dir));
        }
        pb.redirectErrorStream(true);
        Process p = pb.start();

        // wait the process result
        buildProcessResult(er, p, timeout);

        InputStream in = p.getInputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = in.read(buffer)) > 0) {
            sb.append(new String(buffer, 0, length));
        }
        in.close();
        er.setBody(sb.toString());
    } catch (Exception e) {
        er.setCode(ExeRes.FAILURE);
        er.setBody(e.getMessage());
        log.error("execute the command failed:{}", command, e);
    }
    return er;
}

From source file:org.openspaces.test.client.executor.Executor.java

/**
 * Create operating system process and redirect all process output stream to supplied file.
 *
 * @param directory     The new working directory
 * @param processArgs   A string array containing the program and its arguments.
 * @param outStreamFile if not <code>null</code> then any error/standard output stream generated
 *                      by this processes will be redirected to the supplied file.
 * @return The started process./*from w ww .j  a v  a 2  s  .  c om*/
 * @throws IOException Failed to start process.
 */
static Process forkProcess(File directory, String... processArgs) throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder(processArgs);
    processBuilder.directory(directory);
    processBuilder.redirectErrorStream(true);
    return processBuilder.start();
}

From source file:org.exist.launcher.ServiceManager.java

static void run(List<String> args, BiConsumer<Integer, String> consumer) {
    final ProcessBuilder pb = new ProcessBuilder(args);
    final Optional<Path> home = ConfigurationHelper.getExistHome();

    pb.directory(home.orElse(Paths.get(".")).toFile());
    pb.redirectErrorStream(true);/*  w  w w .ja  va2s  .  c  om*/
    if (consumer == null) {
        pb.inheritIO();
    }
    try {
        final Process process = pb.start();
        if (consumer != null) {
            final StringBuilder output = new StringBuilder();
            try (final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "UTF-8"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append('\n').append(line);
                }
            }
            final int exitValue = process.waitFor();
            consumer.accept(exitValue, output.toString());
        }
    } catch (IOException | InterruptedException e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), "Error Running Process", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:de.teamgrit.grit.preprocess.fetch.SvnFetcher.java

/**
 * runSVNCommand runs an svn command in the specified directory.
 *
 * @param connection/*from w w w  .j  ava2  s.co 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);
}

From source file:org.apache.asterix.installer.test.ReplicationIT.java

private static Process remoteInvoke(String cmd, String node) throws Exception {
    ProcessBuilder pb = new ProcessBuilder("vagrant", "ssh", node, "--", cmd);
    File cwd = new File(asterixProjectDir.toString() + "/" + CLUSTER_BASE);
    pb.directory(cwd);
    pb.redirectErrorStream(true);//from  w w  w  . j  a  v  a 2 s  .co  m
    Process p = pb.start();
    p.waitFor();
    return p;
}

From source file:org.jenkinsci.plugins.workflow.steps.scm.SubversionStepTest.java

public static void run(File cwd, String... cmds) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(cmds);
    try {//from  w  w  w .  j av a  2s .co  m
        ProcessBuilder.class.getMethod("inheritIO").invoke(pb);
    } catch (NoSuchMethodException x) {
        // prior to Java 7
    }
    try {
        int r = pb.directory(cwd).start().waitFor();
        Assume.assumeTrue(Arrays.toString(cmds) + " failed with error code " + r, r == 0);
    } catch (Exception ex) {
        Assume.assumeNoException(
                Arrays.toString(cmds) + " failed with exception (required tooling not installed?)", ex);
    }
}