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:ingestor.SingleFileProcessor.java

private boolean UnzipArchive(File inSourceFile) throws IOException, InterruptedException {
    logger.begin("UnzipArchive(" + inSourceFile + ")");
    String line = "";
    String cmd = "";
    Runtime run = Runtime.getRuntime();
    Process pr = null;
    String srcPath = "", tgtPath = "";
    line = GetFileHeader(inSourceFile);/*from  w  w  w  .  j a va 2s .c om*/
    srcPath = inSourceFile.getAbsolutePath();
    tgtPath = inSourceFile.getParentFile().getAbsolutePath();

    logger.force("\tsrcPath=" + srcPath);
    logger.force("\ttgtPath=" + tgtPath);

    logger.force("\tline=" + line);
    if (line.contains("gzip compressed data")) {
        cmd = "/bin/tar -C " + tgtPath + " -xvzf " + srcPath;
    } else if (line.contains("xz compressed data")) {
        cmd = "/bin/tar  -C " + tgtPath + " -xvJf " + srcPath;
    } else if (line.contains("Zip archive data")) {
        cmd = "/usr/bin/unzip " + srcPath + " -d " + tgtPath;
    } else {
        logger.force("\t\tUnable to determine compression type, exiting");
        return false;
    }
    logger.force("\t\tcmd=" + cmd);

    //logger.fine("\nexecuting: "+cmd+"\n");
    pr = run.exec(cmd);

    BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    BufferedReader buferr = new BufferedReader(new InputStreamReader(pr.getErrorStream()));

    // read everything and output to outputStream as you go
    String s = null;
    ScreenLog.out("===== stdout =====");
    while ((s = buf.readLine()) != null) {
        ScreenLog.out("line=" + s);
    }

    ScreenLog.out("===== stderr =====");
    while ((s = buferr.readLine()) != null) {
        ScreenLog.out("line=" + s);
    }
    pr.waitFor();

    logger.end("UnzipArchive(" + inSourceFile + ")==exit(" + pr.exitValue() + ")");
    return pr.exitValue() == 0;
}

From source file:io.hummer.util.test.GenericTestResult.java

