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:com.eucalyptus.blockstorage.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 ww.  java 2 s . c o  m*/
 * @param command
 * @param timeout
 * @return CommandOutput
 * @throws EucalyptusCloudException
 */
private static CommandOutput execute(@Nonnull String[] command, @Nonnull 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 = getExecutorWithInit().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:com.github.maven_nar.NarUtil.java

public static int runCommand(final String cmd, final String[] args, final File workingDirectory,
        final String[] env, final TextStream out, final TextStream err, final TextStream dbg, final Log log,
        final boolean expectFailure) throws MojoExecutionException, MojoFailureException {
    final Commandline cmdLine = new Commandline();

    try {/*from w ww .  ja v a2s  .c om*/
        dbg.println("RunCommand: " + cmd);
        cmdLine.setExecutable(cmd);
        if (args != null) {
            for (final String arg : args) {
                dbg.println("  '" + arg + "'");
            }
            cmdLine.addArguments(args);
        }
        if (workingDirectory != null) {
            dbg.println("in: " + workingDirectory.getPath());
            cmdLine.setWorkingDirectory(workingDirectory);
        }

        if (env != null) {
            dbg.println("with Env:");
            for (final String element : env) {
                final String[] nameValue = element.split("=", 2);
                if (nameValue.length < 2) {
                    throw new MojoFailureException("   Misformed env: '" + element + "'");
                }
                dbg.println("   '" + nameValue[0] + "=" + nameValue[1] + "'");
                cmdLine.addEnvironment(nameValue[0], nameValue[1]);
            }
        }

        final Process process = cmdLine.execute();
        final StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), err);
        final StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), out);

        errorGobbler.start();
        outputGobbler.start();
        process.waitFor();
        final int exitValue = process.exitValue();
        dbg.println("ExitValue: " + exitValue);
        final int timeout = 5000;
        errorGobbler.join(timeout);
        outputGobbler.join(timeout);
        if (exitValue != 0 ^ expectFailure) {
            if (log == null) {
                System.err.println(err.toString());
                System.err.println(out.toString());
                System.err.println(dbg.toString());
            } else {
                log.warn(err.toString());
                log.warn(out.toString());
                log.warn(dbg.toString());
            }
            throw new MojoExecutionException("exit code: " + exitValue);
        }
        return exitValue;
    } catch (final MojoExecutionException e) {
        throw e;
    } catch (final Exception e) {
        throw new MojoExecutionException("Could not launch " + cmdLine, e);
    }
}

From source file:net.duckling.ddl.util.FileUtil.java

/**
 *  Runs a simple command in given directory.
 *  The environment is inherited from the parent process (e.g. the
 *  one in which this Java VM runs)./*from w ww.j a v a 2s .c  o m*/
 *
 *  @return Standard output from the command.
 *  @param  command The command to run
 *  @param  directory The working directory to run the command in
 *  @throws IOException If the command failed
 *  @throws InterruptedException If the command was halted
 */
public static String runSimpleCommand(String command, String directory)
        throws IOException, InterruptedException {
    StringBuffer result = new StringBuffer();

    LOG.info("Running simple command " + command + " in " + directory);

    Process process = Runtime.getRuntime().exec(command, null, new File(directory));

    BufferedReader stdout = null;
    BufferedReader stderr = null;

    try {
        stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
        stderr = new BufferedReader(new InputStreamReader(process.getErrorStream()));

        String line;

        while ((line = stdout.readLine()) != null) {
            result.append(line).append("\n");
        }

        StringBuffer error = new StringBuffer();
        while ((line = stderr.readLine()) != null) {
            error.append(line).append("\n");
        }

        if (error.length() > 0) {
            LOG.error("Command failed, error stream is: " + error);
        }

        process.waitFor();

    } finally {
        // we must close all by exec(..) opened streams: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692
        process.getInputStream().close();
        if (stdout != null) {
            stdout.close();
        }
        if (stderr != null) {
            stderr.close();
        }
    }

    return result.toString();
}

From source file:com.samczsun.helios.Helios.java

private static boolean ensurePython3Set0(boolean forceCheck) {
    String python3Location = Settings.PYTHON3_LOCATION.get().asString();
    if (python3Location.isEmpty()) {
        SWTUtil.showMessage("You need to set the location of the Python/PyPy 3.x executable", true);
        setLocationOf(Settings.PYTHON3_LOCATION);
        python3Location = Settings.PYTHON3_LOCATION.get().asString();
    }/*from w ww.j  a v a  2s  .  c  o  m*/
    if (python3Location.isEmpty()) {
        return false;
    }
    if (python3Verified == null || forceCheck) {
        try {
            Process process = new ProcessBuilder(python3Location, "-V").start();
            String result = IOUtils.toString(process.getInputStream());
            String error = IOUtils.toString(process.getErrorStream());
            python3Verified = error.startsWith("Python 3") || result.startsWith("Python 3");
        } catch (Throwable t) {
            t.printStackTrace();
            StringWriter sw = new StringWriter();
            t.printStackTrace(new PrintWriter(sw));
            SWTUtil.showMessage("The Python 3.x executable is invalid." + Constants.NEWLINE + Constants.NEWLINE
                    + sw.toString());
            python3Verified = false;
        }
    }
    return python3Verified;
}

