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

private String runCommand(String command) {
    String result = "";
    String error = "";
    String s = null;//  w w  w. ja  v  a 2 s .  c o  m
    try {
        Process p = Runtime.getRuntime().exec(command);
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        // read the output from the command
        while ((s = stdInput.readLine()) != null) {
            result = result + s;
        }
        // read any errors from the attempted command
        while ((s = stdError.readLine()) != null) {
            error = error + s;
        }
        if (error != "") {
            return error;
        } else {
            return result;
        }
    } catch (IOException e) {
        return "unknown error";
    }
}

From source file:com.jsystem.j2autoit.AutoItAgent.java

@Override
public int killProcess(String image) {
    try {/*from   www.j  a v  a  2  s.  c o  m*/
        Thread.sleep(shutDownTimeOut);
        Process taskKillProcess = Runtime.getRuntime().exec("TASKKILL /F /IM " + image);
        Log.infoLog("Forcing AutoIt Script Shutdown!!\n");
        StringBuilder sb = new StringBuilder("");
        BufferedReader br = new BufferedReader(new InputStreamReader(taskKillProcess.getInputStream()));
        String line = null;
        while ((line = br.readLine()) != null) {
            if (!line.trim().isEmpty()) {
                sb.append(line).append(NEW_LINE);
            }
        }
        if (sb.length() > 0) {
            Log.infoLog(sb.toString());
        } else {
            br = new BufferedReader(new InputStreamReader(taskKillProcess.getErrorStream()));
            line = null;
            while ((line = br.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    sb.append(line).append(NEW_LINE);
                }
            }
            Log.errorLog(sb.toString());
        }
    } catch (Exception e) {
        Log.errorLog(e.getMessage());
    }
    return 0;
}

From source file:com.eucalyptus.blockstorage.OverlayManager.java

private int losetup(String absoluteFileName, String loDevName) {
    try {/*  w w w  .  j a  v a  2  s. c o m*/
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(
                new String[] { StorageProperties.EUCA_ROOT_WRAPPER, "losetup", loDevName, absoluteFileName });
        StreamConsumer error = new StreamConsumer(proc.getErrorStream());
        StreamConsumer output = new StreamConsumer(proc.getInputStream());
        error.start();
        output.start();
        int errorCode = proc.waitFor();
        output.join();
        LOG.info("Finished executing: losetup " + loDevName + " " + absoluteFileName);
        LOG.info("Result of: losetup " + loDevName + " " + absoluteFileName + " stdout: "
                + output.getReturnValue());
        LOG.info("Result of: losetup" + loDevName + " " + absoluteFileName + " return value: "
                + error.getReturnValue());
        return errorCode;
    } catch (Exception t) {
        LOG.error(t);
    }
    return -1;
}

From source file:com.flexive.shared.FxSharedUtils.java

/**
 * Execute a command on the operating system
 *
 * @param command   name of the command/*from  w w w .j  av a2 s .  c  o m*/
 * @param arguments arguments to pass to the command (one argument per String!)
 * @return result
 */

public static ProcessResult executeCommand(String command, String... arguments) {
    Runtime r = Runtime.getRuntime();
    String[] cmd = new String[arguments.length + (WINDOWS ? 3 : 1)];
    if (WINDOWS) {
        //have to run a shell on windows
        cmd[0] = "cmd";
        cmd[1] = "/c";
    }

    cmd[WINDOWS ? 2 : 0] = command;
    System.arraycopy(arguments, 0, cmd, (WINDOWS ? 3 : 1), arguments.length);
    StringBuilder cmdline = new StringBuilder(200);
    cmdline.append(command);
    for (String argument : arguments)
        cmdline.append(" ").append(argument);
    Process p = null;
    AsyncStreamBuffer out = null;
    AsyncStreamBuffer err = null;
    try {
        p = r.exec(cmd);
        //            p = r.exec(cmdline);
        out = new AsyncStreamBuffer(p.getInputStream());
        err = new AsyncStreamBuffer(p.getErrorStream());
        out.start();
        err.start();
        p.waitFor();
        while (out.isAlive())
            Thread.sleep(10);
        while (err.isAlive())
            Thread.sleep(10);
    } catch (Exception e) {
        String error = e.getMessage();
        if (err != null && err.getResult() != null && err.getResult().trim().length() > 0)
            error = error + "(" + err.getResult() + ")";
        return new ProcessResult(cmdline.toString(), (p == null ? -1 : p.exitValue()),
                (out == null ? "" : out.getResult()), error);
    } finally {
        if (p != null) {
            try {
                p.getInputStream().close();
            } catch (Exception e1) {
                //bad luck
            }
            try {
                p.getErrorStream().close();
            } catch (Exception e1) {
                //bad luck
            }
            try {
                p.getOutputStream().close();
            } catch (Exception e1) {
                //bad luck
            }
        }
    }
    return new ProcessResult(cmdline.toString(), p.exitValue(), out.getResult(), err.getResult());
}

