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:TestFuseDFS.java

/**
 * Wait for the given process to return and check that it exited
 * as required. Log if the process failed.
 *//*from w  w w.j ava 2  s .  co  m*/
private static void checkProcessRet(Process p, boolean expectPass) throws IOException {
    try {
        int ret = p.waitFor();
        if (ret != 0) {
            dumpInputStream(p.getErrorStream());
        }
        if (expectPass) {
            assertEquals(0, ret);
        } else {
            assertTrue(ret != 0);
        }
    } catch (InterruptedException ie) {
        fail("Process interrupted: " + ie.getMessage());
    }
}

From source file:io.fabric8.maven.core.util.ProcessUtil.java

private static Thread startErrorLoggingThread(final Process process, final Logger log, final String commandDesc,
        final boolean useStandardLoggingLevel) {
    Thread logThread = new Thread("[ERR] " + commandDesc) {
        @Override//from  w  w w  .j a  v a2 s  .  c o  m
        public void run() {
            try {
                processOutput(process.getErrorStream(), createErrorHandler(log, useStandardLoggingLevel));
            } catch (IOException e) {
                log.error("Failed to read error stream from %s : %s", commandDesc, e.getMessage());
            }
        }
    };
    logThread.setDaemon(true);
    logThread.start();
    return logThread;
}

From source file:uk.ac.ebi.eva.test.utils.JobTestUtils.java

public static void restoreMongoDbFromDump(String dumpLocation) throws IOException, InterruptedException {
    logger.info("restoring DB from " + dumpLocation);

    Process exec = Runtime.getRuntime().exec("mongorestore " + dumpLocation);
    exec.waitFor();/*from   www. j  a va 2s.c  om*/
    String line;
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
    while ((line = bufferedReader.readLine()) != null) {
        logger.info("mongorestore output:" + line);
    }
    bufferedReader.close();
    bufferedReader = new BufferedReader(new InputStreamReader(exec.getErrorStream()));
    while ((line = bufferedReader.readLine()) != null) {
        logger.info("mongorestore errorOutput:" + line);
    }
    bufferedReader.close();

    logger.info("mongorestore exit value: " + exec.exitValue());
}

From source file:edu.dfci.cccb.mev.analysis.Limma.java

public static void execute(Heatmap heatmap, String selection1, String selection2, final File output,
        final File significant, final File rnk, String dimension)
        throws IOException, ScriptException, AnnotationNotFoundException {
    try (final Provisional input = file();
            final Provisional configuration = file();
            final Provisional script = file();
            final OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(script))) {
        if ("row".equals(dimension))
            configureRows(new FileOutputStream(configuration), heatmap, selection1, selection2);
        else/*from  ww w  .ja v a2s  . co  m*/
            configureColumns(new FileOutputStream(configuration), heatmap, selection1, selection2);
        heatmap.toStream(new FileOutputStream(input));
        if (log.isDebugEnabled())
            try (BufferedReader readBack = new BufferedReader(new FileReader(input))) {
                log.debug("Dump line 1: \"" + readBack.readLine() + "\"");
                log.debug("Dump line 2: \"" + readBack.readLine() + "\"");
            }
        velocity.getTemplate(Limma.script).merge(new VelocityContext(new HashMap<String, String>() {
            private static final long serialVersionUID = 1L;

            {
                if (log.isDebugEnabled())
                    log.debug("Running LIMMA with input " + input.getAbsolutePath() + " configuration "
                            + configuration.getAbsolutePath() + " output " + output.getAbsolutePath()
                            + " significant " + significant);
                put("input", input.getAbsolutePath());
                put("configuration", configuration.getAbsolutePath());
                put("output", output.getAbsolutePath());
                put("significant", significant.getAbsolutePath());
                put("rnk", rnk.getAbsolutePath());
            }
        }), writer);
        writer.flush();
        Process r = Runtime.getRuntime().exec(Limma.r + " " + script.getAbsolutePath());
        try {
            r.waitFor();
        } catch (InterruptedException e) {
            log.error("Interrupted while waiting for R", e);
        }
        if (log.isDebugEnabled()) {
            ByteArrayOutputStream listing = new ByteArrayOutputStream();
            IOUtils.copy(r.getErrorStream(), listing);
            log.debug("Return value " + r.exitValue() + " error output:\n" + listing.toString());
        }
        if (r.exitValue() != 0)
            throw new RuntimeException("Non zero return value from R process " + r.exitValue());
        // r.eval (new InputStreamReader (new ByteArrayInputStream
        // (script.toByteArray ())));
    }
}

From source file:com.sssemil.advancedsettings.MainService.java

public static void grandPermissions(Context context) throws IOException {
    Runtime rt = Runtime.getRuntime();
    String package_name = context.getPackageName();
    String[] commands = { "su", "-c", "\"pm", "grant",
            package_name + " android.permission.CHANGE_CONFIGURATION\"" };
    Process proc = rt.exec(commands);

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

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

    String s;//  w  ww .  ja v a  2  s .c  o m
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
    }
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
    }
}

