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

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

Introduction

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

Prototype

public DefaultExecutor() 

Source Link

Document

Default constructor creating a default PumpStreamHandler and sets the working directory of the subprocess to the current working directory.

Usage

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

/** {@inheritDoc} 
 * @throws SchedulerException /*from  www.  j av a2  s .co  m*/
 */
@Override
public String runParameterSweep(final Model paramSweepConfig, final String timeLimit, final File workDir)
        throws SchedulerException {

    File file = null;
    try {
        //         file = File.createTempFile("paramsweep-", ".xml");
        file = new File(workDir, "paramsweep-config.xml");
        Marshaller marshaller = JAXBContext.newInstance(Model.class).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(paramSweepConfig, file);
        //      } catch (IOException e) {
        //         throw new SchedulerException("Could not create temporary parameter-sweep configuration xml.", e);
    } catch (JAXBException e) {
        throw new SchedulerException(
                "Could not write temporary parameter-sweep configuration xml: " + file.toString(), e);
    }
    CommandLine cmd = new CommandLine(cmdFile);
    Map<String, Object> substitutions = new HashMap<String, Object>();
    substitutions.put(CMD_SUBSTITUTION_NAME_FILE, file);
    cmd.setSubstitutionMap(substitutions);

    if (timeLimit != null && !timeLimit.isEmpty()) {
        cmd.addArgument("-t", false);
        cmd.addArgument(timeLimit, false);
    }

    // add server port argument
    cmd.addArgument("-p", false);
    cmd.addArgument(String.valueOf(serverPort), false);

    cmd.addArgument("${" + CMD_SUBSTITUTION_NAME_FILE + "}", false);

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

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(byteArrayOutputStream);

    executor.setStreamHandler(streamHandler);

    try {
        executor.execute(cmd);
    } catch (ExecuteException e) {
        throw new SchedulerException(
                paramSweepCmd + " exited with " + e.getExitValue() + ". Output:\n" + byteArrayOutputStream, e);
    } catch (IOException e) {
        throw new SchedulerException(
                "Execution of " + paramSweepCmd + " failed. Output:\n" + byteArrayOutputStream, e);
    }

    // the standard output of the script is the job id
    final String jobId = byteArrayOutputStream.toString();

    return jobId;
}

From source file:net.robyf.dbpatcher.util.MySqlUtil.java

private static InputStream executeAndGetOutput(final CommandLine commandLine) {
    try {/*from  w  ww .  java  2s .c  om*/
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        PumpStreamHandler handler = new PumpStreamHandler(outStream);

        DefaultExecutor executor = new DefaultExecutor();
        executor.setWatchdog(new ExecuteWatchdog(300000L));
        executor.setStreamHandler(handler);
        int returnCode = executor.execute(commandLine);
        if (returnCode != 0) {
            throw new UtilException("Error executing: " + commandLine //NOSONAR
                    + ", return code = " + returnCode); //NOSONAR
        }
        return new ByteArrayInputStream(outStream.toByteArray());
    } catch (IOException ioe) {
        throw new UtilException("Error executing: " + commandLine, ioe); //NOSONAR
    }
}

From source file:de.tu_dresden.psy.fca.ConexpCljBridge.java

