Example usage for org.apache.commons.exec DefaultExecutor execute

List of usage examples for org.apache.commons.exec DefaultExecutor execute

Introduction

In this page you can find the example usage for org.apache.commons.exec DefaultExecutor execute.

Prototype

public int execute(final CommandLine command) throws ExecuteException, IOException 

Source Link

Usage

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * <pre>/*from   www . j  a va  2 s. c  o  m*/
 * Kill all the TG server processes.
 * Note that this method blindly tries to kill all the servers of the machine 
 * and do not update the running status of those servers.
 * - taskkill on Windows.
 * - kill -9 on Unix.
 * </pre>
 * 
 * @throws Exception Kill operation fails
 */
public static void killAll() throws Exception {

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    executor.setWorkingDirectory(new File(System.getProperty("java.io.tmpdir")));
    CommandLine cmdLine;
    if (OS.isFamilyWindows())
        cmdLine = CommandLine.parse("taskkill /f /im " + process + ".exe");
    else { // Unix
        File internalScriptFile = new File(ClassLoader
                .getSystemResource(
                        TGServer.class.getPackage().getName().replace('.', '/') + "/TGKillProcessByName.sh")
                .getFile());
        File finalScriptFile = new File(executor.getWorkingDirectory() + "/" + internalScriptFile.getName());
        Files.copy(internalScriptFile.toPath(), finalScriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        cmdLine = CommandLine.parse("sh " + finalScriptFile.getAbsolutePath() + " " + process + "");
    }
    try {
        Thread.sleep(1000);
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        if (output.toString().contains(
                "ERROR: The process \"" + process + (OS.isFamilyWindows() ? ".exe\"" : "") + " not found"))
            return;
        throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message
    }
    // Check one more thing :
    // On Windows when some processes do not get killed taskkill still
    // returns exit code
    if (OS.isFamilyWindows()) {
        if (output.toString().contains("ERROR"))
            throw new ExecuteException(output.toString().trim(), 1);
    } else {
        if (output.toString().contains("ERROR: The process \"" + process + "\" not found"))
            return;
    }

    System.out.println("TGServer - Server(s) successfully killed :");
    if (!output.toString().equals(""))
        System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
}

From source file:com.walmart.gatling.commons.ScriptExecutor.java

private Object runJob(Object message) {
    Master.Job job = (Master.Job) message;
    TaskEvent taskEvent = (TaskEvent) job.taskEvent;

    CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand());
    log.info("Verified Script worker received task: {}", message);
    Map<String, Object> map = new HashMap<>();

    if (StringUtils.isNotEmpty(agentConfig.getJob().getMainClass()))
        cmdLine.addArgument(agentConfig.getJob().getCpOrJar());

    map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName())));
    cmdLine.addArgument("${path}");

    if (!StringUtils.isEmpty(agentConfig.getJob().getMainClass())) {
        cmdLine.addArgument(agentConfig.getJob().getMainClass());
    }/*from   ww w.  j a  v a  2  s  . c o  m*/
    //parameters come from the task event
    for (Pair<String, String> pair : taskEvent.getParameters()) {
        cmdLine.addArgument(pair.getValue());
    }
    cmdLine.addArgument("-rf").addArgument(agentConfig.getJob().getResultPath(job.roleId, job.jobId));

    cmdLine.setSubstitutionMap(map);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(agentConfig.getJob().getExitValues());
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(new File(agentConfig.getJob().getPath()));
    FileOutputStream outFile = null;
    FileOutputStream errorFile = null;
    String outPath = "", errPath = "";
    try {
        outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.jobId);
        errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.jobId);
        //create the std and err files
        outFile = FileUtils.openOutputStream(new File(outPath));
        errorFile = FileUtils.openOutputStream(new File(errPath));

        PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile),
                new ExecLogHandler(errorFile));
        executor.setStreamHandler(psh);
        log.info("command: {}", cmdLine);
        int exitResult = executor.execute(cmdLine);
        //executor.getWatchdog().destroyProcess().
        Worker.Result result = new Worker.Result(exitResult, agentConfig.getUrl(errPath),
                agentConfig.getUrl(outPath), null, job);
        log.info("Exit code: {}", exitResult);
        if (executor.isFailure(exitResult) || exitResult == 1) {
            log.info("Script Executor Failed, job: " + job.jobId);
            //getSender().tell(new Worker.WorkFailed(result), getSelf());
            return new Worker.WorkFailed(result);
        } else {
            result = new Worker.Result(exitResult, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                    agentConfig.getUrl(getMetricsPath(job)), job);
            log.info("Script Executor Completed, job: " + result);
            //getSender().tell(new Worker.WorkComplete(result), getSelf());
            return new Worker.WorkComplete(result);
        }

    } catch (IOException e) {
        log.error(e.toString());
        Worker.Result result = new Worker.Result(-1, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath),
                null, job);
        log.info("Executor Encountered run time exception, result: " + result.toString());
        //getSender().tell(new Worker.WorkFailed(result), getSelf());
        return new Worker.WorkFailed(result);
    } finally {
        IOUtils.closeQuietly(outFile);
        IOUtils.closeQuietly(errorFile);
    }
}

