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:io.github.binout.wordpress2html.writer.Html2AsciidocConverter.java

private void execute(CommandLine cmdLine) throws IOException {
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);/* w  ww  .j  a v a 2s.c  o  m*/
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    int exitValue = executor.execute(cmdLine);
    if (exitValue != 0) {
        throw new RuntimeException("Pandoc is not installed !");
    }
}

From source file:com.github.trecloux.yeoman.YeomanMojo.java

void executeCommand(String command) throws MojoExecutionException {
    try {/*from www .jav a  2 s .  com*/
        if (isWindows()) {
            command = "cmd /c " + command;
        }
        CommandLine cmdLine = CommandLine.parse(command);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(yeomanProjectDirectory);
        executor.execute(cmdLine);
    } catch (IOException e) {
        throw new MojoExecutionException("Error during : " + command, e);
    }
}

From source file:eu.crisis_economics.abm.dashboard.cluster.script.BashScheduler.java

private void makeScriptsExecutable() {
    File scriptsDirectory = new File(scriptsDir + File.separator + schedulerType);
    String[] scripts = scriptsDirectory.list(new PatternFilenameFilter(".*\\.sh"));

    CommandLine commandLine = new CommandLine("chmod");
    commandLine.addArgument("755");
    for (String script : scripts) {
        commandLine.addArgument(scriptsDir + File.separator + schedulerType + File.separator + script, false);
    }/*  w w  w .j a  v a  2s.  c  om*/

    DefaultExecutor executor = new DefaultExecutor();

    try {
        executor.execute(commandLine);
    } catch (ExecuteException e) {
        // ignore this; there will be an exception later, if this scheduler is used
    } catch (IOException e) {
        // ignore this; there will be an exception later, if this scheduler is used
    }
}

From source file:com.meltmedia.cadmium.blackbox.test.CliCommitCloneTest.java

/**
 * <p>Runs the Cadmium CLI command commit from Apache Commons Exec library. Then uses {@link CadmiumAssertions#assertContentDeployed(String, java.io.File, String)} to assert that the content deployed properly.</p>
 * <p>To override the site url, pass <code>-Dcom.meltmedia.cadmium.test.site.url=[URL]</code> to the jvm that this test case will be running in. The site url defaults to <code>http://localhost</code> if not set.</p>
 * @throws IOException See {@link DefaultExecutor#execute(CommandLine)} for more information.
 * @throws ExecuteException See {@link DefaultExecutor#execute(CommandLine)} for more information.
 * @throws InterruptedException /*from   ww  w  . j  a  va2s  .  co  m*/
 * 
 * @see <a href="http://commons.apache.org/exec">Apache Commons Exec</a>
 */
@Test
public void testCommit() throws ExecuteException, IOException {
    String deployUrl = System.getProperty("com.meltmedia.cadmium.test.site.url", DEPLOY_URL);
    CommandLine commitCmd = CommandLine
            .parse("cadmium commit -m \"Testing commit command\" " + TEST_CONTENT_LOCATION + " " + deployUrl);

    DefaultExecutor exec = new DefaultExecutor();
    exec.setExitValue(0);
    ExecuteWatchdog watchDog = new ExecuteWatchdog(60000);
    exec.setWatchdog(watchDog);

    int exitValue = exec.execute(commitCmd);

    assertEquals("Commit command returned with an error status.", exitValue, 0);

    assertContentDeployed("Failed to commit content to remote site.", new File(TEST_CONTENT_LOCATION),
            DEPLOY_URL);
}

From source file:io.werval.maven.MavenDevShellSPI.java

@Override
protected void doRebuild() throws DevShellRebuildException {
    System.out.println("Reload!");
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(output));
    try {//ww w.  j  av  a2 s  . c o  m
        int exitValue = executor.execute(cmdLine);
        if (exitValue != 0) {
            throw new DevShellRebuildException(
                    new MavenExecutionException("Maven exited with a non-zero status: " + exitValue, pom));
        }
    } catch (Exception ex) {
        throw new DevShellRebuildException(ex, output.toString());
    }
}

From source file:com.github.seqware.queryengine.tutorial.PosterSGE.java

/**
 * <p>benchmark.</p>//from www .ja  va 2  s  .  co m
 *
 * @throws java.io.IOException if any.
 */