public ConexpCljBridge() {

    this.b = new byte[1];

    /**//from www .j ava2 s .  co  m
     * build the command line (see conexp-clj/bin/conexp-clj)
     */

    String java_bin = Launcher.getJavaCommand();

    CommandLine conexp_cmd = new CommandLine(java_bin);
    conexp_cmd.addArgument("-server");
    conexp_cmd.addArgument("-cp");
    conexp_cmd.addArgument("./conexp-clj/lib/conexp-clj-0.0.7-alpha-SNAPSHOT-standalone.jar");
    conexp_cmd.addArgument("clojure.main");
    conexp_cmd.addArgument("-e");
    conexp_cmd.addArgument("");
    conexp_cmd.addArgument("./conexp-clj/lib/conexp-clj.clj");

    /**
     * open the pipes
     */

    this.to_conexp = new PipedOutputStream();
    try {
        this.stream_to_conexp = new PipedInputStream(this.to_conexp, 2048);
    } catch (IOException e2) {
        e2.printStackTrace();
    }

    this.stream_error_conexp = new PipedOutputStream();
    this.stream_from_conexp = new PipedOutputStream();

    try {
        this.from_conexp = new PipedInputStream(this.stream_from_conexp, 2048);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    try {
        this.error_conexp = new PipedInputStream(this.stream_error_conexp, 2048);
    } catch (IOException e1) {

        e1.printStackTrace();
    }

    /**
     * setup apache commons exec
     */

    this.result = new DefaultExecuteResultHandler();

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setStreamHandler(
            new PumpStreamHandler(this.stream_from_conexp, this.stream_error_conexp, this.stream_to_conexp));

    /**
     * run in non-blocking mode
     */

    try {
        executor.execute(conexp_cmd, this.result);
    } catch (ExecuteException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    this.output_buffer = "";

}

From source file:com.devesion.maven.jsr308.CheckersPlugin.java

/**
 * Plugin Entry point./* w w  w .  j a  v  a  2  s.c  o m*/
 * 
 * @throws MojoExecutionException exception
 * @throws MojoFailureException exception
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    getLog().info("Executing JSR-308 Checkers");

    if (checkers.size() <= 0) {
        getLog().info("No checkers found, omitting checkers execution");
        return;
    }

    final SourceContext sourceCtx = new SourceContext(compileSourceDirs, includes, excludes);
    final List<String> sources = SourceUtils.getProjectSources(sourceCtx);
    if (sources.isEmpty()) {
        getLog().info("The project does not contains any sources, omitting checkers execution");
        return;
    }

    final CommandLine cl = new CommandLine("java");
    if (checkerJar == null || checkerJar.isEmpty()) {
        checkerJar = ArtifactUtils.getArtifactPath(JSR308_ALL_GROUP_ID, JSR308_ALL_ARTIFACT_ID, dependencies);
        if (checkerJar == null) {
            throw new MojoExecutionException("Cannot find " + JSR308_ALL_GROUP_ID + ":" + JSR308_ALL_ARTIFACT_ID
                    + " artifact jar in the local repository.");
        }
    }

    cl.addArgument("-Xbootclasspath/p:" + checkerJar);
    cl.addArgument("-ea:com.sun.tools");
    if (userJavaParams != null) {
        cl.addArgument(userJavaParams);
    }
    cl.addArgument("-jar");
    cl.addArgument(checkerJar);
    cl.addArgument("-proc:only");

    // adding checkers
    for (String checker : checkers) {
        cl.addArgument("-processor");
        cl.addArgument(checker);
    }

    // adding project sources
    cl.addArguments(sources.toArray(new String[sources.size()]));

    // adding classpath
    final StringBuilder sb = new StringBuilder();
    for (String element : compileClasspathElements) {
        sb.append(element);
        sb.append(File.pathSeparator);
    }

    cl.addArgument("-classpath");
    cl.addArgument(sb.toString());
    if (userJavacParams != null) {
        cl.addArgument(userJavacParams);
    }

    // executing compiler
    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(EXIT_CODE_OK);

    try {
        executor.execute(cl);
    } catch (ExecuteException ex) {

        if (failOnError) {
            throw new MojoExecutionException(
                    "Unable to continue because of some errors reported by checkers - " + ex.getMessage());
        } else {
            getLog().error("Some errors has been reported by checkers - " + ex.getMessage());
        }
    } catch (IOException ex) {
        throw new MojoExecutionException("cannot execute checkers", ex);
    }
}

From source file:de.slackspace.wfail2ban.firewall.impl.DefaultFirewallManager.java

private void addDefaultWindowsFirewallRule(int ruleNumber, String filterName, String ipList) {
    Map<Object, Object> map = new HashMap<Object, Object>();
    map.put("name", createFinalRuleName(ruleNumber, filterName));
    map.put("direction", "in");
    map.put("ipList", ipList);
    CommandLine cmdLine = new CommandLine("cmd.exe");
    cmdLine.addArgument("/C");
    cmdLine.addArgument(System.getenv("WINDIR") + "\\system32\\netsh.exe");
    cmdLine.addArgument("advfirewall");
    cmdLine.addArgument("firewall");
    cmdLine.addArgument("add");
    cmdLine.addArgument("rule");
    cmdLine.addArgument("name=${name}");
    cmdLine.addArgument("dir=${direction}");
    cmdLine.addArgument("action=block");
    cmdLine.addArgument("localip=any");
    cmdLine.addArgument("remoteip=${ipList}");
    cmdLine.addArgument("description=This is a generated rule from wfail2ban. Do not edit!");
    cmdLine.addArgument("profile=any");
    cmdLine.addArgument("interfacetype=any");
    cmdLine.setSubstitutionMap(map);/*from  ww w. j  av a2  s. c  om*/
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    executor.setWatchdog(watchdog);
    try {
        executor.execute(cmdLine);
        if (logger.isDebugEnabled()) {
            logger.debug("Added firewall rule " + createFinalRuleName(ruleNumber, filterName));
        }
    } catch (ExecuteException e) {
        ConsolePrinter.printError("Could not create firewall rule. Continuing with next one...");
        logger.error("", e);
    } catch (IOException e) {
        logger.error("Could not create firewall rule. Error was: ", e);
    }
}

From source file:com.netflix.genie.web.tasks.job.JobCompletionService.java

/**
 * Constructor./*from   w  w  w .  ja  va2s .  co m*/
 *
 * @param jobSearchService         An implementation of the job search service.
 * @param jobPersistenceService    An implementation of the job persistence service.
 * @param genieFileTransferService An implementation of the Genie File Transfer service.
 * @param genieWorkingDir          The working directory where all job directories are created.
 * @param mailServiceImpl          An implementation of the mail service.
 * @param registry                 The metrics registry to use
 * @param jobsProperties           The properties relating to running jobs
 * @param retryTemplate            Retry template for retrying remote calls
 * @throws GenieException if there is a problem
 */
@Autowired
public JobCompletionService(final JobPersistenceService jobPersistenceService,
        final JobSearchService jobSearchService, final GenieFileTransferService genieFileTransferService,
        final Resource genieWorkingDir, final MailService mailServiceImpl, final Registry registry,
        final JobsProperties jobsProperties,
        @Qualifier("genieRetryTemplate") @NotNull final RetryTemplate retryTemplate) throws GenieException {
    this.jobPersistenceService = jobPersistenceService;
    this.jobSearchService = jobSearchService;
    this.genieFileTransferService = genieFileTransferService;
    this.mailServiceImpl = mailServiceImpl;
    this.deleteArchiveFile = jobsProperties.getCleanup().isDeleteArchiveFile();
    this.deleteDependencies = jobsProperties.getCleanup().isDeleteDependencies();
    this.runAsUserEnabled = jobsProperties.getUsers().isRunAsUserEnabled();

    this.executor = new DefaultExecutor();
    this.executor.setStreamHandler(new PumpStreamHandler(null, null));

    try {
        this.baseWorkingDir = genieWorkingDir.getFile();
    } catch (IOException gse) {
        throw new GenieServerException("Could not load the base path from resource");
    }

    // Set up the metrics
    this.registry = registry;
    this.jobCompletionId = registry.createId("genie.jobs.completion.timer");
    this.emailSuccessRate = registry.counter("genie.jobs.email.success.rate");
    this.emailFailureRate = registry.counter("genie.jobs.email.failure.rate");
    this.archivalFailureRate = registry.counter("genie.jobs.archivalFailure.rate");
    this.doneFileProcessingFailureRate = registry.counter("genie.jobs.doneFileProcessingFailure.rate");
    this.finalStatusUpdateFailureRate = registry.counter("genie.jobs.finalStatusUpdateFailure.rate");
    this.processGroupCleanupFailureRate = registry.counter("genie.jobs.processGroupCleanupFailure.rate");
    this.archiveFileDeletionFailure = registry.counter("genie.jobs.archiveFileDeletionFailure.rate");
    this.deleteDependenciesFailure = registry.counter("genie.jobs.deleteDependenciesFailure.rate");
    // Retry template
    this.retryTemplate = retryTemplate;
}

From source file:com.adaptris.hpcc.DfuPlusWrapper.java

protected void executeInternal(CommandLine cmdLine, OutputStream stdout)
        throws ProduceException, AbortJobException {
    int exit = -1;
    ExecuteWatchdog watchdog = new ExecuteWatchdog(EXEC_TIMEOUT_INTERVAL.toMilliseconds());
    try (OutputStream out = stdout) {
        Executor cmd = new DefaultExecutor();
        cmd.setWatchdog(watchdog);/*  www .j  av a  2 s  . c om*/
        PumpStreamHandler pump = new ManagedPumpStreamHandler(out);
        cmd.setStreamHandler(pump);
        cmd.setExitValues(null);
        exit = cmd.execute(cmdLine);
    } catch (Exception e) {
        throw ExceptionHelper.wrapProduceException(e);
    }
    if (watchdog.killedProcess() || exit != 0) {
        throw new AbortJobException("Job killed due to timeout/ExitCode != 0");
    }
}

From source file:com.k42b3.sacmis.Sacmis.java

private void executeCommand() {
    out.setText("");

    try {/*from www.ja  v  a2s  . co m*/
        // save file
        saveFile();

        CommandLine commandLine = CommandLine.parse(this.path + " " + this.args.getText());

        // set timeout
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);

        // create executor
        DefaultExecutor executor = new DefaultExecutor();

        executor.setExitValue(this.exitCode);

        this.baos = new ByteArrayOutputStream();

        this.baosErr = new ByteArrayOutputStream();

        if (this.writerStdIn) {
            this.bais = new ByteArrayInputStream(in.getText().getBytes());

            executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr, this.bais));
        } else {
            executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr));
        }

        executor.setWatchdog(watchdog);

        executor.execute(commandLine, new ExecuteResultHandler() {

            public void onProcessComplete(int e) {
                out.setText(baos.toString());
            }

            public void onProcessFailed(ExecuteException e) {
                out.setText(baosErr.toString());
            }

        });
    } catch (Exception e) {
        out.setText(e.getMessage());
    }
}