From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationHcontentModuleImpl.java

@Override
public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationHcontentException {
    // Ausgabe SIARD-Modul Ersichtlich das KOST-Val arbeitet
    System.out.print("H   ");
    System.out.print("\r");
    int onWork = 41;

    boolean valid = true;
    try {/*from w  w w. ja  va  2s  .  c  om*/
        /* Extract the metadata.xml from the temporary work folder and build a jdom document */
        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        pathToWorkDir = pathToWorkDir + File.separator + "SIARD";
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());
        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /* read the document and for each schema and table entry verify existence in temporary
         * extracted structure */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");
        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            Element schemaFolder = schema.getChild("folder", ns);
            File schemaPath = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("content")
                    .append(File.separator).append(schemaFolder.getText()).toString());
            if (schemaPath.isDirectory()) {
                Element[] tables = schema.getChild("tables", ns).getChildren("table", ns)
                        .toArray(new Element[0]);
                for (Element table : tables) {
                    Element tableFolder = table.getChild("folder", ns);
                    File tablePath = new File(new StringBuilder(schemaPath.getAbsolutePath())
                            .append(File.separator).append(tableFolder.getText()).toString());
                    if (tablePath.isDirectory()) {
                        File tableXml = new File(new StringBuilder(tablePath.getAbsolutePath())
                                .append(File.separator).append(tableFolder.getText() + ".xml").toString());
                        File tableXsd = new File(new StringBuilder(tablePath.getAbsolutePath())
                                .append(File.separator).append(tableFolder.getText() + ".xsd").toString());
                        // TODO: hier erfolgt die Validerung
                        if (verifyRowCount(tableXml, tableXsd)) {

                            // valid = validate1( tableXml, tableXsd ) && valid;

                            // xmllint via cmd
                            // resources\xmllint\xmllint --noout --stream --schema tableXsd tableXml
                            try {
                                // Pfad zum Programm xmllint existiert die Dateien?
                                String pathToxmllintExe = "resources" + File.separator + "xmllint"
                                        + File.separator + "xmllint.exe";
                                String pathToxmllintDll1 = "resources" + File.separator + "xmllint"
                                        + File.separator + "iconv.dll";
                                String pathToxmllintDll2 = "resources" + File.separator + "xmllint"
                                        + File.separator + "libxml2.dll";
                                String pathToxmllintDll3 = "resources" + File.separator + "xmllint"
                                        + File.separator + "zlib1.dll";

                                File fpathToxmllintExe = new File(pathToxmllintExe);
                                File fpathToxmllintDll1 = new File(pathToxmllintDll1);
                                File fpathToxmllintDll2 = new File(pathToxmllintDll2);
                                File fpathToxmllintDll3 = new File(pathToxmllintDll3);
                                if (!fpathToxmllintExe.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT1_MISSING));
                                    valid = false;
                                } else if (!fpathToxmllintDll1.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT2_MISSING));
                                    valid = false;
                                } else if (!fpathToxmllintDll2.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT3_MISSING));
                                    valid = false;
                                } else if (!fpathToxmllintDll3.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT4_MISSING));
                                    valid = false;
                                } else {

                                    StringBuffer command = new StringBuffer("resources" + File.separator
                                            + "xmllint" + File.separator + "xmllint ");
                                    command.append("--noout --stream ");
                                    command.append(" --schema ");
                                    command.append(" ");
                                    command.append("\"");
                                    command.append(tableXsd.getAbsolutePath());
                                    command.append("\"");
                                    command.append(" ");
                                    command.append("\"");
                                    command.append(tableXml.getAbsolutePath());
                                    command.append("\"");

                                    Process proc = null;
                                    Runtime rt = null;

                                    try {
                                        File outTableXml = new File(pathToWorkDir + File.separator + "SIARD_H_"
                                                + tableXml.getName() + ".txt");

                                        Util.switchOffConsoleToTxt(outTableXml);

                                        rt = Runtime.getRuntime();
                                        proc = rt.exec(command.toString().split(" "));
                                        // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden
                                        // ist!

                                        // Fehleroutput holen

                                        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(),
                                                "ERROR-" + tableXml.getName());

                                        // Output holen
                                        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(),
                                                "OUTPUT-" + tableXml.getName());

                                        // Threads starten
                                        errorGobbler.start();
                                        outputGobbler.start();

                                        // Warte, bis wget fertig ist 0 = Alles io
                                        int exitStatus = proc.waitFor();

                                        // 200ms warten bis die Konsole umgeschaltet wird, damit wirklich alles im
                                        // file landet
                                        Thread.sleep(200);
                                        Util.switchOnConsole();

                                        if (0 != exitStatus) {
                                            // message.xml.h.invalid.xml = <Message>{0} ist invalid zu
                                            // {1}</Message></Error>
                                            getMessageService().logError(
                                                    getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                                                            + getTextResourceService().getText(
                                                                    MESSAGE_XML_H_INVALID_XML,
                                                                    tableXml.getName(), tableXsd.getName()));
                                            valid = false;

                                            // Fehlermeldung aus outTableXml auslesen

                                            BufferedReader br = new BufferedReader(new FileReader(outTableXml));
                                            try {
                                                String line = br.readLine();
                                                String linePrev = null;
                                                /* Fehlermeldungen holen, ausser die letzte, die besagt, dass es invalide
                                                 * ist (wurde bereits oben in D, F,E ausgegeben */
                                                while (line != null) {
                                                    if (linePrev != null) {
                                                        getMessageService().logError(getTextResourceService()
                                                                .getText(MESSAGE_XML_MODUL_H_SIARD)
                                                                + getTextResourceService().getText(
                                                                        MESSAGE_XML_H_INVALID_ERROR, linePrev));
                                                    }
                                                    linePrev = line;
                                                    line = br.readLine();
                                                }
                                            } finally {
                                                br.close();

                                                /* Konsole zuerst einmal noch umleiten und die Streams beenden, damit die
                                                 * dateien gelscht werden knnen */
                                                Util.switchOffConsoleToTxtClose(outTableXml);
                                                System.out.println(" . ");
                                                Util.switchOnConsole();
                                                Util.deleteFile(outTableXml);

                                            }
                                        } else {
                                            /* Konsole zuerst einmal noch umleiten und die Streams beenden, damit die
                                             * dateien gelscht werden knnen */
                                            Util.switchOffConsoleToTxtClose(outTableXml);
                                            System.out.println(" . ");
                                            Util.switchOnConsole();
                                            Util.deleteFile(outTableXml);

                                        }
                                        /* Konsole zuerst einmal noch umleiten und die Streams beenden, damit die
                                         * dateien gelscht werden knnen */
                                        Util.switchOffConsoleToTxtClose(outTableXml);
                                        System.out.println(" . ");
                                        Util.switchOnConsole();
                                        Util.deleteFile(outTableXml);

                                    } catch (Exception e) {
                                        getMessageService().logError(
                                                getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                                                        + getTextResourceService().getText(ERROR_XML_UNKNOWN,
                                                                e.getMessage()));
                                        return false;
                                    } finally {
                                        if (proc != null) {
                                            closeQuietly(proc.getOutputStream());
                                            closeQuietly(proc.getInputStream());
                                            closeQuietly(proc.getErrorStream());
                                        }
                                    }
                                }
                            } finally {
                            }
                        }
                    }
                    if (onWork == 41) {
                        onWork = 2;
                        System.out.print("H-   ");
                        System.out.print("\r");
                    } else if (onWork == 11) {
                        onWork = 12;
                        System.out.print("H\\   ");
                        System.out.print("\r");
                    } else if (onWork == 21) {
                        onWork = 22;
                        System.out.print("H|   ");
                        System.out.print("\r");
                    } else if (onWork == 31) {
                        onWork = 32;
                        System.out.print("H/   ");
                        System.out.print("\r");
                    } else {
                        onWork = onWork + 1;
                    }
                }
            }
            if (onWork == 41) {
                onWork = 2;
                System.out.print("H-   ");
                System.out.print("\r");
            } else if (onWork == 11) {
                onWork = 12;
                System.out.print("H\\   ");
                System.out.print("\r");
            } else if (onWork == 21) {
                onWork = 22;
                System.out.print("H|   ");
                System.out.print("\r");
            } else if (onWork == 31) {
                onWork = 32;
                System.out.print("H/   ");
                System.out.print("\r");
            } else {
                onWork = onWork + 1;
            }
        }
    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, ioe.getMessage() + " (IOException)"));
    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (JDOMException)"));
    } catch (SAXException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (SAXException)"));
    }

    return valid;
}

