List of usage examples for org.apache.commons.exec CommandLine getArguments
public String[] getArguments()
From source file:org.jberet.support.io.OsCommandBatchlet.java
/** * {@inheritDoc}/*from ww w.ja va 2 s . c om*/ * <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 {//from w w w.j a v a 2 s .c om 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.ng200.openolympus.cerberus.compilers.GNUCompiler.java
@Override public void compile(final List<Path> inputFiles, final Path outputFile, final Map<String, Object> additionalParameters) throws CompilationException { GNUCompiler.logger.debug("Compiling {} to {} using GCC", inputFiles, outputFile); final CommandLine commandLine = new CommandLine("g++"); commandLine.setSubstitutionMap(additionalParameters); this.arguments.forEach((arg) -> commandLine.addArgument(arg)); commandLine.addArgument("-w"); // Prohibit warnings because they screw // up error detection commandLine.addArgument("-o"); commandLine.addArgument(MessageFormat.format("\"{0}\"", outputFile.toAbsolutePath().toString())); // Set outuput file inputFiles.forEach((file) -> commandLine .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add // input/*from w w w . j a va 2s . com*/ // files GNUCompiler.logger.debug("Running GCC with arguments: {}", Arrays.asList(commandLine.getArguments())); final DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(new int[] { 0, 1 }); final ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(null, errorStream, null)); executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to // compile int result; try { result = executor.execute(commandLine); } catch (final IOException e) { GNUCompiler.logger.error("Could not execute GCC: {}", e); throw new CompilationException("Could not execute GCC", e); } switch (result) { case 0: return; case 1: try { String errorString = errorStream.toString(StandardCharsets.UTF_8.name()); final Pattern pattern = Pattern.compile( "^(" + inputFiles.stream().map(file -> Pattern.quote(file.toAbsolutePath().toString())) .collect(Collectors.joining("|")) + "):", Pattern.MULTILINE); errorString = pattern.matcher(errorString).replaceAll(""); GNUCompiler.logger.debug("Compilation error: {}", errorString); throw new CompilerError("gcc.wrote.stderr", errorString); } catch (final UnsupportedEncodingException e) { throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e); } } }
From source file:org.ng200.openolympus.cerberus.compilers.JavaCompiler.java
@Override public void compile(final List<Path> inputFiles, final Path outputFile, final Map<String, Object> additionalParameters) throws CompilationException, IOException { FileAccess.createDirectories(outputFile); final CommandLine commandLine = new CommandLine("javac"); commandLine.setSubstitutionMap(additionalParameters); this.arguments.forEach((arg) -> commandLine.addArgument(arg)); commandLine.addArgument("-d"); commandLine.addArgument(outputFile.toAbsolutePath().toString()); commandLine.addArgument("-nowarn"); // Prohibit warnings because they // screw//from ww w.j a v a2 s.co m // up error detection inputFiles.forEach((file) -> commandLine .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add // input // files JavaCompiler.logger.info("Running javac with arguments: {}", Arrays.asList(commandLine.getArguments())); final DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(new int[] { 0, 1 }); final ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(null, errorStream, null)); executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to // compile int result; try { result = executor.execute(commandLine); } catch (final IOException e) { JavaCompiler.logger.error("Could not execute javac: {}", e); throw new CompilationException("Could not execute javac", e); } switch (result) { case 0: return; case 1: try { String errorString = errorStream.toString("UTF-8"); final Pattern pattern = Pattern.compile( "^(" + inputFiles.stream().map(file -> Pattern.quote(file.toAbsolutePath().toString())) .collect(Collectors.joining("|")) + "):", Pattern.MULTILINE); errorString = pattern.matcher(errorString).replaceAll(""); JavaCompiler.logger.debug("Compilation error: {}", errorString); throw new CompilerError("javac.wrote.stderr", errorString); } catch (final UnsupportedEncodingException e) { throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", 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)} *//*from w ww.j a v 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; }
From source file:org.sculptor.maven.plugin.GraphvizMojoTest.java
public void testDotCommandLine() throws Exception { GraphvizMojo mojo = createMojo(createProject("test1")); setVariableValueToObject(mojo, "verbose", false); Set<String> changedDotFiles = new HashSet<String>(); changedDotFiles.add("file1.dot"); changedDotFiles.add("file2.dot"); changedDotFiles.add("file3.dot"); CommandLine commandline = mojo.getDotCommandLine(changedDotFiles); assertNotNull(commandline);/* w ww .j a va2 s.c o m*/ String[] arguments = commandline.getArguments(); assertEquals(5, arguments.length); assertEquals("-Tpng", arguments[0]); assertEquals("-O", arguments[1]); assertEquals("file1.dot", arguments[2]); assertEquals("file2.dot", arguments[3]); assertEquals("file3.dot", arguments[4]); }
From source file:org.sculptor.maven.plugin.GraphvizMojoTest.java
public void testVerboseDotCommandLine() throws Exception { GraphvizMojo mojo = createMojo(createProject("test1")); setVariableValueToObject(mojo, "verbose", true); Set<String> changedDotFiles = new HashSet<String>(); changedDotFiles.add("file1.dot"); changedDotFiles.add("file2.dot"); changedDotFiles.add("file3.dot"); CommandLine commandline = mojo.getDotCommandLine(changedDotFiles); assertNotNull(commandline);//from w w w.ja va2s . c om String[] arguments = commandline.getArguments(); assertEquals(6, arguments.length); assertEquals("-v", arguments[0]); assertEquals("-Tpng", arguments[1]); assertEquals("-O", arguments[2]); assertEquals("file1.dot", arguments[3]); assertEquals("file2.dot", arguments[4]); assertEquals("file3.dot", arguments[5]); }