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:msec.org.Tools.java

static public int runCommand(String[] cmd, StringBuffer sb, boolean waitflag) {

    Process pid = null;//from ww w. j  a  v a 2  s .  com
    ProcessBuilder build = new ProcessBuilder(cmd);
    build.redirectErrorStream(true);
    try {
        pid = build.start();
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
    if (sb != null) {
        //BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
        InputStream in = pid.getInputStream();
        byte[] buf = new byte[10240];
        try {
            while (true) {
                int len = in.read(buf);
                if (len <= 0) {
                    break;
                }
                sb.append(new String(buf, 0, len));
            }
        } catch (Exception e) {
        }

    }
    if (waitflag) {
        try {
            pid.waitFor();
            int v = pid.exitValue();
            pid.destroy();
            return v;
        } catch (Exception e) {
        }
    }
    return 0;
}

From source file:com.tascape.qa.th.Utils.java

public static Process cmd(String[] commands, final File file, final File workingDir,
        final String... ignoreRegex) throws IOException {
    FileUtils.touch(file);/*from w w  w  .j  a v a 2  s  . co  m*/
    LOG.debug("Saving console output to {}", file.getAbsolutePath());

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.redirectErrorStream(true);
    pb.directory(workingDir);
    LOG.info("Running command {}:  {}", workingDir == null ? "" : workingDir.getAbsolutePath(),
            pb.command().toString().replaceAll(",", ""));
    final Process p = pb.start();

    Thread t = new Thread(Thread.currentThread().getName() + "-" + p.hashCode()) {
        @Override
        public void run() {
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String console = "console-" + stdIn.hashCode();
            try (PrintWriter pw = new PrintWriter(file)) {
                for (String line = stdIn.readLine(); line != null;) {
                    LOG.trace("{}: {}", console, line);
                    if (null == ignoreRegex || ignoreRegex.length == 0) {
                        pw.println(line);
                    } else {
                        boolean ignore = false;
                        for (String regex : ignoreRegex) {
                            if (!regex.isEmpty() && (line.contains(regex) || line.matches(regex))) {
                                ignore = true;
                                break;
                            }
                        }
                        if (!ignore) {
                            pw.println(line);
                        }
                    }
                    pw.flush();
                    line = stdIn.readLine();
                }
            } catch (IOException ex) {
                LOG.warn(ex.getMessage());
            }
            LOG.trace("command is done");
        }
    };
    t.setDaemon(true);
    t.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            if (p != null) {
                p.destroy();
            }
        }
    });
    return p;
}

From source file:org.apache.spark.network.util.JavaUtils.java

private static void deleteRecursivelyUsingUnixNative(File file) throws IOException {
    ProcessBuilder builder = new ProcessBuilder("rm", "-rf", file.getAbsolutePath());
    Process process = null;// w  w  w  . jav  a  2s  .  c o  m
    int exitCode = -1;

    try {
        // In order to avoid deadlocks, consume the stdout (and stderr) of the process
        builder.redirectErrorStream(true);
        builder.redirectOutput(new File("/dev/null"));

        process = builder.start();

        exitCode = process.waitFor();
    } catch (Exception e) {
        throw new IOException("Failed to delete: " + file.getAbsolutePath(), e);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    if (exitCode != 0 || file.exists()) {
        throw new IOException("Failed to delete: " + file.getAbsolutePath());
    }
}

From source file:org.kududb.client.BaseKuduTest.java

/**
 * Starts a process using the provided command and configures it to be daemon,
 * redirects the stderr to stdout, and starts a thread that will read from the process' input
 * stream and redirect that to LOG.// w w  w. ja v a2 s  . com
 * @param command Process and options
 * @return The started process
 * @throws Exception Exception if an error prevents us from starting the process,
 * or if we were able to start the process but noticed that it was then killed (in which case
 * we'll log the exit value).
 */
static Process configureAndStartProcess(String[] command) throws Exception {
    LOG.info("Starting process: {}", Joiner.on(" ").join(command));
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.redirectErrorStream(true);
    Process proc = processBuilder.start();
    ProcessInputStreamLogPrinterRunnable printer = new ProcessInputStreamLogPrinterRunnable(
            proc.getInputStream());
    Thread thread = new Thread(printer);
    thread.setDaemon(true);
    thread.setName(command[0]);
    PROCESS_INPUT_PRINTERS.add(thread);
    thread.start();

    Thread.sleep(300);
    try {
        int ev = proc.exitValue();
        throw new Exception(
                "We tried starting a process (" + command[0] + ") but it exited with " + "value=" + ev);
    } catch (IllegalThreadStateException ex) {
        // This means the process is still alive, it's like reverse psychology.
    }
    return proc;
}

From source file:org.apache.hyracks.control.nc.service.NCService.java

/**
 * Attempts to launch the "real" NCDriver, based on the configuration
 * information gathered so far.//from   ww  w. j  av  a  2  s.  c o  m
 * @return true if the process was successfully launched and has now
 * exited with a 0 (normal) exit code. false if some configuration error
 * prevented the process from being launched or the process returned
 * a non-0 (abnormal) exit code.
 */
private static boolean launchNCProcess() {
    try {
        ProcessBuilder pb = new ProcessBuilder(buildCommand());
        configEnvironment(pb.environment());
        // QQQ inheriting probably isn't right
        pb.inheritIO();

        if (LOGGER.isLoggable(Level.INFO)) {
            LOGGER.info("Launching NCDriver process");
        }

        // Logfile
        if (!"-".equals(config.logdir)) {
            pb.redirectErrorStream(true);
            File log = new File(config.logdir);
            if (!log.mkdirs()) {
                if (!log.isDirectory()) {
                    throw new IOException(config.logdir + ": cannot create");
                }
                // If the directory IS there, all is well
            }
            File logfile = new File(config.logdir, "nc-" + ncId + ".log");
            // Don't care if this succeeds or fails:
            logfile.delete();
            pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logfile));
            if (LOGGER.isLoggable(Level.INFO)) {
                LOGGER.info("Logging to " + logfile.getCanonicalPath());
            }
        }
        proc = pb.start();

        boolean waiting = true;
        int retval = 0;
        while (waiting) {
            try {
                retval = proc.waitFor();
                waiting = false;
            } catch (InterruptedException ignored) {
            }
        }
        LOGGER.info("NCDriver exited with return value " + retval);
        if (retval == 99) {
            LOGGER.info("Terminating NCService based on return value from NCDriver");
            exit(0);
        }
        return retval == 0;
    } catch (Exception e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, "Configuration from CC broken", e);
        }
        return false;
    }
}

