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:org.dataconservancy.dcs.id.impl.DataciteIdService.java

ByteArrayOutputStream executeCommand(String command) throws IOException {
    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);

    executor.setStreamHandler(psh);/*  www.  java2s.  c o m*/

    int exitValue = executor.execute(cmdLine);
    return stdout;
}

From source file:org.eclipse.kura.linux.net.modem.SupportedUsbModems.java

/**
 * Execute command an return splitted lines
 *
 * @param command//  ww  w . j  a v a2s  . c o m
 *            the command to execute
 * @return the lines output by the command
 * @throws IOException
 *             if executing the commands fails
 */
private static List<String> execute(final String command) throws ExecuteException, IOException {
    final DefaultExecutor executor = new DefaultExecutor();

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(out, NullOutputStream.NULL_OUTPUT_STREAM));

    int rc = executor.execute(CommandLine.parse(command));

    s_logger.debug("Called {} - rc = {}", command, rc);

    return IOUtils.readLines(new ByteArrayInputStream(out.toByteArray()));
}

From source file:org.estatio.webapp.services.other.EstatioOtherServices.java

@Programmatic
String execute(String command) {

    int exitValue = 1;
    CommandLine commandLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);/*www  .ja v  a2s . co m*/
    ExecuteStreamHandler handler = executor.getStreamHandler();

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout);
    executor.setStreamHandler(psh);

    try {
        handler.setProcessOutputStream(System.in);
    } catch (IOException e) {

    }

    try {
        exitValue = executor.execute(commandLine);
    } catch (ExecuteException e) {
        return e.getMessage();
    } catch (IOException e) {
        return e.getMessage();
    }
    return stdout.toString();
}

From source file:org.evosuite.utils.ProcessLauncher.java

public int launchNewProcess(File baseDir, String cmdString, int timeout)
        throws IOException, ProcessTimeoutException {

    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog timeoutWatchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(timeoutWatchdog);

    PumpStreamHandler streamHandler = new PumpStreamHandler(this.outAndErr, this.outAndErr, this.input);
    executor.setStreamHandler(streamHandler);
    if (baseDir != null) {
        executor.setWorkingDirectory(baseDir);
    }/*from  w ww. j  a  v a2  s .  co  m*/

    int exitValue;
    try {
        logger.debug("About to execute command " + cmdString);
        exitValue = executor.execute(CommandLine.parse(cmdString));
        if (executor.isFailure(exitValue) && timeoutWatchdog.killedProcess()) {
            // it was killed on purpose by the watchdog
            logger.debug("A timeout occured while executing a process");
            logger.debug("The command is " + cmdString);
            throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString);
        }

        return exitValue;
    } catch (ExecuteException e) {
        if (timeoutWatchdog.killedProcess()) {
            logger.debug("A timeout occured while executing a process");
            logger.debug("The command is " + cmdString);
            throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString);
        } else {
            throw e;
        }

    }

}

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

@Override
protected final void executeGoal() throws MojoExecutionException {
    if (postStartCommand == null) {
        throw new MojoExecutionException("postStartCommand not set");
    }//from  ww w. ja  va2  s  .c  o  m
    LOG.info("postStartCommand={}", postStartCommand);

    final CommandLine cmdLine = new CommandLine(postStartCommand);
    final DefaultExecutor executor = new DefaultExecutor();
    try {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final PumpStreamHandler psh = new PumpStreamHandler(bos);
        executor.setStreamHandler(psh);
        executor.setWorkingDirectory(getEventStoreDir());
        final int exitCode = executor.execute(cmdLine);
        messages = asList(bos.toString());
        if (exitCode == 0) {
            LOG.info("Post-start command executed successfully");
            logDebug(messages);
        } else {
            LOG.error("Post-start command failed with exit code: {}", exitCode);
            logError(messages);
        }
    } catch (final IOException ex) {
        throw new MojoExecutionException("Error executing the command line: " + cmdLine, ex);
    }
}

From source file:org.geoserver.importer.transform.AbstractCommandLinePreTransform.java

