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

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

Introduction

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

Prototype

public static CommandLine parse(final String line) 

Source Link

Document

Create a command line from a string.

Usage

From source file:org.jberet.support.io.OsCommandBatchlet.java

/**
 * {@inheritDoc}/*from ww w.j  av  a 2s. co  m*/
 * <p>
 * This method runs the OS command.
 * If the command completes successfully, its process exit code is returned.
 * If there is exception while running the OS command, which may be
 * caused by timeout, the command being stopped, or other errors, the process
 * exit code is set as the step exit status, and the exception is thrown.
 *
 * @return the OS command process exit code
 *
 * @throws Exception upon errors
 */
@Override
public String process() throws Exception {
    final DefaultExecutor executor = new DefaultExecutor();
    final CommandLine commandLineObj;
    if (commandLine != null) {
        commandLineObj = CommandLine.parse(commandLine);
    } else {
        if (commandArray == null) {
            throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, null, "commandArray");
        } else if (commandArray.isEmpty()) {
            throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, commandArray.toString(),
                    "commandArray");
        }
        commandLineObj = new CommandLine(commandArray.get(0));
        final int len = commandArray.size();
        if (len > 1) {
            for (int i = 1; i < len; i++) {
                commandLineObj.addArgument(commandArray.get(i));
            }
        }
    }

    if (workingDir != null) {
        executor.setWorkingDirectory(workingDir);
    }
    if (streamHandler != null) {
        executor.setStreamHandler((ExecuteStreamHandler) streamHandler.newInstance());
    }

    SupportLogger.LOGGER.runCommand(commandLineObj.getExecutable(),
            Arrays.toString(commandLineObj.getArguments()), executor.getWorkingDirectory().getAbsolutePath());

    if (commandOkExitValues != null) {
        executor.setExitValues(commandOkExitValues);
    }

    watchdog = new ExecuteWatchdog(
            timeoutSeconds > 0 ? timeoutSeconds * 1000 : ExecuteWatchdog.INFINITE_TIMEOUT);
    executor.setWatchdog(watchdog);

    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    executor.execute(commandLineObj, environment, resultHandler);
    resultHandler.waitFor();

    final ExecuteException exception = resultHandler.getException();
    if (exception != null) {
        stepContext.setExitStatus(String.valueOf(resultHandler.getExitValue()));
        if (!isStopped) {
            throw exception;
        } else {
            SupportLogger.LOGGER.warn("", exception);
        }
    }
    return String.valueOf(resultHandler.getExitValue());
}

From source file:org.jboss.jdocbook.translate.PoSynchronizerImpl.java

private void updateTranslation(File template, File translation, Locale translationLocale) {
    if (!template.exists()) {
        log.trace("skipping PO updates; POT file did not exist : {0}", template);
        return;//from ww w.j av  a  2s . c  o m
    }

    if (translation.lastModified() >= template.lastModified()) {
        log.trace("skipping PO updates; up-to-date : {0}", translation);
        return;
    }

    final String translationLocaleString = componentRegistry.toLanguageString(translationLocale);

    CommandLine commandLine;
    if (translation.exists()) {
        commandLine = CommandLine.parse("msgmerge");
        commandLine.addArgument("--quiet");
        commandLine.addArgument("--update");
        commandLine.addArgument("--backup=none");
        commandLine.addArgument(FileUtils.resolveFullPathName(translation));
        commandLine.addArgument(FileUtils.resolveFullPathName(template));
    } else {
        if (!translation.getParentFile().exists()) {
            boolean created = translation.getParentFile().mkdirs();
            if (!created) {
                log.info("Unable to create PO directory {}", translation.getParentFile().getAbsolutePath());
            }
        }
        commandLine = CommandLine.parse("msginit");
        commandLine.addArgument("--no-translator");
        commandLine.addArgument("--locale=" + translationLocaleString);
        commandLine.addArgument("-i");
        commandLine.addArgument(FileUtils.resolveFullPathName(template));
        commandLine.addArgument("-o");
        commandLine.addArgument(FileUtils.resolveFullPathName(translation));
    }

    log.info("po-synch -> " + commandLine.toString());

    DefaultExecutor executor = new DefaultExecutor();
    try {
        executor.execute(commandLine);
    } catch (IOException e) {
        throw new JDocBookProcessException(
                "Error synchronizing PO file [" + template.getName() + "] for " + translationLocaleString, e);
    }
}

