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:Main.java

public static String runCommand(String[] command, String workdirectory) {
    String result = "";
    //AbLogUtil.d(AbAppUtil.class, "#"+command);
    try {//from  w ww  . j  ava 2 s.co  m
        ProcessBuilder builder = new ProcessBuilder(command);
        // set working directory
        if (workdirectory != null) {
            builder.directory(new File(workdirectory));
        }
        builder.redirectErrorStream(true);
        Process process = builder.start();
        InputStream in = process.getInputStream();
        byte[] buffer = new byte[1024];
        while (in.read(buffer) != -1) {
            String str = new String(buffer);
            result = result + str;
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

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

/**
 * Helper method that executes the given cmd and returns the output. The process will be destroyed 
 * if the process takes longer to execute than the timeout.  
 *///w w w  . java  2 s.co  m
public static void executeCommand(List<String> cmd, long timeout, InputStream input, OutputStream output)
        throws IOException {
    Check.notNull(cmd, "cmd");

    if (cmd.size() == 0) {
        throw new IOException("Process is missing.");
    }

    /*
     * Used for reporting
     */
    String name = StringUtils.join(cmd, ",");

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

    try {
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();

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

        watchdog.addTask(processWatchdogTask, timeout);

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

        watchdog.addTask(threadInterruptTimeoutTask, timeout);

        /*
         * Send the input to the standard input of the process
         */
        if (input != null) {
            IOUtils.copy(input, process.getOutputStream());

            IOUtils.closeQuietly(process.getOutputStream());
        }

        /*
         * Get the standard output from the process
         */
        if (output != null) {
            IOUtils.copy(process.getInputStream(), output);
        }

        int exitValue;

        try {
            exitValue = process.waitFor();
        } catch (InterruptedException e) {
            throw new IOException("Error executing [" + name + "]", e);
        }

        if (exitValue != 0) {
            throw new ProcessException("Error executing [" + name + "]. exit value: " + exitValue, exitValue);
        }
    } finally {
        /*
         * Need to cancel any pending tasks
         */
        watchdog.cancel();
    }
}

From source file:io.jmnarloch.cd.go.plugin.gradle.GradleTaskExecutor.java

/**
 * Executes the actual Gradle build./*ww  w  .  j  av a  2 s . c o m*/
 *
 * @param builder the process builder
 * @param console the log output
 * @return the process return value
 * @throws IOException          if any error occurs during I/O operation
 * @throws InterruptedException if any error occurs during process execution
 */
private static int execute(ProcessBuilder builder, JobConsoleLogger console)
        throws IOException, InterruptedException {

    Process process = null;
    try {
        process = builder.start();

        console.readOutputOf(process.getInputStream());
        console.readErrorOf(process.getErrorStream());
        return process.waitFor();
    } finally {
        if (process != null) {
            process.destroy();
        }
    }
}

From source file:com.offbynull.portmapper.common.ProcessUtils.java

/**
 * Run a process and dump the stdout stream to a string.
 * @param timeout maximum amount of time the process can take to run
 * @param command command/*from  w  w  w.j  a v  a2 s . co  m*/
 * @param args arguments
 * @return stdout from the process dumped to a string
 * @throws IOException if the process encounters an error
 * @throws NullPointerException if any arguments are {@code null} or contains {@code null}
 * @throws IllegalArgumentException any numeric argument is negative
 */
public static String runProcessAndDumpOutput(long timeout, String command, String... args) throws IOException {
    Validate.notNull(command);
    Validate.noNullElements(args);
    Validate.inclusiveBetween(0L, Long.MAX_VALUE, timeout);

    String[] pbCmd = new String[args.length + 1];
    pbCmd[0] = command;
    System.arraycopy(args, 0, pbCmd, 1, args.length);

    ProcessBuilder builder = new ProcessBuilder(pbCmd);

    final AtomicBoolean failedFlag = new AtomicBoolean();

    Timer timer = new Timer("Process timeout timer", true);
    Process proc = null;
    try {
        proc = builder.start();

        final Process finalProc = proc;
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                failedFlag.set(true);
                finalProc.destroy();
            }
        }, timeout);

        String ret = IOUtils.toString(proc.getInputStream());
        if (failedFlag.get()) {
            throw new IOException("Process failed");
        }

        return ret;
    } finally {
        if (proc != null) {
            proc.destroy();
        }
        timer.cancel();
        timer.purge();
    }
}

From source file:Main.java

/**
 * create a child process with environment variables
 * @param command// w  w  w . j  a v a 2  s  . c o  m
 * @param envVars
 * @return
 * @throws InterruptedException
 * @throws IOException
 */
public static String execUnixCommand(String[] command, Map<String, String> envVars)
        throws InterruptedException, IOException {

    /*
    ProcessBuilder processBuilder = new ProcessBuilder(command);
            
    if ( envVars != null ){
    Map<String, String> env = processBuilder.environment();
    env.clear();
    env.putAll(envVars);
    }
            
    Process process = processBuilder.start();
    processBuilder.redirectErrorStream(false);
    process.waitFor();
    String outputWithError = loadStream(process.getInputStream()) + loadStream(process.getErrorStream());
    return outputWithError;
     */

    ProcessBuilder processBuilder = new ProcessBuilder(command);

    if (envVars != null) {
        Map<String, String> env = processBuilder.environment();
        env.clear();
        env.putAll(envVars);
    }
    Process process = processBuilder.start();
    String output = loadStream(process.getInputStream());
    String error = loadStream(process.getErrorStream());
    process.waitFor();
    return output + "\n" + error;
}

