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:net.sourceforge.vulcan.git.ProcessInvoker.java

public InvocationResult invoke(String command, File workDir, String... args) throws IOException {
    CommandLine cmdLine = new CommandLine(executable);

    cmdLine.addArgument(command);/*from  w  w w  .  ja  v  a 2 s  .co m*/
    cmdLine.addArgument("--noninteractive");
    cmdLine.addArguments(args, false);

    err = new ByteArrayOutputStream();

    executor.setExitValues(new int[] { 0, 1 });
    executor.setWorkingDirectory(workDir);
    executor.setStreamHandler(new MyPumpStreamHandler(out, err));

    LOG.debug("Executing " + cmdLine);

    try {
        exitCode = executor.execute(cmdLine);
        return new InvocationResult(isOutputRedirected() ? null : out.toString(), err.toString(),
                exitCode == 0);
    } catch (ExecuteException e) {
        exitCode = e.getExitValue();
        throw e;
    }

}

From source file:nl.tudelft.graphalytics.graphlab.GraphLabPlatform.java

/**
 * Execute the python script belonging to a given AlgorithmType with the given graph location and extra arguments
 * and return the Process created by the Java Runtime.
 * @param job The GraphLab job to execute
 * @return The exit code of the python subprocess
 * @throws IOException When an I/O error occurs
 *//*w  ww.ja v  a  2 s .c  om*/
private int executePythonJob(GraphLabJob job) throws IOException {
    LOG.entry(job);

    if (job == null) {
        LOG.warn("GraphLab job set to execute is null, skipping execution.");
        return LOG.exit(-1);
    }

    // Extract the script resource file
    File scriptFile = extractFile(job.getPythonFile());
    if (scriptFile == null) {
        return LOG.exit(-1);
    }

    // Construct the commandline execution pattern starting with the python executable
    CommandLine commandLine = new CommandLine("python2");

    // Add the arguments that are the same for all jobs
    commandLine.addArgument(scriptFile.getAbsolutePath());
    commandLine.addArgument("--target");
    commandLine.addArgument(TARGET);
    if (USE_HADOOP) {
        commandLine.addArgument("--virtual-cores");
        commandLine.addArgument(VIRTUAL_CORES, false);
        commandLine.addArgument("--heap-size");
        commandLine.addArgument(HEAP_SIZE, false);
    }

    // Add the save_graph_result parameter is true (default false, but can be set to true for automated testing)
    if (saveGraphResult) {
        commandLine.addArgument("--save-result");
    }

    // Let the job format it's arguments and add it to the commandline
    commandLine.addArguments(job.formatParametersAsStrings(), false);

    // Set the executor of the command, if desired this can be changed to a custom implementation
    DefaultExecutor executor = new DefaultExecutor();

    // Set the OutputStream to enable printing the output of the algorithm
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outputStream));

    int result;
    try {
        // Execute the actual command and store the return code
        result = executor.execute(commandLine);
        // Print the command output
        System.out.println(outputStream.toString());
    } catch (ExecuteException e) {
        // Catch the exception thrown when the process exits with result != 0
        System.out.println(outputStream.toString());
        LOG.catching(Level.ERROR, e);
        return LOG.exit(e.getExitValue());
    }
    return LOG.exit(result);
}