protected boolean checkAvailable() throws IOException {
    try {//from   w  w w .  ja  v a 2 s . c  o m
        CommandLine cmd = new CommandLine(getExecutable());
        for (String option : getAvailabilityTestOptions()) {
            cmd.addArgument(option);
        }

        // prepare to run
        DefaultExecutor executor = new DefaultExecutor();

        // grab at least some part of the outputs
        int limit = 16 * 1024;
        try (OutputStream os = new BoundedOutputStream(new ByteArrayOutputStream(), limit);
                OutputStream es = new BoundedOutputStream(new ByteArrayOutputStream(), limit)) {
            PumpStreamHandler streamHandler = new PumpStreamHandler(os, es);
            executor.setStreamHandler(streamHandler);
            int result = executor.execute(cmd);

            if (result != 0) {
                LOGGER.log(Level.SEVERE, "Failed to execute command " + cmd.toString()
                        + "\nStandard output is:\n" + os.toString() + "\nStandard error is:\n" + es.toString());
                return false;
            }

        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Failure to execute command " + cmd.toString(), e);
            return false;
        }
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Failure to locate executable for class " + this.getClass(), e);
        return false;
    }

    return true;
}

From source file:org.geoserver.importer.transform.AbstractCommandLineTransform.java

@Override
public void apply(ImportTask task, ImportData data) throws Exception {
    boolean inline = isInline();
    File executable = getExecutable();
    File inputFile = getInputFile(data);
    Map<String, File> substitutions = new HashMap<>();
    substitutions.put("input", inputFile);
    File outputDirectory = null;//from   ww w  . j a  v  a2s. c  om
    File outputFile = null;
    if (!inline) {
        outputDirectory = getOutputDirectory(data);
        outputFile = new File(outputDirectory, inputFile.getName());
        substitutions.put("output", outputFile);
    }

    // setup the options
    CommandLine cmd = new CommandLine(executable);
    cmd.setSubstitutionMap(substitutions);

    setupCommandLine(inline, cmd);

    // prepare to run
    DefaultExecutor executor = new DefaultExecutor();
    // make sure we don't try to execute for too much time
    executor.setWatchdog(new ExecuteWatchdog(DEFAULT_TIMEOUT));

    // grab at least some part of the outputs
    int limit = 16 * 1024;
    try {
        try (OutputStream os = new BoundedOutputStream(new ByteArrayOutputStream(), limit);
                OutputStream es = new BoundedOutputStream(new ByteArrayOutputStream(), limit)) {
            PumpStreamHandler streamHandler = new PumpStreamHandler(os, es);
            executor.setStreamHandler(streamHandler);
            try {
                int result = executor.execute(cmd);

                if (executor.isFailure(result)) {
                    // toString call is routed to ByteArrayOutputStream, which does the right string
                    // conversion
                    throw new IOException(
                            "Failed to execute command " + cmd.toString() + "\nStandard output is:\n"
                                    + os.toString() + "\nStandard error is:\n" + es.toString());
                }
            } catch (Exception e) {
                throw new IOException("Failure to execute command " + cmd.toString() + "\nStandard output is:\n"
                        + os.toString() + "\nStandard error is:\n" + es.toString(), e);
            }
        }

        // if not inline, replace inputs with output
        if (!inline) {
            List<String> names = getReplacementTargetNames(data);
            File inputParent = inputFile.getParentFile();
            for (String name : names) {
                File output = new File(outputDirectory, name);
                File input = new File(inputParent, name);
                if (output.exists()) {
                    // uses atomic rename on *nix, delete and copy on Windows
                    IOUtils.rename(output, input);
                } else if (input.exists()) {
                    input.delete();
                }
            }
        }
    } finally {
        if (outputDirectory != null) {
            FileUtils.deleteQuietly(outputDirectory);
        }
    }
}

From source file:org.grouplens.lenskit.eval.maven.RScriptMojo.java