From source file:org.jboss.jdocbook.translate.PotSynchronizerImpl.java

private void executeXml2pot(File masterFile, File potFile) {
    CommandLine commandLine = CommandLine.parse("xml2pot");
    commandLine.addArgument(FileUtils.resolveFullPathName(masterFile));

    DefaultExecutor executor = new DefaultExecutor();

    try {//from   w  ww. j a v a2 s .c  o m
        final FileOutputStream xmlStream = new FileOutputStream(potFile);
        PumpStreamHandler streamDirector = new PumpStreamHandler(xmlStream, System.err);
        executor.setStreamHandler(streamDirector);
        try {
            log.trace("updating POT file {0}", potFile);
            executor.execute(commandLine);
        } finally {
            try {
                xmlStream.flush();
                xmlStream.close();
            } catch (IOException ignore) {
                // intentionally empty...
            }
        }
    } catch (IOException e) {
        throw new JDocBookProcessException("unable to open output stream for POT file [" + potFile + "]");
    }
}

From source file:org.jboss.jdocbook.translate.TranslatorImpl.java

private void generateTranslatedXML(File masterFile, File poFile, File translatedFile) {
    if (!masterFile.exists()) {
        log.trace("skipping translation; source file did not exist : {}", masterFile);
        return;/*  w  ww .j a v a2s.co m*/
    }
    if (!poFile.exists()) {
        log.trace("skipping translation; PO file did not exist : {}", poFile);
        return;
    }

    if (translatedFile.exists() && translatedFile.lastModified() >= masterFile.lastModified()
            && translatedFile.lastModified() >= poFile.lastModified()) {
        log.trace("skipping translation; up-to-date : {0}", translatedFile);
        return;
    }

    if (!translatedFile.getParentFile().exists()) {
        boolean created = translatedFile.getParentFile().mkdirs();
        if (!created) {
            log.info("Unable to create directories for translation");
        }
    }

    CommandLine commandLine = CommandLine.parse("po2xml");
    commandLine.addArgument(FileUtils.resolveFullPathName(masterFile));
    commandLine.addArgument(FileUtils.resolveFullPathName(poFile));

    try {
        final FileOutputStream xmlStream = new FileOutputStream(translatedFile);
        DefaultExecutor executor = new DefaultExecutor();
        try {
            PumpStreamHandler streamDirector = new PumpStreamHandler(xmlStream, System.err);
            executor.setStreamHandler(streamDirector);
            executor.execute(commandLine);
        } catch (IOException ioe) {
            throw new JDocBookProcessException("unable to execute po2xml : " + ioe.getMessage());
        } finally {
            try {
                xmlStream.flush();
                xmlStream.close();
            } catch (IOException ignore) {
                // intentionally empty...
            }
        }
    } catch (IOException e) {
        throw new JDocBookProcessException(
                "unable to open output stream for translated XML file [" + translatedFile + "]");
    }
}

From source file:org.jboss.maven.populator.MavenDeployer.java

public void deploy(final String groupId, final String artifactId, final String version,
        final String artifactPath) throws IOException {
    logger.info("Deploying " + artifactPath);

    final Map<String, String> params = new HashMap<String, String>();
    params.put("settingsUrl", settingsPath);
    params.put("artifactId", artifactId);
    params.put("groupId", groupId);
    params.put("version", version);
    params.put("artifactPath", artifactPath);
    params.put("repositoryUrl", repositoryUrl);
    params.put("repositoryId", repositoryId);

    final CommandLine deployCmd = CommandLine.parse(MVN_DEPLOY);
    deployCmd.setSubstitutionMap(params);

    final DefaultExecutor executor = new DefaultExecutor();
    executor.execute(deployCmd);/*  w  ww .  ja v a  2  s  .c  o  m*/
}