public void createGnuplot(String fileName, String[] xValueNames, String[] yValueNames, List<?> levels,
        String plot, String[] titles, ResultType type, String xLabel, String yLabel, String outFile,
        String... additionalCommands) throws Exception {

    List<String> xValueNamesNew = new LinkedList<String>();
    List<Integer> xValueNamesLengths = new LinkedList<Integer>();
    List<String> commandsList = new LinkedList<String>(Arrays.asList(additionalCommands));
    boolean hasCandleSticks = false;
    for (String s : xValueNames) {
        String[] split = s.split(":");
        xValueNamesLengths.add(split.length);
        hasCandleSticks |= split.length > 1;
        for (String sp : split) {
            xValueNamesNew.add(sp);/*from w  ww. ja  v a 2s  .  c o  m*/
        }
    }
    if (hasCandleSticks) {
        if (levels == null) {
            plot = getPlottableAverages(yValueNames, xValueNames);
        } else {
            plot = getPlottableAverages(levels, xValueNames, type, additionalCommands);
        }
    }

    String gnuplotOriginal = null;
    if (new File(fileName).exists()) {
        gnuplotOriginal = ioUtil.readFile(fileName);
    } else {
        String file = fileName;
        if (file.contains("/"))
            file = file.substring(file.indexOf("/") + 1);
        Map<URL, String> resources = cpUtil.getSystemResources(file);
        if (resources.isEmpty()) {
            logger.warn("Unable to find system resource '" + file + "'");
        } else {
            gnuplotOriginal = resources.values().iterator().next();
        }
    }
    boolean multiline = commandsList.contains(CMD_MULTI_LINE);
    boolean drawLineCandle = commandsList.contains(CMD_DRAW_LINE_THROUGH_CANDLESTICKS);
    boolean multipleCandles = commandsList.contains(CMD_MULTIPLE_CANDLES_PER_XTICK);
    boolean multiAxes = commandsList.contains(CMD_MULTI_AXES);

    if (multiAxes) {
        for (int i = 1; i <= titles.length; i++) {
            commandsList.add("set y" + (i > 1 ? i : "") + "tics nomirror");
        }
    }

    String additional = "";
    for (String a : commandsList) {
        if (a.startsWith("##")) {
            // do not add
        } else if (a.startsWith("#")) {
            String left = a.substring(0, a.indexOf("="));
            String right = a.substring(a.indexOf("=") + 1);
            gnuplotOriginal = gnuplotOriginal.replaceAll(left, right);
        } else {
            additional += a + "\n";
        }
    }
    String gnuplot = gnuplotOriginal.replaceAll("#<extra>", additional);

    if (type == ResultType.REGRESSION) {
        gnuplot = gnuplot.replaceAll("#regression", "");
        gnuplot = gnuplot.replaceAll("\"gnuplot.values\" using 1:2 title '<title1>'",
                "\"gnuplot.values\" using 1:2 title '<title1>', regrFunc(x) title 'Linear Regression' with lines");
        gnuplot = gnuplot.replaceAll("with linespoints ls 1", "");
    }

    if (commandsList.contains(CMD_FLIP_AXES)) {
        for (int i = 1; i <= titles.length; i++) {
            gnuplot = gnuplot.replaceAll("using 1:" + (i + 1), "using " + (i + 1) + ":1");
        }
        String tmp = xLabel;
        xLabel = yLabel;
        yLabel = tmp;
    }

    if (xLabel != null)
        gnuplot = gnuplot.replaceAll("<xlabel>", xLabel);
    if (yLabel != null)
        gnuplot = gnuplot.replaceAll("<ylabel>", yLabel);

    Map<Integer, String> fillStylePatterns = collUtil.asMap(0, "4").entry(1, "1").entry(2, "3").entry(3, "2")
            .entry(4, "3").entry(5, "4").entry(6, "5").entry(7, "7");

    for (int i = 1; i <= titles.length; i++) {
        gnuplot = gnuplot.replaceAll("#<do" + i + ">", "");
        if (hasCandleSticks || commandsList.contains(CMD_NO_LINES_JUST_POINTS)
                || commandsList.contains(CMD_MULTI_AXES)) {

            int colIndexStart = 1 + getSublistSum(xValueNamesLengths, 0, i - 1) - xValueNamesLengths.get(i - 1)
                    + 1;
            int colIndexEnd = 1 + getSublistSum(xValueNamesLengths, 0, i - 1);
            String colIndexes = "";
            int maxCols = 4; /* required for candlesticks functionality */
            for (int j = colIndexStart; j <= colIndexEnd && j <= (maxCols + 1); j++) {
                colIndexes += ":" + j;
            }
            String colIndexVariable = "(\\$1)";
            if (multipleCandles)
                colIndexVariable = "(\\$1-0.5+" + ((double) i) * (1.0 / (double) titles.length) + ")";
            if (colIndexStart < colIndexEnd) {
                String plotLine = "\"gnuplot.values\" using " + colIndexVariable + colIndexes + " title '<title"
                        + i + ">' with candlesticks whiskerbars ls " + i + " fs pattern "
                        + fillStylePatterns.get(i);

                if (drawLineCandle) {
                    int idx = colIndexStart + 2;
                    if (xValueNamesLengths.get(i - 1) >= 5) {
                        idx = colIndexStart + 4;
                    }
                    plotLine += ", \"gnuplot.values\" using 1:" + idx + " title '' with lines ls " + i;
                }

                /* draw median line in boxplot/candlesticks */
                if (xValueNamesLengths.get(i - 1) >= 5) {
                    int idx = (colIndexStart + 4);
                    plotLine += ", \"gnuplot.values\" using 1:" + idx + ":" + idx + ":" + idx + ":" + idx
                            + " with candlesticks lt -1 lw 2 notitle " + i;
                }

                if (multiAxes && i > 1) {
                    plotLine += " axes x1y" + i;
                }

                if (multiline) {
                    plotLine = "plot " + plotLine;
                } else {
                    if (i < titles.length)
                        plotLine += ", \\\\";
                }
                gnuplot = gnuplot.replaceAll("#<plot" + i + ">.*\\n", plotLine + "\n");
            } else {
                String plotLine = "\"gnuplot.values\" using 1" + colIndexes + " title '<title" + i
                        + ">' with linespoints ls " + i;
                if (commandsList.contains(CMD_NO_LINES_JUST_POINTS)) {
                    plotLine = plotLine.replace("with linespoints", "with points");
                }

                if (multiAxes) {
                    plotLine += " axes x1y" + i;
                }

                if (multiline) {
                    plotLine = "plot " + plotLine;
                } else {
                    if (i < titles.length)
                        plotLine += ", \\\\";
                }
                gnuplot = gnuplot.replaceAll("#<plot" + i + ">.*\\n", plotLine + "\n");
            }
        }
        gnuplot = gnuplot.replaceAll("#<plot" + i + ">", "");

        if (titles != null && titles.length >= i)
            gnuplot = gnuplot.replace("<title" + i + ">", titles[i - 1]);
    }
    for (int i = titles.length + 1; i < 10; i++) {
        gnuplot = gnuplot.replaceAll("#<do" + i + ">", "#");
    }
    System.out.println(gnuplot);

    ioUtil.saveFile("createImage.temp.gnuplot", gnuplot);
    ioUtil.saveFile("gnuplot.values", plot);

    Process gpProc = Runtime.getRuntime().exec("gnuplot createImage.temp.gnuplot");
    gpProc.waitFor();
    String output = ioUtil.readFile(gpProc.getInputStream());
    output += ioUtil.readFile(gpProc.getErrorStream());
    System.out.println("gnuplot output:\n------\n" + output);
    if (output != null && (output.contains("Not enough columns") || output.contains("no valid points"))) {
        System.out.println("---> Apparently, gnuplot reported an error. Input values were:");
        System.out.println(plot);
    }
    String fixbb = "etc/fixbb";
    String fixbbTmp = null;
    if (!new File(fixbb).exists()) {
        fixbb = "../" + fixbb;
        if (!new File(fixbb).exists()) {
            fixbb = "../" + fixbb;
        }
        if (!new File(fixbb).exists()) {
            Map<URL, String> resources = cpUtil.getSystemResources("fixbb");
            if (!resources.isEmpty()) {
                fixbbTmp = UUID.randomUUID().toString();
                ioUtil.saveFile(fixbbTmp, resources.values().iterator().next());
                new File(fixbbTmp).setExecutable(true);
                new File(fixbbTmp).deleteOnExit();
                fixbb = "./" + fixbbTmp;
            }
        }
    }
    Runtime.getRuntime().exec(fixbb + " graph.eps").waitFor();
    if (fixbbTmp != null) {
        new File(fixbbTmp).delete();
    }
    if (outFile.endsWith(".pdf")) {
        Runtime.getRuntime().exec("epstopdf graph.eps").waitFor();
        new File("graph.pdf").renameTo(new File(outFile));
        new File("graph.pdf").delete();
    } else {
        new File("graph.eps").renameTo(new File(outFile));
    }
    new File("graph.eps").delete();
    new File("gnuplot.values").delete();
    new File("createImage.temp.gnuplot").delete();

}

