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:net.centro.rtb.monitoringcenter.metrics.system.os.OperatingSystemMetricSet.java

private static Double fetchIoWaitPercentage() {
    // Only Linux is supported
    if (!SystemUtils.IS_OS_LINUX) {
        return null;
    }/*  w  ww.  j a  va  2  s  .c  o  m*/

    try {
        // Take the second sample from iostat, as the first one is a static value acquired at the machine start-up
        Process process = Runtime.getRuntime()
                .exec(new String[] { "bash", "-c", "iostat -c 1 2 | awk '/^ /{print $4}'" });

        BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        BufferedReader resultStream = new BufferedReader(new InputStreamReader(process.getInputStream()));

        List<String> outputLines = new ArrayList<>();
        String line = null;
        while ((line = resultStream.readLine()) != null) {
            outputLines.add(line);
        }

        boolean error = false;
        while (errorStream.readLine() != null) {
            error = true;
        }

        errorStream.close();
        resultStream.close();

        try {
            int result = process.waitFor();
            if (result != 0) {
                logger.debug("iostat failed with return code {}", result);
            }
        } catch (InterruptedException e) {
            logger.debug("iostat was interrupted");
        }

        if (!error && outputLines.size() == 2) {
            String iowaitPercentStr = outputLines.get(outputLines.size() - 1);
            try {
                return Double.parseDouble(iowaitPercentStr);
            } catch (NumberFormatException e) {
                logger.debug("Error parsing iowait value from {}", iowaitPercentStr);
            }
        }
    } catch (Exception e) {
        logger.debug("Exception occurred while executing iostat command", e);

        if (InterruptedException.class.isInstance(e)) {
            Thread.currentThread().interrupt();
        }
    }

    return null;
}

From source file:com.arm.connector.bridge.core.Utils.java

/**
 * Execute the AWS CLI/*from  w w  w . j  a v a  2s . c o  m*/
 * @param logger - ErrorLogger instance
 * @param args - arguments for the AWS CLI 
 * @return response from CLI action
 */
public static String awsCLI(ErrorLogger logger, String args) {
    // construct the arguments
    String cmd = "./aws " + args;
    String response = null;
    String error = null;

    try {
        // invoke the AWS CLI
        Process proc = Runtime.getRuntime().exec(cmd);
        response = Utils.convertStreamToString(proc.getInputStream());
        error = Utils.convertStreamToString(proc.getErrorStream());

        // wait to completion
        proc.waitFor();
        int status = proc.exitValue();

        // DEBUG
        if (status != 0) {
            // non-zero exit status
            logger.warning("AWS CLI: Invoked: " + cmd);
            logger.warning("AWS CLI: Response: " + response);
            logger.warning("AWS CLI: Errors: " + error);
            logger.warning("AWS CLI: Exit Code: " + status);
        } else {
            // successful exit status
            logger.info("AWS CLI: Invoked: " + cmd);
            logger.info("AWS CLI: Response: " + response);
            logger.info("AWS CLI: Exit Code: " + status);
        }
    } catch (IOException | InterruptedException ex) {
        logger.warning("AWS CLI: Exception for command: " + cmd, ex);
        response = null;
    }

    // return the resposne
    return response;
}

From source file:com.opentable.db.postgres.embedded.EmbeddedPostgres.java