From source file:com.ikanow.infinit.e.core.mapreduce.HadoopJobRunner.java

@SuppressWarnings("unused")
private String runHadoopJob_commandLine(CustomMapReduceJobPojo job, String jar) {
    String jobid = null;/*from w  w  w .  j a  va  2 s  .c  o m*/
    try {
        job.tempConfigXMLLocation = createConfigXML_commandLine(job.jobtitle, job.inputCollection,
                job._id.toString(), job.tempConfigXMLLocation, job.mapper, job.reducer, job.combiner,
                getQueryOrProcessing(job.query, QuerySpec.QUERY), job.communityIds, job.isCustomTable,
                job.getOutputDatabase(), job.outputKey, job.outputValue, job.outputCollectionTemp,
                job.arguments);
        Runtime rt = Runtime.getRuntime();
        String[] commands = new String[] { "hadoop", "--config", prop_custom.getHadoopConfigPath() + "/hadoop",
                "jar", jar, "-conf", job.tempConfigXMLLocation };
        String command = "";
        for (String s : commands)
            command += s + " ";
        Process pr = rt.exec(commands);

        //Once we start running the command attach to stderr to
        //receive the output to parse out the jobid
        InputStream in = pr.getErrorStream();
        InputStreamReader is = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(is);
        StringBuilder output = new StringBuilder();
        String line = null;

        long startTime = new Date().getTime();
        boolean bGotJobId = false;
        //while we haven't found the id, there are still lines to read, and it hasn't been more than 60 seconds
        while (!bGotJobId && (line = br.readLine()) != null
                && (new Date().getTime() - startTime) < SECONDS_60) {
            output.append(line);
            int getJobIdIndex = -1;
            String searchstring = "INFO mapred.JobClient: Running job: ";
            if ((getJobIdIndex = line.indexOf(searchstring)) >= 0) {
                // Get JobId and trim() it (obviously trivial)
                jobid = line.substring(getJobIdIndex + searchstring.length()).trim();
                bGotJobId = true;
            }
        }

        //60 seconds passed and we never found the id
        if (!bGotJobId) {
            _logger.info("job_start_timeout_error_title=" + job.jobtitle + " job_start_timeout_error_id="
                    + job._id.toString() + " job_start_timeout_error_message=" + output.toString());
            //if we never found the id mark it as errored out
            return "Error:\n" + output.toString();
        }
    } catch (Exception ex) {
        //had an error running command
        //probably log error to the job so we stop trying to run it
        _logger.info("job_start_timeout_error_title=" + job.jobtitle + " job_start_timeout_error_id="
                + job._id.toString() + " job_start_timeout_error_message="
                + HarvestExceptionUtils.createExceptionMessage(ex));
        jobid = "Error:\n" + ex.getMessage(); // (means this gets displayed)         
    }
    return jobid;
}

