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

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Stringify operator returns the command line as a string.

Usage

From source file:com.theoryinpractise.clojure.AbstractClojureCompilerMojo.java

protected void callClojureWith(ExecutionMode executionMode, File[] sourceDirectory, File outputDirectory,
        List<String> compileClasspathElements, String mainClass, String[] clojureArgs)
        throws MojoExecutionException {

    outputDirectory.mkdirs();// w w w . jav a  2s  .c o  m

    String classpath = manifestClasspath(sourceDirectory, outputDirectory, compileClasspathElements);

    final String javaExecutable = getJavaExecutable();
    getLog().debug("Java exectuable used:  " + javaExecutable);
    getLog().debug("Clojure manifest classpath: " + classpath);
    CommandLine cl = null;

    if (ExecutionMode.INTERACTIVE == executionMode && SystemUtils.IS_OS_WINDOWS
            && spawnInteractiveConsoleOnWindows) {
        Scanner sc = new Scanner(windowsConsole);
        Pattern pattern = Pattern.compile("\"[^\"]*\"|'[^']*'|[\\w'/]+");
        cl = new CommandLine(sc.findInLine(pattern));
        String param;
        while ((param = sc.findInLine(pattern)) != null) {
            cl.addArgument(param);
        }
        cl.addArgument(javaExecutable);
    } else {
        cl = new CommandLine(javaExecutable);
    }

    if (vmargs != null) {
        cl.addArguments(vmargs, false);
    }

    cl.addArgument("-Dclojure.compile.path=" + escapeFilePath(outputDirectory), false);

    if (warnOnReflection)
        cl.addArgument("-Dclojure.compile.warn-on-reflection=true");

    cl.addArguments(clojureOptions, false);

    cl.addArgument("-jar");
    File jar;
    if (prependClasses != null && prependClasses.size() > 0) {
        jar = createJar(classpath, prependClasses.get(0));
        cl.addArgument(jar.getAbsolutePath(), false);
        List<String> allButFirst = prependClasses.subList(1, prependClasses.size());
        cl.addArguments(allButFirst.toArray(new String[allButFirst.size()]));
        cl.addArgument(mainClass);
    } else {
        jar = createJar(classpath, mainClass);
        cl.addArgument(jar.getAbsolutePath(), false);
    }

    if (clojureArgs != null) {
        cl.addArguments(clojureArgs, false);
    }

    getLog().debug("Command line: " + cl.toString());

    Executor exec = new DefaultExecutor();
    Map<String, String> env = new HashMap<String, String>(System.getenv());
    //        env.put("path", ";");
    //        env.put("path", System.getProperty("java.home"));

    ExecuteStreamHandler handler = new PumpStreamHandler(System.out, System.err, System.in);
    exec.setStreamHandler(handler);
    exec.setWorkingDirectory(getWorkingDirectory());
    ShutdownHookProcessDestroyer destroyer = new ShutdownHookProcessDestroyer();
    exec.setProcessDestroyer(destroyer);

    int status;
    try {
        status = exec.execute(cl, env);
    } catch (ExecuteException e) {
        status = e.getExitValue();
    } catch (IOException e) {
        status = 1;
    }

    if (status != 0) {
        throw new MojoExecutionException("Clojure failed.");
    }

}

From source file:it.drwolf.ridire.index.cwb.CWBFrequencyList.java