From source file:cc.arduino.Compiler.java

private void exec(String[] command) throws RunnerException {
    // eliminate any empty array entries
    List<String> stringList = new ArrayList<>();
    for (String string : command) {
        string = string.trim();/*from w ww  .j av a 2 s.c o  m*/
        if (string.length() != 0)
            stringList.add(string);
    }
    command = stringList.toArray(new String[stringList.size()]);
    if (command.length == 0)
        return;

    if (verbose) {
        for (String c : command)
            System.out.print(c + " ");
        System.out.println();
    }

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler() {

        @Override
        protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted) {
            final Thread result = new Thread(new MyStreamPumper(is, Compiler.this));
            result.setName("MyStreamPumper Thread");
            result.setDaemon(true);
            return result;

        }
    });

    CommandLine commandLine = new DoubleQuotedArgumentsOnWindowsCommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i], false);
    }

    int result;
    executor.setExitValues(null);
    try {
        result = executor.execute(commandLine);
    } catch (IOException e) {
        RunnerException re = new RunnerException(e.getMessage());
        re.hideStackTrace();
        throw re;
    }
    executor.setExitValues(new int[0]);

    // an error was queued up by message(), barf this back to compile(),
    // which will barf it back to Editor. if you're having trouble
    // discerning the imagery, consider how cows regurgitate their food
    // to digest it, and the fact that they have five stomaches.
    //
    //System.out.println("throwing up " + exception);
    if (exception != null)
        throw exception;

    if (result > 1) {
        // a failure in the tool (e.g. unable to locate a sub-executable)
        System.err.println(I18n.format(tr("{0} returned {1}"), command[0], result));
    }

    if (result != 0) {
        RunnerException re = new RunnerException(tr("Error compiling."));
        re.hideStackTrace();
        throw re;
    }
}

From source file:it.drwolf.ridire.session.async.Mapper.java