From source file:net.brtly.monkeyboard.shell.ShellCommand.java

/**
 * Execute the command on the current thread with a timeout
 * @param timeOut milliseconds for this command to timeout. A timeout of 0 means to wait forever 
 * @return the exit status of the command, or null if there was an exception
 *//*from   w w w. j  av  a  2s.  c  o  m*/
public Integer execute(final long timeOut) {
    _isRunning = true;
    _status = -1;
    _output = null;
    _error = null;
    final ShellCommand sender = this;
    final String command = getCommand();
    _isRunning = true;
    Process proc = null;
    try {
        // create the process which will run the command
        proc = Runtime.getRuntime().exec(command);

        // consume and record the error and output streams
        final StringBuilder out = new StringBuilder();
        final StringBuilder err = new StringBuilder();
        StreamListener streamListener = new StreamListener() {
            @Override
            public void onOutput(StreamType type, String output) {
                if (output != null) {
                    switch (type) {
                    case STDOUT:
                        out.append(output + '\n');
                        _output = out.toString();
                        getListener().onStdOut(sender, output);
                        break;
                    case STDERR:
                        err.append(output + '\n');
                        _error = err.toString();
                        getListener().onStdErr(sender, output);
                    }
                }
            }
        };
        StreamMonitor osm = new StreamMonitor(proc.getInputStream(), StreamType.STDOUT, streamListener);
        StreamMonitor esm = new StreamMonitor(proc.getErrorStream(), StreamType.STDERR, streamListener);
        osm.start();
        esm.start();

        // create and start a Worker thread which this thread will join for
        // the timeout period
        Worker worker = new Worker(proc);
        worker.setName(command);
        worker.start();
        try {
            worker.join(timeOut);
            _status = worker.getExitValue();
            if (_status == null) {
                // if we get this far then we never got an exit value from the
                // worker thread as a result of a timeout
                String errorMessage = "The command [" + command + "] timed out.";
                LOG.warn(errorMessage);
            }

            //            throw new RuntimeException(errorMessage);
        } catch (InterruptedException ex) {
            worker.interrupt();
            Thread.currentThread().interrupt();
            //            throw ex;
        }
    } catch (IOException ex) {
        String errorMessage = "The command [" + command + "] did not complete due to an IO error.";
        LOG.warn(errorMessage, ex);
        //         throw new RuntimeException(errorMessage, ex);
    }

    return _status;
}

