Example usage for java.lang Process getErrorStream

List of usage examples for java.lang Process getErrorStream

Introduction

In this page you can find the example usage for java.lang Process getErrorStream.

Prototype

public abstract InputStream getErrorStream();

Source Link

Document

Returns the input stream connected to the error output of the process.

Usage

From source file:com.github.lindenb.mscheduler.MScheduler.java

private int build(final String argv[]) {
    Transaction txn = null;/*from w w  w. j  av  a2s.com*/
    BufferedReader in = null;
    String makeExecutable = "make";
    try {
        this.options
                .addOption(Option.builder(OPTION_MAKE_EXECUTABLE).hasArg(true).longOpt(OPTION_MAKE_EXECUTABLE)
                        .argName("MAKE").desc("make executable. Default: " + makeExecutable).build());

        this.options.addOption(Option.builder(OPTION_MAKEFILEIN).hasArg(true).longOpt("makefile").argName("DIR")
                .desc("debug Makefile").build());

        final CommandLineParser parser = new DefaultParser();
        this.cmdLine = parser.parse(this.options, argv);
        final List<String> args = this.cmdLine.getArgList();

        if (cmdLine.hasOption(OPTION_MAKE_EXECUTABLE)) {
            makeExecutable = cmdLine.getOptionValue(OPTION_MAKE_EXECUTABLE);
        }

        if (cmdLine.hasOption(OPTION_HELP)) {
            return printHelp("build");
        }

        if (parseWorkingDirectory() != 0)
            return -1;

        if (!cmdLine.hasOption(OPTION_MAKEFILEIN)) {
            LOG.error("option -" + OPTION_MAKEFILEIN + " undefined");
            return -1;
        }
        final File makefileIn = new File(cmdLine.getOptionValue(OPTION_MAKEFILEIN));
        if (!makefileIn.exists()) {
            System.err.println("Option -" + OPTION_MAKEFILEIN + " file doesn't exists: " + makefileIn);
            return -1;
        }

        if (!makefileIn.isFile()) {
            System.err.println("Option -" + OPTION_MAKEFILEIN + " this is not a file : " + makefileIn);
            return -1;
        }
        if (!makefileIn.isAbsolute() || makefileIn.getParentFile() == null) {
            System.err.println("Option -" + OPTION_MAKEFILEIN + " path is not absolute : " + makefileIn);
            return -1;
        }

        if (openEnvironement(txn, true, false) != 0) {
            return -1;
        }

        final List<String> cmdargs = new ArrayList<>();
        cmdargs.add(makeExecutable);
        cmdargs.add("-ndr");
        cmdargs.add("-C");
        cmdargs.add(makefileIn.getParentFile().getPath());
        cmdargs.add("-f");
        cmdargs.add(makefileIn.getName());
        for (final String arg : args)
            cmdargs.add(arg);

        LOG.info("invoking make :" + String.join(" ", cmdargs));
        final ProcessBuilder procbuilder = new ProcessBuilder(cmdargs);
        procbuilder.directory(makefileIn.getParentFile());

        final Process proc = procbuilder.start();
        final StreamBoozer sb = new StreamBoozer(proc.getErrorStream(), System.err, "[make]");
        sb.start();

        LOG.info("Reading graph");
        in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        final Graph graph = Graph.parse(in);
        IoUtils.close(in);
        in = null;
        final Task.Binding taskBinding = new Task.Binding();
        int nTargets = 0;
        LOG.info("inserting targets");
        final DatabaseEntry key = new DatabaseEntry();
        final DatabaseEntry data = new DatabaseEntry();
        for (final Target t : graph.getTargets()) {
            if (nTargets++ % 100 == 0)
                LOG.info("inserting " + t.getName() + " " + nTargets);
            final Task task = new Task(t);

            //skip those targets, eg. "Makefile"
            if (task.shellScriptLines.isEmpty() && task.getPrerequisites().isEmpty()) {
                task.targetStatus = TaskStatus.COMPLETED;
            }

            StringBinding.stringToEntry(t.getName(), key);
            taskBinding.objectToEntry(task, data);
            if (this.targetsDatabase.put(txn, key, data) != OperationStatus.SUCCESS) {
                LOG.error("Cannot insert " + task);
                return -1;
            }
        }

        LOG.info("inserting metadata");
        StringBinding.stringToEntry(BASEDIRKEY, key);
        StringBinding.stringToEntry(makefileIn.getParentFile().getPath(), data);
        if (this.metaDatabase.put(txn, key, data) != OperationStatus.SUCCESS) {
            LOG.error("Cannot insert " + BASEDIRKEY);
            return -1;
        }

        return 0;
    } catch (Exception err) {
        LOG.error("Boum", err);
        return -1;
    } finally {
        close();
    }
}