private String getFrequencyList(boolean deleteFLFile, List<String> semDescription, List<String> funDescription,
        int quantityP, String type, Integer threshold, boolean sorted) {
    CommandLine commandLine = CommandLine.parse(this.cwbscanExecutable);
    commandLine.addArgument("-q");
    if (threshold != null && threshold > 0) {
        commandLine.addArgument("-f");
        commandLine.addArgument(threshold + "");
    }/*from   ww w.j av  a  2  s  . c  o  m*/
    commandLine.addArgument("-r").addArgument(this.cqpRegistry);
    commandLine.addArgument("-C");
    commandLine.addArgument(this.cqpCorpusName);
    if (type.equals("forma")) {
        commandLine.addArgument("word+0");
    } else if (type.equals("PoS")) {
        commandLine.addArgument("pos+0");
    } else if (type.equals("easypos")) {
        commandLine.addArgument("easypos+0");
    } else if (type.equals("lemma")) {
        commandLine.addArgument("lemma+0");
    } else if (type.equals("PoS-forma")) {
        commandLine.addArgument("pos+0");
        commandLine.addArgument("word+0");
    } else if (type.equals("PoS-lemma")) {
        commandLine.addArgument("pos+0");
        commandLine.addArgument("lemma+0");
    }
    String semFuncParam = "";
    if (funDescription != null && funDescription.size() > 0 && funDescription.get(0) != null
            && funDescription.get(0).trim().length() > 0
            || semDescription != null && semDescription.size() > 0 && semDescription.get(0) != null
                    && semDescription.get(0).trim().length() > 0) {
        semFuncParam = "?";
        if (funDescription != null && funDescription.size() > 0 && funDescription.get(0) != null
                && funDescription.get(0).trim().length() > 0) {
            String fd = StringUtils.join(funDescription, "\\|");
            semFuncParam += "text_functional=/\\(" + fd + "\\)/ ";
        }
        if (semDescription != null && semDescription.size() > 0 && semDescription.get(0) != null
                && semDescription.get(0).trim().length() > 0) {
            String sd = StringUtils.join(semDescription, "\\|");
            semFuncParam += "text_semantic=/\\(" + sd + "\\)/ ";

        }
        commandLine.addArgument(semFuncParam);
    }
    if (sorted) {
        commandLine.addArgument("|");
        commandLine.addArgument("sort");
        commandLine.addArgument("-nr");
        commandLine.addArgument("-k");
        commandLine.addArgument("1");
    }
    if (quantityP > 0) {
        commandLine.addArgument("|");
        commandLine.addArgument("head");
        commandLine.addArgument("-" + quantityP);
    }
    File flTempFile = null;
    try {
        flTempFile = File.createTempFile("ridireFL", null);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    commandLine.addArgument(" > ");
    commandLine.addArgument(flTempFile.getAbsolutePath());
    String c = commandLine.toString();
    try {
        File tempSh = File.createTempFile("ridireSH", ".sh");
        FileUtils.writeStringToFile(tempSh, c);
        tempSh.setExecutable(true);
        commandLine = CommandLine.parse(tempSh.getAbsolutePath());
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBFrequencyList.TIMEOUT);
        executor.setWatchdog(watchdog);
        ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024);
        ByteArrayOutputStream baosStdErr = new ByteArrayOutputStream(1024);
        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, baosStdErr, null);
        executor.setStreamHandler(executeStreamHandler);
        int exitValue = 0;
        exitValue = executor.execute(commandLine);
        FileUtils.deleteQuietly(tempSh);
        if (exitValue == 0) {
            StrTokenizer strTokenizer = new StrTokenizer();
            this.frequencyList = new ArrayList<FrequencyItem>();
            List<String> lines = FileUtils.readLines(flTempFile);
            for (String line : lines) {
                strTokenizer.reset(line);
                String[] tokens = strTokenizer.getTokenArray();
                if (tokens.length == 2) {
                    FrequencyItem frequencyItem = new FrequencyItem(tokens[1],
                            Integer.parseInt(tokens[0].trim()));
                    this.frequencyList.add(frequencyItem);
                } else if (tokens.length == 3) {
                    FrequencyItem frequencyItem = new FrequencyItem(tokens[2], tokens[1],
                            Integer.parseInt(tokens[0].trim()));
                    this.frequencyList.add(frequencyItem);
                }
            }
            if (deleteFLFile) {
                FileUtils.deleteQuietly(flTempFile);
            }
        }
    } catch (ExecuteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return flTempFile.getAbsolutePath();
}

From source file:org.apache.bigtop.itest.hive.HiveHelper.java