From source file:ch.kostceco.tools.kostsimy.comparison.moduleim.impl.CompareImageModuleImpl.java

@Override
public boolean validate(File origDatei, File repDatei, File directoryOfLogfile) throws CompareImageException {
    boolean isValid = true;
    // boolean isValidFailed = false;
    boolean compResult = false;
    int allInt = 0;
    boolean allNoInt = false;
    String allStr = "";

    String imToleranceTxt = getConfigurationService().getImTolerance();
    String imTolerance = "5%";
    float percentageInvalid = 99.9999f;
    /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
     * entsprechenden Modul die property anzugeben: <property name="configurationService"
     * ref="configurationService" /> */

    /* Initialisierung ImageMagick -> berprfen der Angaben: existiert die compare.exe,
     * msvcp120.dll, msvcr120.dll, vcomp120.dll am vorgegebenen Ort? */
    String compareExe = "compare.exe";
    String msvcp120Dll = "msvcp120.dll";
    String msvcr120Dll = "msvcr120.dll";
    String vcomp120Dll = "vcomp120.dll";
    String im = "resources" + File.separator + "ImageMagickCompare-6.9.1-Q16";
    boolean imExist = true;
    File fCompareExe = new File(im + File.separator + compareExe);
    if (!fCompareExe.exists()) {
        // Compare.exe von ImageMagick existiert nicht, kein Vergleich --> Abbruch
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                + getTextResourceService().getText(ERROR_XML_IMCMP_MISSING, compareExe));
        imExist = false;/*from  w  ww  .  j  a v a 2  s  .c om*/
    }
    File fMsvcp120Dll = new File(im + File.separator + msvcp120Dll);
    if (!fMsvcp120Dll.exists()) {
        // msvcp120.dll von ImageMagick existiert nicht, kein Vergleich --> Abbruch
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                + getTextResourceService().getText(ERROR_XML_IMCMP_MISSING, msvcp120Dll));
        imExist = false;
    }
    File fMsvcr120Dll = new File(im + File.separator + msvcr120Dll);
    if (!fMsvcr120Dll.exists()) {
        // msvcr120.dll von ImageMagick existiert nicht, kein Vergleich --> Abbruch
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                + getTextResourceService().getText(ERROR_XML_IMCMP_MISSING, msvcr120Dll));
        imExist = false;
    }
    File fVcomp120Dll = new File(im + File.separator + vcomp120Dll);
    if (!fVcomp120Dll.exists()) {
        // vcomp120.dll von ImageMagick existiert nicht, kein Vergleich --> Abbruch
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                + getTextResourceService().getText(ERROR_XML_IMCMP_MISSING, vcomp120Dll));
        imExist = false;
    }
    if (!imExist) {
        // compare.exe/msvcp120.dll/msvcr120.dll/vcomp120.dll von ImageMagick existiert nicht --> Abbruch
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                + getTextResourceService().getText(ERROR_XML_IMCMP_MISSING, vcomp120Dll));
        return false;
    }

    if (imToleranceTxt.contains("N") || imToleranceTxt.contains("n")) {
        // null = 0%
        imTolerance = "0%";
        percentageInvalid = (float) 100.000000000;
        imToleranceTxt = "N";
    } else if (imToleranceTxt.contains("S") || imToleranceTxt.contains("s")) {
        // small = 2%
        imTolerance = "2%";
        percentageInvalid = (float) 99.9999;
        imToleranceTxt = "S";
    } else if (imToleranceTxt.contains("XL") || imToleranceTxt.contains("xl")) {
        // xlarge = 15%
        imTolerance = "15%";
        percentageInvalid = (float) 99.9;
        imToleranceTxt = "XL";
    } else if (imToleranceTxt.contains("L") || imToleranceTxt.contains("l")) {
        // large = 10%
        imTolerance = "10%";
        percentageInvalid = (float) 99.99;
        imToleranceTxt = "L";
    } else {
        // medium = 5%
        imTolerance = "5%";
        imToleranceTxt = "M";
        percentageInvalid = (float) 99.999;
    }
    String pathToCompareExe = fCompareExe.getAbsolutePath();

    File report;
    File reportId;
    String imgPx1 = "1";

    StringBuffer concatenatedOutputs = new StringBuffer();

    try {

        String pathToOutput = directoryOfLogfile.getAbsolutePath() + File.separator + origDatei.getName()
                + "_compare_report.txt";
        String pathToOutputId = directoryOfLogfile.getAbsolutePath() + File.separator + origDatei.getName()
                + "_identify_report.txt";
        String pathToMask = directoryOfLogfile.getAbsolutePath() + File.separator + origDatei.getName()
                + "_mask.jpg";

        /* compare -fuzz 15% -metric AE -quiet -identify -verbose -highlight-color DarkRed Image_1.jpg
         * Image_2.jpg mask.jpg >>results_id.txt 2>results.txt */

        String command = "cmd /c \"\"" + pathToCompareExe + "\" -fuzz " + imTolerance
                + " -metric AE -quiet -identify -verbose -highlight-color DarkRed \""
                + origDatei.getAbsolutePath() + "\" \"" + repDatei.getAbsolutePath() + "\" \"" + pathToMask
                + "\" >>\"" + pathToOutputId + "\" 2>\"" + pathToOutput + "\"";
        /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
         * gehts: cmd /c\"urspruenlicher Befehl\" */

        Process proc = null;
        Runtime rt = null;

        try {
            report = new File(pathToOutput);
            reportId = new File(pathToOutputId);
            // falls das File bereits existiert, z.B. von einem vorhergehenden Durchlauf, lschen
            // wir es
            if (report.exists()) {
                report.delete();
            }
            if (reportId.exists()) {
                reportId.delete();
            }
            Util.switchOffConsole();
            rt = Runtime.getRuntime();
            proc = rt.exec(command.toString().split(" "));
            // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden ist!

            // Fehleroutput holen
            StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

            // Output holen
            StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");

            // Threads starten
            errorGobbler.start();
            outputGobbler.start();

            // Warte, bis wget fertig ist
            proc.waitFor();

            Util.switchOnConsole();
            // Kontrolle ob die Reports existieren
            if (!report.exists()) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                        + getTextResourceService().getText(ERROR_XML_IMCMP_NOREPORT, report.getAbsolutePath()));
                if (!reportId.exists()) {
                    getMessageService().logError(
                            getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService()
                                    .getText(ERROR_XML_IMCMP_NOREPORT, reportId.getAbsolutePath()));
                    return false;
                }
                return false;
            }
            if (!reportId.exists()) {
                getMessageService().logError(
                        getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService()
                                .getText(ERROR_XML_IMCMP_NOREPORT, reportId.getAbsolutePath()));
                return false;
            }
        } catch (Exception e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                    + getTextResourceService().getText(ERROR_XML_IMCMP_SERVICEFAILED, e.getMessage()));
            return false;
        } finally {
            if (proc != null) {
                closeQuietly(proc.getOutputStream());
                closeQuietly(proc.getInputStream());
                closeQuietly(proc.getErrorStream());
            }
        }
        // Kontrolle ob die Reports existieren
        if (!report.exists()) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                    + getTextResourceService().getText(ERROR_XML_IMCMP_NOREPORT, report.getAbsolutePath()));
            if (!reportId.exists()) {
                getMessageService().logError(
                        getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService()
                                .getText(ERROR_XML_IMCMP_NOREPORT, reportId.getAbsolutePath()));
                return false;
            }
            return false;
        }
        if (!reportId.exists()) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                    + getTextResourceService().getText(ERROR_XML_IMCMP_NOREPORT, reportId.getAbsolutePath()));
            return false;
        }

        // Ende IMCMP direkt auszulsen

        // TODO: Marker: ReportId und auswerten (Grsse und der Pixel)
        try {
            BufferedReader in = new BufferedReader(new FileReader(reportId));
            String line;
            String imgSize1 = "1";
            String imgSize2 = "2";
            String imgPx2 = "2";

            while ((line = in.readLine()) != null) {

                concatenatedOutputs.append(line);
                concatenatedOutputs.append(NEWLINE);

                /* Format: TIFF (Tagged Image File Format) Mime type: image/tiff
                 * 
                 * Geometry: 2469x3568+0+0
                 * 
                 * Channel statistics:
                 * 
                 * Pixels: 8809392
                 * 
                 * Geometry und Pixels scheinen immer ausgegeben zu werden
                 * 
                 * Gemotry und Pixels mssen identisch sein */
                if (line.contains("  Geometry: ")) {
                    if (imgSize1.equals("1")) {
                        imgSize1 = line;
                    } else {
                        imgSize2 = line;
                    }
                } else if (line.contains("  Pixels: ")) {
                    if (imgPx1.equals("1")) {
                        imgPx1 = line;
                    } else {
                        imgPx2 = line;
                    }
                }

                // TODO: Marker: Auswertung und Fehlerausgabe wenn nicht bestanden.
            }
            if (imgPx1.equals("1") && imgPx2.equals("2") && imgSize1.equals("1") && imgSize2.equals("2")) {
                // identify_report ist leer oder enthlt nicht das was er sollte
                isValid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                        + getTextResourceService().getText(ERROR_XML_IMCMP_NOREPORTTEXT));
                in.close();
                return false;
            }
            if (!imgPx1.equals(imgPx2)) {
                // die beiden Bilder haben nicht gleich viel Pixels
                isValid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                        + getTextResourceService().getText(ERROR_XML_CI_PIXELINVALID, imgPx1, imgPx2));
            }
            if (!imgSize1.equals(imgSize2)) {
                // die beiden Bilder sind nicht gleich gross
                isValid = false;
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                        + getTextResourceService().getText(ERROR_XML_CI_SIZEINVALID, imgSize1, imgSize2));
            }
            if (!isValid) {
                // die beiden Bilder sind nicht gleich gross
                in.close();
                return false;
            }
            in.close();
        } catch (Exception e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                    + getTextResourceService().getText(ERROR_XML_UNKNOWN, "identify: " + e.getMessage()));
            return false;
        }

        // TODO: Marker: Report auswerten (Bildvergleich) wenn grsse & PixelAnzahl identisch
        try {
            BufferedReader in = new BufferedReader(new FileReader(report));
            String line;
            boolean allNull = false;
            boolean allExist = false;

            while ((line = in.readLine()) != null) {

                concatenatedOutputs.append(line);
                concatenatedOutputs.append(NEWLINE);

                /* img1.tif[0] TIFF 2469x3568 2469x3568+0+0 8-bit Grayscale Gray 8.833MB 1.451u 0:01.774
                 * 
                 * img2.jp2[0] JP2 2469x3568 2469x3568+0+0 8-bit Gray 1.842MB 1.357u 0:01.378
                 * 
                 * all: 0
                 * 
                 * in den ersten zwei zeilen sind die eigenschaften der beiden Bilder enthalten
                 * 
                 * Danach die Anzahl Pixel mit einer grsseren Abweichung aus, allg: 0= vergleichbar */
                if (line.contains(" all: ")) {
                    allExist = true;
                    if (line.contains(" all: 0")) {
                        allNull = true;
                    } else {
                        /* Invalide Px extrahieren "    all: 3563" extrahieren */
                        String lineReportAll = line.substring(9);
                        try {
                            // lineReport = 3563
                            allInt = Integer.parseInt(lineReportAll);
                        } catch (Exception e) {
                            allNoInt = true;
                            allStr = lineReportAll;
                        }
                    }
                }

                if (allNull) {
                    compResult = true;
                }
            }
            in.close();
            if (!allExist) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                        + getTextResourceService().getText(ERROR_XML_IMCMP_NOALL));
                return false;
            }
            if (!compResult) {
                // Bildvergleich nicht bestanden
                if (allNoInt) {
                    /* Bilder mit vielen Pixels die Abweichen (Potenz -> String): Vereinfachte Fehlerausgabe */

                    /* Invalide [allStr] und total px z2 aus imgPx1 "    Pixels: 8809392" extrahieren */
                    String lineReport = imgPx1.substring(12);
                    // lineReport = 8809392

                    isValid = false;

                    getMessageService().logError(
                            getTextResourceService().getText(MESSAGE_XML_MODUL_CI) + getTextResourceService()
                                    .getText(ERROR_XML_CI_CIINVALIDSTR, lineReport, imToleranceTxt, allStr));

                } else {
                    /* Bilder mit einer Abweichung (Int): Prozent ermitteln und mit percentageInvalid
                     * abgleichen */
                    double z1 = 0;
                    double z2 = 0;
                    float percentageCalc = (float) 0.0;
                    float percentageCalcInv = (float) 0.0;

                    /* Invalide z1 [allInt] und total px z2 aus imgPx1 "    Pixels: 8809392" extrahieren */
                    String lineReport = imgPx1.substring(12);
                    // lineReport = 8809392
                    z2 = Double.parseDouble(lineReport);
                    z1 = allInt;

                    percentageCalc = (float) (100 - (100 / z2 * z1));
                    percentageCalcInv = 100 - percentageCalc;

                    // Prozentzahlen vergleichen
                    if (percentageInvalid > percentageCalc) {
                        // Bilder mit einer grsseren Abweichung
                        isValid = false;

                        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                                + getTextResourceService().getText(ERROR_XML_CI_CIINVALID, percentageCalcInv,
                                        z2, imToleranceTxt, z1));
                    }
                }
            }
        } catch (Exception e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                    + getTextResourceService().getText(ERROR_XML_UNKNOWN, "compare: " + e.getMessage()));
            return false;
        }
    } catch (Exception e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_CI)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        return false;
    }

    // reports lschen
    if (report.exists()) {
        report.delete();
    }
    if (reportId.exists()) {
        reportId.delete();
    }

    return isValid;
}

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