From source file:com.ikanow.infinit.e.processing.custom.launcher.CustomHadoopTaskLauncher.java

public String runHadoopJob_commandLine(CustomMapReduceJobPojo job, String jar) {
    String jobid = null;/* w w  w  . j  a v a 2 s.  com*/
    try {
        job.tempConfigXMLLocation = createConfigXML_commandLine(job.jobtitle, job.inputCollection,
                job._id.toString(), job.tempConfigXMLLocation, job.mapper, job.reducer, job.combiner,
                InfiniteHadoopUtils.getQueryOrProcessing(job.query, InfiniteHadoopUtils.QuerySpec.QUERY),
                job.communityIds, job.isCustomTable, job.getOutputDatabase(), job.outputKey, job.outputValue,
                job.outputCollectionTemp, job.arguments, job.incrementalMode, job.submitterID, job.selfMerge,
                job.outputCollection, job.appendResults);
        Runtime rt = Runtime.getRuntime();
        String[] commands = new String[] { "hadoop", "--config", props_custom.getHadoopConfigPath() + "/hadoop",
                "jar", jar, "-conf", job.tempConfigXMLLocation };
        String command = "";
        for (String s : commands)
            command += s + " ";
        Process pr = rt.exec(command);

        //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) < InfiniteHadoopUtils.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="
                + InfiniteHadoopUtils.createExceptionMessage(ex));
        jobid = "Error:\n" + ex.getMessage(); // (means this gets displayed)         
    }
    return jobid;
}

From source file:canreg.client.analysis.Tools.java