@Override
public void execute() throws MojoExecutionException {
    getLog().info("The analysis directory is " + analysisDir);
    getLog().info("The analysisScript is " + analysisScript);
    getLog().info("The R executable is " + rscriptExecutable);

    // Copy the script file into the working directory.  We could just execute
    // it from its original location, but it will be easier for our users to 
    // have the copy from the src directory next to its results in target.
    File scriptFile = new File(analysisScript);
    File scriptCopy = new File(analysisDir, scriptFile.getName());
    try {//from   www. j  a  va 2s.  c  om
        if (!scriptFile.getCanonicalPath().equals(scriptCopy.getCanonicalPath())) {
            copyFile(scriptFile, scriptCopy);
        }
    } catch (IOException e1) {
        throw new MojoExecutionException("Unable to copy scriptFile " + scriptFile.getAbsolutePath()
                + " into working directory " + scriptCopy.getAbsolutePath());
    }

    // Generate the command line for executing R.
    final CommandLine command = new CommandLine(rscriptExecutable).addArgument(scriptCopy.getAbsolutePath(),
            false);
    getLog().debug("command: " + command);

    // Execute the command line, in the working directory.
    final DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File(analysisDir));
    try {
        if (executor.execute(command) != 0) {
            throw new MojoExecutionException("Error code returned for: " + command.toString());
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException("Error executing command: " + command.toString(), e);
    } catch (IOException e) {
        throw new MojoExecutionException("IO Exception while executing command: " + command.toString(), e);
    }
}

From source file:org.jboss.jdocbook.translate.PoSynchronizerImpl.java

private void updateTranslation(File template, File translation, Locale translationLocale) {
    if (!template.exists()) {
        log.trace("skipping PO updates; POT file did not exist : {0}", template);
        return;/*from  w  w  w.  j av a2s .  c  o  m*/
    }

    if (translation.lastModified() >= template.lastModified()) {
        log.trace("skipping PO updates; up-to-date : {0}", translation);
        return;
    }

    final String translationLocaleString = componentRegistry.toLanguageString(translationLocale);

    CommandLine commandLine;
    if (translation.exists()) {
        commandLine = CommandLine.parse("msgmerge");
        commandLine.addArgument("--quiet");
        commandLine.addArgument("--update");
        commandLine.addArgument("--backup=none");
        commandLine.addArgument(FileUtils.resolveFullPathName(translation));
        commandLine.addArgument(FileUtils.resolveFullPathName(template));
    } else {
        if (!translation.getParentFile().exists()) {
            boolean created = translation.getParentFile().mkdirs();
            if (!created) {
                log.info("Unable to create PO directory {}", translation.getParentFile().getAbsolutePath());
            }
        }
        commandLine = CommandLine.parse("msginit");
        commandLine.addArgument("--no-translator");
        commandLine.addArgument("--locale=" + translationLocaleString);
        commandLine.addArgument("-i");
        commandLine.addArgument(FileUtils.resolveFullPathName(template));
        commandLine.addArgument("-o");
        commandLine.addArgument(FileUtils.resolveFullPathName(translation));
    }

    log.info("po-synch -> " + commandLine.toString());

    DefaultExecutor executor = new DefaultExecutor();
    try {
        executor.execute(commandLine);
    } catch (IOException e) {
        throw new JDocBookProcessException(
                "Error synchronizing PO file [" + template.getName() + "] for " + translationLocaleString, e);
    }
}

From source file:org.jboss.jdocbook.translate.PotSynchronizerImpl.java

private void executeXml2pot(File masterFile, File potFile) {
    CommandLine commandLine = CommandLine.parse("xml2pot");
    commandLine.addArgument(FileUtils.resolveFullPathName(masterFile));

    DefaultExecutor executor = new DefaultExecutor();

    try {/*from   w w  w . j a va 2 s .c  o m*/
        final FileOutputStream xmlStream = new FileOutputStream(potFile);
        PumpStreamHandler streamDirector = new PumpStreamHandler(xmlStream, System.err);
        executor.setStreamHandler(streamDirector);
        try {
            log.trace("updating POT file {0}", potFile);
            executor.execute(commandLine);
        } finally {
            try {
                xmlStream.flush();
                xmlStream.close();
            } catch (IOException ignore) {
                // intentionally empty...
            }
        }
    } catch (IOException e) {
        throw new JDocBookProcessException("unable to open output stream for POT file [" + potFile + "]");
    }
}