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:org.wisdom.maven.utils.WisdomExecutor.java

/**
 * Launches the Wisdom server. This method blocks until the wisdom server shuts down.
 * It uses the {@literal Java} executable directly.
 *
 * @param mojo        the mojo/*from w ww. j av a  2 s .  co m*/
 * @param interactive enables the shell prompt
 * @param debug       the debug port (0 to disable it)
 * @param jvmArgs     JVM arguments to add to the `java` command (before the -jar argument).
 * @param destroyer   a process destroyer that can be used to destroy the process, if {@code null}
 *                    a {@link org.apache.commons.exec.ShutdownHookProcessDestroyer} is used.
 * @throws MojoExecutionException if the Wisdom instance cannot be started or has thrown an unexpected status
 *                                while being stopped.
 */
public void execute(AbstractWisdomMojo mojo, boolean interactive, int debug, String jvmArgs,
        ProcessDestroyer destroyer) throws MojoExecutionException {
    // Get java
    File java = ExecUtils.find("java", new File(mojo.javaHome, "bin"));
    if (java == null) {
        throw new MojoExecutionException("Cannot find the java executable");
    }

    CommandLine cmdLine = new CommandLine(java);

    if (debug != 0) {
        cmdLine.addArgument("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=" + debug, false);
    }

    if (!Strings.isNullOrEmpty(jvmArgs)) {
        cmdLine.addArguments(jvmArgs, false);
    }

    cmdLine.addArgument("-jar");
    cmdLine.addArgument("bin/chameleon-core-" + CHAMELEON_VERSION + ".jar");
    if (interactive) {
        cmdLine.addArgument("--interactive");
    }

    appendSystemPropertiesToCommandLine(mojo, cmdLine);

    DefaultExecutor executor = new DefaultExecutor();
    if (destroyer != null) {
        executor.setProcessDestroyer(destroyer);
    } else {
        executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    }

    executor.setWorkingDirectory(mojo.getWisdomRootDirectory());
    if (interactive) {
        executor.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in)); //NOSONAR
        // Using the interactive mode the framework should be stopped using the 'exit' command,
        // and produce a '0' status.
        executor.setExitValue(0);
    } else {
        executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); // NOSONAR
        // As the execution is intended to be interrupted using CTRL+C, the status code returned is expected to be 1
        // 137 or 143 is used when stopped by the destroyer.
        executor.setExitValues(new int[] { 1, 137, 143 });
    }
    try {
        mojo.getLog().info("Launching Wisdom Server");
        mojo.getLog().debug("Command Line: " + cmdLine.toString());
        // The message is different whether or not we are in the interactive mode.
        if (interactive) {
            mojo.getLog().info("You are in interactive mode");
            mojo.getLog().info("Hit 'exit' to shutdown");
        } else {
            mojo.getLog().info("Hit CTRL+C to exit");
        }
        if (debug != 0) {
            mojo.getLog().info("Wisdom launched with remote debugger interface enabled on port " + debug);
        }
        // Block execution until ctrl+c
        executor.execute(cmdLine);
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot execute Wisdom", e);
    }
}

From source file:org.wisdom.maven.utils.WisdomExecutor.java

/**
 * Stops a running instance of wisdom using 'chameleon stop'.
 *
 * @param mojo the mojo//from  w  ww . j  a  v a  2s  .co  m
 * @throws MojoExecutionException if the instance cannot be stopped
 */
public void stop(AbstractWisdomMojo mojo) throws MojoExecutionException {
    File script = new File(mojo.getWisdomRootDirectory(), "chameleon.sh");
    if (!script.isFile()) {
        throw new MojoExecutionException("The 'chameleon.sh' file does not exist in "
                + mojo.getWisdomRootDirectory().getAbsolutePath() + " - cannot stop the Wisdom instance");
    }

    // If there is a RUNNING_PID file, exit immediately.
    File pid = new File(mojo.getWisdomRootDirectory(), "RUNNING_PID");
    if (!pid.isFile()) {
        mojo.getLog().info("The RUNNING_PID file does not exist, are you sure Wisdom is running ?");
        return;
    }

    CommandLine cmdLine = new CommandLine(script);
    cmdLine.addArgument("stop");

    try {
        mojo.getLog().info("Stopping Wisdom Server using '" + cmdLine.toString() + "'.");
        // As we know which command line we are executing, we can safely execute the command.
        Runtime.getRuntime().exec(cmdLine.toStrings(), null, mojo.getWisdomRootDirectory()); //NOSONAR
    } catch (IOException e) {
        throw new MojoExecutionException("Cannot stop Wisdom", e);
    }
}