public void benchmark() throws IOException {
    if (args.length != 3) {
        System.err.println(args.length + " arguments found");
        System.out.println(
                PosterSGE.class.getSimpleName() + " <outputKeyValueFile> <input file dir> <simultaneous jobs>");
        System.exit(-1);
    }

    File outputFile = Utility.checkOutput(args[0]);

    // check if reference has been properly created
    Reference reference = SWQEFactory.getQueryInterface().getLatestAtomByRowKey("hg_19", Reference.class);
    if (reference == null) {
        SGID refID = ReferenceCreator.mainMethod(new String[] { HG_19 });
        reference = SWQEFactory.getQueryInterface().getAtomBySGID(Reference.class, refID);
    }

    // record reference, starting disk space
    keyValues.put("referenceID", reference.getSGID().getRowKey());
    recordSpace("start");
    Utility.writeKeyValueFile(outputFile, keyValues);
    // create new FeatureSet id and pass it onto our children
    CreateUpdateManager manager = SWQEFactory.getModelManager();
    FeatureSet initialFeatureSet = manager.buildFeatureSet().setReference(reference).build();
    manager.flush();

    int count = 0;
    // go through all input files
    File fileDirectory = new File(args[1]);
    File[] listFiles = fileDirectory.listFiles();

    // record start and finish time
    Date startDate = new Date();
    keyValues.put(count + "-start-date-long", Long.toString(startDate.getTime()));
    keyValues.put(count + "-start-date-human", startDate.toString());

    // submit all jobs in parallel via SGE
    StringBuilder jobNames = new StringBuilder();
    for (File inputFile : listFiles) {
        // run without unnecessary parameters
        String cargs = "-w VCFVariantImportWorker -i " + inputFile.getAbsolutePath() + " -b "
                + String.valueOf(BENCHMARKING_BATCH_SIZE) + " -f " + initialFeatureSet.getSGID().getRowKey()
                + " -r " + reference.getSGID().getRowKey();
        String command = "java -Xmx2048m -classpath " + System.getProperty("user.dir")
                + "/seqware-queryengine-0.12.0-full.jar com.github.seqware.queryengine.system.importers.SOFeatureImporter";
        command = command + " " + cargs;
        command = "qsub -q long -l h_vmem=3G -cwd -N dyuen-" + inputFile.getName() + " -b y " + command;

        jobNames.append("dyuen-").append(inputFile.getName()).append(",");
        System.out.println("Running: " + command);
        CommandLine cmdLine = CommandLine.parse(command);
        DefaultExecutor executor = new DefaultExecutor();
        int exitValue = executor.execute(cmdLine);
    }
    String jobs = jobNames.toString().substring(0, jobNames.length() - 1);

    // submit a job that just waits on all the preceding jobs for synchronization
    String command = "java -Xmx1024m -version";
    command = "qsub -cwd -N dyuen-wait -hold_jid " + jobs + " -b y -sync y " + command;
    System.out.println("Running wait: " + command);

    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(null);
    int exitValue = executor.execute(cmdLine);

    FeatureSet fSet = SWQEFactory.getQueryInterface().getLatestAtomBySGID(initialFeatureSet.getSGID(),
            FeatureSet.class);
    keyValues.put(count + "-featuresSet-id", fSet.getSGID().getRowKey());
    keyValues.put(count + "-featuresSet-id-timestamp",
            Long.toString(fSet.getSGID().getBackendTimestamp().getTime()));

    //        // runs count query, touches everything but does not write
    //
    //        keyValues.put(count + "-start-count-date-long", Long.toString(System.currentTimeMillis()));
    //        long fsetcount = fSet.getCount();
    //        keyValues.put(count + "-features-loaded", Long.toString(fsetcount));
    //        keyValues.put(count + "-end-count-date-long", Long.toString(System.currentTimeMillis()));

    Date endDate = new Date();
    keyValues.put(count + "-end-date-long", Long.toString(endDate.getTime()));
    keyValues.put(count + "-end-date-human", endDate.toString());
    recordSpace(String.valueOf(count));
    Utility.writeKeyValueFile(outputFile, keyValues);
    count++;

}

From source file:fr.gouv.culture.vitam.utils.Executor.java

/**
 * Execute an external command/*from  w ww . j a v  a2s  .com*/
 * @param cmd
 * @param tempDelay
 * @param correctValues
 * @param showOutput
 * @param realCommand
 * @return correctValues if ok, < 0 if an execution error occurs, or other error values
 */