From source file:com.samczsun.helios.Helios.java

private static boolean ensurePython2Set0(boolean forceCheck) {
    String python2Location = Settings.PYTHON2_LOCATION.get().asString();
    if (python2Location.isEmpty()) {
        SWTUtil.showMessage("You need to set the location of the Python/PyPy 2.x executable", true);
        setLocationOf(Settings.PYTHON2_LOCATION);
        python2Location = Settings.PYTHON2_LOCATION.get().asString();
    }/*  w w w  .  j  av  a 2  s . c o  m*/
    if (python2Location.isEmpty()) {
        return false;
    }
    if (python2Verified == null || forceCheck) {
        try {
            Process process = new ProcessBuilder(python2Location, "-V").start();
            String result = IOUtils.toString(process.getInputStream());
            String error = IOUtils.toString(process.getErrorStream());
            python2Verified = error.startsWith("Python 2") || result.startsWith("Python 2");
        } catch (Throwable t) {
            StringWriter sw = new StringWriter();
            t.printStackTrace(new PrintWriter(sw));
            SWTUtil.showMessage("The Python 2.x executable is invalid." + Constants.NEWLINE + Constants.NEWLINE
                    + sw.toString());
            t.printStackTrace();
            python2Verified = false;
        }
    }
    return python2Verified;
}

From source file:com.alibaba.otter.shared.common.utils.cmd.Exec.java

public static Result execute(Process process, String cmd, String outputLog, byte[] input, File workingDir)
        throws Exception {
    // ???// w w  w.  j  a v a2  s. c  om
    Thread inputThread = new InputPumper((input == null) ? new byte[] {} : input, process.getOutputStream());
    StreamCollector stderr = null;
    StreamCollector stdout = null;
    FileOutputStream fileOutput = null;
    StreamAppender outputLogger = null;
    String errString = null;
    String outString = null;

    try {
        if (outputLog == null) {
            stdout = new StreamCollector(process.getInputStream());
            stderr = new StreamCollector(process.getErrorStream());
            stdout.start();
            stderr.start();
        } else {
            errString = "stderr output redirected to file " + outputLog;
            outString = "stdout output redirected to file " + outputLog;
            fileOutput = new FileOutputStream(outputLog);
            outputLogger = new StreamAppender(fileOutput);
            outputLogger.writeInput(process.getErrorStream(), process.getInputStream());
        }

        inputThread.start();

        final int exitCode = process.waitFor();

        inputThread.join();

        if (outputLogger != null) {
            outputLogger.finish();
        }

        if (stdout != null) {
            stdout.join();
            outString = stdout.toString();
        }

        if (stderr != null) {
            stderr.join();
            errString = stderr.toString();
        }

        return new Result(cmd.toString(), outString, errString, exitCode);
    } finally {
        IOUtils.closeQuietly(fileOutput);

        if (process != null) {
            // evitons http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6462165
            process.getInputStream().close();
            process.getOutputStream().close();
            process.getErrorStream().close();
            process.destroy();
        }
    }
}

From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java

private static String getProcessOutput(Process p) throws Exception {
    StringBuilder s = new StringBuilder();
    BufferedInputStream bisIn = new BufferedInputStream(p.getInputStream());
    StringWriter writerIn = new StringWriter();
    IOUtils.copy(bisIn, writerIn, "UTF-8");
    s.append(writerIn.toString());//  www .j a v a  2 s. com

    BufferedInputStream bisErr = new BufferedInputStream(p.getErrorStream());
    StringWriter writerErr = new StringWriter();
    IOUtils.copy(bisErr, writerErr, "UTF-8");
    s.append(writerErr.toString());
    if (writerErr.toString().length() > 0) {
        StringBuilder sbErr = new StringBuilder();
        sbErr.append("script execution failed - error message:\n");
        sbErr.append("-------------------------------------------\n");
        sbErr.append(s.toString());
        sbErr.append("-------------------------------------------\n");
        LOGGER.info(sbErr.toString().trim());
        throw new Exception(s.toString().trim());
    }
    return s.toString();
}

From source file:GenAppStoreSales.java