public static Map<String, String> execCommand(CommandLine commandline, Map<String, String> envVars) {

    System.out.println("Executing command:");
    System.out.println(commandline.toString());
    Map<String, String> env = null;
    Map<String, String> entry = new HashMap<String, String>();
    try {//w  w  w.  j a  v  a 2  s .  c o m
        env = EnvironmentUtils.getProcEnvironment();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to get process environment: " + e1.getMessage());
        e1.printStackTrace();
    }
    if (envVars != null) {
        for (String key : envVars.keySet()) {
            env.put(key, envVars.get(key));
        }
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 10000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(streamHandler);
    try {
        executor.execute(commandline, env, resultHandler);
    } catch (ExecuteException e) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to execute command with exit value: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString() + e.getMessage());
        e.printStackTrace();
        return entry;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        LOG.debug("Failed to execute command with exit value: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString() + e.getMessage());
        e.printStackTrace();
        return entry;
    }

    try {
        resultHandler.waitFor();
        /*System.out.println("Command output: "+outputStream.toString());*/
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString());
        return entry;
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        /*System.out.println("Command output: "+outputStream.toString());*/
        LOG.debug("exitValue: " + String.valueOf(resultHandler.getExitValue()));
        LOG.debug("outputStream: " + outputStream.toString());
        entry.put("exitValue", String.valueOf(resultHandler.getExitValue()));
        entry.put("outputStream", outputStream.toString());
        e.printStackTrace();
        return entry;
    }
}

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

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {/*from  ww w .j  ava  2s .  c om*/
        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.zeppelin.spark.SparkRInterpreter.java

@Override
public void open() {
    // create R script
    createRScript();/*from   w  w w. java  2s  . co m*/

    int backendTimeout = Integer.parseInt(System.getenv().getOrDefault("SPARKR_BACKEND_TIMEOUT", "120"));

    // Launch a SparkR backend server for the R process to connect to; this will let it see our
    // Java system properties etc.
    ZeppelinRBackend sparkRBackend = new ZeppelinRBackend();

    Semaphore initialized = new Semaphore(0);
    Thread sparkRBackendThread = new Thread("SparkR backend") {
        @Override
        public void run() {
            sparkRBackendPort = sparkRBackend.init();
            initialized.release();
            sparkRBackend.run();
        }
    };

    sparkRBackendThread.start();

    // Wait for RBackend initialization to finish
    try {
        if (initialized.tryAcquire(backendTimeout, TimeUnit.SECONDS)) {
            // Launch R
            CommandLine cmd = CommandLine.parse(getProperty("zeppelin.sparkr.r"));
            cmd.addArgument(scriptPath, false);
            cmd.addArgument("--no-save", false);
            //      cmd.addArgument(getJavaSparkContext().version(), false);
            executor = new DefaultExecutor();
            outputStream = new ByteArrayOutputStream();
            PipedOutputStream ps = new PipedOutputStream();
            in = null;
            try {
                in = new PipedInputStream(ps);
            } catch (IOException e1) {
                throw new InterpreterException(e1);
            }
            ins = new BufferedWriter(new OutputStreamWriter(ps));

            input = new ByteArrayOutputStream();

            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, outputStream, in);
            executor.setStreamHandler(streamHandler);
            executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT));

            Map env = EnvironmentUtils.getProcEnvironment();

            String sparkRInterpreterObjId = sparkRBackend.put(this);
            String uberdataContextObjId = sparkRBackend.put(getUberdataContext());
            env.put("R_PROFILE_USER", scriptPath);
            env.put("SPARK_HOME", getSparkHome());
            env.put("EXISTING_SPARKR_BACKEND_PORT", String.valueOf(sparkRBackendPort));
            env.put("SPARKR_INTERPRETER_ID", sparkRInterpreterObjId);
            env.put("UBERDATA_CONTEXT_ID", uberdataContextObjId);
            logger.info("executing {} {}", env, cmd.toString());
            executor.execute(cmd, env, this);
            logger.info("executed");
            rScriptRunning = true;

        } else {
            System.err.println("SparkR backend did not initialize in " + backendTimeout + " seconds");
            System.exit(-1);
        }
    } catch (InterruptedException e) {
        new InterpreterException((e));
    } catch (IOException e) {
        new InterpreterException((e));
    }

}

From source file:org.apache.zeppelin.spark.ZeppelinR.java

/**
 * Start R repl/*w ww.  j a v a 2  s .c  o m*/
 * @throws IOException
 */
public void open() throws IOException {
    createRScript();

    zeppelinR.put(hashCode(), this);

    CommandLine cmd = CommandLine.parse(rCmdPath);
    cmd.addArgument("--no-save");
    cmd.addArgument("--no-restore");
    cmd.addArgument("-f");
    cmd.addArgument(scriptPath);
    cmd.addArgument("--args");
    cmd.addArgument(Integer.toString(hashCode()));
    cmd.addArgument(Integer.toString(port));
    cmd.addArgument(libPath);
    cmd.addArgument(Integer.toString(sparkVersion.toNumber()));

    // dump out the R command to facilitate manually running it, e.g. for fault diagnosis purposes
    logger.debug(cmd.toString());

    executor = new DefaultExecutor();
    outputStream = new InterpreterOutputStream(logger);

    input = new PipedOutputStream();
    PipedInputStream in = new PipedInputStream(input);

    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, outputStream, in);
    executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT));
    executor.setStreamHandler(streamHandler);
    Map env = EnvironmentUtils.getProcEnvironment();

    initialOutput = new InterpreterOutput(null);
    outputStream.setInterpreterOutput(initialOutput);
    executor.execute(cmd, env, this);
    rScriptRunning = true;

    // flush output
    eval("cat('')");
}

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
 *///from  w w  w.ja va2  s.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);
    }
}

From source file:org.codehaus.mojo.latex.LaTeXMojo.java

private void execute(CommandLine commandLine, File dir) throws IOException, MojoFailureException {
    final DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(dir);/*from   w  ww  .  ja  v  a 2  s. c  o  m*/
    if (executor.execute(commandLine) != 0) {
        throw new MojoFailureException("Error code returned for: " + commandLine.toString());
    }
}

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";
        }/*from ww w . j ava 2 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./*w  ww .java 2 s  .com*/
 * 
 * @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();

}