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.bonitasoft.platform.setup.PlatformSetupDistributionIT.java

@Test
public void setupSh_should_work_with_init_on_h2_and_prevent_pushing_deletion() throws Exception {
    //given//from   w  ww. jav a 2  s .c  o  m
    CommandLine oCmdLine = PlatformSetupTestUtils.createCommandLine();
    oCmdLine.addArgument("init");
    DefaultExecutor executor = PlatformSetupTestUtils.createExecutor(distFolder);
    executor.setStreamHandler(PlatformSetupTestUtils.getExecuteStreamHandler("yes"));

    //when
    int iExitValue = executor.execute(oCmdLine);

    //then
    assertThat(iExitValue).isEqualTo(0);
    Connection jdbcConnection = PlatformSetupTestUtils.getJdbcConnection(distFolder);
    Statement statement = jdbcConnection.createStatement();
    ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) AS nb FROM CONFIGURATION");
    resultSet.next();
    assertThat(resultSet.getInt("nb")).isGreaterThan(0);

    oCmdLine = PlatformSetupTestUtils.createCommandLine();
    oCmdLine.addArgument("pull");
    iExitValue = executor.execute(oCmdLine);
    assertThat(iExitValue).isEqualTo(0);

    final Path platform_engine = distFolder.toPath().resolve("platform_conf").resolve("current")
            .resolve("platform_engine");
    FileUtils.deleteDirectory(platform_engine.toFile());

    oCmdLine = PlatformSetupTestUtils.createCommandLine();
    oCmdLine.addArgument("push");
    executor.setExitValue(1);
    iExitValue = executor.execute(oCmdLine);
    assertThat(iExitValue).isEqualTo(1);

    oCmdLine.addArgument("--force");
    executor.setExitValue(0);
    iExitValue = executor.execute(oCmdLine);
    assertThat(iExitValue).isEqualTo(0);
}

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 {/* w  w w .  j  a va 2  s .c  om*/
        CommandLine oCmdLine = new CommandLine("sh");
        oCmdLine.addArgument("setup.sh");
        return oCmdLine;
    }
}

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");
    }/* w  w  w .  ja  va  2s  .co  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 ww .j ava  2  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 www. j  av a2s .c  o 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.cassandra.AbstractCassandraMojo.java

/**
 * Creates the command line to launch the cassandra server.
 *
 * @return the command line to launch the cassandra server.
 * @throws IOException if there are issues creating the cassandra home directory.
 *//*from  ww  w .  ja v  a  2s.  c o m*/
protected CommandLine newServiceCommandLine(File cassandraDir, String listenAddress, String rpcAddress,
        BigInteger initialToken, String[] seeds, boolean jmxRemoteEnabled, int jmxPort) throws IOException {
    createCassandraHome(cassandraDir, listenAddress, rpcAddress, initialToken, seeds);
    CommandLine commandLine = newJavaCommandLine();
    commandLine.addArgument("-Xmx" + maxMemory + "m");
    //Only value should be quoted so we have to do it ourselves explicitly and disable additional quotation of whole
    //argument because it causes errors during launch. Also URLEncode.encode on value seems to work correctly too,
    //it is done for log4j.configuration during toURL().toString() conversion.
    commandLine.addArgument(
            "-Dcassandra.storagedir="
                    + org.apache.commons.exec.util.StringUtils.quoteArgument(cassandraDir.getAbsolutePath()),
            false);
    if (stopKey != null && stopPort > 0 && stopPort < 65536) {
        commandLine.addArgument("-D" + CassandraMonitor.KEY_PROPERTY_NAME + "=" + stopKey);
        commandLine.addArgument("-D" + CassandraMonitor.PORT_PROPERTY_NAME + "=" + stopPort);
        commandLine.addArgument("-D" + CassandraMonitor.HOST_PROPERTY_NAME + "=" + listenAddress);
    }
    commandLine.addArgument("-Dlog4j.configurationFile="
            + new File(new File(cassandraDir, "conf"), "log4j-server.xml").toURI().toURL().toString());
    commandLine.addArgument("-Dcom.sun.management.jmxremote=" + jmxRemoteEnabled);
    commandLine.addArgument("-DcassandraLogLevel=" + logLevel);
    if (jmxRemoteEnabled) {
        commandLine.addArgument("-Dcom.sun.management.jmxremote.port=" + jmxPort);
        commandLine.addArgument("-Dcom.sun.management.jmxremote.ssl=false");
        commandLine.addArgument("-Dcom.sun.management.jmxremote.authenticate=false");
    }

    if (systemPropertyVariables != null && !systemPropertyVariables.isEmpty()) {
        for (Map.Entry<String, String> entry : systemPropertyVariables.entrySet()) {
            commandLine.addArgument("-D" + entry.getKey() + "=" + entry.getValue());
        }
    }

    commandLine.addArgument("-jar");
    // It seems that java cannot handle quoted jar file names...
    commandLine.addArgument(new File(new File(cassandraDir, "bin"), "cassandra.jar").getAbsolutePath(), false);

    return commandLine;
}