public static int exec(List<String> cmd, long tempDelay, int[] correctValues, boolean showOutput,
        String realCommand) {
    // Create command with parameters
    CommandLine commandLine = new CommandLine(cmd.get(0));
    for (int i = 1; i < cmd.size(); i++) {
        commandLine.addArgument(cmd.get(i));
    }
    DefaultExecutor defaultExecutor = new DefaultExecutor();
    ByteArrayOutputStream outputStream;
    outputStream = new ByteArrayOutputStream();
    PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream);
    defaultExecutor.setStreamHandler(pumpStreamHandler);

    defaultExecutor.setExitValues(correctValues);
    AtomicBoolean isFinished = new AtomicBoolean(false);
    ExecuteWatchdog watchdog = null;
    Timer timer = null;
    if (tempDelay > 0) {
        // If delay (max time), then setup Watchdog
        timer = new Timer(true);
        watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        defaultExecutor.setWatchdog(watchdog);
        CheckEndOfExecute endOfExecute = new CheckEndOfExecute(isFinished, watchdog, realCommand);
        timer.schedule(endOfExecute, tempDelay);
    }
    int status = -1;
    try {
        // Execute the command
        status = defaultExecutor.execute(commandLine);
    } catch (ExecuteException e) {
        if (e.getExitValue() == -559038737) {
            // Cannot run immediately so retry once
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
            }
            try {
                status = defaultExecutor.execute(commandLine);
            } catch (ExecuteException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            } catch (IOException e1) {
                pumpStreamHandler.stop();
                System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                        + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
                status = -2;
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                return status;
            }
        } else {
            pumpStreamHandler.stop();
            System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                    + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
            status = -2;
            try {
                outputStream.close();
            } catch (IOException e2) {
            }
            return status;
        }
    } catch (IOException e) {
        pumpStreamHandler.stop();
        System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage()
                + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString());
        status = -2;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
        return status;
    } finally {
        isFinished.set(true);
        if (timer != null) {
            timer.cancel();
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e1) {
        }
    }
    pumpStreamHandler.stop();
    if (defaultExecutor.isFailure(status) && watchdog != null) {
        if (watchdog.killedProcess()) {
            // kill by the watchdoc (time out)
            if (showOutput) {
                System.err.println(StaticValues.LBL.error_error.get() + "Exec is in Time Out");
            }
        }
        status = -3;
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    } else {
        if (showOutput) {
            System.out.println("Exec: " + outputStream.toString());
        }
        try {
            outputStream.close();
        } catch (IOException e2) {
        }
    }
    return status;
}

From source file:it.unisi.bdm.crawler.PhantomjsBrowser.java

@Override
/**//  w ww  .jav  a2s.  co  m
 * Invokes PhantomJS in order to download the page associated to `url`.
 * Please note that since the browser sometimes hangs, it's execution is
 * monitored by a wathdog that kills it after this.timeout ms.
 * 
 * @param url
 * @return Page
 * @throws BrowserTimeoutException If PhantomJS hangs.
 */
public Page getPage(String url) throws BrowserTimeoutException {
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);

    String line = "library/phantomjs library/crawler.js " + url;
    CommandLine cmdLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(this.timeout);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(psh);

    try {
        executor.execute(cmdLine);
    } catch (Exception e) {
        throw new BrowserTimeoutException();
    }

    String json = stdout.toString();
    return new Gson().fromJson(json, Page.class);
}

From source file:com.rest4j.generator.PHPGeneratorTest.java

@Test
public void testPHPClient() throws Exception {
    gen.setStylesheet("com/rest4j/client/php.xslt");
    new File("target/php").mkdir();
    gen.setApiXmlUrl(getClass().getResource("doc-generator-graph.xml"));
    gen.setOutputDir("target/php");
    gen.addParam(new TemplateParam("common-params", "access-token"));
    gen.addParam(new TemplateParam("prefix", "Test"));
    gen.addParam(new TemplateParam("additional-client-code", "// ADDITIONAL CODE"));
    gen.generate();//from ww  w  . j av  a  2  s  .  c om

    // check the syntax
    CommandLine cmdLine = CommandLine.parse("php apiclient.php");
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File("target/php"));
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    int exitValue = executor.execute(cmdLine);
    assertFalse(executor.isFailure(exitValue));

    // check existence of Parameter Object class
    String client = IOUtils.toString(new File("target/php/apiclient.php").toURI());
    assertTrue(client, client.contains("class TestPatchBRequest"));

    assertTrue(client.contains("ADDITIONAL CODE"));
}

From source file:fitnesse.maven.io.CommandShell.java

public String execute(File workingDir, String... commands) {
    CommandLine commandLine = CommandLine.parse(commands[0]);
    for (int i = 1; i < commands.length; i++) {
        commandLine.addArgument(commands[i]);
    }//from ww  w  . java 2  s  .  c  o  m
    DefaultExecutor executor = new DefaultExecutor();
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        executor.setStreamHandler(new PumpStreamHandler(baos));
        executor.setWorkingDirectory(workingDir);
        executor.execute(commandLine);
        return new String(baos.toByteArray());
    } catch (ExecuteException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}