@SuppressWarnings("unchecked")
private StringWithEncoding transformPDF2HTML(File resourceFile, EntityManager entityManager)
        throws IOException, InterruptedException {
    String workingDirName = System.getProperty("java.io.tmpdir");
    String userDir = System.getProperty("user.dir");
    byte[] buf = new byte[Mapper.BUFLENGTH];
    int count = 0;
    GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(resourceFile));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while ((count = gzis.read(buf)) != -1) {
        baos.write(buf, 0, count);/*from   w  ww.java 2s . co  m*/
    }
    gzis.close();
    baos.close();
    byte[] byteArray = baos.toByteArray();
    String uuid = UUID.randomUUID().toString();
    String pdfFileName = uuid + ".pdf";
    String htmlFileName = uuid + ".html";
    File tmpDir = new File(workingDirName);
    String htmlFileNameCompletePath = workingDirName + JobMapperMonitor.FILE_SEPARATOR + htmlFileName;
    File fileToConvert = new File(tmpDir, pdfFileName);
    FileUtils.writeByteArrayToFile(fileToConvert, byteArray);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    CommandParameter cp = entityManager.find(CommandParameter.class, CommandParameter.PDFTOHTML_EXECUTABLE_KEY);
    CommandLine commandLine = CommandLine.parse(cp.getCommandValue());
    commandLine.addArgument("-c");
    commandLine.addArgument("-i");
    commandLine.addArgument(fileToConvert.getAbsolutePath());
    commandLine.addArgument(htmlFileNameCompletePath);
    executor.setExitValue(0);
    executor.execute(commandLine);
    try {
        FileUtils.moveFileToDirectory(
                new File(userDir + JobMapperMonitor.FILE_SEPARATOR + uuid + "-outline.html"), tmpDir, false);
    } catch (IOException e) {
    }
    cp = entityManager.find(CommandParameter.class, CommandParameter.PDFCLEANER_EXECUTABLE_KEY);
    commandLine = CommandLine
            .parse("java -Xmx128m -jar -Djava.io.tmpdir=" + this.tempDir + " " + cp.getCommandValue());
    commandLine.addArgument(htmlFileNameCompletePath);
    commandLine.addArgument("39");
    commandLine.addArgument("6");
    commandLine.addArgument("5");
    executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.PDFCLEANER_TIMEOUT);
    executor.setWatchdog(watchdog);
    ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024);
    ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, null, null);
    executor.setStreamHandler(executeStreamHandler);
    int exitValue = executor.execute(commandLine);
    String htmlString = null;
    if (exitValue == 0) {
        htmlString = baosStdOut.toString();
    }
    FileUtils.deleteQuietly(new File(htmlFileNameCompletePath));
    PrefixFileFilter pff = new PrefixFileFilter(uuid);
    for (File f : FileUtils.listFiles(tmpDir, pff, null)) {
        FileUtils.deleteQuietly(f);
    }
    if (htmlString != null) {
        htmlString = htmlString.replaceAll("&nbsp;", " ");
        htmlString = htmlString.replaceAll("<br.*?>", " ");
        CharsetDetector charsetDetector = new CharsetDetector();
        charsetDetector.setText(htmlString.getBytes());
        String encoding = charsetDetector.detect().getName();
        return new StringWithEncoding(htmlString, encoding);
    }
    return null;
}

From source file:com.tibco.tgdb.test.lib.TGServer.java

/**
 * <pre>/*w ww  .  j a va2 s. co  m*/
 * Kill the TG server.
 * - taskkill on Windows.
 * - kill -9 on Unix.
 * </pre>
 * 
 * @throws Exception
 *             Kill operation fails
 */
public void kill() throws Exception {

    if (this.pid == 0)
        throw new TGGeneralException(
                "TG server does not have a PID - Probably due to a previous start-up failure");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(output);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(psh);
    CommandLine cmdLine;
    if (OS.isFamilyWindows())
        cmdLine = CommandLine.parse("taskkill /f /pid " + this.getPid() + " /t");
    else
        cmdLine = CommandLine.parse("kill -9 " + this.getPid() + "");
    try {
        executor.execute(cmdLine);
    } catch (ExecuteException ee) {
        // System.out.println("TGServer with pid " + this.getPid() + " not killed :");
        // System.out.println("\t- " + output.toString().trim().replace("\n","\n\t- "));
        throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message
    }
    System.out.println("TGServer - Server with pid " + this.getPid() + " successfully killed :");
    if (!output.toString().equals(""))
        System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- "));
    this.running = false;
    this.pid = 0;
}

From source file:it.drwolf.ridire.session.async.Mapper.java

