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:net.pms.util.ProcessUtil.java

public static String run(int[] expectedExitCodes, String... cmd) {
    try {/*from   w ww  .j  a  v a  2  s .  c  o  m*/
        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb.redirectErrorStream(true);
        Process p = pb.start();
        StringBuilder output;
        try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;
            output = new StringBuilder();
            while ((line = br.readLine()) != null) {
                output.append(line).append("\n");
            }
        }
        p.waitFor();
        boolean expected = false;
        if (expectedExitCodes != null) {
            for (int expectedCode : expectedExitCodes) {
                if (expectedCode == p.exitValue()) {
                    expected = true;
                    break;
                }
            }
        }
        if (!expected) {
            LOGGER.debug("Warning: command {} returned {}", Arrays.toString(cmd), p.exitValue());
        }
        return output.toString();
    } catch (Exception e) {
        LOGGER.error("Error running command " + Arrays.toString(cmd), e);
    }
    return "";
}

From source file:org.apache.storm.daemon.supervisor.ClientSupervisorUtils.java

/**
 * Launch a new process as per {@link ProcessBuilder} with a given
 * callback.//from  w  w w  .j  a va 2 s  .c  o m
 * @param command the command to be executed in the new process
 * @param environment the environment to be applied to the process. Can be
 *                    null.
 * @param logPrefix a prefix for log entries from the output of the process.
 *                  Can be null.
 * @param exitCodeCallback code to be called passing the exit code value
 *                         when the process completes
 * @param dir the working directory of the new process
 * @return the new process
 * @throws IOException
 * @see ProcessBuilder
 */
public static Process launchProcess(List<String> command, Map<String, String> environment,
        final String logPrefix, final ExitCodeCallback exitCodeCallback, File dir) throws IOException {
    ProcessBuilder builder = new ProcessBuilder(command);
    Map<String, String> procEnv = builder.environment();
    if (dir != null) {
        builder.directory(dir);
    }
    builder.redirectErrorStream(true);
    if (environment != null) {
        procEnv.putAll(environment);
    }
    final Process process = builder.start();
    if (logPrefix != null || exitCodeCallback != null) {
        Utils.asyncLoop(new Callable<Object>() {
            public Object call() {
                if (logPrefix != null) {
                    Utils.readAndLogStream(logPrefix, process.getInputStream());
                }
                if (exitCodeCallback != null) {
                    try {
                        process.waitFor();
                        exitCodeCallback.call(process.exitValue());
                    } catch (InterruptedException ie) {
                        LOG.info("{} interrupted", logPrefix);
                        exitCodeCallback.call(-1);
                    }
                }
                return null; // Run only once.
            }
        });
    }
    return process;
}

From source file:org.apache.geode.management.internal.cli.util.MergeLogs.java