From source file:org.apache.cloudstack.wix.HeatMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {//from  ww w .  j a v  a  2s .c  o  m
        CommandLine commandLine = new CommandLine("heat");

        if (dir != null && !dir.trim().isEmpty()) {
            commandLine.addArgument("dir");
            commandLine.addArgument(dir);
        }

        commandLine.addArgument("-gg");
        commandLine.addArgument("-cg");
        commandLine.addArgument(componentGroup);
        commandLine.addArgument("-ke");
        commandLine.addArgument("-sfrag");

        if (template == null || template.trim().isEmpty()) {
            commandLine.addArgument("-template");
            commandLine.addArgument("fragment");
        } else {
            commandLine.addArgument("-template");
            commandLine.addArgument(template);
        }

        if (outputFile != null) {
            commandLine.addArgument("-out");
            commandLine.addArgument(outputFile.getAbsolutePath());
        }

        if (directoryName != null) {
            commandLine.addArgument("-dr");
            commandLine.addArgument(directoryName);
        }

        if (vars != null) {
            commandLine.addArguments(vars, false);
        }

        DefaultExecutor executor = new DefaultExecutor();
        getLog().debug("working directory " + commandLine.toString());
        executor.setWorkingDirectory(getWorkingDirectory(workingDirectory));
        int exitValue = executor.execute(commandLine);

        if (exitValue != 0) {
            throw new MojoExecutionException("Problem executing heat, return code " + exitValue);
        }

    } catch (ExecuteException e) {
        throw new MojoExecutionException("Problem executing heat", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Problem executing heat", e);
    }
}

From source file:org.apache.maven.plugin.cxx.AbstractLaunchMojo.java

@Override
public void execute() throws MojoExecutionException {
    if (isSkip()) {
        getLog().info("skipping execute as per configuraion");
        return;//from w  w w.  ja  v a2s  .c  om
    }

    if (basedir == null) {
        throw new IllegalStateException("basedir is null. Should not be possible.");
    }

    List<String> commandArguments = getCommandLineArgs();

    Properties enviro = getEnvs();

    ensureExistWorkingDirectory();

    CommandLine commandLine = ExecutorService.getExecutablePath(getExecutable(), enviro, getWorkingDir());

    Executor exec = new DefaultExecutor();

    commandLine.addArguments((String[]) commandArguments.toArray(new String[commandArguments.size()]), false);

    exec.setWorkingDirectory(getWorkingDir());

    try {
        getLog().info("Executing command line: " + commandLine);

        preExecute(exec, commandLine, enviro);

        int resultCode = ExecutorService.executeCommandLine(exec, commandLine, enviro, getOutputStreamOut(),
                getOutputStreamErr(), getInputStream());

        postExecute(resultCode);
    } catch (ExecuteException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    }
}

From source file:org.apache.maven.plugin.cxx.CoverageMojo.java

@Override
protected void postExecute(int resultCode) throws MojoExecutionException {
    String outputReportName = new String();
    if (reportsfileDir.isAbsolute()) {
        outputReportName = reportsfileDir.getAbsolutePath() + "/" + getReportFileName();
    } else {/*from   www.jav a 2s.  c o m*/
        outputReportName = basedir.getAbsolutePath() + "/" + reportsfileDir.getPath() + "/"
                + getReportFileName();
    }
    getLog().info("Coverage report location " + outputReportName);

    OutputStream outStream = System.out;
    File file = new File(outputReportName);
    try {
        new File(file.getParent()).mkdirs();
        file.createNewFile();
        outStream = new FileOutputStream(file);
    } catch (IOException e) {
        getLog().error("Coverage report redirected to stdout since " + outputReportName + " can't be opened");
    }

    InputStream pyScript = getClass().getResourceAsStream("/gcovr.py");

    CommandLine commandLine = new CommandLine("python");
    Executor exec = new DefaultExecutor();
    String[] args = parseCommandlineArgs("-");
    commandLine.addArguments(args, false);
    args = parseCommandlineArgs(gcovrArgs);
    commandLine.addArguments(args, false);
    exec.setWorkingDirectory(getWorkingDir());
    try {
        getLog().info("Executing command line: " + commandLine);

        int res = ExecutorService.executeCommandLine(exec, commandLine, getEnvs(),
                outStream/*getOutputStreamOut()*/, getOutputStreamErr(), pyScript/*getInputStream()*/ );
        // this is a hugly workaround against a random bugs from hudson cobertura plugin.
        // hudson cobertura plugin randomly truncat coverage reports file to a 1024 size multiple
        // while it copy reports from slave to master node
        for (int j = 0; j < 200; j++) {
            for (int i = 0; i < 80; i++) {
                outStream.write(' ');
            }
            outStream.write('\n');
        }
        outStream.flush();

        if (isResultCodeAFailure(res)) {
            throw new MojoExecutionException("Result of command line execution is: '" + res + "'.");
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    }
}

From source file:org.apache.maven.plugin.cxx.VeraxxMojo.java

@Override
protected void preExecute(Executor exec, CommandLine commandLine, Properties 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  ww  . jav a 2  s.co  m
    try {
        res = ExecutorService.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());
        veraxxVersion = 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");
        veraxxVersion = 0;
    } else {
        getLog().info("Use Vera++ v1.2.0 (and more) output parsing style");
        veraxxVersion = 1;
    }
}

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

