List of usage examples for org.apache.commons.exec CommandLine getExecutable
public String getExecutable()
From source file:org.eclipse.php.composer.ui.terminal.ComposerLauncher.java
@Override public void launch(String argument, String... params) throws ExecuteException, IOException, InterruptedException { CommandLine cmd = environment.getCommand(); cmd.addArgument(argument);//from w ww . ja va 2 s.c o m cmd.addArguments(params); Map<String, String> env = new HashMap<String, String>(System.getenv()); PHPLaunchUtilities.appendExecutableToPathEnv(env, new File(cmd.getExecutable()).getParentFile()); PHPLaunchUtilities.appendLibrarySearchPathEnv(env, new File(cmd.getExecutable()).getParentFile()); Map<String, Object> properties = new HashMap<String, Object>(); List<String> envs = new ArrayList<>(env.size()); for (String key : env.keySet()) { envs.add(key + '=' + env.get(key)); } properties.put(ITerminalsConnectorConstants.PROP_PROCESS_ENVIRONMENT, envs.toArray(new String[envs.size()])); properties.put(ITerminalsConnectorConstants.PROP_PROCESS_MERGE_ENVIRONMENT, true); ITerminalServiceOutputStreamMonitorListener[] outListeners = new ITerminalServiceOutputStreamMonitorListener[] { new ITerminalServiceOutputStreamMonitorListener() { @Override public void onContentReadFromStream(byte[] byteBuffer, int bytesRead) { for (ExecutionResponseListener handler : getListeners()) { handler.executionMessage(new String(byteBuffer, 0, bytesRead)); } } } }; properties.put(ITerminalsConnectorConstants.PROP_STDOUT_LISTENERS, outListeners); // workaround for colored output on Windows if (Platform.OS_WIN32.equals(Platform.getOS())) { StringBuilder builder = new StringBuilder(); builder.append("@echo off").append(WINDOWS_END_OF_LINE); // $NON-NLS-1$ // 65001 - UTF-8 builder.append("chcp 65001").append(WINDOWS_END_OF_LINE); // $NON-NLS-1$ builder.append("cls").append(WINDOWS_END_OF_LINE); //$NON-NLS-1$ builder.append(escapePath(cmd.getExecutable())).append(' '); for (String arg : cmd.getArguments()) { builder.append(arg).append(' '); } File file = File.createTempFile("composer_windows_", ".bat"); // $NON-NLS-1$ //$NON-NLS-2$ file.deleteOnExit(); try (BufferedWriter writer = new BufferedWriter(new FileWriter(file));) { writer.write(builder.toString()); } catch (FileNotFoundException ex) { ComposerPlugin.logException(ex); } properties.put(ITerminalsConnectorConstants.PROP_PROCESS_PATH, "cmd"); //$NON-NLS-1$ String args = "/C " + file.getAbsolutePath(); //$NON-NLS-1$ properties.put(ITerminalsConnectorConstants.PROP_PROCESS_ARGS, args); } else { properties.put(ITerminalsConnectorConstants.PROP_PROCESS_PATH, escapePath(cmd.getExecutable())); StringBuilder builder = new StringBuilder(); for (String arg : cmd.getArguments()) { builder.append(arg + ' '); } properties.put(ITerminalsConnectorConstants.PROP_PROCESS_ARGS, builder.toString()); } Logger.debug("Setting executor working directory to " + project.getLocation().toOSString()); //$NON-NLS-1$ properties.put(ITerminalsConnectorConstants.PROP_PROCESS_WORKING_DIR, project.getLocation().toOSString()); String title = MessageFormat.format(Messages.ComposerConsoleManager_ConsoleLabel, Messages.ComposerConsoleManager_ConsoleName, project.getName()); IConsoleManager consoleManager = ConsolePlugin.getDefault().getConsoleManager(); final CountDownLatch latch = new CountDownLatch(1); terminalConsole = new TerminalConsole(title, 0, properties, new Done() { @Override public void done(IStatus status) { latch.countDown(); } }); for (ExecutionResponseListener handler : getListeners()) { handler.executionStarted(); } consoleManager.addConsoles(new IConsole[] { terminalConsole }); consoleManager.showConsoleView(terminalConsole); latch.await(); for (ExecutionResponseListener handler : getListeners()) { handler.executionFinished("", 0); //$NON-NLS-1$ } }
From source file:org.jberet.support.io.OsCommandBatchlet.java
/** * {@inheritDoc}/*from ww w. j ava2 s. com*/ * <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.mule.test.infrastructure.process.Controller.java
protected int doExecution(DefaultExecutor executor, CommandLine commandLine, Map<Object, Object> env) { try {//w w w . j a va 2 s.c o m return executor.execute(commandLine, env); } catch (ExecuteException e) { return e.getExitValue(); } catch (Exception e) { throw new MuleControllerException( "Error executing [" + commandLine.getExecutable() + " " + commandLine.getArguments() + "]", e); } }
From source file:org.sakuli.aop.SahiCommandExecutionAspect.java
/** * Due to the fact, the parsing of the sahi method {@link net.sf.sahi.util.Utils#getCommandTokens(String)} won't * work correctly, this {@link Around} advice use the Apache libary {@link CommandLine#parse(String)} to modify it. * See http://community.sahipro.com/forums/discussion/8552/sahi-os-5-0-and-chrome-user-data-dir-containing-spaces-not-working. * * @param joinPoint the {@link ProceedingJoinPoint} of the invoked method * @param commandString the original argument as{@link String} * @return the result of {@link CommandLine#parse(String)} *///www. jav a2 s. c o m @Around("execution(* net.sf.sahi.util.Utils.getCommandTokens(..)) && args(commandString)") public String[] getCommandTokens(ProceedingJoinPoint joinPoint, String commandString) { Logger LOGGER = getLogger(joinPoint); CommandLine parsed = CommandLine.parse(commandString); String[] tokens = new String[] { parsed.getExecutable() }; tokens = ArrayUtils.addAll(tokens, parsed.getArguments()); try { Object result = joinPoint.proceed(); if (result instanceof String[] && !Arrays.equals(tokens, (String[]) result)) { if (commandString.startsWith("sh -c \'")) { //exclude this kind of arguments, because the won't parsed correctly //LOGGER.info("SAHI-RESULT {}", printArray((Object[]) result)); //LOGGER.info("SAKULI-RESULT {}", printArray(tokens)); return (String[]) result; } LOGGER.info("MODIFIED SAHI COMMAND TOKENS: {} => {}", printArray((String[]) result), printArray(tokens)); } } catch (Throwable e) { LOGGER.error("Exception during execution of JoinPoint net.sf.sahi.util.Utils.getCommandTokens", e); } return tokens; }