public static LinkedList<String> callR(String rScript, String rpath, String reportFileName)
        throws TableErrorException {
    LinkedList<String> filesCreated = new LinkedList<String>();
    Runtime rt = Runtime.getRuntime();
    ArrayList<String> commandList = new ArrayList<String>();
    commandList.add(rpath);/*from ww w . j a v  a2  s.  c  o  m*/
    commandList.add("CMD");
    commandList.add("BATCH");
    commandList.add("--vanilla");
    commandList.add("--slave");
    commandList.add(rScript);
    commandList.add(reportFileName);

    //String command = canreg.common.Tools.encapsulateIfNeeded(rpath)
    //        + " CMD BATCH --vanilla --slave "
    //        + canreg.common.Tools.encapsulateIfNeeded(rScript) + " "
    //        + canreg.common.Tools.encapsulateIfNeeded(reportFileName);
    System.out.println(commandList);
    Process pr = null;
    try {
        pr = rt.exec(commandList.toArray(new String[] {}));
        // collect the output from the R program in a stream
        // BufferedInputStream is = new BufferedInputStream(pr.getInputStream());
        pr.waitFor();
        BufferedInputStream is = new BufferedInputStream(new FileInputStream(reportFileName));
        // convert the output to a string
        String theString = convertStreamToString(is);
        Logger.getLogger(RTableBuilderGrouped.class.getName()).log(Level.INFO, "Messages from R: \n{0}",
                theString);
        // System.out.println(theString);
        // and add all to the list of files to return
        for (String fileName : theString.split("\n")) {
            if (fileName.startsWith("-outFile:")) {
                fileName = fileName.replaceFirst("-outFile:", "");
                if (new File(fileName).exists()) {
                    filesCreated.add(fileName);
                }
            }
        }
    } catch (InterruptedException ex) {
        Logger.getLogger(RTableBuilder.class.getName()).log(Level.SEVERE, null, ex);
    } catch (java.util.NoSuchElementException ex) {
        Logger.getLogger(RTableBuilder.class.getName()).log(Level.SEVERE, null, ex);
        if (pr != null) {
            BufferedInputStream errorStream = new BufferedInputStream(pr.getErrorStream());
            String errorMessage = convertStreamToString(errorStream);
            System.out.println(errorMessage);
            throw new TableErrorException("R says:\n \"" + errorMessage + "\"");
        }
    } catch (IOException ex) {
        Logger.getLogger(Tools.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        if (pr != null) {
            System.out.println(pr.exitValue());
        }
    }
    return filesCreated;
}

From source file:es.ehu.si.ixa.qwn.ppv.CLI.java

private void ukb_compile(String execpath, String kbfile) {
    String graph = FilenameUtils.removeExtension(kbfile);
    graph = graph + ".bin";

    try {// w ww .ja  v a 2s .  co  m
        String[] command = { execpath + File.separator + "compile_kb", "-o", graph, kbfile };
        //System.err.println("UKB komandoa: "+Arrays.toString(command));

        ProcessBuilder ukbBuilder = new ProcessBuilder().command(command);
        //.redirectErrorStream(true);
        Process compile_kb = ukbBuilder.start();
        int success = compile_kb.waitFor();
        //System.err.println("compile_kb succesful? "+success);
        if (success != 0) {
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(compile_kb.getErrorStream()), 1);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.err.println(line);
            }
        }
    } catch (Exception e) {
        System.err.println("Graph compilation: error when calling compile_kb.\n");
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.turn.ttorrent.client.Client.java

private void mergeFiles() {
    for (Torrent.TorrentFile file : this.torrent.files) {
        String filesPath = "";
        for (int i = 0; i < (file.size / this.torrent.pieceLength); i++) {
            filesPath += new File(this.torrent.parentPath, file.getPath() + "." + i).getAbsolutePath() + " ";
            //FilenameUtils.concat(this.torrent.parentPath, file.getPath()+"."+i+" ");
            System.out.println(filesPath);
        }//w  w  w.  jav a2s .  c  o m
        try {
            System.out.println("Complete command " + this.torrent.getCompleteCommand());
            ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c",
                    this.torrent.getCompleteCommand()/*"cat $PART_LIST > $FILE"*/);
            Map<String, String> env = pb.environment();
            env.put("PART_LIST", filesPath);
            env.put("FILE", new File(this.torrent.parentPath, file.getPath()).getAbsolutePath());
            //FilenameUtils.concat(this.torrent.parentPath, file.getPath()));
            Process pr = pb.start();

            BufferedReader bre = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
            String line;
            while ((line = bre.readLine()) != null) {
                System.err.println(line);
            }
            bre.close();

            int exitVal;
            if ((exitVal = pr.waitFor()) != 0)
                ;
            else
                logger.info("Files merged...");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:ch.kostceco.tools.siardexcerpt.excerption.moduleexcerpt.impl.ExcerptCGrepModuleImpl.java

@Override
public boolean validate(File siardDatei, File outFile, String excerptString) throws ExcerptCGrepException {
    // Ausgabe -> Ersichtlich das SIARDexcerpt arbeitet
    int onWork = 41;

    boolean isValid = true;

    File fGrepExe = new File("resources" + File.separator + "grep" + File.separator + "grep.exe");
    String pathToGrepExe = fGrepExe.getAbsolutePath();
    if (!fGrepExe.exists()) {
        // grep.exe existiert nicht --> Abbruch
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fGrepExe.getAbsolutePath()));
        return false;
    } else {//  w ww.  ja v a2s  .co  m
        File fMsys10dll = new File("resources" + File.separator + "grep" + File.separator + "msys-1.0.dll");
        if (!fMsys10dll.exists()) {
            // msys-1.0.dll existiert nicht --> Abbruch
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                    + getTextResourceService().getText(ERROR_XML_C_MISSINGFILE, fMsys10dll.getAbsolutePath()));
            return false;
        }
    }

    File tempOutFile = new File(outFile.getAbsolutePath() + ".tmp");
    String content = "";

    // Record aus Maintable herausholen
    try {
        if (tempOutFile.exists()) {
            Util.deleteDir(tempOutFile);
        }

        /* Nicht vergessen in "src/main/resources/config/applicationContext-services.xml" beim
         * entsprechenden Modul die property anzugeben: <property name="configurationService"
         * ref="configurationService" /> */

        String name = getConfigurationService().getMaintableName();
        String folder = getConfigurationService().getMaintableFolder();
        String cell = getConfigurationService().getMaintablePrimarykeyCell();

        File fMaintable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator
                + "schema0" + File.separator + folder + File.separator + folder + ".xml");

        try {
            // grep "<c11>7561234567890</c11>" table13.xml >> output.txt
            String command = "cmd /c \"" + pathToGrepExe + " \"<" + cell + ">" + excerptString + "</" + cell
                    + ">\" " + fMaintable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\"";
            /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
             * gehts: cmd /c\"urspruenlicher Befehl\" */

            // System.out.println( command );

            Process proc = null;
            Runtime rt = null;

            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name));

            try {
                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();

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                        + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                return false;
            } finally {
                if (proc != null) {
                    closeQuietly(proc.getOutputStream());
                    closeQuietly(proc.getInputStream());
                    closeQuietly(proc.getErrorStream());
                }
            }

            Scanner scanner = new Scanner(tempOutFile);
            content = "";
            try {
                content = scanner.useDelimiter("\\Z").next();
            } catch (Exception e) {
                // Grep ergab kein treffer Content Null
                content = "";
            }
            scanner.close();

            getMessageService()
                    .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content));
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name));

            if (tempOutFile.exists()) {
                Util.deleteDir(tempOutFile);
            }
            content = "";

            // Ende Grep

        } catch (Exception e) {
            getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                    + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
            return false;
        }

    } catch (Exception e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        return false;
    }

    // Ende MainTable

    // grep der SubTables
    try {
        String name = null;
        String folder = null;
        String cell = null;

        InputStream fin = new FileInputStream(
                new File("configuration" + File.separator + "SIARDexcerpt.conf.xml"));
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /* read the document and for each subTable */
        Namespace ns = Namespace.getNamespace("");

        // select schema elements and loop
        List<Element> subtables = document.getRootElement().getChild("subtables", ns).getChildren("subtable",
                ns);
        for (Element subtable : subtables) {
            name = subtable.getChild("name", ns).getText();
            folder = subtable.getChild("folder", ns).getText();
            cell = subtable.getChild("foreignkeycell", ns).getText();

            // System.out.println( name + " - " + folder + " - " + cell );
            File fSubtable = new File(siardDatei.getAbsolutePath() + File.separator + "content" + File.separator
                    + "schema0" + File.separator + folder + File.separator + folder + ".xml");

            try {
                // grep "<c11>7561234567890</c11>" table13.xml >> output.txt
                String command = "cmd /c \"" + pathToGrepExe + " \"<" + cell + ">" + excerptString + "</" + cell
                        + ">\" " + fSubtable.getAbsolutePath() + " >> " + tempOutFile.getAbsolutePath() + "\"";
                /* Das redirect Zeichen verunmglicht eine direkte eingabe. mit dem geschachtellten Befehl
                 * gehts: cmd /c\"urspruenlicher Befehl\" */

                // System.out.println( command );

                Process proc = null;
                Runtime rt = null;

                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_OPEN, name));

                try {
                    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();

                } catch (Exception e) {
                    getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                            + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                    return false;
                } finally {
                    if (proc != null) {
                        closeQuietly(proc.getOutputStream());
                        closeQuietly(proc.getInputStream());
                        closeQuietly(proc.getErrorStream());
                    }
                }

                Scanner scanner = new Scanner(tempOutFile);
                content = "";
                try {
                    content = scanner.useDelimiter("\\Z").next();
                } catch (Exception e) {
                    // Grep ergab kein treffer Content Null
                    content = "";
                }
                scanner.close();

                getMessageService()
                        .logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CONTENT, content));
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_ELEMENT_CLOSE, name));

                if (tempOutFile.exists()) {
                    Util.deleteDir(tempOutFile);
                }
                content = "";

                // Ende Grep

            } catch (Exception e) {
                getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                        + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
                return false;
            }

            // Ende SubTables
            if (onWork == 41) {
                onWork = 2;
                System.out.print("-   ");
                System.out.print("\r");
            } else if (onWork == 11) {
                onWork = 12;
                System.out.print("\\   ");
                System.out.print("\r");
            } else if (onWork == 21) {
                onWork = 22;
                System.out.print("|   ");
                System.out.print("\r");
            } else if (onWork == 31) {
                onWork = 32;
                System.out.print("/   ");
                System.out.print("\r");
            } else {
                onWork = onWork + 1;
            }
        }
        System.out.print("   ");
        System.out.print("\r");
    } catch (Exception e) {
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_C)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage()));
        return false;
    }

    return isValid;
}