From source file:com.ibm.bi.dml.test.integration.AutomatedTestBase.java

/**
 * Runs an R script in the old or the new way
 *//*from  w ww  .  j ava 2s  .c  om*/
protected void runRScript(boolean newWay) {

    String executionFile = sourceDirectory + selectedTest + ".R";

    // *** HACK ALERT *** HACK ALERT *** HACK ALERT ***
    // Some of the R scripts will fail if the "expected" directory doesn't exist.
    // Make sure the directory exists.
    File expectedDir = new File(baseDirectory, "expected" + "/" + cacheDir);
    expectedDir.mkdirs();
    // *** END HACK ***

    String cmd;
    if (!newWay) {
        executionFile = executionFile + "t";
        cmd = "R -f " + executionFile;
    } else {
        // *** HACK ALERT *** HACK ALERT *** HACK ALERT ***
        // Rscript does *not* load the "methods" package by default
        // to save on start time. The "Matrix" package used in the
        // tests requires the "methods" package and should still
        // load and attach it, but in R 3.2 with the latest version
        // of the "Matrix" package, "methods" is loaded *but not
        // attached* when run with Rscript.  Therefore, we need to
        // explicitly load it with Rscript.
        cmd = rCmd.replaceFirst("Rscript",
                "Rscript --default-packages=methods,datasets,graphics,grDevices,stats,utils");
        // *** END HACK ***
    }

    if (System.getProperty("os.name").contains("Windows")) {
        cmd = cmd.replace('/', '\\');
        executionFile = executionFile.replace('/', '\\');
    }
    if (DEBUG) {
        if (!newWay) { // not sure why have this condition
            TestUtils.printRScript(executionFile);
        }
    }
    if (!newWay) {
        ParameterBuilder.setVariablesInScript(sourceDirectory, selectedTest + ".R", testVariables);
    }

    if (cacheDir.length() > 0) {
        File expectedFile = null;
        String[] outputFiles = null;
        TestConfiguration testConfig = getTestConfiguration(selectedTest);
        if (testConfig != null) {
            outputFiles = testConfig.getOutputFiles();
        }

        if (outputFiles != null && outputFiles.length > 0) {
            expectedFile = new File(expectedDir.getPath() + "/" + outputFiles[0]);
            if (expectedFile.canRead()) {
                System.out.println("Skipping R script cmd: " + cmd);
                return;
            }
        }
    }

    try {
        long t0 = System.nanoTime();
        System.out.println("starting R script");
        System.out.println("cmd: " + cmd);
        Process child = Runtime.getRuntime().exec(cmd);

        String outputR = IOUtils.toString(child.getInputStream());
        System.out.println("Standard Output from R:" + outputR);
        String errorString = IOUtils.toString(child.getErrorStream());
        System.err.println("Standard Error from R:" + errorString);

        //
        // To give any stream enough time to print all data, otherwise there
        // are situations where the test case fails, even before everything
        // has been printed
        //
        child.waitFor();
        //      Thread.sleep(30000);

        try {
            if (child.exitValue() != 0) {
                throw new Exception(
                        "ERROR: R has ended irregularly\n" + outputR + "\nscript file: " + executionFile);
            }
        } catch (IllegalThreadStateException ie) {
            //
            // In UNIX JVM does not seem to be able to close threads
            // correctly. However, give it a try, since R processed the
            // script, therefore we can terminate the process.
            //
            child.destroy();
        }

        long t1 = System.nanoTime();
        System.out.println("R is finished (in " + ((double) t1 - t0) / 1000000000 + " sec)");

    } catch (Exception e) {
        e.printStackTrace();
        StringBuilder errorMessage = new StringBuilder();
        errorMessage.append("failed to run script " + executionFile);
        errorMessage.append("\nexception: " + e.toString());
        errorMessage.append("\nmessage: " + e.getMessage());
        errorMessage.append("\nstack trace:");
        for (StackTraceElement ste : e.getStackTrace()) {
            errorMessage.append("\n>" + ste);
        }
        fail(errorMessage.toString());
    }
}

