Example usage for org.apache.commons.exec CommandLine addArguments

List of usage examples for org.apache.commons.exec CommandLine addArguments

Introduction

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

Prototype

public CommandLine addArguments(final String addArguments, final boolean handleQuoting) 

Source Link

Document

Add multiple arguments.

Usage

From source file:org.codehaus.mojo.VeraxxMojo.java

protected void preExecute(Executor exec, CommandLine commandLine, Map enviro) throws MojoExecutionException {
    OutputStream outStream = /*System.out;*/new ByteArrayOutputStream();
    OutputStream errStream = new ByteArrayOutputStream();

    CommandLine commandLineCheck = new CommandLine(getExecutable());
    Executor execCheck = new DefaultExecutor();
    String[] args = parseCommandlineArgs("--version");
    commandLineCheck.addArguments(args, false);
    execCheck.setWorkingDirectory(exec.getWorkingDirectory());

    getLog().info("Executing command line: " + commandLineCheck);

    int res = 0;/*  w w w.  jav a 2s  .  c  om*/
    try {
        res = executeCommandLine(execCheck, commandLineCheck, enviro, outStream/*getOutputStreamOut()*/,
                errStream/*getOutputStreamErr()*/, getInputStream());
    } catch (ExecuteException e) {
        getLog().info(
                "Exec Exception while detecting Vera++ version. Assume old Vera++ v1.1.x (and less) output parsing style");
        getLog().info("Vera++ err output is : " + errStream.toString());
        veraxx_version = 0;
        /*throw new MojoExecutionException( "preExecute Command execution failed.", e );*/
        return;
    } catch (IOException e) {
        getLog().info("Vera++ detected version is : " + outStream.toString());
        getLog().info("Vera++ err output is : " + errStream.toString());
        // due to jdk8 bug :: https://bugs.openjdk.java.net/browse/JDK-8054565
        // we use this dirty try/catch ...
        // because this quick command line call can close the output stream before jvm does
        getLog().info("jvm " + System.getProperty("java.version") + " (8u11 - 9) workaround, ignoring a "
                + e.toString() + " during vera++ test command line.");
        //throw new MojoExecutionException( "preExecute Command execution failed.", e );
    }

    if (isResultCodeAFailure(res)) {
        getLog().info("Vera++ returned a failure result code : " + res);
        //throw new MojoExecutionException( "preExecute Result of " + commandLineCheck + " execution is: '" + res + "'." );
    }
    DefaultArtifactVersion newFormatMinVersion = new DefaultArtifactVersion("1.2.0");
    DefaultArtifactVersion currentVeraVersion = new DefaultArtifactVersion(outStream.toString());

    getLog().debug("Vera++ detected version is : " + outStream.toString());
    getLog().debug("Vera++ version as ArtefactVersion is : " + currentVeraVersion.toString());

    if (currentVeraVersion.compareTo(newFormatMinVersion) < 0) {
        getLog().info("Use old Vera++ v1.1.x (and less) output parsing style");
        veraxx_version = 0;
    } else {
        getLog().info("Use Vera++ v1.2.0 (and more) output parsing style");
        veraxx_version = 1;
    }
}

From source file:org.eclipse.sisu.equinox.launching.internal.DefaultEquinoxLauncher.java

@Override
public int execute(LaunchConfiguration configuration, int forkedProcessTimeoutInSeconds)
        throws EquinoxLaunchingException {

    String executable = configuration.getJvmExecutable();
    if (executable == null || "".equals(executable)) {
        // use the same JVM as the one used to run Maven (the "java.home" one)
        executable = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
        if (File.separatorChar == '\\') {
            executable = executable + ".exe";
        }//w w w. j av  a2  s . co m
    }
    CommandLine cli = new CommandLine(executable);

    final boolean handleQuotes = false;
    cli.addArguments(configuration.getVMArguments(), handleQuotes);

    cli.addArguments(new String[] { "-jar", getCanonicalPath(configuration.getLauncherJar()) }, handleQuotes);

    cli.addArguments(configuration.getProgramArguments(), handleQuotes);

    log.info("Command line:\n\t" + cli.toString());

    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = null;
    if (forkedProcessTimeoutInSeconds > 0) {
        watchdog = new ExecuteWatchdog(forkedProcessTimeoutInSeconds * 1000L);
        executor.setWatchdog(watchdog);
    }
    // best effort to avoid orphaned child process
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.setWorkingDirectory(configuration.getWorkingDirectory());
    try {
        return executor.execute(cli, getMergedEnvironment(configuration));
    } catch (ExecuteException e) {
        if (watchdog != null && watchdog.killedProcess()) {
            log.error("Timeout " + forkedProcessTimeoutInSeconds + " s exceeded. Process was killed.");
        }
        return e.getExitValue();
    } catch (IOException e) {
        throw new EquinoxLaunchingException(e);
    }
}

