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

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

Introduction

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

Prototype

public CommandLine addArgument(final String argument) 

Source Link

Document

Add a single argument.

Usage

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

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {/*from   w  w w .  j  a v  a  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.geode.examples.replicated.ReplicatedTest.java

/**
 * Execute the kill script that looks for pid files
 * @throws IOException// www  . j  a v  a 2 s  . c o m
 * @throws InterruptedException
 */
private void runKillScript() throws IOException, InterruptedException {
    CommandLine cmdLine = CommandLine.parse(shell.getFileFromClassLoader(pidkillerScriptFileName)
            .map(x -> x.getAbsolutePath()).orElseThrow(IllegalArgumentException::new));
    cmdLine.addArgument(testFolder.getRoot().getAbsolutePath());

    DefaultExecuteResultHandler resultHandler = shell.execute(cmdLine, scriptTimeout, environment,
            testFolder.getRoot());
    resultHandler.waitFor(scriptTimeout);
}

From source file:org.apache.maven.plugin.cxx.utils.ExecutorService.java

public static CommandLine getExecutablePath(String executableName, Properties enviro, File dir) {
    File execFile = new File(executableName);
    String exec = null;//from   w  ww  . ja  v  a 2  s .com
    if (execFile.exists() && execFile.isFile() && execFile.canExecute()) {
        //getLog().debug( "Toolchains are ignored, 'executable' parameter is set to " + execFile.getAbsolutePath() );
        exec = execFile.getAbsolutePath();
    } else {
        if (OS.isFamilyWindows()) {
            String ex = executableName.indexOf(".") < 0 ? executableName + ".bat" : executableName;
            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 = executableName;
    }

    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.apache.sling.testing.serversetup.jarexec.JarExecutor.java

/** Start the jar if not done yet, and setup runtime hook
 *  to stop it.// www .j a  v  a 2s . c  om
 */
public void start() throws Exception {
    final ExecuteResultHandler h = new ExecuteResultHandler() {
        public void onProcessFailed(ExecuteException ex) {
            log.error("Process execution failed:" + ex, ex);
        }

        public void onProcessComplete(int result) {
            log.info("Process execution complete, exit code=" + result);
        }
    };

    final String vmOptions = config.getProperty(PROP_VM_OPTIONS);
    executor = new DefaultExecutor();
    final CommandLine cl = new CommandLine(jvmFullPath);
    if (vmOptions != null && vmOptions.length() > 0) {
        cl.addArguments(vmOptions);
    }
    cl.addArgument("-jar");
    cl.addArgument(jarToExecute.getAbsolutePath());

    // Additional options for the jar that's executed.
    // $JAREXEC_SERVER_PORT$ is replaced our serverPort value
    String jarOptions = config.getProperty(PROP_JAR_OPTIONS);
    if (jarOptions != null && jarOptions.length() > 0) {
        jarOptions = jarOptions.replaceAll("\\$JAREXEC_SERVER_PORT\\$", String.valueOf(serverPort));
        log.info("Executable jar options: {}", jarOptions);
        cl.addArguments(jarOptions);
    }

    final String workFolderOption = config.getProperty(PROP_WORK_FOLDER);
    if (workFolderOption != null && workFolderOption.length() > 0) {
        final File workFolder = new File(workFolderOption);
        if (!workFolder.isDirectory()) {
            throw new IOException("Work dir set by " + PROP_WORK_FOLDER + " option does not exist: "
                    + workFolder.getAbsolutePath());
        }
        log.info("Setting working directory for executable jar: {}", workFolder.getAbsolutePath());
        executor.setWorkingDirectory(workFolder);
    }

    String tmStr = config.getProperty(PROP_EXIT_TIMEOUT_SECONDS);
    final int exitTimeoutSeconds = tmStr == null ? DEFAULT_EXIT_TIMEOUT : Integer.valueOf(tmStr);

    if ("true".equals(config.getProperty(PROP_SYNC_EXEC, ""))) {
        final long start = System.currentTimeMillis();
        log.info("Executing and waiting for result: " + cl);
        final int result = executor.execute(cl);
        final int expected = Integer.valueOf(config.getProperty(PROP_SYNC_EXEC_EXPECTED, "0"));
        log.info("Execution took " + (System.currentTimeMillis() - start) + " msec");
        if (result != expected) {
            throw new ExecutorException("Expected result code " + expected + ", got " + result);
        }
    } else {
        log.info("Executing asynchronously: " + cl);
        executor.setStreamHandler(new PumpStreamHandler());
        final ShutdownHookSingleProcessDestroyer pd = new ShutdownHookSingleProcessDestroyer(
                "java -jar " + jarToExecute.getName(), exitTimeoutSeconds);
        final boolean waitOnShutdown = Boolean.valueOf(config.getProperty(PROP_WAIT_ONSHUTDOWN, "false"));
        log.info("Setting up ProcessDestroyer with waitOnShutdown=" + waitOnShutdown);
        pd.setWaitOnShutdown(waitOnShutdown);
        executor.setProcessDestroyer(pd);
        executor.execute(cl, h);
    }
}

From source file:org.apache.storm.util.CoreUtil.java

@ClojureClass(className = "backtype.storm.util#exec-command!")
public static void execCommand(String command) throws ExecuteException, IOException {
    String[] cmdlist = command.split(" ");
    CommandLine cmd = new CommandLine(cmdlist[0]);
    for (int i = 1; i < cmdlist.length; i++) {
        cmd.addArgument(cmdlist[i]);
    }//from  w w  w.ja v a2  s  . c  o m

    DefaultExecutor exec = new DefaultExecutor();
    exec.execute(cmd);
}

From source file:org.apache.storm.utils.ServerUtils.java

public static int execCommand(String... command) throws ExecuteException, IOException {
    CommandLine cmd = new CommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        cmd.addArgument(command[i]);
    }/* w  ww.j  ava  2 s .c  o m*/

    DefaultExecutor exec = new DefaultExecutor();
    return exec.execute(cmd);
}

From source file:org.apache.tika.parser.geo.topic.GeoParser.java

public HashMap<String, ArrayList<String>> searchGeoNames(ArrayList<String> locationNameEntities)
        throws ExecuteException, IOException {
    CommandLine cmdLine = new CommandLine("lucene-geo-gazetteer");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    cmdLine.addArgument("-s");
    for (String name : locationNameEntities) {
        cmdLine.addArgument(name);//from w ww  .  j  a  v a2 s  .c om
    }

    LOG.fine("Executing: " + cmdLine);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    exec.setWatchdog(watchdog);
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    int exitValue = exec.execute(cmdLine, EnvironmentUtils.getProcEnvironment());
    String outputJson = outputStream.toString("UTF-8");
    JSONArray json = (JSONArray) JSONValue.parse(outputJson);

    HashMap<String, ArrayList<String>> returnHash = new HashMap<String, ArrayList<String>>();
    for (int i = 0; i < json.size(); i++) {
        JSONObject obj = (JSONObject) json.get(i);
        for (Object key : obj.keySet()) {
            String theKey = (String) key;
            JSONArray vals = (JSONArray) obj.get(theKey);
            ArrayList<String> stringVals = new ArrayList<String>(vals.size());
            for (int j = 0; j < vals.size(); j++) {
                String val = (String) vals.get(j);
                stringVals.add(val);
            }

            returnHash.put(theKey, stringVals);
        }
    }

    return returnHash;

}

From source file:org.apache.tika.parser.pot.PooledTimeSeriesParser.java

private String computePoT(File input) throws IOException, TikaException {

    CommandLine cmdLine = new CommandLine("pooled-time-series");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    cmdLine.addArgument("-f");
    cmdLine.addArgument(input.getAbsolutePath());
    LOG.trace("Executing: {}", cmdLine);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setExitValue(0);//from  w  w w .ja v  a2s. com
    ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
    exec.setWatchdog(watchdog);
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    exec.setStreamHandler(streamHandler);
    int exitValue = exec.execute(cmdLine, EnvironmentUtils.getProcEnvironment());
    return outputStream.toString("UTF-8");

}

From source file:org.apache.zeppelin.python.IPythonInterpreter.java

private void launchIPythonKernel(int ipythonPort) throws IOException {
    LOGGER.info("Launching IPython Kernel at port: " + ipythonPort);
    // copy the python scripts to a temp directory, then launch ipython kernel in that folder
    File pythonWorkDir = Files.createTempDirectory("zeppelin_ipython").toFile();
    String[] ipythonScripts = { "ipython_server.py", "ipython_pb2.py", "ipython_pb2_grpc.py" };
    for (String ipythonScript : ipythonScripts) {
        URL url = getClass().getClassLoader().getResource("grpc/python" + "/" + ipythonScript);
        FileUtils.copyURLToFile(url, new File(pythonWorkDir, ipythonScript));
    }/*from   w  w w  .  java  2s  .co m*/

    CommandLine cmd = CommandLine.parse(pythonExecutable);
    cmd.addArgument(pythonWorkDir.getAbsolutePath() + "/ipython_server.py");
    cmd.addArgument(ipythonPort + "");
    DefaultExecutor executor = new DefaultExecutor();
    ProcessLogOutputStream processOutput = new ProcessLogOutputStream(LOGGER);
    executor.setStreamHandler(new PumpStreamHandler(processOutput));
    watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchDog);

    if (useBuiltinPy4j) {
        //TODO(zjffdu) don't do hard code on py4j here
        File py4jDestFile = new File(pythonWorkDir, "py4j-src-0.10.7.zip");
        FileUtils.copyURLToFile(getClass().getClassLoader().getResource("python/py4j-src-0.10.7.zip"),
                py4jDestFile);
        if (additionalPythonPath != null) {
            // put the py4j at the end, because additionalPythonPath may already contain py4j.
            // e.g. PySparkInterpreter
            additionalPythonPath = additionalPythonPath + ":" + py4jDestFile.getAbsolutePath();
        } else {
            additionalPythonPath = py4jDestFile.getAbsolutePath();
        }
    }

    Map<String, String> envs = setupIPythonEnv();
    executor.execute(cmd, envs, this);

    // wait until IPython kernel is started or timeout
    long startTime = System.currentTimeMillis();
    while (true) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            LOGGER.error("Interrupted by something", e);
        }

        try {
            StatusResponse response = ipythonClient.status(StatusRequest.newBuilder().build());
            if (response.getStatus() == IPythonStatus.RUNNING) {
                LOGGER.info("IPython Kernel is Running");
                break;
            } else {
                LOGGER.info("Wait for IPython Kernel to be started");
            }
        } catch (Exception e) {
            // ignore the exception, because is may happen when grpc server has not started yet.
            LOGGER.info("Wait for IPython Kernel to be started");
        }

        if ((System.currentTimeMillis() - startTime) > ipythonLaunchTimeout) {
            throw new IOException(
                    "Fail to launch IPython Kernel in " + ipythonLaunchTimeout / 1000 + " seconds");
        }
    }
}

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

/**
 * Start R repl/*  w w w . j a  va2  s  .co  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('')");
}