From source file:org.jboss.tools.windup.runtime.WindupRmiClient.java

public void startWindup(final IProgressMonitor monitor, String jreHome) {
    logInfo("Begin start RHAMT."); //$NON-NLS-1$
    monitor.worked(1);/*  w  ww. j  av a 2  s .c om*/

    String windupExecutable = WindupRuntimePlugin.computeWindupExecutable();

    if (windupExecutable == null) {
        WindupRuntimePlugin.logErrorMessage("rhamt-cli not specified."); //$NON-NLS-1$
        return;
    }

    boolean executable = new File(windupExecutable).setExecutable(true);
    if (!executable) {
        WindupRuntimePlugin.logErrorMessage("rhamt-cli not executable."); //$NON-NLS-1$
        return;
    }

    CommandLine cmdLine = CommandLine.parse(windupExecutable);

    Map<String, String> env = Maps.newHashMap();
    for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
        env.put(entry.getKey(), entry.getValue());
    }
    if (!jreHome.trim().isEmpty()) {
        env.put(JAVA_HOME, jreHome);
    }

    logInfo("Using " + JAVA_HOME + " - " + jreHome);

    cmdLine.addArgument("--startServer"); //$NON-NLS-1$
    cmdLine.addArgument(String.valueOf(getRmiPort()));
    watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    ExecuteResultHandler handler = new ExecuteResultHandler() {
        @Override
        public void onProcessFailed(ExecuteException e) {
            logInfo("The RHAMT process failed:"); //$NON-NLS-1$
            logInfo(e.getMessage()); //$NON-NLS-1$
            executionBuilder = null;
            notifyServerChanged();
        }

        @Override
        public void onProcessComplete(int exitValue) {
            logInfo("The RHAMT process has completed."); //$NON-NLS-1$
            executionBuilder = null;
            notifyServerChanged();
        }
    };
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() {
        @Override
        protected void processLine(String line, int logLevel) {
            logInfo("Message from RHAMT executor: " + line); //$NON-NLS-1$
            monitor.worked(1);
        }
    }));
    executor.setWatchdog(watchdog);
    executor.setExitValue(1);
    monitor.worked(1);
    try {
        logInfo("Starting RHAMT in server mode..."); //$NON-NLS-1$
        logInfo("Command-line: " + cmdLine); //$NON-NLS-1$
        executor.execute(cmdLine, env, handler);
    } catch (IOException e) {
        WindupRuntimePlugin.log(e);
    }
}

From source file:org.jbpm.process.workitem.exec.ExecWorkItemHandler.java

public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
    String command = (String) workItem.getParameter("Command");
    CommandLine commandLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    try {/*  ww w .  j  a v a  2  s . c o m*/
        executor.execute(commandLine);
        manager.completeWorkItem(workItem.getId(), null);
    } catch (Throwable t) {
        t.printStackTrace();
        manager.abortWorkItem(workItem.getId());
    }
}

From source file:org.jcronjob.agent.AgentProcessor.java