public void execute() throws MojoExecutionException {
    if (isSkip()) {
        getLog().info("skipping execute as per configuraion");
        return;/*  w  w  w  . j  a v  a 2s .  c  o  m*/
    }

    if (basedir == null) {
        throw new IllegalStateException("basedir is null. Should not be possible.");
    }

    List commandArguments = getCommandLineArgs();

    Map enviro = getEnvs();

    EnsureExistWorkingDirectory();

    CommandLine commandLine = getExecutablePath(enviro, getWorkingDir());

    Executor exec = new DefaultExecutor();

    commandLine.addArguments((String[]) commandArguments.toArray(new String[commandArguments.size()]), false);

    exec.setWorkingDirectory(getWorkingDir());

    try {
        getLog().info("Executing command line: " + commandLine);

        preExecute(exec, commandLine, enviro);

        int resultCode = executeCommandLine(exec, commandLine, enviro, getOutputStreamOut(),
                getOutputStreamErr(), getInputStream());

        postExecute(resultCode);
    } catch (ExecuteException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    }
}

From source file:org.codehaus.mojo.antlr.AbstractAntlrMojo.java

protected void performGeneration(GenerationPlan plan, Artifact antlrArtifact) throws MojoExecutionException {
    if (!plan.getGenerationDirectory().getParentFile().exists()) {
        plan.getGenerationDirectory().getParentFile().mkdirs();
    }/*from w  w  w.j a va  2  s .  c  o m*/

    // ----------------------------------------------------------------------
    // Wrap arguments
    // Note: grammar file should be last
    // ----------------------------------------------------------------------

    List arguments = new LinkedList();
    addArgIf(arguments, debug, "-debug");
    addArgIf(arguments, diagnostic, "-diagnostic");
    addArgIf(arguments, trace, "-trace");
    addArgIf(arguments, traceParser, "-traceParser");
    addArgIf(arguments, traceLexer, "-traceLexer");
    addArgIf(arguments, traceTreeParser, "-traceTreeParser");

    addArgs(arguments);

    arguments.add("-o");
    arguments.add(plan.getGenerationDirectory().getPath());

    if (plan.getCollectedSuperGrammarIds().size() > 0) {
        arguments.add("-glib");
        StringBuffer buffer = new StringBuffer();
        Iterator ids = plan.getCollectedSuperGrammarIds().iterator();
        while (ids.hasNext()) {
            buffer.append(new File(sourceDirectory, (String) ids.next()));
            if (ids.hasNext()) {
                buffer.append(';');
            }
        }
        arguments.add(buffer.toString());
    }

    arguments.add(plan.getSource().getPath());

    String[] args = (String[]) arguments.toArray(new String[arguments.size()]);

    if (plan.getImportVocabTokenTypesDirectory() != null
            && !plan.getImportVocabTokenTypesDirectory().equals(plan.getGenerationDirectory())) {
        // we need to spawn a new process to properly set up PWD
        CommandLine commandLine = new CommandLine("java");
        commandLine.addArgument("-classpath", false);
        commandLine.addArgument(generateClasspathForProcessSpawning(antlrArtifact), true);
        commandLine.addArgument("antlr.Tool", false);
        commandLine.addArguments(args, true);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(plan.getImportVocabTokenTypesDirectory());
        try {
            executor.execute(commandLine);
        } catch (IOException e) {
            getLog().warn("Error spawning process to execute antlr tool : " + e.getMessage());
        }

        return;
    }

    // ----------------------------------------------------------------------
    // Call Antlr
    // ----------------------------------------------------------------------

    if (getLog().isDebugEnabled()) {
        getLog().debug("antlr args=\n" + StringUtils.join(args, "\n"));
    }

    boolean failedSetManager = false;
    SecurityManager oldSm = null;
    try {
        oldSm = System.getSecurityManager();
        System.setSecurityManager(NoExitSecurityManager.INSTANCE);
    } catch (SecurityException ex) {
        // ANTLR-12
        oldSm = null;
        failedSetManager = true;
        // ignore, in embedded environment the security manager can already be set.
        // in such a case assume the exit call is handled properly..
        getLog().warn("Cannot set custom SecurityManager. "
                + "Antlr's call to System.exit() can cause application shutdown "
                + "if not handled by the current SecurityManager.");
    }

    String originalUserDir = null;
    if (plan.getImportVocabTokenTypesDirectory() != null) {
        originalUserDir = System.getProperty("user.dir");
        System.setProperty("user.dir", plan.getImportVocabTokenTypesDirectory().getPath());
    }

    PrintStream oldErr = System.err;

    OutputStream errOS = new StringOutputStream();
    PrintStream err = new PrintStream(errOS);
    System.setErr(err);

    try {
        executeAntlrInIsolatedClassLoader((String[]) arguments.toArray(new String[0]), antlrArtifact);
    } catch (SecurityException e) {
        if (e.getMessage().equals("exitVM-0")
                || e.getClass().getName().equals("org.netbeans.core.execution.ExitSecurityException")) // netbeans
                                                                                                                                             // IDE Sec
                                                                                                                                             // Manager.
        {
            // ANTLR-12
            // now basically every secutiry manager could set different message, how to handle in generic way?
            // probably only by external execution
            // / in case of NetBeans SecurityManager, it's not possible to distinguish exit codes, rather swallow
            // than fail.
            getLog().debug(e);
        } else {
            throw new MojoExecutionException(
                    "Antlr execution failed: " + e.getMessage() + "\n Error output:\n" + errOS, e);
        }
    } finally {
        if (originalUserDir != null) {
            System.setProperty("user.dir", originalUserDir);
        }
        if (!failedSetManager) {
            System.setSecurityManager(oldSm);
        }
        System.setErr(oldErr);
        System.err.println(errOS.toString());
    }
}

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

