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.codice.alliance.distribution.sdk.video.stream.mpegts.MpegTsUdpClient.java

private static CommandLine getFFmpegInfoCommand(final String videoFilePath) {
    final String bundledFFmpegBinaryPath = getBundledFFmpegBinaryPath();
    File file = new File("target/ffmpeg/" + bundledFFmpegBinaryPath);
    return new CommandLine(file.getAbsolutePath()).addArgument(SUPPRESS_PRINTING_BANNER_FLAG)
            .addArgument(INPUT_FILE_FLAG).addArgument(videoFilePath, HANDLE_QUOTING);
}

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);// ww  w . ja va2  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  ww  w .j av a2 s  . c  o  m
 *
 * @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");
        }
    }
}

From source file:org.docwhat.iated.AppState.java

public String editFile(File file) {
    String editor = getEditor();/*  w  ww.j a v  a  2 s . com*/
    CommandLine cmd;

    if (OS.isFamilyMac() && editor.matches(".*\\.app")) {
        cmd = new CommandLine("/usr/bin/open");
        cmd.addArgument("-a").addArgument(editor).addArgument(file.toString());
    } else {
        cmd = new CommandLine(editor);
        cmd.addArgument(file.toString());
    }

    Executor executor = new DefaultExecutor();
    try {
        executor.execute(cmd);
    } catch (ExecuteException ex) {
        //TODO Do something meaningful with the exception.
        throw new RuntimeException(ex);
    } catch (IOException ex) {
        //TODO Do something meaningful with the exception.
        throw new RuntimeException(ex);
    }
    return "bogus-token";
}

From source file:org.eclipse.ecf.python.AbstractPythonLauncher.java

@Override
public void launch(String[] args, OutputStream output) throws Exception {
    synchronized (this.launchLock) {
        if (isLaunched())
            throw new IllegalStateException("Already started");

        this.shuttingDown = false;
        if (enabled) {
            String pythonLaunchCommand = createPythonLaunchCommand();
            if (pythonLaunchCommand == null)
                throw new NullPointerException("pythonLaunchCommand must not be null");

            logger.debug("pythonLaunchCommand=" + pythonLaunchCommand);

            this.executor = createExecutor();
            if (this.pythonWorkingDirectory != null)
                this.executor.setWorkingDirectory(pythonWorkingDirectory);

            if (output == null) {
                output = new LogOutputStream() {
                    @Override//ww  w.j a va 2  s.  c  o  m
                    protected void processLine(String line, int level) {
                        logger.debug("PYTHON: " + line);
                    }
                };
            }
            executor.setStreamHandler(new PumpStreamHandler(output));

            this.executor.setProcessDestroyer(new PythonProcessDestroyer());

            ExecuteResultHandler executeHandler = new DefaultExecuteResultHandler() {
                @Override
                public void onProcessComplete(int exitValue) {
                    logger.debug("PYTHON EXIT=" + exitValue);
                }

                @Override
                public void onProcessFailed(ExecuteException e) {
                    if (!shuttingDown)
                        logger.debug("PYTHON EXCEPTION", e);
                }
            };

            CommandLine commandLine = new CommandLine(pythonExec).addArgument(PYTHON_LAUNCH_COMMAND_OPTION);
            commandLine.addArgument(pythonLaunchCommand, true);

            List<String> argsList = (args == null) ? Collections.emptyList() : Arrays.asList(args);

            if (this.javaPort != null && !argsList.contains(JAVA_PORT_OPTION)) {
                commandLine.addArgument(JAVA_PORT_OPTION);
                commandLine.addArgument(String.valueOf(this.javaPort));
            }

            if (this.pythonPort != null && !argsList.contains(PYTHON_PORT_OPTION)) {
                commandLine.addArgument(PYTHON_PORT_OPTION);
                commandLine.addArgument(String.valueOf(this.pythonPort));
            }

            if (args != null)
                commandLine.addArguments(args);
            logger.debug("PythonLauncher.launch: " + commandLine);
            try {
                executor.execute(commandLine, executeHandler);
            } catch (Exception e) {
                this.executor = null;
                throw e;
            }
        } else
            logger.debug("PythonLauncher DISABLED.   Python process must be started manually");
    }
}

