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

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

Introduction

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

Prototype

public CommandLine(final CommandLine other) 

Source Link

Document

Copy constructor.

Usage

From source file:org.bonitasoft.platform.setup.PlatformSetupTestUtils.java

public static CommandLine createCommandLine() {
    if (OS.isFamilyWindows() || OS.isFamilyWin9x()) {
        CommandLine oCmdLine = new CommandLine("cmd");
        oCmdLine.addArgument("/c");
        oCmdLine.addArgument("setup.bat");
        return oCmdLine;
    } else {/* www .  j a  v  a  2s .  c  om*/
        CommandLine oCmdLine = new CommandLine("sh");
        oCmdLine.addArgument("setup.sh");
        return oCmdLine;
    }
}

From source file:org.brailleblaster.util.ProgramCaller.java

public ProgramCaller(String command, String[] args, int returnValue) throws ExecuteException, IOException {
    cmdLine = new CommandLine(command + BBIni.getNativeCommandSuffix());
    for (int i = 0; i < args.length; i++)
        cmdLine.addArgument(args[i]);//from w w w  . ja v a 2s. co  m
    resultHandler = new DefaultExecuteResultHandler();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(returnValue);
    executor.setWatchdog(watchdog);
    executor.execute(cmdLine, resultHandler);
}

From source file:org.cloudifysource.shell.commands.StartLocalCloud.java

private CommandLine createCommandLine() {
    String os = System.getProperty("os.name");
    logger.fine("os.name = " + os);
    if (os == null) {
        throw new java.lang.IllegalStateException("The System Property variable 'os.name' was not set");
    }//from ww  w  .j ava  2  s  . c o  m

    os = os.toLowerCase();
    CommandLine cmdLine = null;
    boolean isWindows = os.startsWith("win");

    if (isWindows) {
        cmdLine = new CommandLine(WINDOWS_EXECUTABLE);
        for (String param : WINDOWS_PREFIX) {
            cmdLine.addArgument(param);
        }

    } else {
        cmdLine = new CommandLine(LINUX_EXECUTABLE);
    }

    for (String param : AGENT_PARAMETERS) {
        cmdLine.addArgument(param);

    }

    if (isWindows) {
        for (String param : WINDOWS_SUFFIX) {
            cmdLine.addArgument(param);
        }
    } else {
        for (String param : LINUX_SUFFIX) {
            cmdLine.addArgument(param);
        }
    }

    return cmdLine;
}

From source file:org.cloudifysource.shell.commands.TestRecipe.java

/**
 * Create a complete command line, including path and arguments.
 *
 * @return Configured command line, ready for execution
 */// w w  w . j a  v a2  s.  c  om
private CommandLine createCommandLine() {
    final String javaPath = getJavaPath();

    final String gsHome = Environment.getHomeDirectory();
    final String[] commandParams = { "-Dcom.gs.home=" + gsHome,
            "-Dorg.hyperic.sigar.path=" + gsHome + "/lib/platform/sigar",
            "-D" + CloudifyConstants.TEST_RECIPE_TIMEOUT_SYSPROP + "=" + timeout,
            IntegratedProcessingUnitContainer.class.getName(), "-cluster", "id=1", "total_members=1" };
    final CommandLine cmdLine = new CommandLine(javaPath);

    for (final String param : commandParams) {
        cmdLine.addArgument(param);
    }
    if (this.serviceFileName != null) {
        cmdLine.addArgument("-properties");
        cmdLine.addArgument(
                "embed://" + CloudifyConstants.CONTEXT_PROPERTY_SERVICE_FILE_NAME + "=" + this.serviceFileName);
    }

    // -Dcom.gs.usm.RecipeShutdownTimeout=10

    return cmdLine;
}

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

/**
 * The current build session instance./*from   w  ww.  j  av  a 2  s . co  m*/
 * 
 * @parameter expression="${session}"
 * @required
 * @readonly
 */
//private MavenSession session;

