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

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

Introduction

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

Prototype

int execute(CommandLine command) throws ExecuteException, IOException;

Source Link

Document

Methods for starting synchronous execution.

Usage

From source file:org.fornax.toolsupport.sculptor.maven.plugin.GeneratorMojo.java

/**
 * Executes the commandline running the Eclipse MWE2 launcher and returns
 * the commandlines exit value.//from  ww w  .j  av  a 2 s  .  c  o m
 * 
 * @param changedFiles
 *            list of files from <code>checkFileSets</code> which are
 *            modified since last generator execution or <code>null</code>
 *            if code generation is enforced
 */
protected List<File> executeGenerator(Set<String> changedFiles) throws MojoExecutionException {
    List<File> createdFiles = null;

    // Build executor for projects base directory
    ScanningMavenLogOutputStream stdout = getStdoutStream();
    ScanningMavenLogOutputStream stderr = getStderrStream();
    Executor exec = getExecutor();
    exec.setWorkingDirectory(project.getBasedir());
    exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

    // Execute commandline and check return code
    try {
        int exitValue = exec.execute(getGeneratorCommandLine(changedFiles));

        // Check exit value and output streams for errors
        if (exitValue == 0 && stdout.getErrorCount() == 0 && stderr.getLineCount() == 0) {

            // Return list of created files
            createdFiles = stdout.getCreatedFiles();
        }
    } catch (ExecuteException e) {
        // ignore
    } catch (IOException e) {
        // ignore
    }
    return createdFiles;
}

From source file:org.fornax.toolsupport.sculptor.maven.plugin.GraphvizMojo.java

/**
 * Executes the command line tool <code>dot</code>.
 * /*from www  . jav  a 2 s. c o  m*/
 * @param dotFiles
 *            list of dot files from the
 *            {@link AbstractSculptorMojo#statusFile}
 */
protected boolean executeDot(Set<String> dotFiles) throws MojoExecutionException {

    // Build executor for projects base directory
    MavenLogOutputStream stdout = getStdoutStream();
    MavenLogOutputStream stderr = getStderrStream();
    Executor exec = getExecutor();
    exec.setWorkingDirectory(project.getBasedir());
    exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in));

    // Execute commandline and check return code
    try {
        int exitValue = exec.execute(getDotCommandLine(dotFiles));
        if (exitValue == 0 && stdout.getErrorCount() == 0) {
            return true;
        }
    } catch (ExecuteException e) {
        // ignore
    } catch (IOException e) {
        // ignore
    }
    return false;
}

From source file:org.fuin.esmp.EventStoreDownloadMojo.java

private void applyFileMode(final File file, final FileMode fileMode) throws MojoExecutionException {

    if (OS.isFamilyUnix() || OS.isFamilyMac()) {
        final String smode = fileMode.toChmodStringFull();
        final CommandLine cmdLine = new CommandLine("chmod");
        cmdLine.addArgument(smode);//  w  w w .j  a v a  2  s  . c o  m
        cmdLine.addArgument(file.getAbsolutePath());
        final Executor executor = new DefaultExecutor();
        try {
            final int result = executor.execute(cmdLine);
            if (result != 0) {
                throw new MojoExecutionException("Error # " + result + " while trying to set mode \"" + smode
                        + "\" for file: " + file.getAbsolutePath());
            }
        } catch (final IOException ex) {
            throw new MojoExecutionException(
                    "Error while trying to set mode \"" + smode + "\" for file: " + file.getAbsolutePath(), ex);
        }
    } else {
        file.setReadable(fileMode.isUr() || fileMode.isGr() || fileMode.isOr());
        file.setWritable(fileMode.isUw() || fileMode.isGw() || fileMode.isOw());
        file.setExecutable(fileMode.isUx() || fileMode.isGx() || fileMode.isOx());
    }
}

From source file:org.fuin.esmp.EventStoreStopMojo.java

@Override
protected final void executeGoal() throws MojoExecutionException {
    init();/*w ww  .  j av a2 s .c om*/
    LOG.info("command={}", command);

    final CommandLine cmdLine = createCommandLine();
    final Executor executor = new DefaultExecutor();
    try {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final PumpStreamHandler psh = new PumpStreamHandler(bos);
        executor.setStreamHandler(psh);
        executor.setWorkingDirectory(getEventStoreDir());
        final int result = executor.execute(cmdLine);
        if (result != 0) {
            throw new MojoExecutionException("Error stopping the event store: " + result);
        }
        final List<String> messages = asList(bos.toString());
        logDebug(messages);
        deletePid();
        LOG.info("Event store successfully stopped");

    } catch (final IOException ex) {
        throw new MojoExecutionException("Error executing the command line: " + cmdLine, ex);
    }

}

From source file:org.fuin.owndeb.commons.DebUtils.java