From source file:org.eclipse.php.composer.core.launch.environment.SysPhpPrjPhar.java

public CommandLine getCommand() {
    CommandLine cmd = new CommandLine(php.trim());

    // specify php.ini location
    File iniFile = PHPINIUtil.findPHPIni(php);
    if (iniFile != null) {
        cmd.addArgument("-c"); //$NON-NLS-1$
        cmd.addArgument(iniFile.getAbsolutePath());
    }//from w  w  w .j  a  v  a 2 s . com

    // specify composer.phar location
    cmd.addArgument(phar.trim());
    return cmd;
}

From source file:org.eclipse.php.composer.core.launch.environment.SysPhpSysPhar.java

public CommandLine getCommand() {
    CommandLine cmd = new CommandLine(php.trim());
    cmd.addArgument(phar.trim());

    return cmd;
}

From source file:org.eclipse.php.composer.ui.preferences.launcher.ExecutableTester.java

@Override
public void run() {

    try {//from  w ww.ja  v  a  2  s  .co  m
        ScriptExecutor executor = new ScriptExecutor();
        CommandLine cmd = new CommandLine(phPexeItem.getExecutable());
        cmd.addArgument("testexecutable"); //$NON-NLS-1$

        Bundle bundle = Platform.getBundle(ComposerUIPlugin.PLUGIN_ID);
        URL entry = bundle.getEntry("Resources/launcher"); //$NON-NLS-1$

        File file = new File(FileLocator.resolve(entry).toURI());

        if (file != null) {
            executor.setWorkingDirectory(file);
        }

        executor.addResponseListener(listener);
        executor.execute(cmd);
    } catch (Exception e) {
        Logger.logException(e);
    }
}

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   w  ww. j  a  va  2  s.  c o  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.eclipse.smarthome.io.net.exec.ExecUtil.java

/**
 * <p>/*from  w  ww .  j  av  a 2s .com*/
 * Executes <code>commandLine</code>. Sometimes (especially observed on
 * MacOS) the commandLine isn't executed properly. In that cases another
 * exec-method is to be used. To accomplish this please use the special
 * delimiter '<code>@@</code>'. If <code>commandLine</code> contains this
 * delimiter it is split into a String[] array and the special exec-method
 * is used.
 * </p>
 * <p>
 * A possible {@link IOException} gets logged but no further processing is
 * done.
 * </p>
 * 
 * @param commandLine
 *            the command line to execute
 * @param timeout
 *            timeout for execution in milliseconds
 * @return response data from executed command line
 */
public static String executeCommandLineAndWaitResponse(String commandLine, int timeout) {
    String retval = null;

    CommandLine cmdLine = null;

    if (commandLine.contains(CMD_LINE_DELIMITER)) {
        String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
        cmdLine = new CommandLine(cmdArray[0]);

        for (int i = 1; i < cmdArray.length; i++) {
            cmdLine.addArgument(cmdArray[i], false);
        }
    } else {
        cmdLine = CommandLine.parse(commandLine);
    }

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    Executor executor = new DefaultExecutor();

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);

    executor.setExitValue(1);
    executor.setStreamHandler(streamHandler);
    executor.setWatchdog(watchdog);

    try {
        executor.execute(cmdLine, resultHandler);
        logger.debug("executed commandLine '{}'", commandLine);
    } catch (ExecuteException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    } catch (IOException e) {
        logger.error("couldn't execute commandLine '" + commandLine + "'", e);
    }

    // some time later the result handler callback was invoked so we
    // can safely request the exit code
    try {
        resultHandler.waitFor();
        int exitCode = resultHandler.getExitValue();
        retval = StringUtils.chomp(stdout.toString());
        logger.debug("exit code '{}', result '{}'", exitCode, retval);

    } catch (InterruptedException e) {
        logger.error("Timeout occured when executing commandLine '" + commandLine + "'", e);
    }

    return retval;
}