@Override
public Response execute(Request request) throws TException {
    if (!this.password.equalsIgnoreCase(request.getPassword())) {
        return errorPasswordResponse(request);
    }/*from  w w w.  ja  v a 2  s . c  om*/

    String command = request.getParams().get("command") + EXITCODE_SCRIPT;

    String pid = request.getParams().get("pid");

    logger.info("[cronjob]:execute:{},pid:{}", command, pid);

    File shellFile = CommandUtils.createShellFile(command, pid);

    Integer exitValue = 1;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Response response = Response.response(request);
    try {
        CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath());
        DefaultExecutor executor = new DefaultExecutor();

        ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream);
        executor.setStreamHandler(stream);
        response.setStartTime(new Date().getTime());
        exitValue = executor.execute(commandLine);
        exitValue = exitValue == null ? 0 : exitValue;
    } catch (Exception e) {
        if (e instanceof ExecuteException) {
            exitValue = ((ExecuteException) e).getExitValue();
        } else {
            exitValue = CronJob.StatusCode.ERROR_EXEC.getValue();
        }
        if (exitValue == CronJob.StatusCode.KILL.getValue()) {
            logger.info("[cronjob]:job has be killed!at pid :{}", request.getParams().get("pid"));
        } else {
            logger.info("[cronjob]:job execute error:{}", e.getCause().getMessage());
        }
    } finally {
        if (outputStream != null) {
            String text = outputStream.toString();
            if (notEmpty(text)) {
                try {
                    response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY)));
                    response.setExitCode(Integer.parseInt(
                            text.substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim()));
                } catch (IndexOutOfBoundsException e) {
                    response.setMessage(text);
                    response.setExitCode(exitValue);
                } catch (NumberFormatException e) {
                    response.setExitCode(exitValue);
                }
            } else {
                response.setExitCode(exitValue);
            }
            try {
                outputStream.close();
            } catch (Exception e) {
                logger.error("[cronjob]:error:{}", e);
            }
        } else {
            response.setExitCode(exitValue);
        }
        response.setSuccess(response.getExitCode() == CronJob.StatusCode.SUCCESS_EXIT.getValue()).end();
        if (shellFile != null) {
            shellFile.delete();//
        }
    }
    logger.info("[cronjob]:execute result:{}", response.toString());
    return response;
}

From source file:org.jfastcgi.client.FastCGIHandler.java

public void startProcess(final String cmd) throws IOException {
    final DefaultExecutor pe = new DefaultExecutor();
    processExecutor = pe;// www .  j a v  a 2  s .  co  m
    pe.setWatchdog(new ExecuteWatchdog(60000));

    processExecutor.setStreamHandler(new ExecuteStreamHandler() {

        private final Set<StreamLogger> loggers = new HashSet<StreamLogger>();

        public void stop() throws IOException {

        }

        public void start() throws IOException {

        }

        public void setProcessOutputStream(final InputStream is) throws IOException {
            loggers.add(new StreamLogger(is,
                    LoggerFactory.getLogger(FastCGIHandler.class.getName() + ".externalprocess.stdout")));
        }

        public void setProcessInputStream(final OutputStream os) throws IOException {

        }

        public void setProcessErrorStream(final InputStream is) throws IOException {
            loggers.add(new StreamLogger(is,
                    LoggerFactory.getLogger(FastCGIHandler.class.getName() + ".externalprocess.stderr")));
        }
    });

    getLog().info("Starting external process : " + cmd);
    pe.execute(CommandLine.parse(cmd), new DefaultExecuteResultHandler() {
        @Override
        public void onProcessFailed(final ExecuteException e) {
            super.onProcessFailed(e);
            getLog().error("while running process", e);
        }

        @Override
        public void onProcessComplete(final int exitValue) {
            getLog().info(String.format("external process exited with code %s : %s", exitValue, cmd));
        }
    });

}

From source file:org.kercoin.magrit.core.build.BuildTask.java

private int build(ByteArrayOutputStream stdout, PrintStream printOut) throws IOException {
    String command = findCommand();
    printOut.println(String.format("Starting build with command '%s'", command));

    CommandLine cmdLine = CommandLine.parse(command);
    DefaultExecutor executable = new DefaultExecutor();
    executable.setWorkingDirectory(repository.getDirectory().getParentFile());
    executable.setStreamHandler(new PumpStreamHandler(stdout));

    return executable.execute(cmdLine);
}