private static void execute(final CommandLine cmdLine, final File workingDir, final String errorMsg) {

    LOG.debug("Execute: " + cmdLine.toString());

    final Executor executor = new DefaultExecutor();
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final PumpStreamHandler psh = new PumpStreamHandler(bos);
    executor.setStreamHandler(psh);//from   w w  w . ja v a  2s  . c o m
    executor.setWorkingDirectory(workingDir);
    try {
        final int result = executor.execute(cmdLine);
        if (result != 0) {
            logError(asList(bos.toString()));
            throw new RuntimeException("Error # " + result + " / " + errorMsg);
        }
    } catch (final IOException ex) {
        logError(asList(bos.toString()));
        throw new RuntimeException(errorMsg, ex);
    }
}

From source file:org.kitodo.imagemanagement.ConvertRunner.java

/**
 * Executes the ImageMagick command using Apache Commons Exec.
 *
 * @param commandLine/* w w w. ja va2  s  .  c o m*/
 *            command line to execute
 * @throws IOException
 *             if I/O fails
 */
void run(IMOperation commandLine) throws IOException {
    Executor executor = new DefaultExecutor();

    OutputStream outAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outAndErr));

    long timeoutMillis = 1000
            * KitodoConfig.getIntParameter(ParameterImageManagement.TIMEOUT_SEC, DEFAULT_TIMEOUT_MINS);
    executor.setWatchdog(new ExecuteWatchdog(timeoutMillis));

    CommandLine command;
    try {
        String sshHosts = KitodoConfig.getParameter(ParameterImageManagement.SSH_HOST);
        command = new CommandLine("ssh");
        String[] hosts = sshHosts.split(",");
        String host = hosts[RANDOMNESS_GENERATOR.nextInt(hosts.length)];
        command.addArgument(host, false);
        command.addArgument(convertCommand + ' ' + commandLine.toString(), false);
    } catch (NoSuchElementException e) {
        logger.trace("SSH not configured.", e);
        command = new CommandLine(convertCommand);
        command.addArguments(commandLine.toString());
    }

    try {
        logger.debug("Executing: {}", command);
        logger.trace("Timeout: {} mins", timeoutMillis / 60000d);
        executor.execute(command);
        logger.debug("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
    } catch (IOException | RuntimeException e) {
        logger.error("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
        throw e;
    }
}

From source file:org.kitodo.imagemanagementmodule.ConvertRunner.java

/**
 * Executes the ImageMagick command using Apache Commons Exec.
 *
 * @param commandLine/*from w  w w.j  a  va 2 s  . c  om*/
 *            command line to execute
 * @throws IOException
 *             if I/O fails
 */
void run(IMOperation commandLine) throws IOException {
    Executor executor = new DefaultExecutor();

    OutputStream outAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outAndErr));

    long timeoutMillis = 1000
            * Config.getIntParameter("ImageManagementModule.timeoutSec", DEFAULT_TIMEOUT_MINS);
    executor.setWatchdog(new ExecuteWatchdog(timeoutMillis));

    CommandLine command;
    try {
        String sshHosts = Config.getParameter("ImageManagementModule.sshHosts");
        command = new CommandLine("ssh");
        String[] hosts = sshHosts.split(",");
        String host = hosts[RANDOMNESS_GENERATOR.nextInt(hosts.length)];
        command.addArgument(host, false);
        command.addArgument(convertCommand + ' ' + commandLine.toString(), false);
    } catch (NoSuchElementException e) {
        logger.trace("SSH not configured.", e);
        command = new CommandLine(convertCommand);
        command.addArguments(commandLine.toString());
    }

    try {
        logger.debug("Executing: {}", command);
        logger.trace("Timeout: {} mins", timeoutMillis / 60000d);
        executor.execute(command);
        logger.debug("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
    } catch (IOException | RuntimeException e) {
        logger.error("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
        throw e;
    }
}

From source file:org.openqa.selenium.iphone.IPhoneSimulatorBinary.java

public void launch() {
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(createOutputStream()));
    try {/*from  w w w . ja  va  2 s  .  com*/
        exitCode = executor.execute(commandLine);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.openqa.selenium.iphone.IPhoneSimulatorCommandExecutorTest.java

private void killIphoneSimulatorProcesses() {
    try {/*from  w ww . ja v a2  s .co m*/
        File scriptFile = File.createTempFile("iWebDriver.kill.", ".script");
        FileWriter writer = new FileWriter(scriptFile);
        writer.write("ps ax | grep 'iPhone Simulator' | grep -v grep | awk '{print $1}' | xargs kill");
        writer.flush();
        writer.close();
        FileHandler.makeExecutable(scriptFile);
        CommandLine killCommandLine = CommandLine.parse(scriptFile.getAbsolutePath());
        Executor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(null, null));
        executor.execute(killCommandLine);
        // need to wait for the port to free up
        // TODO same as needs to be done in IPhoneSimulatorBinary
        Thread.sleep(5000);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.rhq.server.control.ControlCommand.java

protected void killPid(String pid) throws IOException {
    Executor executor = new DefaultExecutor();
    executor.setWorkingDirectory(getBinDir());
    PumpStreamHandler streamHandler = new PumpStreamHandler(createNullOutputStream(), createNullOutputStream());
    executor.setStreamHandler(streamHandler);
    org.apache.commons.exec.CommandLine commandLine;

    commandLine = new org.apache.commons.exec.CommandLine("kill").addArgument(pid);
    executor.execute(commandLine);
}