From source file:org.fuin.kickstart4j.Kickstart4J.java

/**
 * Executes the installer/updater.//from w ww  .j  a v a2 s  .  c o m
 * 
 * @throws CanceledException
 *             The user canceled the installation.
 * @throws InvalidConfigException
 *             The configuration is invalid.
 */
public final void execute() throws CanceledException, InvalidConfigException {

    Locale.setDefault(config.getLocale());
    final File destDir = getDestDir();
    config.getCmdLineOptions().put("destDir", destDir.toString());

    // Check configuration AFTER destination directory is set
    // and logging is initialized
    config.check();
    initLogging();
    listener.initComplete();

    // Start the update
    final UpdateSet updateSet = new UpdateSet(config.getSrcFiles(), config.getMkDirs(), destDir,
            config.isLazyLoading());
    if (updateSet.isUpdateNecessary()) {
        if (LOG.isInfoEnabled()) {
            LOG.info("An update is available: New=" + updateSet.getNewFiles().size() + ", Changed="
                    + updateSet.getChangedFiles().size() + ", Deleted=" + updateSet.getDeletedFiles().size()
                    + ", SilentInstall=" + config.isSilentInstall() + ", SilentUpdate="
                    + config.isSilentUpdate() + ", FirstInstallation=" + config.isFirstInstallation());
        }
        if (config.isSilentUpdate() || config.isFirstInstallation()
                || isAnswerYes(config.getMessages().getUpdateAvailable())) {
            execute(updateSet);
            final File installationIncompleteFile = new File(destDir, INCOMPLETE_FILE);
            if (installationIncompleteFile.exists()) {
                installationIncompleteFile.delete();
            }
        }
    } else {
        LOG.info("Files are up to date");
    }

    final JFrame startFrame = showStartFrame();

    config.getCmdLineOptions().put("classpath", updateSet.createClasspath());

    // Write the config to the target directory
    saveConfigToTargetDir(destDir);

    // Run the target application
    final CommandLine commandLine = new CommandLine(config.getJavaExe());
    commandLine.addArguments(config.getJavaArgs(), false);
    logStart(destDir, commandLine.toString());
    new ApplicationStarter(destDir, commandLine, startFrame, listener, config).execute();

}

From source file:org.jahia.modules.docviewer.PDF2SWFConverterService.java

protected CommandLine getConvertCommandLine(File inputFile, File outputFile) {
    CommandLine cmd = new CommandLine(getExecutablePath());
    cmd.addArgument("${inFile}");
    cmd.addArgument("-o");
    cmd.addArgument("${outFile}");
    cmd.addArguments(getParameters(), false);

    Map<String, File> params = new HashMap<String, File>(2);
    params.put("inFile", inputFile);
    params.put("outFile", outputFile);

    cmd.setSubstitutionMap(params);/* w w w  .  java 2 s  .  com*/

    return cmd;
}

From source file:org.jahia.utils.ProcessHelper.java

/**
 * Executes the external process using the provided command, arguments (optional), parameter substitution map to expand variables in the
 * command or arguments in form of <code>${variable}<code> (optional) and a working directory (optional).
 * Buffers for process output and error stream can be provided.
 * //from  w  w  w  .  jav  a2s  . c  o  m
 * @param command
 *            the command to be executed
 * @param arguments
 *            optional arguments for the command
 * @param parameterSubstitutionMap
 *            optional values for variables to be expanded
 * @param workingDir
 *            optional working directory for the process to be started from
 * @param resultOut
 *            the buffer to write the process execution output into (optional)
 * @param resultErr
 *            the buffer to write the process execution error into (optional)
 * @return the execution status
 * @return redirectOutputs if set to <code>true</code> the output of the execution will be also redirected to standard system out and
 *         the error to error out
 * @throws JahiaRuntimeException
 *             in case the process execution failed
 */
