Example usage for java.lang ProcessBuilder start

List of usage examples for java.lang ProcessBuilder start

Introduction

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

Prototype

public Process start() throws IOException 

Source Link

Document

Starts a new process using the attributes of this process builder.

Usage

From source file:org.projectbuendia.openmrs.web.controller.ProfileManager.java

/**
 * Executes a command with one argument, returning true if the command succeeds.
 * Gathers the output from stdout and stderr into the provided list of lines.
 *//*from  w  w w  . j a  v  a2 s.c o  m*/
private boolean execute(String command, File arg, List<String> lines) {
    ProcessBuilder pb = new ProcessBuilder(command, arg.getAbsolutePath());
    pb.redirectErrorStream(true); // redirect stderr to stdout
    try {
        Process proc = pb.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
        proc.waitFor();
        return proc.exitValue() == 0;
    } catch (Exception e) {
        log.error("Exception while executing: " + command + " " + arg, e);
        lines.add(e.getMessage());
        return false;
    }
}

From source file:com.hivemq.maven.HiveMQMojo.java

/**
 * Starts the HiveMQ process with the given parameters
 *
 * @param commandParameters the parameters
 * @return the running HiveMQ process// w w w.j a va 2s . com
 * @throws MojoExecutionException if the execution of HiveMQ did not work
 */
private Process startHiveMQ(final List<String> commandParameters) throws MojoExecutionException {
    final ProcessBuilder processBuilder = new ProcessBuilder(commandParameters);

    processBuilder.directory(hiveMQDir);
    processBuilder.redirectErrorStream(true);

    Process p;
    try {
        p = processBuilder.start();
    } catch (IOException e) {
        log.error("An error occured while starting HiveMQ:", e);
        throw new MojoExecutionException("An error occured while starting HiveMQ", e);
    }
    return p;
}

From source file:mitm.common.util.ProcessRunner.java

public int run(List<String> cmd) throws IOException {
    if (cmd == null || cmd.size() == 0) {
        throw new IllegalArgumentException("cmd is invalid.");
    }/* ww  w  .j  a va 2s . c  o  m*/

    /*
     * Used to show which command was executed
     */
    String cmdLine = logArguments ? StringUtils.join(cmd, ",") : cmd.get(0);

    logger.debug("Starting application. cmdLine: " + cmdLine);

    /*
     * Watchdog that will be used to destroy the process on a timeout
     */
    TaskScheduler watchdog = new TaskScheduler(ProcessRunner.class.getCanonicalName() + "#" + cmdLine);

    try {
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);

        Process process = processBuilder.start();

        if (timeout > 0) {
            /*
             * Task that will destroy the process on a timeout
             */
            Task processWatchdogTask = new DestroyProcessTimeoutTask(process, watchdog.getName());

            watchdog.addTask(processWatchdogTask, timeout);

            /*
             * Task that will interrupt the current thread on a timeout
             */
            Task threadInterruptTimeoutTask = new ThreadInterruptTimeoutTask(Thread.currentThread(),
                    watchdog.getName());

            watchdog.addTask(threadInterruptTimeoutTask, timeout);
        }

        Thread inputThread = null;
        Thread outputThread = null;
        Thread errorThread = null;

        if (input != null) {
            inputThread = new StreamCopier(input, process.getOutputStream(), "input", false, true);
            inputThread.start();
        }

        if (output != null) {
            outputThread = new StreamCopier(process.getInputStream(), output, "output", true, false);
            outputThread.start();
        }

        if (error != null) {
            errorThread = new StreamCopier(process.getErrorStream(), error, "error", true, false);
            errorThread.start();
        }

        try {
            exitCode = process.waitFor();

            /*
             * We need to wait for the threads to finish because otherwise there is
             * a chance we will start using the output before all the output has been
             * written/read.
             */
            if (inputThread != null) {
                inputThread.join();
            }

            if (outputThread != null) {
                outputThread.join();
            }

            if (errorThread != null) {
                errorThread.join();
            }

            /*
             * We MUST close the standard streams otherwise some "FIFO pipes" won't be closed until
             * the garbage collector is run. If there are too many open "FIFO pipes", the following
             * exception might occur:
             * 
             * java.io.IOException: error=24, Too many open files
             * 
             * Closing the standard streams makes sure that the pipes are closed.
             * 
             * Note: The Javadoc for Process does not mention that you should close the standard streams
             * even if not used. Perhaps they rely on the GC?
             * 
             * Note2: The number of FIFI pipes can be counted with:
             * 
             * lsof | grep java | grep pipe | wc -l
             */
            IOUtils.closeQuietly(process.getInputStream());
            IOUtils.closeQuietly(process.getOutputStream());
            IOUtils.closeQuietly(process.getErrorStream());
        } catch (InterruptedException e) {
            throw new IOException("Error running [" + cmdLine + "]", e);
        }

        if (exitCode != successExitCode) {
            throw new ProcessException("Error running [" + cmdLine + "]. exit value: " + exitCode, exitCode);
        }
    } finally {
        logger.debug("Application finished. cmdLine: " + cmdLine);

        /*
         * Need to cancel any pending watchdog tasks
         */
        watchdog.cancel();
    }

    return exitCode;
}

