Example usage for java.lang Process getErrorStream

List of usage examples for java.lang Process getErrorStream

Introduction

In this page you can find the example usage for java.lang Process getErrorStream.

Prototype

public abstract InputStream getErrorStream();

Source Link

Document

Returns the input stream connected to the error output of the process.

Usage

From source file:Main.java

public static int doShellCommand(String[] cmds, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {

    Process proc = null;
    int exitCode = -1;

    if (runAsRoot)
        proc = Runtime.getRuntime().exec("su");
    else// w w w.  ja va2 s  . c  om
        proc = Runtime.getRuntime().exec("sh");

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    for (int i = 0; i < cmds.length; i++) {
        out.write(cmds[i]);
        out.write("\n");
    }

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {

        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        exitCode = proc.waitFor();

    }

    return exitCode;

}

From source file:com.samczsun.helios.utils.Utils.java

public static String readProcess(Process process) {
    StringBuilder result = new StringBuilder();
    result.append("--- BEGIN PROCESS DUMP ---").append("\n");
    result.append("---- STDOUT ----").append("\n");
    InputStream inputStream = process.getInputStream();
    byte[] inputStreamBytes = new byte[0];
    try {/*from   w w w  .  ja  v a2  s.c o  m*/
        inputStreamBytes = IOUtils.toByteArray(inputStream);
    } catch (IOException e) {
        result.append("An error occured while reading from stdout").append("\n");
        result.append("Caused by: ").append(e.getClass()).append(" ").append(e.getMessage()).append("\n");
    } finally {
        if (inputStreamBytes.length > 0) {
            result.append(new String(inputStreamBytes, StandardCharsets.UTF_8));
        }
    }
    result.append("---- STDERR ----").append("\n");
    inputStream = process.getErrorStream();
    inputStreamBytes = new byte[0];
    try {
        inputStreamBytes = IOUtils.toByteArray(inputStream);
    } catch (IOException e) {
        result.append("An error occured while reading from stderr").append("\n");
        result.append("Caused by: ").append(e.getClass()).append(" ").append(e.getMessage()).append("\n");
    } finally {
        if (inputStreamBytes.length > 0) {
            result.append(new String(inputStreamBytes, StandardCharsets.UTF_8));
        }
    }

    result.append("---- EXIT VALUE ----").append("\n");

    int exitValue = -0xCAFEBABE;
    try {
        exitValue = process.waitFor();
    } catch (InterruptedException e) {
        result.append("An error occured while obtaining the exit value").append("\n");
        result.append("Caused by: ").append(e.getClass()).append(" ").append(e.getMessage()).append("\n");
    } finally {
        if (exitValue != -0xCAFEBABE) {
            result.append("Process finished with exit code ").append(exitValue).append("\n");
        }
    }

    return result.toString();
}

From source file:Main.java

public static int doShellCommand(String[] cmds, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {
    Process proc = null;
    int exitCode = -1;

    if (runAsRoot) {
        proc = Runtime.getRuntime().exec("su");
    } else {/*from www .  j  a va 2s.co m*/
        proc = Runtime.getRuntime().exec("sh");
    }

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    for (int i = 0; i < cmds.length; i++) {
        out.write(cmds[i]);
        out.write("\n");
    }

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {
        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        exitCode = proc.waitFor();
    }

    return exitCode;
}

From source file:hoot.services.command.CommandRunner.java

private static int handleProcessStatic(Process pProcess, String pOrigCmd, Writer pOut, Writer pErr,
        List<CharPump> stdOutErrList, MutableBoolean interrupt) throws IOException, InterruptedException {

    CharPump outpump = new CharPump(new BufferedReader(new InputStreamReader(pProcess.getInputStream())), pOut,
            pOrigCmd, interrupt);// w  w  w . ja v  a 2s.  co  m
    stdOutErrList.add(outpump);
    CharPump errpump = new CharPump(new BufferedReader(new InputStreamReader(pProcess.getErrorStream())), pErr,
            pOrigCmd, interrupt);
    stdOutErrList.add(errpump);
    outpump.start();
    errpump.start();
    outpump.join();
    errpump.join();

    if (_log.isInfoEnabled())
        _log.info("Waiting for '" + pOrigCmd + "' to complete.");
    int status = pProcess.waitFor();

    return status;
}

From source file:net.pickapack.io.cmd.CommandLineHelper.java

/**
 *
 * @param cmd//from ww  w . j a  v a2s.co  m
 * @param waitFor
 * @return
 */
public static int invokeNativeCommand(String[] cmd, boolean waitFor) {
    try {
        Runtime r = Runtime.getRuntime();
        final Process ps = r.exec(cmd);
        //            ProcessBuilder pb = new ProcessBuilder(cmd);
        //            Process ps = pb.start();

        new Thread() {
            {
                setDaemon(true);
            }

            @Override
            public void run() {
                try {
                    IOUtils.copy(ps.getInputStream(), System.out);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            {
                setDaemon(true);
            }

            @Override
            public void run() {
                try {
                    IOUtils.copy(ps.getErrorStream(), System.out);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        if (waitFor) {
            int exitValue = ps.waitFor();
            if (exitValue != 0) {
                System.out.println("WARN: Process exits with non-zero code: " + exitValue);
            }

            ps.destroy();

            return exitValue;
        }

        return 0;
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

From source file:gov.nist.appvet.tool.sigverifier.Service.java

private static boolean execute(String command, StringBuffer output) {
    List<String> commandArgs = Arrays.asList(command.split("\\s+"));
    ProcessBuilder pb = new ProcessBuilder(commandArgs);
    Process process = null;
    IOThreadHandler outputHandler = null;
    IOThreadHandler errorHandler = null;
    int exitValue = -1;
    try {/*  w  ww .  jav a2s  .c om*/
        if (command == null || command.isEmpty()) {
            log.error("Command is null or empty");
            return false;
        }
        log.debug("Executing " + command);
        process = pb.start();
        outputHandler = new IOThreadHandler(process.getInputStream());
        outputHandler.start();
        errorHandler = new IOThreadHandler(process.getErrorStream());
        errorHandler.start();
        if (process.waitFor(Properties.commandTimeout, TimeUnit.MILLISECONDS)) {
            // Process has waited and exited within the timeout
            exitValue = process.exitValue();
            if (exitValue == 0) {
                log.debug("Command terminated normally: \n" + outputHandler.getOutput() + "\nErrors: "
                        + errorHandler.getOutput());
                StringBuffer resultOut = outputHandler.getOutput();
                output.append(resultOut);
                return true;
            } else {
                log.error("Command terminated abnormally: \n" + outputHandler.getOutput() + "\nErrors: "
                        + errorHandler.getOutput());
                StringBuffer resultError = errorHandler.getOutput();
                output.append(resultError);
                return false;
            }
        } else {
            // Process exceed timeout or was interrupted
            log.error("Command timed-out or was interrupted: \n" + outputHandler.getOutput() + "\nErrors: "
                    + errorHandler.getOutput());
            StringBuffer resultOutput = outputHandler.getOutput();
            StringBuffer resultError = errorHandler.getOutput();
            if (resultOutput != null) {
                output.append(resultOutput);
                return false;
            } else if (resultError != null) {
                output.append(resultError);
            } else {
                output.append(Properties.toolName + " timed-out");
            }
            return false;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (InterruptedException e) {
        e.printStackTrace();
        return false;
    } finally {
        if (outputHandler.isAlive()) {
            try {
                outputHandler.inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (errorHandler.isAlive()) {
            try {
                errorHandler.inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (process.isAlive()) {
            process.destroy();
        }
    }
}

From source file:net.modsec.ms.connector.ConnRequestHandler.java

/**
 * Executes the shell scripts for starting, restarting and stopping modsecurity. 
 * @param cmd - path of the shell script.
 * @param jsonResp  - response to WebSiren(webapp) request.
 * @return jsonresponse - response to WebSiren(webapp) request. 
 *//*from   w  ww. ja  va 2 s. c  o m*/
@SuppressWarnings("unchecked")
public static JSONObject executeShScript(String cmd, JSONObject jsonResp) {

    log.info("starting shell script execution ... :" + cmd);
    try {

        Process process = Runtime.getRuntime().exec(cmd);
        String outStr = "", s = "";

        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        while ((s = br.readLine()) != null) {
            outStr += s;
        }

        log.info("Output String : " + outStr);

        String errOutput = "";
        BufferedReader br2 = new BufferedReader(new InputStreamReader(process.getErrorStream()));

        while (br2.ready() && (s = br2.readLine()) != null) {
            errOutput += s;
        }
        log.info("Error String : " + errOutput);

        if (errOutput.contains("Syntax error")) {

            jsonResp.put("status", "1");
            jsonResp.put("message", "Failed to start modsecurity");

        } else {

            jsonResp.put("status", "0");
            jsonResp.put("message", outStr);

        }

    } catch (IOException e) {

        jsonResp.put("status", "1");
        jsonResp.put("message", "Error: internal service is down");
        log.info("Error Message: " + e.getMessage());
        //e.printStackTrace();

    }

    return jsonResp;
}

From source file:com.searchbox.framework.web.SystemController.java

/**
 * Utility function to execute a function
 *///from  w w  w . j a v  a 2 s  .  c o  m
private static String execute(String cmd) {
    DataInputStream in = null;
    Process process = null;

    try {
        process = Runtime.getRuntime().exec(cmd);
        in = new DataInputStream(process.getInputStream());
        // use default charset from locale here, because the command invoked
        // also uses the default locale:
        return IOUtils.toString(new InputStreamReader(in, Charset.defaultCharset()));
    } catch (Exception ex) {
        // ignore - log.warn("Error executing command", ex);
        return "(error executing: " + cmd + ")";
    } finally {
        if (process != null) {
            IOUtils.closeQuietly(process.getOutputStream());
            IOUtils.closeQuietly(process.getInputStream());
            IOUtils.closeQuietly(process.getErrorStream());
        }
    }
}

From source file:io.siddhi.doc.gen.core.utils.DocumentationUtils.java

/**
 * Executing a command//from  ww  w . j  a va2s  . co m
 *
 * @param command The command to be executed
 * @param logger  The maven plugin logger
 * @return The output lines from executing the command
 * @throws Throwable if any error occurs during the execution of the command
 */
private static List<String> getCommandOutput(String[] command, Log logger) throws Throwable {
    logger.info("Executing: " + String.join(" ", command));
    Process process = Runtime.getRuntime().exec(command);
    List<String> executionOutputLines = new ArrayList<>();

    // Logging the output of the command execution
    InputStream[] inputStreams = new InputStream[] { process.getInputStream(), process.getErrorStream() };
    BufferedReader bufferedReader = null;
    try {
        for (InputStream inputStream : inputStreams) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream, Constants.DEFAULT_CHARSET));
            String commandOutput;
            while (true) {
                commandOutput = bufferedReader.readLine();
                if (commandOutput == null) {
                    break;
                }

                executionOutputLines.add(commandOutput);
            }
        }
        process.waitFor();
    } finally {
        IOUtils.closeQuietly(bufferedReader);
    }

    return executionOutputLines;
}

From source file:Main.java

public static int doShellCommand(String cmd, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {

    Process proc = null;
    int exitCode = -1;

    if (runAsRoot)
        proc = Runtime.getRuntime().exec("su");
    else//from   w w w .ja  v a2 s. c om
        proc = Runtime.getRuntime().exec("sh");

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    //   TorService.logMessage("executing shell cmd: " + cmds[i] + "; runAsRoot=" + runAsRoot + ";waitFor=" + waitFor);

    out.write(cmd);
    out.write("\n");

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {

        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        exitCode = proc.waitFor();

    }

    return exitCode;

}