From source file:Install.java

private void printExecutionOutput(Process p, boolean showCmdOutput, boolean showError, boolean showUIOutput)
        throws IOException {
    try {// w ww . ja v  a  2  s.c om
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

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

        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

        String line;

        // note for future modification:
        // handling stdout and stderr this way might block...this should
        // be handled with separate threads to process stdout and stderr
        while ((line = in.readLine()) != null) {
            if (showCmdOutput) {
                System.out.println(line);
            } else if (showUIOutput) {
                fireActionEvent(line);
            }
        }

        // print out all the stderr that happened
        while ((line = sin.readLine()) != null) {
            if (showError) {
                System.out.println(line);
            }
        }

        in.close();
        sin.close();
        out.close();

    } catch (IOException e) {
        System.out.println("Error executing system command.");
        throw e;
    }
}

From source file:edu.stanford.muse.util.Util.java

public static void run_command(String[] cmd, String dir) throws IOException {
    // introduced the envp array with the PATH= string after
    // /opt/local/bin/convert started failing
    // while converting pdf to jpg. it would fail
    // saying" sh: gs: command not found"

    File f = null;/*from w ww. j a v a2s  .c o m*/

    if (dir != null) {
        f = new File(dir);
        if (!f.exists())
            f = null;
    }

    Process p = Runtime.getRuntime().exec(cmd,
            new String[] { "PATH=/opt/local/bin:/bin:/sbin:/usr/bin:/opt/local/sbin" }, f);

    // printing the process's stderr on screen
    Reader r = new InputStreamReader(p.getErrorStream());
    while (true) {
        int i = r.read();
        if (i == -1)
            break;
        System.err.print((char) i);
    }
    r.close();

    try {
        p.waitFor();
    } catch (InterruptedException ie) {
        System.out.println("Unable to complete command");
        throw new RuntimeException(ie);
    }
}