protected void postExecute(int resultCode) throws MojoExecutionException {
    String OutputReportName = new String();
    if (reportsfileDir.isAbsolute()) {
        OutputReportName = reportsfileDir.getAbsolutePath() + "/" + getReportFileName();
    } else {//ww  w.ja  v  a2s .  co  m
        OutputReportName = basedir.getAbsolutePath() + "/" + reportsfileDir.getPath() + "/"
                + getReportFileName();
    }
    getLog().info("Coverage report location " + OutputReportName);

    OutputStream outStream = System.out;
    File file = new File(OutputReportName);
    try {
        new File(file.getParent()).mkdirs();
        file.createNewFile();
        outStream = new FileOutputStream(file);
    } catch (IOException e) {
        getLog().error("Coverage report redirected to stdout since " + OutputReportName + " can't be opened");
    }

    InputStream pyScript = getClass().getResourceAsStream("/gcovr.py");

    CommandLine commandLine = new CommandLine("python");
    Executor exec = new DefaultExecutor();
    String[] args = parseCommandlineArgs("-");
    commandLine.addArguments(args, false);
    args = parseCommandlineArgs(gcovrArgs);
    commandLine.addArguments(args, false);
    exec.setWorkingDirectory(getWorkingDir());
    try {
        getLog().info("Executing command line: " + commandLine);

        int res = executeCommandLine(exec, commandLine, getEnvs(), outStream/*getOutputStreamOut()*/,
                getOutputStreamErr(), pyScript/*getInputStream()*/ );
        // this is a hugly workaround against a random bugs from hudson cobertura plugin.
        // hudson cobertura plugin randomly truncat coverage reports file to a 1024 size multiple
        // while it copy reports from slave to master node
        for (int j = 0; j < 200; j++) {
            for (int i = 0; i < 80; i++) {
                outStream.write(' ');
            }
            outStream.write('\n');
        }
        outStream.flush();

        if (isResultCodeAFailure(res)) {
            throw new MojoExecutionException("Result of command line execution is: '" + res + "'.");
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    } catch (IOException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    }
}

From source file:org.codehaus.mojo.exec.ExecMojo.java

/**
 * priority in the execute method will be to use System properties arguments over the pom specification.
 *
 * @throws MojoExecutionException if a failure happens
 *//*w  ww.ja va  2s. c  o  m*/
public void execute() throws MojoExecutionException {
    if (executable == null) {
        if (executableDependency == null) {
            throw new MojoExecutionException("The parameter 'executable' is missing or invalid");
        }

        executable = findExecutableArtifact().getFile().getAbsolutePath();
        getLog().debug("using executable dependency " + executable);
    }

    if (isSkip()) {
        getLog().info("skipping execute as per configuration");
        return;
    }

    if (basedir == null) {
        throw new IllegalStateException("basedir is null. Should not be possible.");
    }

    try {

        handleWorkingDirectory();

        String argsProp = getSystemProperty("exec.args");

        List<String> commandArguments = new ArrayList<String>();

        if (hasCommandlineArgs()) {
            handleCommandLineArgs(commandArguments);
        } else if (!StringUtils.isEmpty(argsProp)) {
            handleSystemPropertyArguments(argsProp, commandArguments);
        } else {
            if (arguments != null) {
                handleArguments(commandArguments);
            }
        }

        if (hasAdditionalArgs()) {
            handleAdditionalArgs(commandArguments);
        }

        Map<String, String> enviro = handleSystemEnvVariables();

        CommandLine commandLine = getExecutablePath(enviro, workingDirectory);

        String[] args = commandArguments.toArray(new String[commandArguments.size()]);

        commandLine.addArguments(args, false);

        Executor exec = new DefaultExecutor();
        exec.setWorkingDirectory(workingDirectory);
        fillSuccessCodes(exec);

        getLog().debug("Executing command line: " + commandLine);

        try {
            int resultCode;
            if (outputFile != null) {
                if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) {
                    getLog().warn(
                            "Could not create non existing parent directories for log file: " + outputFile);
                }

                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(outputFile);

                    resultCode = executeCommandLine(exec, commandLine, enviro, outputStream);
                } finally {
                    IOUtil.close(outputStream);
                }
            } else {
                resultCode = executeCommandLine(exec, commandLine, enviro, System.out, System.err);
            }

            if (isResultCodeAFailure(resultCode)) {
                String message = "Result of " + commandLine.toString() + " execution is: '" + resultCode + "'.";
                getLog().error(message);
                throw new MojoExecutionException(message);
            }
        } catch (ExecuteException e) {
            getLog().error("Command execution failed.", e);
            throw new MojoExecutionException("Command execution failed.", e);
        } catch (IOException e) {
            getLog().error("Command execution failed.", e);
            throw new MojoExecutionException("Command execution failed.", e);
        }

        registerSourceRoots();
    } catch (IOException e) {
        throw new MojoExecutionException("I/O Error", e);
    }
}