From source file:it.drwolf.ridire.utility.RIDIREReTagger.java

public String retagFile(File f) throws ExecuteException, IOException {
    // Map<String, File> map = new HashMap<String, File>();
    String fileIN = f.getAbsolutePath();
    String fileOut = f.getAbsolutePath() + ".iso";
    String posOld = f.getAbsolutePath() + ".iso.pos";
    String posNew = f.getAbsolutePath() + ".pos";
    // first convert from utf8 to iso8859-1
    CommandLine commandLine = CommandLine.parse("iconv");
    commandLine.addArgument("-c").addArgument("-s").addArgument("-f").addArgument("utf8").addArgument("-t")
            .addArgument("iso8859-1//TRANSLIT").addArgument("-o").addArgument(fileOut, false)
            .addArgument(fileIN, false);
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(RIDIREReTagger.TREETAGGER_TIMEOUT);
    executor.setWatchdog(watchdog);//from   w ww. j  a  v  a  2s .c o m
    int exitValue = executor.execute(commandLine);
    if (exitValue == 0) {
        // tag using latin1 and Baroni's tagset
        commandLine = CommandLine.parse(this.treeTaggerBin);
        commandLine.addArgument(fileOut, false);
        executor = new DefaultExecutor();
        executor.setExitValue(0);
        watchdog = new ExecuteWatchdog(RIDIREReTagger.TREETAGGER_TIMEOUT);
        executor.setWatchdog(watchdog);
        TreeTaggerLog treeTaggerLog = new TreeTaggerLog();
        PumpStreamHandler executeStreamHandler = new PumpStreamHandler(treeTaggerLog, null);
        executor.setStreamHandler(executeStreamHandler);
        int exitValue2 = executor.execute(commandLine);
        if (exitValue2 == 0) {
            // FileUtils.deleteQuietly(new File(fileOut));
            File posTagFile = new File(posOld);
            FileUtils.writeLines(posTagFile, treeTaggerLog.getLines());
        }
        // reconvert to utf8
        commandLine = CommandLine.parse("iconv");
        commandLine.addArgument("-s").addArgument("-f").addArgument("iso8859-1").addArgument("-t")
                .addArgument("utf8//TRANSLIT").addArgument("-o").addArgument(posNew, false)
                .addArgument(posOld, false);
        executor = new DefaultExecutor();
        watchdog = new ExecuteWatchdog(RIDIREReTagger.TREETAGGER_TIMEOUT);
        executor.setWatchdog(watchdog);
        int exitValue3 = executor.execute(commandLine);
        if (exitValue3 == 0) {
            // FileUtils.deleteQuietly(new File(f.getPath() + ".iso.pos"));
            return new File(posNew).getCanonicalPath();
        }
    }
    return null;
}

