Example usage for java.lang ProcessBuilder redirectErrorStream

List of usage examples for java.lang ProcessBuilder redirectErrorStream

Introduction

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

Prototype

boolean redirectErrorStream

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

Click Source Link

Usage

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);//from   w  w  w.jav  a 2s  .  c o  m
    pb.redirectErrorStream(true);
    Process p = pb.start();
    p.waitFor();
    return p;
}

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  w  w  . j ava  2  s  . c  o m*/
 * @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.jsweet.transpiler.util.ProcessUtil.java

/**
 * Runs the given command.//  www  . ja  va  2  s . com
 * 
 * @param command
 *            the command name
 * @param directory
 *            the working directory of the created process
 * @param async
 *            tells if the command should be run asynchronously (in a
 *            separate thread)
 * @param stdoutConsumer
 *            consumes the standard output stream as lines of characters
 * @param endConsumer
 *            called when the process actually ends
 * @param errorHandler
 *            upcalled when the command does not terminate successfully
 * @param args
 *            the command-line arguments
 * @return the process that was created to execute the command (can be still
 *         running at this point if <code>async</code> is <code>true</code>)
 */
public static Process runCommand(String command, File directory, boolean async, Consumer<String> stdoutConsumer,
        Consumer<Process> endConsumer, Runnable errorHandler, String... args) {

    String[] cmd;
    if (System.getProperty("os.name").startsWith("Windows")) {
        if (nodeCommands.contains(command)) {
            cmd = new String[] { getNpmPath(command) };
        } else {
            cmd = new String[] { "cmd", "/c", command };
        }
    } else {
        if (nodeCommands.contains(command)) {
            cmd = new String[] { getNpmPath(command) };
        } else {
            cmd = new String[] { command };
        }
    }
    cmd = ArrayUtils.addAll(cmd, args);

    logger.debug("run command: " + StringUtils.join(cmd, " "));
    Process[] process = { null };
    try {
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        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[0] = processBuilder.start();

        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                try {
                    try (BufferedReader in = new BufferedReader(
                            new InputStreamReader(process[0].getInputStream()))) {
                        String line;
                        while ((line = in.readLine()) != null) {
                            if (stdoutConsumer != null) {
                                stdoutConsumer.accept(line);
                            } else {
                                logger.info(command + " - " + line);
                            }
                        }
                    }

                    process[0].waitFor();
                    if (endConsumer != null) {
                        endConsumer.accept(process[0]);
                    }
                    if (process[0].exitValue() != 0) {
                        if (errorHandler != null) {
                            errorHandler.run();
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    if (errorHandler != null) {
                        errorHandler.run();
                    }
                }
            }
        };
        if (async) {
            new Thread(runnable).start();
        } else {
            runnable.run();
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        if (errorHandler != null) {
            errorHandler.run();
        }
        return null;
    }
    return process[0];
}

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

/**
 * execute local command//from w  w w.  ja 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:com.github.DroidPHP.ServerUtils.java

/**
 * //from w ww.ja va  2s .  c  o m
 * @param mUsername
 * @param mPassword
 */

public static void startMYSQLMointor(String mUsername, String mPassword) {
    String[] query = new String[] { getAppDirectory() + "/mysql-monitor", "-h", "127.0.0.1", "-T", "-f", "-r",
            "-t", "-E", "--disable-pager", "-n", "--user=" + mUsername, "--password=" + mPassword,
            "--default-character-set=utf8", "-L" };
    try {

        ProcessBuilder pb = (new ProcessBuilder(query));
        pb.redirectErrorStream(true);
        proc = pb.start();
        stdin = proc.getOutputStream();
        stdout = proc.getInputStream();

    } catch (IOException e) {

        Log.e(TAG, "MSQL Monitor", e);
        /**
         * I have commented <string>proc.destroy</strong> because this is
         * usually cause bug
         */
        // proc.destroy();
    }

}

From source file:org.apache.zeppelin.python.PythonCondaInterpreter.java

public static String runCommand(List<String> commands) throws IOException, InterruptedException {

    StringBuilder sb = new StringBuilder();

    ProcessBuilder builder = new ProcessBuilder(commands);
    builder.redirectErrorStream(true);
    Process process = builder.start();
    InputStream stdout = process.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
    String line;// ww w  .  j a  v a2s.com
    while ((line = br.readLine()) != null) {
        sb.append(line);
        sb.append("\n");
    }
    int r = process.waitFor(); // Let the process finish.

    if (r != 0) {
        throw new RuntimeException(
                "Failed to execute `" + StringUtils.join(commands, " ") + "` exited with " + r);
    }

    return sb.toString();
}

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);
    if (consumer == null) {
        pb.inheritIO();//from   w  ww  . j a v a2s .c  o m
    }
    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:org.mpi.vasco.util.commonfunc.FileOperations.java

/**
 * Execute shell commands.// w ww  .  j av a2 s  .  c o  m
 */
public static void executeShellCommands(String shellFilePath) {
    Debug.println("execute shell command " + shellFilePath);
    String dirPath = getToLevelDir(shellFilePath);
    Debug.println("get top level dir " + dirPath);
    makeScriptExecutable(shellFilePath);

    List<String> commands = new ArrayList<String>();
    commands.add("sh");
    commands.add(shellFilePath);
    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(new File(dirPath));
    pb.redirectErrorStream(true);
    Process process;
    try {
        process = pb.start();
        //Read output
        StringBuilder out = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null, previous = null;
        while ((line = br.readLine()) != null)
            if (!line.equals(previous)) {
                previous = line;
                out.append(line).append('\n');
                Debug.println(line);
            }

        //Check result
        if (process.waitFor() == 0)
            Debug.println("Success!");
        else {
            System.out.println("Failed!");
            System.err.println(out.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    /*try {
       Process proc = Runtime.getRuntime().exec("cd " +dirPath +" && sh "+shellFilePath);
         InputStream stdin = proc.getInputStream();
         InputStreamReader isr = new InputStreamReader(stdin);
         BufferedReader br = new BufferedReader(isr);
         String line = null;
         System.out.println("<OUTPUT>");
         while ( (line = br.readLine()) != null)
      System.out.println(line);
       System.out.println("</OUTPUT>");
       try {
       if(proc.waitFor() == 0){
          Debug.println("command succeeds");
       }else{
          Debug.println("command failed");
       }
    } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }
       } catch (IOException e) {
    // TODO Auto-generated catch block
       e.printStackTrace();
    } */

}

From source file:org.apache.asterix.installer.test.ReplicationIT.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);/*  ww w  . j  ava2s.  c  om*/
    pb.redirectErrorStream(true);
    Process p = pb.start();
    p.waitFor();
    return p;
}

From source file:com.kylinolap.metadata.tool.HiveSourceTableMgmt.java

public static InputStream executeHiveCommand(String command) throws IOException {

    ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "hive -e \"" + command + "\"");

    // Run hive//from w  w w .j a  v  a2  s . co  m
    pb.redirectErrorStream(true);
    Process p = pb.start();
    InputStream is = p.getInputStream();

    return is;
}