From source file:org.cloudifysource.azure.CliAzureDeploymentTest.java

public static String runCliCommands(File cliExecutablePath, List<List<String>> commands, boolean isDebug)
        throws IOException, InterruptedException {
    if (!cliExecutablePath.isFile()) {
        throw new IllegalArgumentException(cliExecutablePath + " is not a file");
    }//  www  . j av  a  2s . c  o m

    File workingDirectory = cliExecutablePath.getAbsoluteFile().getParentFile();
    if (!workingDirectory.isDirectory()) {
        throw new IllegalArgumentException(workingDirectory + " is not a directory");
    }

    int argsCount = 0;
    for (List<String> command : commands) {
        argsCount += command.size();
    }

    // needed to properly intercept error return code
    String[] cmd = new String[(argsCount == 0 ? 0 : 1) + 4 /* cmd /c call cloudify.bat ["args"] */];
    int i = 0;
    cmd[i] = "cmd";
    i++;
    cmd[i] = "/c";
    i++;
    cmd[i] = "call";
    i++;
    cmd[i] = cliExecutablePath.getAbsolutePath();
    i++;
    if (argsCount > 0) {
        cmd[i] = "\"";
        //TODO: Use StringBuilder
        for (List<String> command : commands) {
            if (command.size() > 0) {
                for (String arg : command) {
                    if (cmd[i].length() > 0) {
                        cmd[i] += " ";
                    }
                    cmd[i] += arg;
                }
                cmd[i] += ";";
            }
        }
        cmd[i] += "\"";
    }
    final ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.directory(workingDirectory);
    pb.redirectErrorStream(true);

    String extCloudifyJavaOptions = "";

    if (isDebug) {
        extCloudifyJavaOptions += "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9000 -Xnoagent -Djava.compiler=NONE";
    }

    pb.environment().put("EXT_CLOUDIFY_JAVA_OPTIONS", extCloudifyJavaOptions);
    final StringBuilder sb = new StringBuilder();

    logger.info("running: " + cliExecutablePath + " " + Arrays.toString(cmd));

    // log std output and redirected std error
    Process p = pb.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = reader.readLine();
    while (line != null) {
        sb.append(line).append("\n");
        line = reader.readLine();
        logger.info(line);
    }

    final String readResult = sb.toString();
    final int exitValue = p.waitFor();

    logger.info("Exit value = " + exitValue);
    if (exitValue != 0) {
        Assert.fail("Cli ended with error code: " + exitValue);
    }
    return readResult;
}

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);/*  ww  w  .ja va 2 s  .c  o m*/
    if (isWindowsOs()) {
        builder.command("cmd.exe", "/c", new File(homeDir, "bin\\" + script + ".bat").getAbsolutePath(), args);
    } else {
        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:com.tascape.qa.th.Utils.java

/**
 * Executes command, and waits for the expected pass/fail phrase in console printout within timeout,
 *
 * @param command    command line/*from  w  w w. j  a va2  s . c  om*/
 * @param pass       skip checking if null
 * @param fail       skip checking if null
 * @param timeout    set 0 for not to check the output message, otherwise, waiting for timeout
 * @param workingDir working directory
 *
 * @return console output as a list of strings
 *
 * @throws IOException          for command error
 * @throws InterruptedException when interrupted
 */
public static List<String> cmd(String[] command, final String pass, final String fail, final long timeout,
        final String workingDir) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(command);
    if (workingDir != null) {
        pb.directory(new File(workingDir));
    }
    pb.redirectErrorStream(true);
    LOG.debug("Running command: " + pb.command().toString().replace(",", ""));
    final Process p = pb.start();
    Thread thread;
    final List<String> output = new ArrayList<>();

    if (timeout == 0) {
        LOG.debug("This is a start-and-exit command");
        output.add(PASS);
        return output;
    } else {
        thread = new Thread() {
            @Override
            public void run() {
                try {
                    LOG.debug("Command timeouts in {} ms", timeout);
                    Thread.sleep(timeout);
                    try {
                        p.exitValue();
                    } catch (IllegalThreadStateException ex) {
                        LOG.debug("killing subprocess {} - {}", p, ex.getMessage());
                        p.destroy();
                    }
                } catch (InterruptedException ex) {
                    LOG.warn(ex.getMessage());
                }
            }
        };
        thread.setName(Thread.currentThread().getName() + "-" + p.hashCode());
        thread.setDaemon(true);
        thread.start();
    }

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String c = p + " - ";
    for (String line = stdIn.readLine(); line != null;) {
        LOG.trace("{}{}", c, line);
        output.add(line);
        try {
            line = stdIn.readLine();
        } catch (IOException ex) {
            LOG.warn(ex.getMessage());
            break;
        }
    }
    LOG.debug("Command exit code {}", p.waitFor());
    thread.interrupt();
    try {
        stdIn.close();
    } catch (IOException ex) {
        LOG.warn("", ex);
    }

    for (String s : output) {
        if (pass != null && (s.contains(pass) || s.matches(pass))) {
            output.add(PASS);
            break;
        } else if (fail != null && s.contains(fail)) {
            output.add(FAIL);
            break;
        }
    }
    return output;
}