private StringWithEncoding createPlainTextResource(File f, CrawledResource cr, EntityManager entityManager)
        throws SAXException, TikaException, IOException, TransformerConfigurationException,
        InterruptedException {/* www .  j  av a  2  s  .  c  o  m*/
    File resourceDir = new File(FilenameUtils.getFullPath(f.getCanonicalPath().replaceAll("__\\d+", ""))
            + JobMapperMonitor.RESOURCESDIR);
    String alchemyKey = entityManager.find(Parameter.class, Parameter.ALCHEMY_KEY.getKey()).getValue();
    String readabilityKey = entityManager.find(Parameter.class, Parameter.READABILITY_KEY.getKey()).getValue();
    String resourceFileName = cr.getDigest() + ".gz";
    File resourceFile = new File(resourceDir, resourceFileName);
    StringWithEncoding rawContentAndEncoding = null;
    String contentType = cr.getContentType();
    // long t1 = System.currentTimeMillis();
    if (contentType != null && contentType.contains("application/msword")) {
        rawContentAndEncoding = this.transformDOC2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("application/rtf")) {
        rawContentAndEncoding = this.transformRTF2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("text/plain")) {
        // txt -> html -> txt is for txt cleaning
        rawContentAndEncoding = this.transformTXT2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("pdf")) {
        rawContentAndEncoding = this.transformPDF2HTML(resourceFile, entityManager);
    }
    if (contentType != null && contentType.contains("html")) {
        rawContentAndEncoding = this.getGuessedEncodingAndSetRawContentFromGZFile(resourceFile);
    }
    // long t2 = System.currentTimeMillis();
    // System.out.println("Transformation: " + (t2 - t1));
    if (rawContentAndEncoding != null) {
        if (rawContentAndEncoding.getEncoding() == null) {
            rawContentAndEncoding = new StringWithEncoding(rawContentAndEncoding.getString(), "UTF8");
        }
        // t1 = System.currentTimeMillis();
        String cleanText = this.replaceUnsupportedChars(rawContentAndEncoding.getString());
        rawContentAndEncoding = new StringWithEncoding(cleanText, rawContentAndEncoding.getEncoding());
        File tmpFile = File.createTempFile("ridire", null);
        FileUtils.writeStringToFile(tmpFile, rawContentAndEncoding.getString(), "UTF-8");
        String ridireCleanerJar = entityManager
                .find(CommandParameter.class, CommandParameter.RIDIRE_CLEANER_EXECUTABLE_KEY).getCommandValue();
        String host = entityManager.find(Parameter.class, Parameter.READABILITY_HOSTAPP.getKey()).getValue();
        CommandLine commandLine = CommandLine
                .parse("java -Xmx128m -Djava.io.tmpdir=" + this.tempDir + " -jar " + ridireCleanerJar);
        commandLine.addArgument("-f");
        commandLine.addArgument(tmpFile.getPath());
        commandLine.addArgument("-e");
        commandLine.addArgument("UTF-8");
        commandLine.addArgument("-h");
        commandLine.addArgument(host);
        commandLine.addArgument("-k");
        commandLine.addArgument(alchemyKey);
        commandLine.addArgument("-r");
        commandLine.addArgument(readabilityKey);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.READABILITY_TIMEOUT);
        executor.setWatchdog(watchdog);
        ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024);
        ByteArrayOutputStream baosStdErr = new ByteArrayOutputStream(1024);
        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, baosStdErr, null);
        executor.setStreamHandler(executeStreamHandler);
        int exitValue = executor.execute(commandLine);
        if (exitValue == 0) {
            rawContentAndEncoding = new StringWithEncoding(baosStdOut.toString(), "UTF-8");
            // TODO filter real errors
            rawContentAndEncoding.setCleaner(baosStdErr.toString().trim());
        }
        FileUtils.deleteQuietly(tmpFile);
    }
    return rawContentAndEncoding;
}

From source file:com.walmart.gatling.commons.ReportExecutor.java

