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:ape.RemountFileSysReadOnlyCommand.java

public boolean runImpl(String[] args) throws ParseException, IOException {
    String cmd = "echo u > /proc/sysrq-trigger";
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);
    Process p = null;//from  w w w  .jav  a2s  .  c o  m

    try {
        p = pb.start();
    } catch (IOException e) {
        System.err.println("Executing remount catches IOException");
        e.printStackTrace();
        return false;
    }

    // If the process returns a non-zero value, there is some error executing the command
    try {
        if (p.waitFor() != 0) {
            System.err.println("Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'");
            return false;
        }
    } catch (InterruptedException e) {
        System.err.println("Executing '" + cmd + "' was interrupted");
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.kylinolap.common.util.OSCommandExecutor.java

private void runNativeCommand() throws IOException {
    String[] cmd = new String[3];
    String osName = System.getProperty("os.name");
    if (osName.startsWith("Windows")) {
        cmd[0] = "cmd.exe";
        cmd[1] = "/C";
    } else {//  www .  ja va  2  s  .  c o  m
        cmd[0] = "/bin/bash";
        cmd[1] = "-c";
    }
    cmd[2] = command;

    ProcessBuilder builder = new ProcessBuilder(cmd);
    builder.redirectErrorStream(true);
    Process proc = builder.start();

    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    IOUtils.copy(proc.getInputStream(), buf);
    output = buf.toString("UTF-8");

    try {
        exitCode = proc.waitFor();
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}

From source file:com.kelveden.karma.AbstractKarmaMojo.java

protected Process startKarmaProcess(ProcessBuilder builder) throws MojoExecutionException {
    try {/*w  ww. j av a  2 s .  c o  m*/
        builder.redirectErrorStream(true);

        System.out.println(StringUtils.join(builder.command().iterator(), " "));

        return builder.start();

    } catch (IOException e) {
        throw new MojoExecutionException("There was an error executing Karma.", e);
    }
}

From source file:net.landora.video.programs.ProgramsAddon.java

public boolean isAvaliable(Program program) {
    String path = getConfiguredPath(program);
    if (path == null) {
        return false;
    }/*from   ww  w .j a v  a 2s. c om*/

    ArrayList<String> command = new ArrayList<String>();
    command.add(path);
    command.addAll(program.getTestArguments());
    ProcessBuilder builder = new ProcessBuilder(command);
    builder.redirectErrorStream(true);

    try {
        Process p = builder.start();
        IOUtils.copy(p.getInputStream(), new NullOutputStream());
        p.waitFor();
        return true;
    } catch (Exception e) {
        log.info("Error checking for program: " + program, e);
        return false;
    }
}

From source file:com.dickthedeployer.dick.web.service.CommandService.java

public String invoke(Path workingDir, String... command) throws RuntimeException {
    try {/*from ww w .j a v  a 2 s .com*/
        log.info("Executing command {} in path {}", Arrays.toString(command), workingDir.toString());
        StringBuilder text = new StringBuilder();
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(workingDir.toFile());
        builder.redirectErrorStream(true);

        Process process = builder.start();

        try (Scanner s = new Scanner(process.getInputStream())) {
            while (s.hasNextLine()) {
                text.append(s.nextLine());
            }
            int result = process.waitFor();
            log.info("Process exited with result {} and output {}", result, text);

            if (result != 0) {
                throw new CommandExecutionException();
            }
            return text.toString();
        }
    } catch (IOException | InterruptedException ex) {
        throw new CommandExecutionException(ex);
    }
}

From source file:com.st.symfony.Symfony.java

public void run(final String command, final long replyTimeout) throws Exception {

    String[] commands = command.split("\\s+");

    ProcessBuilder pb = new ProcessBuilder(commands);
    File log = new File(this.logFilePath);
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(log));
    Process p = pb.start();//  ww  w . j  a  va  2s.c  o  m

    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

    String line = null;
    StringBuilder output = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        System.out.println(line + "\n");
        output.append(line + "\n");
    }

    p.waitFor();

}

From source file:org.apache.hadoop.mpich.MpichContainerWrapper.java