From source file:de.uni_freiburg.informatik.ultimate.licence_manager.authors.SvnAuthorProvider.java

private static boolean isSvnAvailable() {
    final ProcessBuilder pbuilder = new ProcessBuilder("svn", "--version");
    try {//from w  ww.j  a va 2 s.  co  m
        final Process process = pbuilder.start();
        if (process.waitFor(1000, TimeUnit.MILLISECONDS)) {
            final List<String> lines = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
            if (lines == null || lines.isEmpty()) {
                return false;
            }
            sSvnVersion = lines.get(0);
            return true;
        }
    } catch (IOException | InterruptedException e) {
        System.err.println("Could not find 'svn' executable, disabling author provider");
        return false;
    }
    return false;
}

From source file:com.mewmew.fairy.v1.book.Xargs.java

public static void exec(Map<String, String> env, String cmd[], boolean redirectError, Output<String> output)
        throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(cmd);
    if (env != null) {
        pb.environment().putAll(env);//ww  w  .  j av a2 s . c  o m
    }
    if (redirectError) {
        pb.redirectErrorStream(true);
    }
    final Process p = pb.start();
    if (!redirectError) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    LineIterator err = new LineIterator(new InputStreamReader(p.getErrorStream()));
                    while (err.hasNext()) {
                        err.next();
                    }
                } finally {
                }
            }
        }).start();
    }
    LineIterator out = new LineIterator(new InputStreamReader(p.getInputStream()));
    while (out.hasNext()) {
        output.output(out.nextLine());
    }
    int code = p.waitFor();
    if (code != 0) {
        throw new RuntimeException(String.format("return != 0, code = %d", code));
    }
}

From source file:com.junoyoon.BullsUtil.java

/**
 * Run command and/*from   ww w. ja va  2 s .  c o m*/
 * 
 * @param cmd
 * @return
 * @throws IOException
 */
public static String getCmdOutput(List<String> cmd) throws IOException {
    ProcessBuilder builder = new ProcessBuilder();
    builder.command().addAll(cmd);
    builder.redirectErrorStream(true);
    StringBuilder result = new StringBuilder(1024);
    Process proc = builder.start();
    boolean firstLine = true;
    for (Object eachLineObject : IOUtils.readLines(proc.getInputStream())) {
        String eachLine = (String) eachLineObject;
        if (firstLine) {
            eachLine = eachLine.replace("charset=us-ascii", "charset=" + Constant.DEFAULT_ENCODING);
            firstLine = false;
        }
        result.append(eachLine).append("\n");
    }
    return result.toString();
}

From source file:energy.usef.environment.tool.security.VaultService.java

/**
 * Executes a class's static main method with the current java executable and classpath in a separate process.
 * /*from  ww  w.j a va  2s  .  c o m*/
 * @param klass the class to call the static main method for
 * @param params the parameters to provide
 * @return the exit code of the process
 * @throws IOException
 * @throws InterruptedException
 */
public static int exec(@SuppressWarnings("rawtypes") Class klass, List<String> params)
        throws IOException, InterruptedException {
    String javaHome = System.getProperty("java.home");
    String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
    String classpath = System.getProperty("java.class.path");
    String className = klass.getCanonicalName();

    // construct the command line
    List<String> command = new ArrayList<String>();
    command.add(javaBin);
    command.add("-cp");
    command.add(classpath);
    command.add(className);
    command.addAll(params);
    LOGGER.debug("executing class '{}' with params '{}' in classpath '{}' with java binary '{}'", className,
            params.toString(), classpath, javaBin);

    // build and start the Vault's process
    ProcessBuilder builder = new ProcessBuilder(command);
    Process process = builder.start();
    process.waitFor();

    // get the input and error streams of the process and log them
    InputStream in = process.getInputStream();
    InputStream en = process.getErrorStream();
    InputStreamReader is = new InputStreamReader(in);
    InputStreamReader es = new InputStreamReader(en);
    BufferedReader br = new BufferedReader(is);
    BufferedReader be = new BufferedReader(es);

    String read = br.readLine();
    while (read != null) {
        LOGGER.debug(read);
        read = br.readLine();
    }
    read = be.readLine();
    while (read != null) {
        LOGGER.debug(read);
        read = be.readLine();
    }

    br.close();
    is.close();
    in.close();

    return process.exitValue();
}

From source file:jmupen.JMupenUpdater.java

public static void restartApplication() {
    final String javaBin;
    if (JMupenUtils.getOs().equalsIgnoreCase("win")) {
        javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java.exe";
    } else {/*ww  w .  j a  v  a  2  s. co m*/
        javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
    }
    File currentJar = null;
    try {
        currentJar = getJarFile();
    } catch (URISyntaxException ex) {
        System.err.println("Malformed JAR URL " + ex.getLocalizedMessage());
    }

    if (currentJar == null) {
        return;
    }

    /* is it a jar file? */
    if (!currentJar.getName().endsWith(".jar")) {
        return;
    }

    /* Build command: java -jar application.jar */
    final ArrayList<String> command = new ArrayList<String>();
    command.add(javaBin);
    command.add("-jar");
    command.add(currentJar.getPath());

    final ProcessBuilder builder = new ProcessBuilder(command);
    try {
        builder.start();
    } catch (IOException ex) {
        System.err.println("Error restarting app. " + ex.getLocalizedMessage());
    }
    System.exit(0);
}