From source file:org.wisdom.ractivejs.RactiveJsTemplateCompilerMojo.java

/**
 * Parse the ractive template into a JavaScript file.
 * Run the ractive script from the plugin resource with node, and ractive module.
 *
 * @param template the ractive template file
 * @throws WatchingException if the template cannot be parsed
 *//*www .  ja v a2 s .  c o  m*/
private void parseTemplate(File template) throws WatchingException {
    File destination = getOutputJSFile(template);

    // Create the destination folder.
    if (!destination.getParentFile().isDirectory()) {
        destination.getParentFile().mkdirs();
    }

    // Parse with Ractive.js
    CommandLine cmdLine = new CommandLine(getNodeManager().getNodeExecutable());
    cmdLine.addArgument(ractiveExec.getAbsolutePath(), false);
    cmdLine.addArgument(ractiveModule.getAbsolutePath(), false);
    cmdLine.addArgument(template.getAbsolutePath(), false);
    cmdLine.addArgument(destination.getAbsolutePath(), false);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);

    PumpStreamHandler streamHandler = new PumpStreamHandler(new LoggedOutputStream(getLog(), false),
            new LoggedOutputStream(getLog(), true));

    executor.setStreamHandler(streamHandler);

    getLog().info("Executing " + cmdLine.toString());

    try {
        executor.execute(cmdLine);
    } catch (IOException e) {
        throw new WatchingException("Error during the execution of " + RACTIVE_SCRIPT_NPM_NAME, e);
    }
}

From source file:org.xdi.util.process.ProcessHelper.java

public static boolean executeProgram(CommandLine commandLine, String workingDirectory,
        boolean executeInBackground, int successExitValue, OutputStream outputStream) {
    long printJobTimeout = PRINT_JOB_TIMEOUT;

    ExecuteStreamHandler streamHandler = null;
    if (outputStream != null) {
        streamHandler = new PumpStreamHandler(outputStream);
    }/*from   w  ww .j av  a  2s  . c o m*/

    PrintResultHandler printResult = null;
    try {
        log.debug(String.format("Preparing to start process %s", commandLine.toString()));
        printResult = executeProgram(commandLine, workingDirectory, printJobTimeout, executeInBackground,
                successExitValue, streamHandler);
        log.debug(String.format("Successfully start process %s", commandLine.toString()));
    } catch (Exception ex) {
        log.trace(String.format("Problem during starting process %s", commandLine.toString()), ex);
        ex.printStackTrace();
        return false;
    }

    // come back to check the print result
    log.debug(String.format("Waiting for the proces %s finish", commandLine.toString()));
    try {
        if (printResult == null) {
            return false;
        }
        printResult.waitFor();
    } catch (InterruptedException ex) {
        log.error(String.format("Problem during process execution %s", commandLine.toString()), ex);
    }

    log.debug(String.format("Process %s has finished", commandLine.toString()));

    return true;
}

From source file:org.xdi.util.process.ProcessHelper.java

/**
 * //from  www .j a v a2  s.c om
 * @param printJobTimeout
 *            the printJobTimeout (ms) before the watchdog terminates the
 *            print process
 * @param printInBackground
 *            printing done in the background or blocking
 * @param streamHandler
 * @return a print result handler (implementing a future)
 * @throws IOException
 *             the test failed
 */
public static PrintResultHandler executeProgram(CommandLine commandLine, String workingDirectory,
        long printJobTimeout, boolean printInBackground, int successExitValue,
        ExecuteStreamHandler streamHandler) throws IOException {
    ExecuteWatchdog watchdog = null;
    PrintResultHandler resultHandler;

    // Create the executor and consider the successExitValue as success
    Executor executor = new DefaultExecutor();
    executor.setExitValue(successExitValue);

    if (StringHelper.isNotEmpty(workingDirectory)) {
        executor.setWorkingDirectory(new File(workingDirectory));
    }

    // Redirect streams if needed
    if (streamHandler != null) {
        executor.setStreamHandler(streamHandler);
    }

    // Create a watchdog if requested
    if (printJobTimeout > 0) {
        watchdog = new ExecuteWatchdog(printJobTimeout);
        executor.setWatchdog(watchdog);
    }

    // Pass a "ExecuteResultHandler" when doing background printing
    if (printInBackground) {
        log.debug(String.format("Executing non-blocking process %s", commandLine.toString()));
        resultHandler = new PrintResultHandler(watchdog);
        executor.execute(commandLine, resultHandler);
    } else {
        log.debug(String.format("Executing blocking process %s", commandLine.toString()));
        successExitValue = executor.execute(commandLine);
        resultHandler = new PrintResultHandler(successExitValue);
    }

    return resultHandler;
}

