List of usage examples for org.apache.commons.exec DefaultExecutor DefaultExecutor
public DefaultExecutor()
From source file:org.jahia.services.templates.SourceControlFactory.java
/** * Sets the executables for various SCM providers. * /*ww w. j a va2s .c om*/ * @param sourceControlExecutables * a map with paths to SCM executables by SCM type */ public void setSourceControlExecutables(Map<String, String> sourceControlExecutables) { this.sourceControlExecutables = new HashMap<String, String>(); for (Map.Entry<String, String> entry : sourceControlExecutables.entrySet()) { try { DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler( new PumpStreamHandler(new StringOutputStream(), new StringOutputStream())); executor.execute(new CommandLine(entry.getValue()), System.getenv()); } catch (ExecuteException e) { // ignore this one as the command always returns error code 1 } catch (IOException e) { if (logger.isDebugEnabled()) { logger.debug("Unable to execute the " + entry.getKey() + " SCM executable: " + entry.getValue() + ". The SCM provider will be disabled. Cause: " + e.getMessage(), e); } else { logger.info("Cannot find a valid " + entry.getKey() + " SCM executable at: " + entry.getValue() + ". The SCM provider will be skipped."); } continue; } this.sourceControlExecutables.put(entry.getKey(), entry.getValue()); } }
From source file:org.jahia.utils.ProcessHelper.java
/** * Executes the external process using the provided command, arguments (optional), parameter substitution map to expand variables in the * command or arguments in form of <code>${variable}<code> (optional) and a working directory (optional). * Buffers for process output and error stream can be provided. * //from w w w. j av a 2 s .c om * @param command * the command to be executed * @param arguments * optional arguments for the command * @param parameterSubstitutionMap * optional values for variables to be expanded * @param workingDir * optional working directory for the process to be started from * @param resultOut * the buffer to write the process execution output into (optional) * @param resultErr * the buffer to write the process execution error into (optional) * @return the execution status * @return redirectOutputs if set to <code>true</code> the output of the execution will be also redirected to standard system out and * the error to error out * @throws JahiaRuntimeException * in case the process execution failed */ public static int execute(String command, String arguments[], Map<String, Object> parameterSubstitutionMap, File workingDir, StringBuilder resultOut, StringBuilder resultErr, boolean redirectOutputs) throws JahiaRuntimeException { long timer = System.currentTimeMillis(); CommandLine cmd = new CommandLine(command); if (arguments != null && arguments.length > 0) { cmd.addArguments(arguments, false); } if (parameterSubstitutionMap != null && !parameterSubstitutionMap.isEmpty()) { cmd.setSubstitutionMap(parameterSubstitutionMap); } if (logger.isDebugEnabled()) { logger.debug("Executing command: {}", cmd.toString()); } else if (redirectOutputs) { logger.info("Executing command: "); logger.info(cmd.toString()); } int exitValue = 0; StringOutputStream out = new StringOutputStream(redirectOutputs ? System.out : null); StringOutputStream err = new StringOutputStream(redirectOutputs ? System.err : null); try { DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(out, err)); if (workingDir != null) { if (workingDir.exists() || workingDir.mkdirs()) { executor.setWorkingDirectory(workingDir); } } exitValue = executor.execute(cmd, System.getenv()); } catch (ExecuteException ee) { return ee.getExitValue(); } catch (Exception e) { throw new JahiaRuntimeException(e); } finally { if (resultErr != null) { resultErr.append(err.toString()); } if (resultOut != null) { resultOut.append(out.toString()); } if (exitValue > 0) { logger.error("External process finished with error. Cause: {}", err.toString()); } if (logger.isDebugEnabled()) { logger.debug("Execution took {} ms and finished with status {} and output {}", new Object[] { (System.currentTimeMillis() - timer), exitValue, out.toString() }); } } return exitValue; }
From source file:org.jberet.support.io.OsCommandBatchlet.java
/** * {@inheritDoc}// w ww. java 2 s. 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 a v a 2 s .com } 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 ww w. jav a 2 s . co 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;/*from w w w .j a va2 s. c o 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);/*from w ww .j ava 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);//from ww w . j ava2s . c o m 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.jboss.windup.decorator.java.decompiler.BackupOfJadretroDecompilerAdapter.java
private void executeJad(File classLocation, File sourceOutputLocation) { try {/*from ww w.j av a 2 s . c om*/ // Build command array CommandLine cmdLine = new CommandLine(APP_NAME); cmdLine.addArgument("-d"); cmdLine.addArgument("${outputLocation}"); cmdLine.addArgument("-f"); cmdLine.addArgument("-o"); cmdLine.addArgument("-s"); cmdLine.addArgument("java"); cmdLine.addArgument("${classLocation}"); Map<String, Object> argMap = new HashMap<String, Object>(); argMap.put("outputLocation", sourceOutputLocation); argMap.put("classLocation", classLocation); cmdLine.setSubstitutionMap(argMap); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); int exitValue = executor.execute(cmdLine); LOG.debug("Decompiler exited with exit code: " + exitValue); if (!sourceOutputLocation.exists()) { LOG.error("Expected decompiled source: " + sourceOutputLocation.getAbsolutePath() + "; did not find file. This likey means that the decompiler did not successfully decompile the class."); } else { LOG.debug("Decompiled to: " + sourceOutputLocation.getAbsolutePath()); } } catch (IOException e) { throw new FatalWindupException( "Error running " + APP_NAME + " decompiler. Validate that " + APP_NAME + " is on your PATH.", e); } catch (Exception e) { throw new FatalWindupException( "Error running " + APP_NAME + " decompiler. Validate that " + APP_NAME + " is on your PATH.", e); } }
From source file:org.jboss.windup.decorator.java.decompiler.JadretroDecompilerAdapter.java
private void executeJad(File classLocation, File sourceOutputLocation) { try {/* w w w . j a v a 2s . c om*/ // Build command array CommandLine cmdLine = new CommandLine(APP_NAME); cmdLine.addArgument("-d"); cmdLine.addArgument("${outputLocation}"); cmdLine.addArgument("-f"); cmdLine.addArgument("-o"); cmdLine.addArgument("-s"); cmdLine.addArgument("java"); cmdLine.addArgument("${classLocation}"); Map<String, Object> argMap = new HashMap<String, Object>(); argMap.put("outputLocation", sourceOutputLocation); argMap.put("classLocation", classLocation); cmdLine.setSubstitutionMap(argMap); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); int exitValue = executor.execute(cmdLine); LOG.debug("Decompiler exited with exit code: " + exitValue); if (!sourceOutputLocation.exists()) { LOG.error("Expected decompiled source: " + sourceOutputLocation.getAbsolutePath() + "; did not find file. This likey means that the decompiler did not successfully decompile the class."); } else { LOG.debug("Decompiled to: " + sourceOutputLocation.getAbsolutePath()); } } catch (IOException e) { throw new FatalWindupException( "Error running " + APP_NAME + " decompiler. Validate that " + APP_NAME + " is on your PATH.", e); } }