CommandLine getExecutablePath(Map enviro, File dir) {
    File execFile = new File(getExecutable());
    String exec = null;
    if (execFile.exists()) {
        getLog().debug("Toolchains are ignored, 'executable' parameter is set to " + getExecutable());
        exec = execFile.getAbsolutePath();
    } else {
        if (OS.isFamilyWindows()) {
            String ex = getExecutable().indexOf(".") < 0 ? getExecutable() + ".bat" : getExecutable();
            File f = new File(dir, ex);
            if (f.exists()) {
                exec = ex;
            } else {
                // now try to figure the path from PATH, PATHEXT env vars
                // if bat file, wrap in cmd /c
                String path = (String) enviro.get("PATH");
                if (path != null) {
                    String[] elems = StringUtils.split(path, File.pathSeparator);
                    for (int i = 0; i < elems.length; i++) {
                        f = new File(new File(elems[i]), ex);
                        if (f.exists()) {
                            exec = ex;
                            break;
                        }
                    }
                }
            }
        }
    }

    if (exec == null) {
        exec = getExecutable();
    }

    CommandLine toRet;
    if (OS.isFamilyWindows() && exec.toLowerCase(Locale.getDefault()).endsWith(".bat")) {
        toRet = new CommandLine("cmd");
        toRet.addArgument("/c");
        toRet.addArgument(exec);
    } else {
        toRet = new CommandLine(exec);
    }

    return toRet;
}

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  v  a 2s .  c  om*/

    // ----------------------------------------------------------------------
    // 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.cassandra.AbstractCassandraMojo.java

/**
 * Create a {@link CommandLine} to launch Java.
 *
 * @return a {@link CommandLine} to launch Java.
 *//*  w ww. jav  a  2s . co  m*/
protected CommandLine newJavaCommandLine() {
    String exec = null;
    Toolchain tc = getToolchain();

    // if the file doesn't exist & toolchain is null, java is probably in the PATH...
    // we should probably also test for isFile and canExecute, but the second one is only
    // available in SDK 6.
    if (tc != null) {
        getLog().info("Toolchain in cassandra-maven-plugin: " + tc);
        exec = tc.findTool("java");
    } else {
        if (OS.isFamilyWindows()) {
            String ex = "java.exe";
            // now try to figure the path from PATH, PATHEXT env vars
            // if bat file, wrap in cmd /c
            String path = System.getenv("PATH");
            if (path != null) {
                for (String elem : StringUtils.split(path, File.pathSeparator)) {
                    File f = new File(new File(elem), ex);
                    if (f.exists()) {
                        exec = ex;
                        break;
                    }
                }
            }
        }
    }

    if (exec == null) {
        exec = "java";
    }

    return new CommandLine(exec);
}

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 {/*w w  w  .ja va  2  s.  c  om*/
        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

CommandLine getExecutablePath(Map<String, String> enviro, File dir) {
    File execFile = new File(executable);
    String exec = null;//  w  ww.ja  v a  2  s .  co m
    if (execFile.isFile()) {
        getLog().debug("Toolchains are ignored, 'executable' parameter is set to " + executable);
        exec = execFile.getAbsolutePath();
    }

    if (exec == null) {
        Toolchain tc = getToolchain();

        // if the file doesn't exist & toolchain is null, the exec is probably in the PATH...
        // we should probably also test for isFile and canExecute, but the second one is only
        // available in SDK 6.
        if (tc != null) {
            getLog().info("Toolchain in exec-maven-plugin: " + tc);
            exec = tc.findTool(executable);
        } else {
            if (OS.isFamilyWindows()) {
                List<String> paths = this.getExecutablePaths(enviro);
                paths.add(0, dir.getAbsolutePath());

                exec = findExecutable(executable, paths);
            }
        }
    }

    if (exec == null) {
        exec = executable;
    }

    CommandLine toRet;
    if (OS.isFamilyWindows() && !hasNativeExtension(exec) && hasExecutableExtension(exec)) {
        // run the windows batch script in isolation and exit at the end
        final String comSpec = System.getenv("ComSpec");
        toRet = new CommandLine(comSpec == null ? "cmd" : comSpec);
        toRet.addArgument("/c");
        toRet.addArgument(exec);
    } else {
        toRet = new CommandLine(exec);
    }

    return toRet;
}

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 ww .jav  a  2 s. 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;
    }
}