private void runJob(Master.GenerateReport job) {
    TaskEvent taskEvent = job.reportJob.taskEvent;
    CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand());
    Map<String, Object> map = new HashMap<>();

    map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName())));
    cmdLine.addArgument("${path}");

    //parameters come from the task event
    for (Pair<String, String> pair : taskEvent.getParameters()) {
        cmdLine.addArgument(pair.getValue());
    }// www. j a v a 2 s  .  c  o m
    String dir = agentConfig.getJob().getLogDirectory() + "reports/" + job.reportJob.trackingId + "/";
    cmdLine.addArgument(dir);

    cmdLine.setSubstitutionMap(map);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(agentConfig.getJob().getExitValues());
    ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);
    executor.setWorkingDirectory(new File(agentConfig.getJob().getPath()));
    FileOutputStream outFile = null;
    FileOutputStream errorFile = null;
    try {
        List<String> resultFiles = new ArrayList<>(job.results.size());
        //download all files adn
        /*int i=0;
        for (Worker.Result result : job.results) {
        String destFile = dir  + i++ + ".log";
        resultFiles.add(destFile);
        DownloadFile.downloadFile(result.metrics,destFile);
        }*/
        AtomicInteger index = new AtomicInteger();
        job.results.parallelStream().forEach(result -> {
            String destFile = dir + index.incrementAndGet() + ".log";
            resultFiles.add(destFile);
            DownloadFile.downloadFile(result.metrics, destFile);
        });
        String outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.reportJob.trackingId);
        String errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.reportJob.trackingId);
        //create the std and err files
        outFile = FileUtils.openOutputStream(new File(outPath));
        errorFile = FileUtils.openOutputStream(new File(errPath));

        PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile),
                new ExecLogHandler(errorFile));

        executor.setStreamHandler(psh);
        System.out.println(cmdLine);
        int exitResult = executor.execute(cmdLine);
        ReportResult result;
        if (executor.isFailure(exitResult)) {
            result = new ReportResult(dir, job.reportJob, false);
            log.info("Report Executor Failed, result: " + job.toString());
        } else {
            result = new ReportResult(job.reportJob.getHtml(), job.reportJob, true);
            log.info("Report Executor Completed, result: " + result.toString());
        }
        for (String resultFile : resultFiles) {
            FileUtils.deleteQuietly(new File(resultFile));
        }
        getSender().tell(result, getSelf());

    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(outFile);
        IOUtils.closeQuietly(errorFile);
    }

}

From source file:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java

/**
 * This calls a TIBCO binary.//from  ww w .j  a  va  2 s . co  m
 * 
 * @param binary, the TIBCO binary file to execute
 * @param tras, the TRA files associated with the TIBCO binary
 * @param arguments, command-line arguments
 * @param workingDir, working directory from where the binary is launched
 * @param errorMsg, error message to display in case of a failure
 * @param fork, if true the chiild process will be detached from the caller
 * 
 * @throws IOException
 * @throws MojoExecutionException
 */