public static void mergeLogsInNewProcess(Path logDirectory) {
    // create a new process for merging
    LogWrapper.getInstance().fine("Exporting logs merging logs" + logDirectory);
    List<String> commandList = new ArrayList<String>();
    commandList.add(System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar + "java");
    commandList.add("-classpath");
    commandList.add(System.getProperty("java.class.path", "."));
    commandList.add(MergeLogs.class.getName());

    commandList.add(logDirectory.toAbsolutePath().toString());

    ProcessBuilder procBuilder = new ProcessBuilder(commandList);
    StringBuilder output = new StringBuilder();
    String errorString = new String();
    try {/*from w  ww .  java  2  s.  co  m*/
        LogWrapper.getInstance().fine("Exporting logs now merging logs");
        Process mergeProcess = procBuilder.redirectErrorStream(true).start();

        mergeProcess.waitFor();

        InputStream inputStream = mergeProcess.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;

        while ((line = br.readLine()) != null) {
            output.append(line).append(GfshParser.LINE_SEPARATOR);
        }
        mergeProcess.destroy();
    } catch (Exception e) {
        LogWrapper.getInstance().severe(e.getMessage());
    }
    if (output.toString().contains("Merged logs to: ")) {
        LogWrapper.getInstance().fine("Exporting logs Sucessfully merged logs");
    } else {
        LogWrapper.getInstance().severe("Could not merge");
    }
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java

/**
 * Run a command and wait/*from w w  w.  j  a va  2 s .c o m*/
 *
 * @param cmd The command to run
 * @param workingDir The folder where the command is run
 * @param executeFrom For logging message to the center of where to execute the command.
 * @return
 */
public static Process executeCommandAndForget(String cmd, String workingDir, String executeFrom) {
    logger.debug("Execute command: " + cmd);
    if (workingDir == null) {
        workingDir = "/tmp";
    }

    String[] splitStr = cmd.split("\\s+");
    ProcessBuilder pb = new ProcessBuilder(splitStr);
    pb.directory(new File(workingDir));
    pb = pb.redirectErrorStream(true); // this is important to redirect the error stream to output stream, prevent blocking with long output
    pb.redirectOutput(new File("/tmp/salsa.conductor.log"));
    Map<String, String> env = pb.environment();
    String path = env.get("PATH");
    path = path + File.pathSeparator + "/usr/bin:/usr/sbin";
    logger.debug("PATH to execute command: " + pb.environment().get("PATH"));
    env.put("PATH", path);
    Process p;
    try {
        p = pb.start();
        return p;
    } catch (IOException ex) {
        logger.debug("Cannot run the command: " + cmd);
        return null;
    }

}

From source file:org.janusgraph.HBaseStorageSetup.java

/**
 * Run the parameter as an external process. Returns if the command starts
 * without throwing an exception and returns exit status 0. Throws an
 * exception if there's any problem invoking the command or if it does not
 * return zero exit status./*from   ww w  .  j  a v  a  2s  . com*/
 *
 * Blocks indefinitely while waiting for the command to complete.
 *
 * @param argv
 *            passed directly to {@link ProcessBuilder}'s constructor
 */
private static void runCommand(String... argv) {

    final String cmd = Joiner.on(" ").join(argv);
    log.info("Executing {}", cmd);

    ProcessBuilder pb = new ProcessBuilder(argv);
    pb.redirectErrorStream(true);
    Process startup;
    try {
        startup = pb.start();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    StreamLogger sl = new StreamLogger(startup.getInputStream());
    sl.setDaemon(true);
    sl.start();

    try {
        int exitcode = startup.waitFor(); // wait for script to return
        if (0 == exitcode) {
            log.info("Command \"{}\" exited with status 0", cmd);
        } else {
            throw new RuntimeException("Command \"" + cmd + "\" exited with status " + exitcode);
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    try {
        sl.join(1000L);
    } catch (InterruptedException e) {
        log.warn("Failed to cleanup stdin handler thread after running command \"{}\"", cmd, e);
    }
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java

public static int executeCommandGetReturnCode(String cmd, String workingDir, String executeFrom) {
    if (workingDir == null) {
        workingDir = "/tmp";
    }//w w w .j  a  v a 2s  .c o m
    logger.debug("Execute command: " + cmd + ". Working dir: " + workingDir);
    try {
        String[] splitStr = cmd.split("\\s+");
        ProcessBuilder pb = new ProcessBuilder(splitStr);
        pb.directory(new File(workingDir));
        pb = pb.redirectErrorStream(true); // this is important to redirect the error stream to output stream, prevent blocking with long output
        Map<String, String> env = pb.environment();
        String path = env.get("PATH");
        path = path + File.pathSeparator + "/usr/bin:/usr/sbin";
        logger.debug("PATH to execute command: " + pb.environment().get("PATH"));
        env.put("PATH", path);

        Process p = pb.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            logger.debug(line);
        }
        p.waitFor();
        int returnCode = p.exitValue();
        logger.debug("Execute command done: " + cmd + ". Get return code: " + returnCode);
        return returnCode;
    } catch (InterruptedException | IOException e1) {
        logger.error("Error when execute command. Error: " + e1);
    }
    return -1;
}

From source file:net.pms.util.ProcessUtil.java

public static boolean kill(Integer pid, int signal) {
    boolean killed = false;
    LOGGER.warn("Sending kill -" + signal + " to the Unix process: " + pid);
    try {//from  w  ww. ja v  a  2s. com
        ProcessBuilder processBuilder = new ProcessBuilder("kill", "-" + signal, Integer.toString(pid));
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        // consume the error and output process streams
        StreamGobbler.consume(process.getInputStream(), true);
        int exit = waitFor(process);
        if (exit == 0) {
            killed = true;
            LOGGER.debug("Successfully sent kill -" + signal + " to the Unix process: " + pid);
        }
    } catch (IOException e) {
        LOGGER.error("Error calling: kill -" + signal + " " + pid, e);
    }

    return killed;
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java

/**
 * Run a command and wait/*from w  w  w .  j  a  v  a2 s . c  om*/
 *
 * @param cmd The command to run
 * @param workingDir The folder where the command is run
 * @param executeFrom For logging message to the center of where to execute the command.
 * @return
 */
public static String executeCommandGetOutput(String cmd, String workingDir, String executeFrom) {
    logger.debug("Execute command: " + cmd);
    if (workingDir == null) {
        workingDir = "/tmp";
    }
    try {
        String[] splitStr = cmd.split("\\s+");
        ProcessBuilder pb = new ProcessBuilder(splitStr);
        pb.directory(new File(workingDir));
        pb = pb.redirectErrorStream(true); // this is important to redirect the error stream to output stream, prevent blocking with long output
        Map<String, String> env = pb.environment();
        String path = env.get("PATH");
        path = path + File.pathSeparator + "/usr/bin:/usr/sbin";
        logger.debug("PATH to execute command: " + pb.environment().get("PATH"));
        env.put("PATH", path);

        Process p = pb.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        StringBuffer output = new StringBuffer();
        int lineCount = 0;
        while ((line = reader.readLine()) != null) {
            if (lineCount < 10) { // only get 10 lines to prevent the overflow
                output.append(line);
            }
            lineCount += 1;
            logger.debug(line);
        }
        if (lineCount >= 10) {
            logger.debug("... there are alot of more output here which is not shown ! ...");
        }
        p.waitFor();
        System.out.println("Execute Commang output: " + output.toString().trim());

        if (p.exitValue() == 0) {
            logger.debug("Command exit 0, result: " + output.toString().trim());
            return output.toString().trim();
        } else {
            logger.debug("Command return non zero code: " + p.exitValue());
            return null;
        }
    } catch (InterruptedException | IOException e1) {
        logger.error("Error when execute command. Error: " + e1);
    }
    return null;
}

From source file:alluxio.cli.ValidateEnv.java

private static boolean validateRemote(String node, String target, String name, CommandLine cmd)
        throws InterruptedException {
    System.out.format("Validating %s environment on %s...%n", target, node);
    if (!Utils.isAddressReachable(node, 22)) {
        System.err.format("Unable to reach ssh port 22 on node %s.%n", node);
        return false;
    }/*from   ww w  .j a  v  a 2s  .c om*/

    // args is not null.
    String argStr = String.join(" ", cmd.getArgs());
    String homeDir = Configuration.get(PropertyKey.HOME);
    String remoteCommand = String.format("%s/bin/alluxio validateEnv %s %s %s", homeDir, target,
            name == null ? "" : name, argStr);
    String localCommand = String.format(
            "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand);
    String[] command = { "bash", "-c", localCommand };
    try {
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);
        builder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        builder.redirectInput(ProcessBuilder.Redirect.INHERIT);
        Process process = builder.start();
        process.waitFor();
        return process.exitValue() == 0;
    } catch (IOException e) {
        System.err.format("Unable to validate on node %s: %s.%n", node, e.getMessage());
        return false;
    }
}

From source file:fr.inria.eventcloud.deployment.cli.launchers.EventCloudsManagementServiceDeployer.java

/**
 * Deploys an EventCloudsRegistry and an EventClouds Management Service in a
 * separate JVM according to the specified parameters.
 * /*from w w w .j  a  v a2s . co m*/
 * @param onRelease
 *            {@code true} if the lastest release of the EventCloud has to
 *            be used, {@code false} to use the latest snapshot version.
 * @param port
 *            the port used to deploy the EventClouds Management Service and
 *            which will also be used to deploy WS-Notification services.
 * @param urlSuffix
 *            the suffix appended to the end of the URL associated to the
 *            EventClouds Management Service to be deployed.
 * @param activateLoggers
 *            {@code true} if the loggers have to be activated,
 *            {@code false} otherwise.
 * @param properties
 *            additional Java properties set to the new JVM.
 * 
 * @return the endpoint URL of the EventClouds Management Service.
 * 
 * @throws IOException
 *             if an error occurs during the deployment.
 */
public synchronized static String deploy(boolean onRelease, int port, String urlSuffix, boolean activateLoggers,
        String... properties) throws IOException {
    if (eventCloudsManagementServiceProcess == null) {
        String binariesBaseUrl = EVENTCLOUD_BINARIES_URL;

        if (onRelease) {
            binariesBaseUrl += "releases/latest/";
        } else {
            binariesBaseUrl += "snapshots/latest/";
        }

        List<String> cmd = new ArrayList<String>();

        String javaBinaryPath = System.getProperty("java.home") + File.separator + "bin" + File.separator
                + "java";
        if (System.getProperty("os.name").startsWith("Windows")) {
            javaBinaryPath = javaBinaryPath + ".exe";
        }
        cmd.add(javaBinaryPath);

        cmd.add("-cp");
        cmd.add(addClassPath(binariesBaseUrl + "libs/"));

        cmd.addAll(addProperties(binariesBaseUrl + "resources/", activateLoggers));

        Collections.addAll(cmd, properties);

        cmd.add(EventCloudsManagementServiceDeployer.class.getCanonicalName());
        cmd.add(Integer.toString(port));
        cmd.add(urlSuffix);

        final ProcessBuilder processBuilder = new ProcessBuilder(cmd.toArray(new String[cmd.size()]));
        processBuilder.redirectErrorStream(true);
        eventCloudsManagementServiceProcess = processBuilder.start();

        final BufferedReader reader = new BufferedReader(
                new InputStreamReader(eventCloudsManagementServiceProcess.getInputStream()));
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        if (!servicesDeployed.getValue() && line.contains(LOG_MANAGEMENT_WS_DEPLOYED)) {
                            servicesDeployed.setValue(true);
                            synchronized (servicesDeployed) {
                                servicesDeployed.notifyAll();
                            }
                        }
                        System.out.println("ECManagement " + line);
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        });
        t.setDaemon(true);
        t.start();

        synchronized (servicesDeployed) {
            while (!servicesDeployed.getValue()) {
                try {
                    servicesDeployed.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        StringBuilder eventCloudsManagementWsEndpoint = new StringBuilder("http://");
        eventCloudsManagementWsEndpoint.append(ProActiveInet.getInstance().getInetAddress().getHostAddress());
        eventCloudsManagementWsEndpoint.append(':');
        eventCloudsManagementWsEndpoint.append(port);
        eventCloudsManagementWsEndpoint.append('/');
        eventCloudsManagementWsEndpoint.append(urlSuffix);
        return eventCloudsManagementWsEndpoint.toString();
    } else {
        throw new IllegalStateException("EventClouds management process already deployed");
    }
}