From source file:org.openbaton.marketplace.core.VNFPackageManagement.java

private void updateVims() throws IOException, InterruptedException, ClassNotFoundException, SDKException {

    NFVORequestor requestor = new NFVORequestor(obUsername, obPassword, "", obSslEnabled, obNfvoIp, obNfvoPort,
            "1");

    String cmd = "curl -u openbatonOSClient:secret -X POST http://" + obNfvoIp + ":" + obNfvoPort
            + "/oauth/token -H \"Accept:application/json\" -d username=" + obUsername + "&password="
            + obPassword + "&grant_type=password";

    log.debug("Executing command: " + cmd);

    Process process = Runtime.getRuntime().exec(cmd);
    int res = process.waitFor();
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));

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

    String s;/*from w  ww  .  j a  v  a  2 s.com*/
    String output = "";
    String imageId = null;
    if (res != 0) {
        log.warn("Probably the upload of the image went wrong!");
        while ((s = stdError.readLine()) != null) {
            log.warn(s);
        }
    } else {
        while ((s = stdInput.readLine()) != null) {

            output += s;
        }
    }

    log.debug("Result is: " + output);

    String token = new GsonBuilder().create().fromJson(output, JsonObject.class).get("value").getAsString();

    ProjectAgent projectAgent = requestor.getProjectAgent();
    for (Project project : projectAgent.findAll()) {
        requestor.setProjectId(project.getId());
        VimInstanceRestAgent vimInstanceRestAgent = requestor.getVimInstanceAgent();
        vimInstanceRestAgent.setProjectId(project.getId());
        for (VimInstance vimInstance : vimInstanceRestAgent.findAll()) {
            String vimId = vimInstance.getId();
            log.debug("Found Vim Id: " + vimId);
            Runtime.getRuntime()
                    .exec("curl POST -H \"Content-type: application/json\" -H \"Authorization: Bearer " + token
                            + "\" http://" + obNfvoIp + ":" + obNfvoPort + "/api/v1/datacenters/" + vimId
                            + "/refresh");
        }
    }
}