public static int execute(String command, String arguments[], Map<String, Object> parameterSubstitutionMap,
        File workingDir, StringBuilder resultOut, StringBuilder resultErr, boolean redirectOutputs)
        throws JahiaRuntimeException {

    long timer = System.currentTimeMillis();

    CommandLine cmd = new CommandLine(command);

    if (arguments != null && arguments.length > 0) {
        cmd.addArguments(arguments, false);
    }

    if (parameterSubstitutionMap != null && !parameterSubstitutionMap.isEmpty()) {
        cmd.setSubstitutionMap(parameterSubstitutionMap);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Executing command: {}", cmd.toString());
    } else if (redirectOutputs) {
        logger.info("Executing command: ");
        logger.info(cmd.toString());
    }

    int exitValue = 0;

    StringOutputStream out = new StringOutputStream(redirectOutputs ? System.out : null);
    StringOutputStream err = new StringOutputStream(redirectOutputs ? System.err : null);
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(out, err));
        if (workingDir != null) {
            if (workingDir.exists() || workingDir.mkdirs()) {
                executor.setWorkingDirectory(workingDir);
            }
        }
        exitValue = executor.execute(cmd, System.getenv());
    } catch (ExecuteException ee) {
        return ee.getExitValue();
    } catch (Exception e) {
        throw new JahiaRuntimeException(e);
    } finally {
        if (resultErr != null) {
            resultErr.append(err.toString());
        }
        if (resultOut != null) {
            resultOut.append(out.toString());
        }
        if (exitValue > 0) {
            logger.error("External process finished with error. Cause: {}", err.toString());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Execution took {} ms and finished with status {} and output {}",
                    new Object[] { (System.currentTimeMillis() - timer), exitValue, out.toString() });
        }
    }

    return exitValue;
}

From source file:org.mule.tooling.jubula.cliexecutor.internal.DefaultCliExecutor.java

@Override
public int run(final File executable, final String... params) {
    try {//from   w  w w.j a  va 2  s.  c  o m
        final DefaultExecutor executor = new DefaultExecutor();
        final CommandLine command = CommandLine.parse(executable.getAbsolutePath());
        command.addArguments(params, true);
        return executor.execute(command);
    } catch (final ExecuteException e) {
        throw new RuntimeException(e);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.mule.tooling.jubula.cliexecutor.internal.DefaultCliExecutor.java

@Override
public void runAsync(final String commandString, final Callback callback, final String... params) {
    try {/*w  ww.  ja va2s.c  om*/
        final DefaultExecutor executor = new DefaultExecutor();
        final CommandLine command = CommandLine.parse(commandString);
        command.addArguments(params, true);
        executor.execute(command, new ExecuteResultHandler() {

            @Override
            public void onProcessFailed(final ExecuteException returnCode) {
                callback.failure(returnCode.getExitValue());
            }

            @Override
            public void onProcessComplete(final int returnCode) {
                callback.success(returnCode);
            }
        });
    } catch (final ExecuteException e) {
        throw new RuntimeException(e);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.nanoko.playframework.mojo.Play2DebugMojo.java

public void execute() throws MojoExecutionException {

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);

    cmdLine.addArgument("debug");
    cmdLine.addArguments(getPlay2SystemPropertiesArguments(), false);
    cmdLine.addArgument("run");
    DefaultExecutor executor = new DefaultExecutor();

    // As where not linked to a project, we can't set the working directory.
    // So it will use the directory where mvn was launched.

    executor.setExitValue(0);//from   w ww.  j a va  2 s.  c o m
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        // Ignore.
    }
}

From source file:org.nanoko.playframework.mojo.Play2StartMojo.java

public void execute() throws MojoExecutionException {

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArguments(getPlay2SystemPropertiesArguments(), false);
    cmdLine.addArgument("start");
    System.out.println(cmdLine.toString());
    DefaultExecutor executor = new DefaultExecutor();

    // As where not linked to a project, we can't set the working directory.
    // So it will use the directory where mvn was launched.

    executor.setExitValue(0);//from w  w  w .j  a  va2  s .com
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        // Ignore.
    }
}

From source file:org.nanoko.playframework.mojo.Play2StopMojo.java

public void execute() throws MojoExecutionException {

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArguments(getPlay2SystemPropertiesArguments(), false);
    cmdLine.addArgument("stop");
    System.out.println(cmdLine.toString());
    DefaultExecutor executor = new DefaultExecutor();

    // As where not linked to a project, we can't set the working directory.
    // So it will use the directory where mvn was launched.

    executor.setExitValue(0);/* w w w  . ja  va  2  s  .co  m*/
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        // Ignore.
    }
}