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.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//ww w .  jav a2s.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//w  w w. ja  v a 2  s. c  o 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
 *//*from   w w w .j ava 2  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(String programPath, String workingDirectory, boolean executeInBackground,
        int successExitValue, OutputStream outputStream) {
    CommandLine commandLine = new CommandLine(programPath);
    return executeProgram(commandLine, workingDirectory, executeInBackground, successExitValue, outputStream);
}

From source file:org.zanata.rest.service.VirusScanner.java

private CommandLine buildCommandLine(File file) {
    CommandLine cmdLine = new CommandLine(SCANNER_NAME);
    if (USING_CLAM) {
        cmdLine.addArguments(CLAMDSCAN_ARGS, false);
    }// w w w  .jav  a 2  s.  c om
    cmdLine.addArgument(file.getPath(), false);
    return cmdLine;
}

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

/**
 * Verifies that configuration is satisfied to bild the project and builds it.
 * //from ww  w .j  ava  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

@Override
public void onStart() throws IOException {
    // TODO check somehow that the file exists and then exit
    CommandLine cmd = new CommandLine("/bin/sh");
    cmd.addArgument("-c");
    cmd.addArgument("nohup " + parameters.command() + " " + parameters.serverId() + " " + parameters().id()
            + " 2>&1 0</dev/null & ", false);

    LOG.debug("local starting {}", cmd);
    execute(cmd);/*  w  w  w  .j ava2  s .c  o m*/
}

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

@Override
public void onStop() throws IOException {
    LOG.debug("local  " + parameters().id() + " stopping");
    CommandLine cmd = new CommandLine("/bin/sh");
    cmd.addArgument("-c");
    cmd.addArgument(//from   w  w w  .  ja  v  a 2s .  c o m
            String.format("pgrep %s; if [ $? -eq 0 ]; then pkill %s; fi ", parameters.id(), parameters.id()),
            false);
    execute(cmd);
}

From source file:sce.ProcessExecutor.java

public String executeProcess(String[] processParameters) throws JobExecutionException {
    try {/*  w  w w  . ja va2s.  c om*/
        //Command to be executed
        CommandLine command = new CommandLine(processParameters[0]);

        String[] params = new String[processParameters.length - 1];
        for (int i = 0; i < processParameters.length - 1; i++) {
            params[i] = processParameters[i + 1];
        }

        //Adding its arguments
        command.addArguments(params);

        //set timeout in seconds
        ExecuteWatchdog watchDog = new ExecuteWatchdog(
                this.timeout == 0 ? ExecuteWatchdog.INFINITE_TIMEOUT : this.timeout * 1000);
        this.watchdog = watchDog;

        //Result Handler for executing the process in a Asynch way
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        //MyResultHandler resultHandler = new MyResultHandler();

        //Using Std out for the output/error stream
        //ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        //This is used to end the process when the JVM exits
        ShutdownHookProcessDestroyer processDestroyer = new ShutdownHookProcessDestroyer();

        //Our main command executor
        DefaultExecutor executor = new DefaultExecutor();

        //Setting the properties
        executor.setStreamHandler(new PumpStreamHandler(null, null));
        executor.setWatchdog(watchDog);
        //executor.setExitValue(1); // this has to be set if the java code contains System.exit(1) to avoid a FAILED status

        //Setting the working directory
        //Use of recursion along with the ls makes this a long running process
        //executor.setWorkingDirectory(new File("/home"));
        executor.setProcessDestroyer(processDestroyer);

        //if set, use the java environment variables when running the command
        if (!this.environment.equals("")) {
            Map<String, String> procEnv = EnvironmentUtils.getProcEnvironment();
            EnvironmentUtils.addVariableToEnvironment(procEnv, this.environment);
            //Executing the command
            executor.execute(command, procEnv, resultHandler);
        } else {
            //Executing the command
            executor.execute(command, resultHandler);
        }

        //The below section depends on your need
        //Anything after this will be executed only when the command completes the execution
        resultHandler.waitFor();

        /*int exitValue = resultHandler.getExitValue();
         System.out.println(exitValue);
         if (executor.isFailure(exitValue)) {
         System.out.println("Execution failed");
         } else {
         System.out.println("Execution Successful");
         }
         System.out.println(outputStream.toString());*/
        //return outputStream.toString();
        if (watchdog.killedProcess()) {
            throw new JobExecutionException("Job Interrupted", new InterruptedException());
        }
        if (executor.isFailure(resultHandler.getExitValue())) {
            ExecuteException ex = resultHandler.getException();
            throw new JobExecutionException(ex.getMessage(), ex);
        }
        return "1";
    } catch (ExecuteException ex) {
        throw new JobExecutionException(ex.getMessage(), ex);
    } catch (IOException | InterruptedException | JobExecutionException ex) {
        throw new JobExecutionException(ex.getMessage(), ex);
    }
}

From source file:uk.org.sappho.applications.transcript.service.registry.vcs.Command.java

public Command(String executable) {

    commandLine = new CommandLine(executable);
}