From source file:cc.arduino.Compiler.java

private void callArduinoBuilder(TargetBoard board, TargetPlatform platform, TargetPackage aPackage,
        String vidpid, BuilderAction action, OutputStream outStream, OutputStream errStream)
        throws RunnerException {
    List<String> cmd = new ArrayList<>();
    cmd.add(BaseNoGui.getContentFile("arduino-builder").getAbsolutePath());
    cmd.add(action.value);/* w ww  . j  a  v  a  2s  .co  m*/
    cmd.add("-logger=machine");

    File installedPackagesFolder = new File(BaseNoGui.getSettingsFolder(), "packages");

    addPathFlagIfPathExists(cmd, "-hardware", BaseNoGui.getHardwareFolder());
    addPathFlagIfPathExists(cmd, "-hardware", installedPackagesFolder);
    addPathFlagIfPathExists(cmd, "-hardware", BaseNoGui.getSketchbookHardwareFolder());

    addPathFlagIfPathExists(cmd, "-tools", BaseNoGui.getContentFile("tools-builder"));
    addPathFlagIfPathExists(cmd, "-tools", Paths.get(BaseNoGui.getHardwarePath(), "tools", "avr").toFile());
    addPathFlagIfPathExists(cmd, "-tools", installedPackagesFolder);

    addPathFlagIfPathExists(cmd, "-built-in-libraries", BaseNoGui.getContentFile("libraries"));
    addPathFlagIfPathExists(cmd, "-libraries", BaseNoGui.getSketchbookLibrariesFolder().folder);

    String fqbn = Stream.of(aPackage.getId(), platform.getId(), board.getId(), boardOptions(board))
            .filter(s -> !s.isEmpty()).collect(Collectors.joining(":"));
    cmd.add("-fqbn=" + fqbn);

    if (!"".equals(vidpid)) {
        cmd.add("-vid-pid=" + vidpid);
    }

    cmd.add("-ide-version=" + BaseNoGui.REVISION);
    cmd.add("-build-path");
    cmd.add(buildPath);
    cmd.add("-warnings=" + PreferencesData.get("compiler.warning_level"));

    if (PreferencesData.getBoolean("compiler.cache_core") == true && buildCache != null) {
        cmd.add("-build-cache");
        cmd.add(buildCache.getAbsolutePath());
    }

    PreferencesData.getMap().subTree("runtime.build_properties_custom").entrySet().stream()
            .forEach(kv -> cmd.add("-prefs=" + kv.getKey() + "=" + kv.getValue()));

    cmd.add("-prefs=build.warn_data_percentage=" + PreferencesData.get("build.warn_data_percentage"));

    for (Map.Entry<String, String> entry : BaseNoGui.getBoardPreferences().entrySet()) {
        if (entry.getKey().startsWith("runtime.tools")) {
            cmd.add("-prefs=" + entry.getKey() + "=" + entry.getValue());
        }
    }

    //commandLine.addArgument("-debug-level=10", false);

    if (verbose) {
        cmd.add("-verbose");
    }

    cmd.add(pathToSketch.getAbsolutePath());

    if (verbose) {
        System.out.println(StringUtils.join(cmd, ' '));
    }

    int result;
    try {
        Process proc = ProcessUtils.exec(cmd.toArray(new String[0]));
        MessageSiphon in = new MessageSiphon(proc.getInputStream(), (msg) -> {
            try {
                outStream.write(msg.getBytes());
            } catch (Exception e) {
                exception = new RunnerException(e);
            }
        });
        MessageSiphon err = new MessageSiphon(proc.getErrorStream(), (msg) -> {
            try {
                errStream.write(msg.getBytes());
            } catch (Exception e) {
                exception = new RunnerException(e);
            }
        });

        in.join();
        err.join();
        result = proc.waitFor();
    } catch (Exception e) {
        throw new RunnerException(e);
    }

    if (exception != null)
        throw exception;

    if (result > 1) {
        System.err.println(I18n.format(tr("{0} returned {1}"), cmd.get(0), result));
    }

    if (result != 0) {
        RunnerException re = new RunnerException(
                I18n.format(tr("Error compiling for board {0}."), board.getName()));
        re.hideStackTrace();
        throw re;
    }
}