/**
 * Runs a command specified by a compiler invocation.
 *
 * @param compilerInvocation/*from   ww w . j  a va2  s .  c  o  m*/
 *            specifies what program with which flags is being executed
 * @param pathToSourceFolder
 *            the path to the source folder of the submission
 * @return CompilerOutput with fields initialized according to the outcome
 *         of the process
 * @throws BadFlagException
 *             if a flag is not known to javac
 */
private CompilerOutput runJavacProcess(List<String> compilerInvocation, Path pathToSourceFolder, boolean junit)
        throws BadFlagException {
    Process compilerProcess = null;
    try {
        ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation);
        // make sure the compiler stays in its directory.
        if (Files.isDirectory(pathToSourceFolder, LinkOption.NOFOLLOW_LINKS)) {
            compilerProcessBuilder.directory(pathToSourceFolder.toFile());
        } else {
            compilerProcessBuilder.directory(pathToSourceFolder.getParent().toFile());
        }
        compilerProcess = compilerProcessBuilder.start();
    } catch (IOException e) {
        // If we cannot call the compiler we return a CompilerOutput
        // which is
        // 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 javac reports
    // nothing at all.
    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);
        }

        compilerOutputStream.close();
        compilerStreamReader.close();
        compilerOutputBuffer.close();
        compilerProcess.destroy();
    } catch (IOException e) {
        // Reading might go wrong here if javac should unexpectedly
        // terminate
        LOGGER.severe("Could not read compiler ourput from its output stream." + " Aborting compile of: "
                + pathToSourceFolder.toString() + " Got message: " + e.getMessage());
        compilerOutput.setClean(false);
        compilerOutput.setCompileStreamBroken(true);
        return compilerOutput;
    }

    splitCompilerOutput(compilerOutputLines, compilerOutput);

    if (compilerOutputLines.size() == 0) {
        compilerOutput.setClean(true);
    }

    return compilerOutput;
}

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