From source file:com.att.android.arodatacollector.utils.AROCollectorUtils.java

/**
 * Executes the specified linux command on the device shell.
 * //from  ww w  .  ja v  a2 s.c  o  m
 * @param shellCommand
 *            A linux native shell command.
 * 
 * @return The output from the linux native shell command.
 */
public String runCommand(String shellCommand) {
    String stdout;
    String sRet = "";
    String stderr;
    try {
        final Process m_process = Runtime.getRuntime().exec(shellCommand);
        final StringBuilder sbread = new StringBuilder();
        final Thread tout = new Thread(new Runnable() {
            public void run() {
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(m_process.getInputStream()), 8192);
                String ls_1 = null;
                try {
                    while ((ls_1 = bufferedReader.readLine()) != null) {
                        sbread.append(ls_1).append("\n");
                    }
                } catch (IOException e) {
                    AROLogger.e(TAG, "IOException in runCommand" + e);
                } finally {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        AROLogger.e(TAG, "Exception in runCommand bufferedReader.close()" + e);
                    }
                }
            }
        });
        tout.start();
        final StringBuilder sberr = new StringBuilder();
        final Thread terr = new Thread(new Runnable() {
            public void run() {
                final BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(m_process.getErrorStream()), 8192);
                String ls_1 = null;
                try {
                    while ((ls_1 = bufferedReader.readLine()) != null) {
                        sberr.append(ls_1).append("\n");
                    }
                } catch (IOException e) {
                    AROLogger.e(TAG, "Exception in runCommand" + e);
                } finally {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        AROLogger.e(TAG, "Exception in runCommand bufferedReader.close()" + e);
                    }
                }
            }
        });
        terr.start();
        while (tout.isAlive()) {
            Thread.sleep(50);
        }
        if (terr.isAlive())
            terr.interrupt();
        stdout = sbread.toString();
        stderr = sberr.toString();
        sRet = stdout + stderr;
    } catch (java.io.IOException ee) {
        AROLogger.e(TAG, "Exception in runCommand" + ee);
        return null;
    } catch (InterruptedException ie) {
        AROLogger.e(TAG, "Exception in runCommand" + ie);
        return null;
    }
    return sRet;
}

From source file:de.teamgrit.grit.checking.compile.HaskellCompileChecker.java

/**
 * checkProgram invokes the Haskell compiler on a given file and reports
 * the output./*  ww  w. j  av a2  s. c  o  m*/
 * 
 * @param pathToProgramFile
 *            Specifies the file or folder containing that should be
 *            compiled. (accepts .lhs and .hs files)
 * @param compilerName
 *            The compiler to be used (usually ghc).
 * @param compilerFlags
 *            Additional flags to be passed to the compiler.
 * @throws FileNotFoundException
 *             Is thrown when the file in pathToProgramFile cannot be
 *             opened
 * @throws BadCompilerSpecifiedException
 *             Is thrown when the given compiler cannot be called
 * @return A {@link CompilerOutput} that contains all compiler messages and
 *         flags on how the compile run went.
 * @throws BadFlagException
 *             When ghc doesn't recognize a flag, this exception is thrown.
 */