From source file:org.codehaus.mojo.cassandra.AbstractCassandraMojo.java

/**
 * Creates the command line to launch the {@code nodetool} utility.
 *
 * @param args the command line arguments to pass to the {@code nodetool} utility.
 * @return the {@link CommandLine} to launch {@code nodetool} with the supplied arguments.
 * @throws IOException if there are issues creating the cassandra home directory.
 *//*w w  w .ja  va2s.co m*/
protected CommandLine newNodetoolCommandLine(String... args) throws IOException {
    createCassandraHome();
    CommandLine commandLine = newJavaCommandLine();
    commandLine.addArgument("-jar");
    // It seems that java cannot handle quoted jar file names...
    commandLine.addArgument(new File(new File(cassandraDir, "bin"), "nodetool.jar").getAbsolutePath(), false);
    commandLine.addArgument("--host");
    commandLine.addArgument("127.0.0.1");
    commandLine.addArgument("--port");
    commandLine.addArgument(Integer.toString(jmxPort));
    commandLine.addArguments(args);
    return commandLine;
}

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;/* ww  w .  ja va  2 s  . c  o 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.codice.git.GitIntegrationTest.java

private int executeGitCommand(String[] args) throws IOException {
    int exitValue = 0;
    List<String> outputLines = null;
    CommandLine cmdLine = new CommandLine("git");
    for (String arg : args) {
        cmdLine.addArgument(arg);
    }/*  www  .  jav  a  2 s . c  o  m*/
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWorkingDirectory(trash);
    CollectingLogOutputStream output = new CollectingLogOutputStream();
    PumpStreamHandler pump = new PumpStreamHandler(output, output);
    executor.setStreamHandler(pump);
    try {
        exitValue = executor.execute(cmdLine);
        outputLines = output.getLines();
    } catch (IOException e) {
        boolean hookRan = false;
        String errorMessage = "";
        // Check if we got the aborted message from the hook - implies it ran successfully
        outputLines = output.getLines();
        if ((outputLines != null) && (outputLines.size() > 0)) {
            errorMessage = outputLines.get(0);
            for (String line : outputLines) {
                if (line.contains("HOOK ABORTED")) {
                    hookRan = true;
                    break;
                }
            }
        }
        if (hookRan) {
            LOGGER.debug("Hook ran successfully - returning an error to abort the git command");
        } else {
            LOGGER.warn("Unexpected error during hook processing - first line of output: {}", errorMessage, e);
            throw e;
        }
        exitValue = 1;
    }

    for (String line : outputLines) {
        System.err.println(line);
    }
    return exitValue;
}

From source file:org.codice.git.hook.Artifact.java

/**
 * Downloads the artifact using maven.//from   w  w w.  j a v a  2s.c om
 *
 * @param settings the maven settings file or "" if using the default one
 * @param out      the output stream where to print messages to the user
 * @throws IOException if an error occurs
 */
protected void downloadUsingMaven(String settings, PrintStream out) throws IOException {
    final CommandLine cmd = new CommandLine(SystemUtils.IS_OS_WINDOWS ? "mvn.cmd" : "mvn");

    cmd.addArgument("-f").addArgument(new File(handler.getBasedir(), "pom.xml").getAbsolutePath());
    if (StringUtils.isNotEmpty(settings)) {
        cmd.addArgument("-s").addArgument(settings);
    }
    cmd.addArgument("org.apache.maven.plugins:maven-dependency-plugin:3.0.0:copy")
            .addArgument("-Dartifact=" + mvnInfo)
            .addArgument("-DoutputDirectory=" + handler.getBasedir().getAbsolutePath())
            .addArgument("-Dmdep.stripClassifier=true").addArgument("-Dmdep.stripVersion=true");
    if (!install) {
        cmd.addArgument("-quiet");
    }
    final DefaultExecutor exec = new DefaultExecutor();

    exec.setExitValue(0);
    try {
        exec.execute(cmd);
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "failed to download blacklist words artifact", e);
        if (file.exists()) { // ignore the error and continue with the one that is there
            return;
        }
        out.printf("%sFailed to download artifact '%s'; %s.%n", eprefix, mvnInfo, e.getMessage());
        throw new IOException("failed to download blacklist words artifact", e);
    }
    if (!mvnName.equals(file.getName())) {
        final File f = new File(handler.getBasedir(), mvnName);

        out.printf("%sMoving %s to %s.%n", iprefix, mvnName, file);
        if (!f.renameTo(file)) {
            LOGGER.log(Level.WARNING, "failed to copy {0} file", file.getName());
            if (file.exists()) { // ignore the error and continue with the one that is there
                return;
            }
            out.printf("%sFailed to move %s to %s.%n", eprefix, mvnName, file);
            throw new IOException("failed to copy " + file.getName() + " file");
        }
    }
}