@Override
public CompilerOutput checkProgram(Path pathToProgramFile, Path outputFolder, String compilerName,
        List<String> compilerFlags)
        throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException {

    // First we build the command to invoke the compiler. This consists of
    // the compiler executable, the path of the
    // file to compile and compiler flags. So for example we call:
    List<String> compilerInvocation = createCompilerInvocation(pathToProgramFile, compilerName, compilerFlags);
    // Now we build a launchable process from the given parameters and set
    // the working directory.
    Process compilerProcess = null;

    try {/*from w ww  . j ava  2 s .  com*/
        ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation);
        // make sure the compiler stays in its directory.
        if (Files.isDirectory(pathToProgramFile)) {
            compilerProcessBuilder.directory(pathToProgramFile.toFile());
        } else {
            compilerProcessBuilder.directory(pathToProgramFile.getParent().toFile());
        }
        compilerProcess = compilerProcessBuilder.start();
    } 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);
        LOGGER.severe("Couldn't launch GCC. Check whether it's in the system's PATH");
        return compilerInvokeError;
    }

    // Now we read compiler output. If everything is ok gcc reports
    // nothing at all.
    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);
        }

        compilerOutputStream.close();
        compilerStreamReader.close();
        compilerOutputBuffer.close();
        compilerProcess.destroy();
    } catch (IOException e) {
        // Reading might go wrong here if gcc should unexpectedly terminate
        LOGGER.severe("Error while reading from compiler stream.");
        compilerOutput.setClean(false);
        compilerOutput.setCompileStreamBroken(true);
        return compilerOutput;
    }

    if (compilerOutputLines.size() == 0) {
        compilerOutput.setClean(true);
    }

    compilerOutput = splitCompilerOutput(compilerOutputLines, compilerOutput);

    // delete all .o and .exe files
    // these are output files generated by gcc which we won't need
    // anymore
    File[] candidateToplevelFiles = pathToProgramFile.toFile().listFiles();
    for (File candidateFile : candidateToplevelFiles) {
        if (!candidateFile.isDirectory()) {
            String extension = FilenameUtils.getExtension(candidateFile.toString());
            if (extension.matches("([Oo]|([Ee][Xx][Ee]))")) {
                // We only pass the filename, since gcc will be
                // confined to the dir the file is located in.
                candidateFile.delete();
            }
        }

    }

    return compilerOutput;
}