From source file: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. ja  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();

    System.out.println("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 + "\n");
        }

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

        if (error.length() > 0) {
            System.out.println("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.modeln.build.common.tool.CMnCmdLineTool.java

/**
 * Wait for the executing process to complete.
 *
 * @param  process  Process to monitor/*  ww w  .  j av a  2  s  . c o  m*/
 * @param  profile  Enable or disable execution profiling
 */
public static int wait(Process process, boolean profile) throws InterruptedException {
    Date startDate = null;
    if (profile) {
        startDate = new Date();
    }

    // Use a separate thread to relay the process output to the user
    CMnProcessOutput stdout = new CMnProcessOutput(process, process.getInputStream());
    CMnProcessOutput stderr = new CMnProcessOutput(process, process.getErrorStream());
    Thread out = new Thread(stdout);
    Thread err = new Thread(stderr);
    out.start();
    err.start();

    // Wait for the process to complete
    int result = process.waitFor();

    // Display the elapsed time for this operation
    if (profile) {
        displayElapsedTime(startDate, new Date(), "Execution complete: ");
    }

    return result;
}

From source file:edu.kit.dama.util.SystemUtils.java

/**
 * Lock a folder in a Unix system. Therefor, the script previously generated
 * by generateScript() is used to lock the provided folder 'pLocalFolder'.
 *
 * @param pLocalScriptFile The lock script.
 * @param pLocalFolder The folder to lock.
 *
 * @return TRUE if the locking succeeded.
 *///from   w  ww. ja va2s .  c  o  m
private static boolean applyScriptToFolder(String pLocalScriptFile, String... pArguments) {
    BufferedReader brStdOut = null;
    BufferedReader brStdErr = null;
    try {
        String line;
        StringBuilder stdOut = new StringBuilder();
        StringBuilder stdErr = new StringBuilder();

        List<String> cmdArrayList = new ArrayList<>();
        cmdArrayList.add("sh");
        cmdArrayList.add(pLocalScriptFile);
        if (pArguments != null) {
            cmdArrayList.addAll(Arrays.asList(pArguments));
        }

        Process p = Runtime.getRuntime().exec(cmdArrayList.toArray(new String[cmdArrayList.size()]));

        brStdOut = new BufferedReader(new InputStreamReader(p.getInputStream()));
        brStdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((line = brStdOut.readLine()) != null) {
            stdOut.append(line).append("\n");
        }
        brStdOut.close();
        while ((line = brStdErr.readLine()) != null) {
            stdErr.append(line).append("\n");
        }
        brStdErr.close();
        int result = p.waitFor();
        LOGGER.debug("Script finished execution with return code {}", result);
        LOGGER.debug("StdOut: {}", stdOut.toString());
        LOGGER.warn("StdErr: {}", stdErr.toString());
    } catch (IOException err) {
        LOGGER.error("Script execution failed", err);
        return false;
    } catch (InterruptedException err) {
        LOGGER.error("Script execution might have failed", err);
        return false;
    } finally {
        if (brStdErr != null) {
            try {
                brStdErr.close();
            } catch (IOException ex) {
            }
        }
        if (brStdOut != null) {
            try {
                brStdOut.close();
            } catch (IOException ex) {
            }
        }
    }
    return true;
}

From source file:ee.ria.xroad.proxy.ProxyMain.java

private static void readProxyVersion() {
    try {//  w  w  w.  ja  va  2 s . com
        String cmd;

        if (Files.exists(Paths.get("/etc/redhat-release"))) {
            cmd = "rpm -q --queryformat '%{VERSION}-%{RELEASE}' xroad-proxy";
        } else {
            cmd = "dpkg-query -f '${Version}' -W xroad-proxy";
        }

        Process p = Runtime.getRuntime().exec(cmd);
        p.waitFor();
        version = IOUtils.toString(p.getInputStream()).replace("'", "");

        if (StringUtils.isBlank(version)) {
            version = "unknown";

            log.warn("Unable to read proxy version: {}", IOUtils.toString(p.getErrorStream()));
        }
    } catch (Exception ex) {
        version = "unknown";
        log.warn("Unable to read proxy version", ex);
    }
}

From source file:SystemKit.java

/**
 * Returns the first line of the result of a shell command.
 * Taken from UUID./*  w w  w .ja v  a2 s.  c  o  m*/
 *
 * @param commands the commands to run
 * @return the first line of the command
 * @throws IOException
 *
 * @since 3.3.3
 */
static String getFirstLineOfCommand(String[] commands) throws IOException {
    Process p = null;
    BufferedReader reader = null;
    try {
        p = Runtime.getRuntime().exec(commands);
        reader = new BufferedReader(new InputStreamReader(p.getInputStream()), 128);
        return reader.readLine();
    } finally {
        if (p != null) {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ex) {
                }
            }
            try {
                p.getErrorStream().close();
            } catch (IOException ex) {
            }
            try {
                p.getOutputStream().close();
            } catch (IOException ex) {
            }
            p.destroy();
        }
    }
}