protected int launchTIBCOBinary(File binary, List<File> tras, ArrayList<String> arguments, File workingDir,
        String errorMsg, boolean fork, boolean synchronous) throws IOException, MojoExecutionException {
    Integer result = 0;

    if (tras == null) { // no value specified as Mojo parameter, we use the .tra in the same directory as the binary
        String traPathFileName = binary.getAbsolutePath();
        traPathFileName = FilenameUtils.removeExtension(traPathFileName);
        traPathFileName += ".tra";
        tras = new ArrayList<File>();
        tras.add(new File(traPathFileName));
    }

    HashMap<File, File> trasMap = new HashMap<File, File>();
    for (File tra : tras) {
        // copy of ".tra" file in the working directory
        File tmpTRAFile = new File(directory, tra.getName());
        trasMap.put(tra, tmpTRAFile);
        copyFile(tra, tmpTRAFile);
    }

    for (File tra : trasMap.keySet()) {
        if (trasMap.containsKey(tibcoDesignerTRAPath)
                && ((tibcoBuildEARUseDesignerTRA && tra == tibcoBuildEARTRAPath)
                        || (tibcoBuildLibraryUseDesignerTRA && tra == tibcoBuildLibraryTRAPath))) {
            if (tras.size() > 1) {
                ReplaceRegExp replaceRegExp = new ReplaceRegExp();
                replaceRegExp.setFile(trasMap.get(tra));
                replaceRegExp.setMatch("tibco.include.tra (.*/designer.tra)");
                replaceRegExp.setReplace(
                        "tibco.include.tra " + trasMap.get(tibcoDesignerTRAPath).toString().replace('\\', '/'));
                replaceRegExp.setByLine(true);

                replaceRegExp.execute();
            }
        }

        if (tra == tibcoBuildEARTRAPath || tra == tibcoDesignerTRAPath || tra == tibcoBWEngineTRAPath) { // FIXME: should check more properly
            // append user.home at the end to force the use of custom Designer5.prefs
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(trasMap.get(tra), true)));
            out.println("");
            out.println("java.property.user.home=" + directory.getAbsolutePath().replace("\\", "/"));
            out.close();
        }
    }

    CommandLine cmdLine = new CommandLine(binary);

    for (String argument : arguments) {
        cmdLine.addArgument(argument);
    }
    getLog().debug("launchTIBCOBinary command line : " + cmdLine.toString());
    getLog().debug("working dir : " + workingDir);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(workingDir);

    if (timeOut > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut * 1000);
        executor.setWatchdog(watchdog);
    }

    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    ByteArrayOutputStream stdOutAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdOutAndErr));

    if (fork) {
        CommandLauncher commandLauncher = CommandLauncherFactory.createVMLauncher();
        commandLauncher.exec(cmdLine, null, workingDir);
    } else {
        try {
            if (synchronous) {
                result = executor.execute(cmdLine);
            } else {
                executor.execute(cmdLine, new DefaultExecuteResultHandler());
            }
        } catch (ExecuteException e) {
            // TODO : grer erreurs des excutables (ventuellement parser les erreurs classiques)
            getLog().info(cmdLine.toString());
            getLog().info(stdOutAndErr.toString());
            getLog().info(result.toString());
            throw new MojoExecutionException(errorMsg, e);
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }

    return result;
}

From source file:net.sourceforge.seqware.pipeline.plugins.ITUtility.java

/**
 * Run an arbitrary command and check it against an expected return value
 *
 * @param line/*from w w w  . j a  v a  2 s.c om*/
 * @param expectedReturnValue
 * @param dir working directory, can be null if you don't want to change directories
 * @return
 * @throws IOException
 */
public static String runArbitraryCommand(String line, int expectedReturnValue, File dir) throws IOException {
    Log.info("Running " + line);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine commandline = CommandLine.parse(line);
    DefaultExecutor exec = new DefaultExecutor();
    if (dir != null) {
        exec.setWorkingDirectory(dir);
    }
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    exec.setExitValue(expectedReturnValue);
    try {
        int exitValue = exec.execute(commandline);
        Assert.assertTrue(
                "exit value for full jar with no params should be " + expectedReturnValue + " was " + exitValue,
                exitValue == expectedReturnValue);
        String output = outputStream.toString();
        return output;
    } catch (ExecuteException e) {
        Log.error("Execution failed with:");
        Log.error(outputStream.toString());
        throw e;
    }
}

From source file:net.spinetrak.rpitft.command.Command.java

Result execute(final Stream stream_) {
    final CommandLine commandline = CommandLine.parse(_script);
    final DefaultExecutor exec = new DefaultExecutor();
    final ExecuteWatchdog watchdog = new ExecuteWatchdog(500);
    exec.setWatchdog(watchdog);//from  w  w w . j a v a2 s.  c  om
    final PumpStreamHandler streamHandler = new PumpStreamHandler(stream_.getStream());
    exec.setStreamHandler(streamHandler);
    int result = -1;
    try {
        result = exec.execute(commandline);
    } catch (final IOException ex_) {
        //LOGGER.error(ex_.getMessage());
    }
    return new Result(stream_, result);
}