From source file:org.apache.solr.hadoop.SolrRecordWriter.java

public static Path findSolrConfig(Configuration conf) throws IOException {
    Path solrHome = null;//w w w.  jav  a  2s . c o  m
    // FIXME when mrunit supports the new cache apis
    //URI[] localArchives = context.getCacheArchives();
    Path[] localArchives = DistributedCache.getLocalCacheArchives(conf);
    if (localArchives.length == 0) {
        throw new IOException(String.format("No local cache archives, where is %s:%s",
                SolrOutputFormat.getSetupOk(), SolrOutputFormat.getZipName(conf)));
    }
    for (Path unpackedDir : localArchives) {
        // Only logged if debugging
        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Examining unpack directory %s for %s", unpackedDir,
                    SolrOutputFormat.getZipName(conf)));

            ProcessBuilder lsCmd = new ProcessBuilder(
                    new String[] { "/bin/ls", "-lR", unpackedDir.toString() });
            lsCmd.redirectErrorStream();
            Process ls = lsCmd.start();
            byte[] buf = new byte[16 * 1024];
            InputStream all = ls.getInputStream();
            try {
                int count;
                while ((count = all.read(buf)) >= 0) {
                    System.err.write(buf, 0, count);
                }
            } catch (IOException ignore) {
            } finally {
                all.close();
            }
            String exitValue;
            try {
                exitValue = String.valueOf(ls.waitFor());
            } catch (InterruptedException e) {
                exitValue = "interrupted";
            }
            System.err.format("Exit value of 'ls -lR' is %s%n", exitValue);
        }
        if (unpackedDir.getName().equals(SolrOutputFormat.getZipName(conf))) {
            LOG.info("Using this unpacked directory as solr home: {}", unpackedDir);
            solrHome = unpackedDir;
            break;
        }
    }
    return solrHome;
}

From source file:science.atlarge.graphalytics.graphmat.GraphmatPlatform.java

public static void runCommand(String format, String binaryName, List<String> args)
        throws InterruptedException, IOException {
    String argsString = "";
    for (String arg : args) {
        argsString += arg + " ";
    }// w ww.j  ava2s.c  o m

    System.out.println("format = " + format);
    System.out.println("binaryName = " + binaryName);
    System.out.println("argsString = " + argsString);
    String cmd = String.format(format, binaryName, argsString);

    LOG.info("running command: {}", cmd);

    ProcessBuilder pb = new ProcessBuilder(cmd.split(" "));
    //      pb.redirectErrorStream(true);
    //      pb.redirectError(Redirect.INHERIT);
    //      pb.redirectOutput(Redirect.INHERIT);
    //      pb.inheritIO();
    pb.redirectErrorStream(true);
    Process process = pb.start();

    InputStreamReader isr = new InputStreamReader(process.getInputStream());
    BufferedReader br = new BufferedReader(isr);
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }

    int exit = process.waitFor();

    if (exit != 0) {
        throw new IOException("unexpected error code");
    }
}