/** Connects to the AppleStore and download pending sale reports
 * (if they are still available)/*from   w w  w.ja  va2s .c  om*/
 * Requires Auntoingestion.class in the same path together with GenAppStoreSales 
 * @throws IOException 
 */
private static void autoingestionDownload(String reportName, String dateType, String dateCode)
        throws IOException {
    File reportFile = new File(sourcePath, reportName);
    Runtime rt = Runtime.getRuntime();

    if (!reportFile.isFile()) {
        String s;

        System.out.println(reportName + " requesting...");
        Process downloadReport = rt
                .exec("java Autoingestion" + autoingestionPreArgs + dateType + " " + "Summary " + dateCode);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(downloadReport.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(downloadReport.getErrorStream()));

        // read the output from the command
        while ((s = stdInput.readLine()) != null)
            System.out.println(s);

        // read any errors from the attempted command
        while ((s = stdError.readLine()) != null)
            System.out.println(s);
        //            System.out.println("gzip -d " + currentPath.replace(" ", "\\ ") + "/" + reportName);
        //            System.out.println("mv " + reportName + " " + sourcePath.replace(" ", "\\ ") + "/" + reportName);
        rt.exec("gzip -d " + currentPath.replace(" ", "\\ ") + "/" + reportName);
        rt.exec("mv " + reportName + " " + sourcePath.replace(" ", "\\ ") + "/" + reportName);
        rt.exec("rm " + currentPath.replace(" ", "\\ ") + "/*.gz");

    }
    //       else System.out.println(reportName + " verified");
}

From source file:exm.stc.ui.Main.java

private static void runPreprocessor(Logger logger, String input, String output, List<String> preprocArgs) {
    List<String> cmd = new ArrayList<String>();
    /*//from www.  jav  a  2  s  .co  m
      -undef flag is provided to disable non-standard macros
     */
    if (useGCCProcessor()) {
        // We use gcc -E because cpp is broken on Mac GCC 4.2.1
        //    Cf. http://stackoverflow.com/questions/4137923
        cmd.addAll(Arrays.asList("gcc", "-E", "-undef", "-x", "c", input, "-o", output));
    } else {
        cmd.addAll(Arrays.asList("cpp", "-undef", input, output));
    }

    for (String dir : Settings.getModulePath()) {
        cmd.add("-I");
        cmd.add(dir);
    }

    for (String macro : preprocArgs) {
        cmd.add("-D");
        cmd.add(macro);
    }

    String cmdString = StringUtils.join(cmd, ' ');
    try {
        logger.debug("Running cpp: " + cmdString);
        Process cpp = Runtime.getRuntime().exec(cmd.toArray(new String[] {}));
        int cppExitCode = -1;
        boolean done = false;
        do {
            try {
                cppExitCode = cpp.waitFor();
                done = true;
            } catch (InterruptedException ex) {
                // Continue on after spurious interrupt
            }
        } while (!done);

        StringWriter sw = new StringWriter();
        IOUtils.copy(cpp.getErrorStream(), sw, "UTF-8");
        String cppStderr = sw.toString();

        logger.debug("Preprocessor exit code: " + cppExitCode);
        logger.debug("Preprocessor stderr: " + cppStderr);

        if (cppExitCode != 0) {
            // Print stderr message first, then clarify that failure was in preprocessor
            System.out.println(cppStderr);
            System.out.println("Aborting due to failure in cpp preprocessor invoked as: " + cmdString + ". "
                    + ("Exit code was " + cppExitCode + ". "));
            System.exit(1);
        } else if (cppStderr.length() != 0) {
            logger.warn("Preprocessor warnings:\n" + cppStderr);
        }
    } catch (IOException e) {
        System.out.println("I/O error while launching preprocessor with command line:" + cmdString + ": "
                + e.getMessage());
        System.exit(1);
    }
}

From source file:com.l2jfree.sql.L2DataSource.java

protected static final void writeBackup(String databaseName, Process run) {
    try {//from ww  w  . j  ava 2s .c  o  m
        boolean success = false;

        InputStream in = null;
        try {
            in = run.getInputStream();

            success = writeBackup(databaseName, in);
        } catch (IOException e) {
            _log.warn("DatabaseBackupManager: Could not make backup:", e);
        } finally {
            IOUtils.closeQuietly(in);
        }

        if (!success) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(run.getErrorStream()));

                for (String line; (line = br.readLine()) != null;)
                    _log.warn("DatabaseBackupManager: " + line);
            } catch (Exception e) {
                _log.warn("DatabaseBackupManager: Could not make backup:", e);
            } finally {
                IOUtils.closeQuietly(br);
            }
        }

        run.waitFor();
    } catch (Exception e) {
        _log.warn("DatabaseBackupManager: Could not make backup:", e);
    }
}