From source file:de.yaio.services.webshot.server.controller.WebshotProvider.java

protected WebShotResultHandler runCommand(final String command, final String[] params, final long jobTimeout)
        throws IOException {
    int exitValue;
    boolean inBackground = false;
    ExecuteWatchdog watchdog = null;//from w w  w.ja v  a2  s . co  m
    WebShotResultHandler resultHandler;

    // build up the command line to using a 'java.io.File'
    final CommandLine commandLine = new CommandLine(command);
    commandLine.addArguments(params);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("start command " + command + " with params"
                + new ReflectionToStringBuilder(params, ToStringStyle.SHORT_PREFIX_STYLE).toString());
    }

    // create the executor and consider the exitValue '1' as success
    final Executor executor = new DefaultExecutor();
    executor.setExitValue(0);

    // create a watchdog if requested
    if (jobTimeout > 0) {
        watchdog = new ExecuteWatchdog(jobTimeout);
        executor.setWatchdog(watchdog);
    }

    if (inBackground) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[WebShot] Executing non-blocking WebShot job  ...");
        }
        resultHandler = new WebShotResultHandler(watchdog);
        executor.execute(commandLine, resultHandler);
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[WebShot] Executing blocking WebShot job  ...");
        }
        exitValue = executor.execute(commandLine);
        resultHandler = new WebShotResultHandler(exitValue);
    }

    return resultHandler;
}