public void run() {
    try {//from   ww  w  . ja  v  a  2 s . c om
        clientSock = new Socket(ioServer, ioServerPort);
        System.setOut(new PrintStream(clientSock.getOutputStream(), true));
        System.setErr(new PrintStream(clientSock.getOutputStream(), true));

        String hostName = InetAddress.getLocalHost().getHostName();
        System.out.println("Starting process " + executable + " on " + hostName);

        List<String> commands = new ArrayList<String>();
        commands.add(executable);
        if (appArgs != null && appArgs.length > 0) {
            commands.addAll(Arrays.asList(appArgs));
        }

        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.redirectErrorStream(true);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);

        Map<String, String> evns = processBuilder.environment();
        evns.put("PMI_RANK", rank);
        evns.put("PMI_SIZE", np);
        evns.put("PMI_ID", pmiid);
        evns.put("PMI_PORT", pmiServer + ":" + pmiServerPort);

        if (this.isSpawn) {
            evns.put("PMI_SPAWNED", "1");
        }

        LOG.info("Starting process:");
        for (String cmd : commands) {
            LOG.info(cmd + "\n");
        }

        Process process = processBuilder.start();
        System.out.println("Process exit with value " + process.waitFor());
        System.out.println("EXIT");//Stopping IOThread
        clientSock.close();
    } catch (UnknownHostException exp) {
        System.err.println("Unknown Host Exception, Host not found");
        exp.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:name.martingeisse.ecobuild.util.CommandLineToolInvocation.java

@Override
protected void invoke(List<String> tokens) throws IOException {

    final ProcessBuilder processBuilder = new ProcessBuilder(tokens);
    processBuilder.directory(getWorkingDirectory());
    processBuilder.redirectErrorStream(true);
    final Process process;
    try {// www  . j  a  v  a  2  s .  com
        process = processBuilder.start();
    } catch (IOException e) {
        getLogger().logError(
                "Exception while starting tool. Command Line: " + getCommand() + " / " + tokens.get(0));
        throw e;
    }
    final MyLoggerWriter loggerWriter = new MyLoggerWriter(getLogger());
    IOUtils.copy(process.getInputStream(), loggerWriter);
    loggerWriter.endStartedLine();
    try {
        process.waitFor();
    } catch (final InterruptedException e) {
        throw new ToolBuildException("An InterruptedException occurred", e);
    }

}

From source file:com.kylinolap.common.util.CliCommandExecutor.java

private Pair<Integer, String> runNativeCommand(String command) throws IOException {
    String[] cmd = new String[3];
    String osName = System.getProperty("os.name");
    if (osName.startsWith("Windows")) {
        cmd[0] = "cmd.exe";
        cmd[1] = "/C";
    } else {//  ww w.  ja v  a 2s  . c o m
        cmd[0] = "/bin/bash";
        cmd[1] = "-c";
    }
    cmd[2] = command;

    ProcessBuilder builder = new ProcessBuilder(cmd);
    builder.redirectErrorStream(true);
    Process proc = builder.start();

    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    IOUtils.copy(proc.getInputStream(), buf);
    String output = buf.toString("UTF-8");

    try {
        int exitCode = proc.waitFor();
        return new Pair<Integer, String>(exitCode, output);
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}

From source file:science.atlarge.graphalytics.powergraph.PowergraphJob.java

public void run() throws IOException, InterruptedException {
    List<String> args = new ArrayList<>();
    args.add(verticesPath);//  w  w w  . ja va  2s .c o m
    args.add(edgesPath);
    args.add(graphDirected ? "1" : "0");
    addJobArguments(args);

    if (outputFile != null) {
        args.add("--output-file");
        args.add(outputFile.getAbsolutePath());
    }

    int numThreads = config.getInt("platform.powergraph.num-threads", -1);

    if (numThreads > 0) {
        args.add("--ncpus");
        args.add(String.valueOf(numThreads));
    }

    args.add("--job-id");
    args.add(jobId);

    String argsString = "";

    for (String arg : args) {
        argsString += arg += " ";
    }

    String nodes = config.getString("platform.powergraph.nodes");
    String cmd = String.format("./bin/sh/run-mpi.sh %s %s %s %s", nodes, logPath,
            PowergraphPlatform.POWERGRAPH_BINARY_NAME, argsString);

    LOG.info("executing command: " + cmd);

    ProcessBuilder pb = new ProcessBuilder(cmd.split(" "));
    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");
    }
}