From source file:es.bsc.servicess.ide.PackagingUtils.java

private static void preInstrumentOrchestration(String runtime, String orchClass, List<String> methods,
        IFolder classes, List<Dependency> depLibraries, IProgressMonitor myProgressMonitor)
        throws CoreException {
    Runtime rt = Runtime.getRuntime();
    if (runtime != null && orchClass != null && methods != null && methods.size() > 0) {
        String classpath = new String();
        for (Dependency d : depLibraries) {
            if (d.getType().equalsIgnoreCase(ProjectMetadata.JAR_DEP_TYPE)
                    || d.getType().equalsIgnoreCase(ProjectMetadata.CLASS_FOLDER_DEP_TYPE))
                classpath = classpath.concat(":" + d.getLocation());
        }/* ww w.j a v  a2  s  . c o  m*/
        boolean first = true;
        String methodsString = new String();
        for (String m : methods) {
            if (first) {
                methodsString = methodsString.concat(m);
                first = false;
            } else
                methodsString = methodsString.concat(" " + m);
        }
        String command = new String(runtime + "/../scripts/pre_instrument.sh "
                + classes.getLocation().toOSString() + classpath + " " + runtime + "/.." + " "
                + classes.getLocation().toOSString() + " " + orchClass + " " + methodsString);
        log.debug("Command to exec: " + command);
        Process ps;
        try {
            ps = rt.exec(command);
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(ps.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(ps.getErrorStream()));
            String s = null;
            // read the output from the command
            log.debug("Here is the standard output of the command:\n");
            while ((s = stdInput.readLine()) != null) {
                log.debug(s);
            }

            // read any errors from the attempted command
            log.debug("Here is the standard error of the command (if any):\n");
            while ((s = stdError.readLine()) != null) {
                log.debug(s);
            }

            // if (ps.exitValue() != 0){
            if (ps.waitFor() != 0) {
                throw (new CoreException(
                        new Status(IStatus.ERROR, Activator.PLUGIN_ID, "metadata info not found")));
            }
        } catch (IOException e) {
            CoreException ce = new CoreException(
                    new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
            ce.setStackTrace(e.getStackTrace());
            throw (ce);
        } catch (InterruptedException e) {
            CoreException ce = new CoreException(
                    new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
            ce.setStackTrace(e.getStackTrace());
            throw (ce);
        }
    } else {
        throw (new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "metadata info not found")));
    }
}