private static List<String> system(ProcessBuilder.Redirect errorRedirector,
        ProcessBuilder.Redirect outputRedirector, String... command) {
    try {//from   www .  j ava 2s.c o m
        final ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectError(errorRedirector);
        builder.redirectOutput(outputRedirector);
        final Process process = builder.start();
        Verify.verify(0 == process.waitFor(), "Process %s failed\n%s", Arrays.asList(command),
                IOUtils.toString(process.getErrorStream()));
        try (InputStream stream = process.getInputStream()) {
            return IOUtils.readLines(stream);
        }
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.eucalyptus.storage.TGTWrapper.java

/**
 * executeTGTs the specified tgt command in a separate process. 
 * A {@link DirectStorageInfo#timeoutInMillis timeout} is enforced on 
 * the process using {@link java.util.concurrent.ExecutorService ExecutorService} 
 * framework. If the process does not complete with in the timeout, it is cancelled.
 * //from  w w w . jav a 2 s .co  m
 * @param command
 * @param timeout
 * @return CommandOutput
 * @throws EucalyptusCloudException
 */
private static CommandOutput execute(@NotNull String[] command, @NotNull Long timeout)
        throws EucalyptusCloudException, CallTimeoutException {
    try {
        Integer returnValue = -999999;
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        StreamConsumer error = new StreamConsumer(process.getErrorStream());
        StreamConsumer output = new StreamConsumer(process.getInputStream());
        error.start();
        output.start();
        Callable<Integer> processMonitor = new ProcessMonitor(process);
        Future<Integer> processController = service.submit(processMonitor);
        try {
            returnValue = processController.get(timeout, TimeUnit.MILLISECONDS);
        } catch (TimeoutException tex) {
            String commandStr = buildCommand(command);
            LOG.error(commandStr + " timed out. Cancelling the process, logging a fault and exceptioning out");
            processController.cancel(true);
            Faults.forComponent(Storage.class).havingId(TGT_HOSED).withVar("component", "Storage Controller")
                    .withVar("timeout", Long.toString(timeout)).log();
            throw new CallTimeoutException("No response from the command " + commandStr
                    + ". Process timed out after waiting for " + timeout + " milliseconds");
        }
        output.join();
        error.join();
        LOG.debug("TGTWrapper executed: " + JOINER.join(command) + "\n return=" + returnValue + "\n stdout="
                + output.getReturnValue() + "\n stderr=" + error.getReturnValue());
        return new CommandOutput(returnValue, output.getReturnValue(), error.getReturnValue());
    } catch (CallTimeoutException e) {
        throw e;
    } catch (Exception ex) {
        throw new EucalyptusCloudException(ex);
    }
}

From source file:automenta.climatenet.ImportKML.java

public static void exec(String cmd) {
    try {//from   w  w  w .  j  a v a  2s .  c o m
        String[] cmdParm = { "/bin/sh", "-c", cmd };

        Process proc = Runtime.getRuntime().exec(cmdParm);
        IOUtils.copy(proc.getInputStream(), System.out);
        IOUtils.copy(proc.getErrorStream(), System.err);
        proc.waitFor();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:hdfs.FileUtil.java

private static String copyStderr(Process p) throws IOException {
    InputStream err = p.getErrorStream();
    StringBuilder result = new StringBuilder();
    byte[] buff = new byte[4096];
    int len = err.read(buff);
    while (len > 0) {
        result.append(new String(buff, 0, len));
        len = err.read(buff);/*from   w ww .j a  va  2s.  c  om*/
    }
    return result.toString();
}

From source file:com.ikon.util.ExecutionUtils.java

/**
 * Execute command line: implementation/*w w  w .  ja  va 2  s.  com*/
 */
private static ExecutionResult runCmdImpl(final String cmd[], final long timeout)
        throws SecurityException, InterruptedException, IOException {
    log.debug("runCmdImpl({}, {})", Arrays.toString(cmd), timeout);
    ExecutionResult ret = new ExecutionResult();
    long start = System.currentTimeMillis();
    final ProcessBuilder pb = new ProcessBuilder(cmd);
    final Process process = pb.start();

    Timer t = new Timer("Process Execution Timeout");
    t.schedule(new TimerTask() {
        @Override
        public void run() {
            process.destroy();
            log.warn("Process killed due to timeout.");
            log.warn("CommandLine: {}", Arrays.toString(cmd));
        }
    }, timeout);

    try {
        ret.setStdout(IOUtils.toString(process.getInputStream()));
        ret.setStderr(IOUtils.toString(process.getErrorStream()));
    } catch (IOException e) {
        // Ignore
    }

    process.waitFor();
    t.cancel();
    ret.setExitValue(process.exitValue());

    // Check return code
    if (ret.getExitValue() != 0) {
        log.warn("Abnormal program termination: {}", ret.getExitValue());
        log.warn("CommandLine: {}", Arrays.toString(cmd));
        log.warn("STDERR: {}", ret.getStderr());
    } else {
        log.debug("Normal program termination");
    }

    process.destroy();
    log.debug("Elapse time: {}", FormatUtil.formatSeconds(System.currentTimeMillis() - start));
    return ret;
}

From source file:edu.cwru.jpdg.Javac.java

/**
 * Compiles the java.//  w w  w .  j ava  2s . c  o m
 */
public static List<String> javac(String basepath, String name, String s) {
    Path dir = Paths.get(cwd).resolve(basepath);
    if (Files.notExists(dir)) {
        create_dir(dir);
    }
    Path java = dir.resolve(name + ".java");
    Path build = dir.resolve("build");
    if (!Files.notExists(build)) {
        try {
            FileUtils.deleteDirectory(build.toFile());
        } catch (IOException e) {
            throw new RuntimeException("Couldn't rm -r build dir");
        }
    }
    create_dir(build);

    byte[] bytes = s.getBytes();
    try {
        Files.write(java, bytes);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }

    try {
        Process p = Runtime.getRuntime()
                .exec(new String[] { "javac", "-d", build.toString(), java.toString() });
        String line;
        BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
        List<String> stdout_lines = new ArrayList<String>();
        line = stdout.readLine();
        while (line != null) {
            stdout_lines.add(line);
            line = stdout.readLine();
        }
        BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        List<String> stderr_lines = new ArrayList<String>();
        line = stderr.readLine();
        while (line != null) {
            stderr_lines.add(line);
            line = stderr.readLine();
        }
        if (p.waitFor() != 0) {
            System.err.println(StringUtils.join(stdout_lines, "\n"));
            System.err.println("-------------------------------------");
            System.err.println(StringUtils.join(stderr_lines, "\n"));
            throw new RuntimeException("javac failed");
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e.getMessage());
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }

    return abs_paths(find_classes(build.toString()));
}

From source file:Main.java

public static String[] execSQL(String dbName, String query) {
    Process process = null;
    Runtime runtime = Runtime.getRuntime();
    OutputStreamWriter outputStreamWriter;

    try {//  ww  w .jav a2 s  .  c  om
        String command = dbName + " " + "'" + query + "'" + ";";
        process = runtime.exec("su");

        outputStreamWriter = new OutputStreamWriter(process.getOutputStream());

        outputStreamWriter.write("sqlite3 " + command);

        outputStreamWriter.flush();
        outputStreamWriter.close();
        outputStreamWriter.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    final InputStreamReader errorStreamReader = new InputStreamReader(process.getErrorStream());

    (new Thread() {
        @Override
        public void run() {
            try {

                BufferedReader bufferedReader = new BufferedReader(errorStreamReader);
                String s;
                while ((s = bufferedReader.readLine()) != null) {
                    Log.d("com.suraj.waext", "WhatsAppDBHelper:" + s);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }).start();

    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String s;
        StringBuilder op = new StringBuilder();

        while ((s = bufferedReader.readLine()) != null) {
            op.append(s).append("\n");
        }

        return op.toString().split("\n");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;

}

From source file:com.comcast.oscar.netsnmp.NetSNMP.java

/**
 * //w  w w .j  a  v  a 2  s  .c o m
 * @param sSnmpTranslateCMD
 * @return OID Translation - Null is snmptranslate is not installed*/
private static ArrayList<String> runSnmpTranslate(String sSnmpTranslateCMD) {

    boolean localDebug = Boolean.FALSE;

    if (debug | localDebug)
        System.out.println(sSnmpTranslateCMD);

    ArrayList<String> als = new ArrayList<String>();

    Process p = null;
    try {
        p = Runtime.getRuntime().exec(sSnmpTranslateCMD);
    } catch (IOException e1) {
        /* If not found or installed */
        return null;
    }

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

    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    String sStd_IO = "";

    /*Read the output from the command If Any */

    int iCounter = 0;
    try {
        while ((sStd_IO = stdInput.readLine()) != null) {

            //Clean up White Space
            if (!sStd_IO.isEmpty())
                als.add(sStd_IO);

            if (debug | localDebug)
                System.out.println(++iCounter + " IN: " + sStd_IO);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        while ((sStd_IO = stdError.readLine()) != null) {

            als.add(sStd_IO);

            if (debug | localDebug)
                System.out.println(++iCounter + " OUT: " + sStd_IO);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return als;
}