From source file:com.pluribus.vcf.helper.TestSetup.java

@BeforeTest(alwaysRun = true)
@Parameters({ "resetSwitch" })
//Run ansible reset switch script
public void resetSwitchAnsible(@Optional("1") String resetSwitch) throws Exception {
    if (Integer.parseInt(resetSwitch) == 1) {
        String out1;/*from w w w.j  a  v  a  2 s .  co  m*/
        StringBuffer output = null;

        String[] command = { "src/test/resources/resetSwitch.expect" };
        ProcessBuilder probuilder = new ProcessBuilder(command);

        //You can set up your work directory
        probuilder.directory(new File(System.getProperty("user.dir")));
        Process process = probuilder.start();

        //Read out dir output
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        System.out.printf("Output of running %s is:\n", Arrays.toString(command));
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        //Wait to get exit value
        try {
            int exitValue = process.waitFor();
            System.out.println("\n\nExit Value is " + exitValue);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return;
}

From source file:io.syndesis.verifier.LocalProcessVerifier.java

private String getConnectorClasspath(Connector connector) throws IOException, InterruptedException {
    byte[] pom = new byte[0]; // TODO: Fix generation to use an Action projectGenerator.generatePom(connector);
    java.nio.file.Path tmpDir = Files.createTempDirectory("syndesis-connector");
    try {/* w  w w .j av a  2  s. c om*/
        Files.write(tmpDir.resolve("pom.xml"), pom);
        ArrayList<String> args = new ArrayList<>();
        args.add("mvn");
        args.add("org.apache.maven.plugins:maven-dependency-plugin:3.0.0:build-classpath");
        if (localMavenRepoLocation != null) {
            args.add("-Dmaven.repo.local=" + localMavenRepoLocation);
        }
        ProcessBuilder builder = new ProcessBuilder().command(args)
                .redirectError(ProcessBuilder.Redirect.INHERIT).directory(tmpDir.toFile());
        Map<String, String> environment = builder.environment();
        environment.put("MAVEN_OPTS", "-Xmx64M");
        Process mvn = builder.start();
        try {
            String result = parseClasspath(mvn.getInputStream());
            if (mvn.waitFor() != 0) {
                throw new IOException(
                        "Could not get the connector classpath, mvn exit value: " + mvn.exitValue());
            }
            return result;
        } finally {
            mvn.getInputStream().close();
            mvn.getOutputStream().close();
        }
    } finally {
        FileSystemUtils.deleteRecursively(tmpDir.toFile());
    }
}

From source file:uk.co.codezen.maven.composer.mojo.AbstractComposerMojo.java

/**
 * Execute an arbitrary command, forwarding the process stdout to the Log info level
 * and the process stderr to the Java error level.
 *
 * @param command Command to execute// w w w  .  j a  v a  2s .co  m
 * @param workingDirectory Working directory
 * @throws IOException IO problem executing command
 */
private int runCommand(List<String> command, String workingDirectory) throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.directory(new File(workingDirectory));
    Process composerProcess = processBuilder.start();

    // Link Maven stdout/stderr with process
    pipe(composerProcess.getInputStream(), System.out);
    pipe(composerProcess.getErrorStream(), System.err);

    while (true) {
        try {
            composerProcess.waitFor();
            break;
        } catch (InterruptedException e) {
            // Do nothing, re-run loop
        }
    }

    return composerProcess.exitValue();
}

From source file:jp.co.tis.gsp.tools.dba.dialect.MysqlDialect.java

@Override
public void exportSchema(ExportParams params) throws MojoExecutionException {
    BufferedInputStream in = null;
    FileOutputStream out = null;/*from w  ww  .j ava  2s  .c o m*/
    try {
        File dumpFile = params.getDumpFile();
        String user = params.getUser();
        String password = params.getPassword();
        String schema = params.getSchema();

        ProcessBuilder pb = new ProcessBuilder("mysqldump", schema, "-u", user, "--password=" + password,
                "--default-character-set=utf8", "--hex-blob", "-R");
        Process process = pb.start();
        in = new BufferedInputStream(process.getInputStream());

        out = FileOutputStreamUtil.create(dumpFile);
        byte[] buf = new byte[4096];
        while (true) {
            int res = in.read(buf);
            if (res <= 0)
                break;
            out.write(buf, 0, res);
        }

    } catch (IOException e) {
        throw new MojoExecutionException("mysqldump", e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:azkaban.jobExecutor.utils.process.AzkabanProcess.java

/**
 * Execute this process, blocking until it has completed.
 *//*from  w w w .j  ava  2s.  c  om*/
public void run() throws IOException {
    if (this.isStarted() || this.isComplete()) {
        throw new IllegalStateException("The process can only be used once.");
    }

    ProcessBuilder builder = new ProcessBuilder(cmd);
    builder.directory(new File(workingDir));
    builder.environment().putAll(env);
    builder.redirectErrorStream(true);
    this.process = builder.start();
    try {
        this.processId = processId(process);
        if (processId == 0) {
            logger.debug("Spawned thread with unknown process id");
        } else {
            logger.debug("Spawned thread with process id " + processId);
        }

        this.startupLatch.countDown();

        LogGobbler outputGobbler = new LogGobbler(new InputStreamReader(process.getInputStream()), logger,
                Level.INFO, 30);
        LogGobbler errorGobbler = new LogGobbler(new InputStreamReader(process.getErrorStream()), logger,
                Level.ERROR, 30);

        outputGobbler.start();
        errorGobbler.start();
        int exitCode = -1;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            logger.info("Process interrupted. Exit code is " + exitCode, e);
        }

        completeLatch.countDown();

        // try to wait for everything to get logged out before exiting
        outputGobbler.awaitCompletion(5000);
        errorGobbler.awaitCompletion(5000);

        if (exitCode != 0) {
            String output = new StringBuilder().append("Stdout:\n").append(outputGobbler.getRecentLog())
                    .append("\n\n").append("Stderr:\n").append(errorGobbler.getRecentLog()).append("\n")
                    .toString();
            throw new ProcessFailureException(exitCode, output);
        }

    } finally {
        IOUtils.closeQuietly(process.getInputStream());
        IOUtils.closeQuietly(process.getOutputStream());
        IOUtils.closeQuietly(process.getErrorStream());
    }
}

From source file:edu.stanford.junction.director.JAVADirector.java

private Process launchJAR(URL jarURL, URI activityURI) {
    final String JAR_PATH = "jars/";

    String jarName = JAR_PATH + "/" + jarURL.getPath().substring(1).replace("/", "-");
    File jarFile = new File(jarName);
    File tmpFile = new File(jarName + ".tmp");
    if (!jarFile.exists() && !tmpFile.exists()) {
        try {/*ww w .  j  a v  a2s.c om*/
            FileOutputStream out = new FileOutputStream(tmpFile);

            InputStream in = jarURL.openStream();
            byte[] buf = new byte[4 * 1024];
            int bytesRead;
            while ((bytesRead = in.read(buf)) != -1) {
                out.write(buf, 0, bytesRead);
            }
            in.close();
            out.close();

            boolean res = tmpFile.renameTo(jarFile);
            if (!res) {
                throw new Exception("Could not rename file.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    if (!jarFile.exists()) {
        System.out.println("Failed to get JAR file " + jarFile.getName());
        return null;
    }

    // Launch the new JVM
    try {
        List<String> command = new ArrayList<String>();
        command.add("java");
        command.add("-jar");
        command.add(jarFile.getAbsolutePath());
        command.add(activityURI.toString());

        System.out.println("Executing: " + command.toString());

        ProcessBuilder pb = new ProcessBuilder(command);
        pb.directory(jarFile.getParentFile());
        pb.redirectErrorStream(true);
        Process p = pb.start();
        // TODO: make sure it worked

        return p;
    } catch (Exception e) {
        System.out.println("failed to launch JAR.");
        e.printStackTrace();
    }
    return null;
}

From source file:net.sf.mavenjython.JythonMojo.java

public void runJythonScriptOnInstall(File outputDirectory, List<String> args) throws MojoExecutionException {
    getLog().info("running " + args + " in " + outputDirectory);
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(outputDirectory);/*from w  ww .  ja v  a2  s .c om*/
    final Process p;
    try {
        p = pb.start();
    } catch (IOException e) {
        throw new MojoExecutionException("Executing jython failed. tried to run: " + pb.command(), e);
    }
    copyIO(p.getInputStream(), System.out);
    copyIO(p.getErrorStream(), System.err);
    copyIO(System.in, p.getOutputStream());
    try {
        if (p.waitFor() != 0) {
            throw new MojoExecutionException("Jython failed with return code: " + p.exitValue());
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Python tests were interrupted", e);
    }

}