@Override
public CompilerOutput checkProgram(Path pathToProgramFile, String compilerName, List<String> compilerFlags)
        throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException {

    Process compilerProcess = null;

    try {
        // create compiler invocation.
        List<String> compilerInvocation = createCompilerInvocation(pathToProgramFile, compilerName,
                compilerFlags);

        ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation);

        // make sure the compiler stays in its directory.
        compilerProcessBuilder.directory(pathToProgramFile.getParent().toFile());

        compilerProcess = compilerProcessBuilder.start();
        // this will never happen because createCompilerInvocation never
        // throws this Exception. Throw declaration needs to be in method
        // declaration because of the implemented Interface although we
        // never use it in the HaskellCompileChecker
    } catch (CompilerOutputFolderExistsException e) {
        LOGGER.severe("A problem while compiling, which never should happen, occured" + e.getMessage());
    } catch (BadCompilerSpecifiedException e) {
        throw new BadCompilerSpecifiedException(e.getMessage());
    } catch (IOException e) {

        // If we cannot call the compiler we return a CompilerOutput
        // initialized with false, false, indicating
        // that the compiler wasn't invoked properly and that there was no
        // clean Compile.
        CompilerOutput compilerInvokeError = new CompilerOutput();
        compilerInvokeError.setClean(false);
        compilerInvokeError.setCompilerInvoked(false);
        return compilerInvokeError;
    }

    // Now we read compiler output. If everything is ok ghc reports
    // nothing in the errorStream.
    InputStream compilerOutputStream = compilerProcess.getErrorStream();
    InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream);
    BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader);
    String line;

    CompilerOutput compilerOutput = new CompilerOutput();
    compilerOutput.setCompilerInvoked(true);

    List<String> compilerOutputLines = new LinkedList<>();

    try {
        while ((line = compilerOutputBuffer.readLine()) != null) {
            compilerOutputLines.add(line);
        }
        // Errors are separated via an empty line (""). But after the
        // the last error the OutputBuffer has nothing more to write.
        // In order to recognize the last error we insert an empty String
        // at the end of the list.
        // Only needs to be done when there are errors.
        if (compilerOutputLines.size() != 0) {
            line = "";
            compilerOutputLines.add(line);
        }

        compilerOutputStream.close();
        compilerStreamReader.close();
        compilerOutputBuffer.close();
        compilerProcess.destroy();

    } catch (IOException e) {

        // Reading might go wrong here if ghc should unexpectedly die
        LOGGER.severe("Error while reading from compiler stream.");
        compilerOutput.setClean(false);
        compilerOutput.setCompileStreamBroken(true);
        return compilerOutput;
    }

    // ghc -c generates a .o(object) and a .hi(haskell interface) file.
    // But we don't need those files so they can be deleted.
    // The generated files have the same name like our input file so we
    // can just exchange the file endings in order to get the
    // correct file paths for deletion
    if (Files.isDirectory(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) {

        // we use a file walker in order to find all files in the folder
        // and its subfolders
        RegexDirectoryWalker dirWalker = new RegexDirectoryWalker(".+\\.([Ll])?[Hh][Ss]");
        try {
            Files.walkFileTree(pathToProgramFile, dirWalker);
        } catch (IOException e) {
            LOGGER.severe("Could not walk submission " + pathToProgramFile.toString()
                    + " while building copiler invocation: " + e.getMessage());
        }

        for (Path candidatePath : dirWalker.getFoundFiles()) {
            File candidateFile = candidatePath.toFile();
            if (!candidateFile.isDirectory()) {
                String extension = FilenameUtils.getExtension(candidateFile.toString());
                if (extension.matches("[Ll]?[Hh][Ss]")) {
                    File ghcGeneratedObject = new File(
                            FilenameUtils.removeExtension(candidateFile.toString()) + ".o");
                    File ghcGeneratedInterface = new File(
                            FilenameUtils.removeExtension(candidateFile.toString()) + ".hi");
                    ghcGeneratedObject.delete();
                    ghcGeneratedInterface.delete();
                }
            }
        }
    } else {
        String extension = FilenameUtils.getExtension(pathToProgramFile.toString());
        if (extension.matches("[Ll]?[Hh][Ss]")) {
            File ghcGeneratedObject = new File(
                    FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".o");
            File ghcGeneratedInterface = new File(
                    FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".hi");
            ghcGeneratedObject.delete();
            ghcGeneratedInterface.delete();
        }

    }

    // if there are no errors there is no Output to handle
    if (compilerOutputLines.size() != 0) {
        compilerOutput = splitCompilerOutput(compilerOutputLines, compilerOutput);
    } else {
        compilerOutput.setClean(true);
    }
    return compilerOutput;
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncDAO.java

/**
 * @param cmdWithArguments//from  ww  w. j  a v  a2 s .  c  o  m
 * @param wd
 * @return
 */
private String execCmd(File wd, String[] cmdWithArguments) {
    log.debug("executing command: " + Arrays.toString(cmdWithArguments));

    StringBuffer out = new StringBuffer();
    try {
        Process p = (wd != null) ? Runtime.getRuntime().exec(cmdWithArguments, null, wd)
                : Runtime.getRuntime().exec(cmdWithArguments);

        out.append("Normal cmd output:\n");
        Reader reader = new InputStreamReader(p.getInputStream());
        BufferedReader input = new BufferedReader(reader);
        int readChar = 0;
        while ((readChar = input.read()) != -1) {
            out.append((char) readChar);
        }
        input.close();
        reader.close();

        out.append("ErrorStream cmd output:\n");
        reader = new InputStreamReader(p.getErrorStream());
        input = new BufferedReader(reader);
        readChar = 0;
        while ((readChar = input.read()) != -1) {
            out.append((char) readChar);
        }
        input.close();
        reader.close();

        Integer exitValue = p.waitFor();

        log.debug("Process exit value: " + exitValue);

    } catch (Exception e) {
        log.error("Error while executing command: '" + cmdWithArguments + "'", e);
    }

    log.debug("execCmd output: \n" + out.toString());

    return out.toString();
}

From source file:com.netxforge.oss2.core.utilsII.ExecRunner.java

/**
 * The <code>exec(String, PrintWriter, PrintWriter)</code> method runs a
 * process inside of a watched thread. It returns the client's exit code and
 * feeds its STDOUT and STDERR to the passed-in streams.
 *
 * @return The command's return code//from w w  w  .  j  a  v a 2 s .co m
 * @param command
 *            The program or command to run
 * @param stdoutWriter
 *            java.io.PrintWriter
 * @param stderrWriter
 *            java.io.PrintWriter
 * @throws java.io.IOException
 *             thrown if a problem occurs
 * @throws java.lang.InterruptedException
 *             thrown if a problem occurs
 */
public int exec(final String command, final PrintWriter stdoutWriter, final PrintWriter stderrWriter)
        throws IOException, InterruptedException {

    // Default exit value is non-zero to indicate a problem.
    int exitVal = 1;

    // //////////////////////////////////////////////////////////////
    final Runtime rt = Runtime.getRuntime();
    Process proc;
    String[] cmd = null;

    // First get the start time & calculate comparison numbers
    final Date startTime = new Date();
    final long startTimeMs = startTime.getTime();
    final long maxTimeMs = startTimeMs + (maxRunTimeSecs * 1000);

    // //////////////////////////////////////////////////////////////
    // First determine the OS to build the right command string
    final String osName = System.getProperty("os.name");
    if (osName.equals("Windows 95") || osName.equals("Windows 98") || osName.equals("Windows ME")) {
        cmd = new String[3];
        cmd[0] = WINDOWS_9X_ME_COMMAND_1;
        cmd[1] = WINDOWS_9X_ME_COMMAND_2;
        cmd[2] = command;
    } else if (osName.contains("Windows")) { // "Windows NT", "Windows 2000", etc.
        cmd = new String[3];
        cmd[0] = WINDOWS_NT_2000_COMMAND_1;
        cmd[1] = WINDOWS_NT_2000_COMMAND_2;
        cmd[2] = command;
    } else {
        // Linux (and probably other *nixes) prefers to be called
        // with each argument supplied separately, so we first
        // Tokenize it across spaces as the boundary.
        final StringTokenizer st = new StringTokenizer(command, " ");
        cmd = new String[st.countTokens()];
        int token = 0;
        while (st.hasMoreTokens()) {
            String tokenString = st.nextToken();
            cmd[token++] = tokenString;
        }
    }

    // Execute the command and start the two output gobblers
    if (cmd != null && cmd.length > 0) {
        proc = rt.exec(cmd);
    } else {
        throw new IOException("Insufficient commands!");
    }

    final StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), stdoutWriter);
    final StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), stderrWriter);
    outputGobbler.start();
    errorGobbler.start();

    // Wait for the program to finish running and return the
    // exit value obtained from the executable
    while (true) {

        try {
            exitVal = proc.exitValue();
            break;
        } catch (final IllegalThreadStateException e) {

            // If we get this exception, then the process isn't
            // done executing and we determine if our time is up.
            if (maxRunTimeSecs > 0) {

                final Date endTime = new Date();
                final long endTimeMs = endTime.getTime();
                if (endTimeMs > maxTimeMs) {
                    // Time's up - kill the process and the gobblers and
                    // return
                    proc.destroy();
                    maxRunTimeExceeded = true;
                    stderrWriter.println(MAX_RUN_TIME_EXCEEDED_STRING);
                    outputGobbler.quit();
                    errorGobbler.quit();
                    return exitVal;

                } else {
                    // Time is not up yet so wait 100 ms before testing
                    // again
                    Thread.sleep(POLL_DELAY_MS);
                }

            }

        }

    }

    // //////////////////////////////////////////////////////////////
    // Wait for output gobblers to finish forwarding the output
    while (outputGobbler.isAlive() || errorGobbler.isAlive()) {
    }

    // //////////////////////////////////////////////////////////////
    // All done, flush the streams and return the exit value
    stdoutWriter.flush();
    stderrWriter.flush();
    return exitVal;

}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * issue the kill -9 command if ffmpeg couldn't be stopped with kill -15
 *//*from  w  w  w  .j a  v a2 s .  c  om*/