From source file:es.bsc.servicess.ide.PackagingUtils.java

private static void instrumentOrchestrations(String runtime, String[] cls, IFolder classes,
        List<Dependency> depLibraries, IProgressMonitor myProgressMonitor) throws CoreException {
    Runtime rt = Runtime.getRuntime();
    if (runtime != null && cls != null) {
        String classpath = new String();
        for (Dependency d : depLibraries) {
            if (d.getType().equalsIgnoreCase(ProjectMetadata.JAR_DEP_TYPE)
                    || d.getType().equalsIgnoreCase(ProjectMetadata.CLASS_FOLDER_DEP_TYPE))
                classpath = classpath.concat(":" + d.getLocation());
        }/*from w  w  w  .j a va2 s .c o  m*/
        for (String cl : cls) {
            String command = new String(
                    runtime + "/../scripts/instrument.sh " + cl + " " + classes.getLocation().toOSString()
                            + classpath + " " + runtime + "/.." + " " + classes.getLocation().toOSString());
            log.debug("Command to exec: " + command);
            Process ps;
            try {
                ps = rt.exec(command);
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(ps.getInputStream()));

                BufferedReader stdError = new BufferedReader(new InputStreamReader(ps.getErrorStream()));
                String s = null;
                // read the output from the command
                log.debug("Here is the standard output of the command:\n");
                while ((s = stdInput.readLine()) != null) {
                    log.debug(s);
                }

                // read any errors from the attempted command
                log.debug("Here is the standard error of the command (if any):\n");
                while ((s = stdError.readLine()) != null) {
                    log.debug(s);
                }

                // if (ps.exitValue() != 0){
                if (ps.waitFor() != 0) {
                    throw (new CoreException(
                            new Status(IStatus.ERROR, Activator.PLUGIN_ID, "metadata info not found")));
                }
            } catch (IOException e) {
                CoreException ce = new CoreException(
                        new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
                ce.setStackTrace(e.getStackTrace());
                throw (ce);
            } catch (InterruptedException e) {
                CoreException ce = new CoreException(
                        new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
                ce.setStackTrace(e.getStackTrace());
                throw (ce);
            }

        }
    } else {
        throw (new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "metadata info not found")));
    }

}