From source file:pl.net.ptak.InstallShieldBuildMojo.java

/**
 * Verifies that configuration is satisfied to bild the project and builds it.
 * /*from  ww  w .  j a  v a  2 s  .c o m*/
 * @throws MojoExecutionException when plugin is misconfigured
 * @throws MojoFailureException when plugin execution result was other than expected
 * @see org.apache.maven.plugin.AbstractMojo#execute()
 */
public void execute() throws MojoExecutionException, MojoFailureException {

    if (!OS.isFamilyWindows()) {
        throw new MojoExecutionException("This plugin is for Windows systems only");
    }

    if (!installshieldOutputDirectory.exists()) {
        installshieldOutputDirectory.mkdirs();
    }

    if (installshieldProjectFile == null || !installshieldProjectFile.exists()) {
        if (failWhenNoInstallshieldFile) {
            getLog().error(String.format("IS Project File available: %b", installshieldProjectFile.exists()));
            throw new MojoFailureException("InstallShield project file not found");
        } else {
            getLog().info("IS Project File not found. IS build skipped");
        }
    } else {

        String canonicalProjectFilePath = resolveCanonicalPath(installshieldProjectFile);

        getLog().info(String.format("About to build file %s", canonicalProjectFilePath));

        String canonicalOutputDirectoryPath = resolveCanonicalPath(installshieldOutputDirectory);

        getLog().info(String.format("Output will be placed in %s", canonicalOutputDirectoryPath));

        CommandLine installshieldCommandLine = new CommandLine(installshieldExecutable);

        addCmdLnArguments(installshieldCommandLine, "-p", canonicalProjectFilePath);
        addCmdLnArguments(installshieldCommandLine, "-b", canonicalOutputDirectoryPath);
        if (usePomVersion && null != version && !version.isEmpty()) {
            addCmdLnArguments(installshieldCommandLine, "-y", version);

        }

        if (null != productConfiguration && !productConfiguration.isEmpty()) {
            addCmdLnArguments(installshieldCommandLine, "-a", productConfiguration);
        }

        if (null != productRelease && !productRelease.isEmpty()) {
            addCmdLnArguments(installshieldCommandLine, "-r", productRelease);
        }

        if (null != properties && !properties.isEmpty()) {
            for (Entry<String, String> entry : properties.entrySet()) {
                addCmdLnArguments(installshieldCommandLine, "-z",
                        String.format("%s=%s", entry.getKey(), entry.getValue()));
            }
        }

        if (null != pathVariables && !pathVariables.isEmpty()) {
            for (Entry<String, String> entry : pathVariables.entrySet()) {
                addCmdLnArguments(installshieldCommandLine, "-l",
                        String.format("%s=%s", entry.getKey(), entry.getValue()));
            }
        }

        Executor exec = new DefaultExecutor();

        getLog().debug(
                String.format("IS Build Command to be executed: %s", installshieldCommandLine.toString()));

        try {
            int exitCode = exec.execute(installshieldCommandLine);
            getLog().debug(String.format("IS build exit code: %d", exitCode));
            if (exitCode != 0) {
                throw new MojoFailureException("Failed to build IS project");
            }
        } catch (IOException e) {
            String errorMessage = "Failed to execute InstallShield build";
            getLog().error(errorMessage);
            getLog().debug("Details to failure: ", e);
            throw new MojoFailureException(errorMessage);
        }
    }

}

From source file:ro.cosu.vampires.server.resources.local.LocalResource.java

private void execute(CommandLine cmd) throws IOException {
    executor.setWorkingDirectory(Paths.get("").toAbsolutePath().toFile());
    executor.setStreamHandler(new PumpStreamHandler(collectingLogOutputStream));
    // watchdog for 3 hours. a bit excessive ?
    executor.setWatchdog(new ExecuteWatchdog(1000 * 60 * 60 * 3));

    int exitCode = 0;
    try {/*from ww  w.j  a v  a  2s  .  c  o m*/
        LOG.debug("execute {}", cmd.toString());
        exitCode = executor.execute(cmd);
        if (exitCode != 0) {
            LOG.error("Output {}", collectingLogOutputStream.getLines());
            throw new IOException("Non zero exit code");
        }
    } catch (IOException e) {
        LOG.debug("{} has failed with error {}: {}", this, exitCode, e);
        LOG.debug("{}", Joiner.on("\n").join(collectingLogOutputStream.getLines()));
        throw e;
    }
}