private void kill9Ffmpeg() {

    Process sh = null;
    DataOutputStream os = null;

    int pid = 0, exitValue = -1;
    try {
        //have a 1 sec delay since it takes some time for the kill -15 to end ffmpeg
        Thread.sleep(1000);
        pid = mAroUtils.getProcessID("ffmpeg");

        if (pid != 0) {
            //ffmpeg still running
            if (DEBUG) {
                Log.i(TAG, "ffmpeg still running after kill -15. Will issue kill -9 " + pid);
            }

            sh = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(sh.getOutputStream());
            String Command = "kill -9 " + pid + "\n";
            os.writeBytes(Command);

            Command = "exit\n";
            os.writeBytes(Command);
            os.flush();

            //clear the streams so that it doesnt block the process
            //sh.inputStream is actually the output from the process
            StreamClearer stdoutClearer = new StreamClearer(sh.getInputStream(), "stdout", false);
            new Thread(stdoutClearer).start();
            StreamClearer stderrClearer = new StreamClearer(sh.getErrorStream(), "stderr", true);
            new Thread(stderrClearer).start();

            exitValue = sh.waitFor();
            if (exitValue == 0) {
                mVideoRecording = false;
            } else {
                Log.e(TAG, "could not kill ffmpeg in kill9Ffmpeg, exitValue=" + exitValue);
            }

        } else {
            mVideoRecording = false;
            if (DEBUG) {
                Log.i(TAG, "ffmpeg had been ended successfully by kill -15");
            }
        }
    } catch (Exception e1) {
        Log.e(TAG, "exception in kill9Ffmpeg", e1);
    } finally {
        try {
            if (os != null) {
                os.close();
            }

            if (sh != null) {
                sh.destroy();
            }
        } catch (Exception e) {
            Log.e(TAG, "exception in kill9Ffmpeg DataOutputStream close", e);
        }
    }
}