List of usage examples for org.apache.commons.exec CommandLine addArgument
public CommandLine addArgument(final String argument)
From source file:com.github.mjeanroy.maven.plugins.node.commands.CommandExecutor.java
/** * Execute command line and return the result status. * * @param workingDirectory Working directory (i.e where the command line is executed). * @param command Command, containing executable path with arguments. * @param logger Logger to use to log command output. * @return Command result object.// ww w . j av a 2s . c om */ public CommandResult execute(File workingDirectory, Command command, Log logger) { CommandLine commandLine = new CommandLine(command.getExecutable()); for (String argument : command.getArguments()) { commandLine.addArgument(argument); } try { Executor executor = new DefaultExecutor(); executor.setWorkingDirectory(workingDirectory); executor.setExitValue(0); // Define custom output stream LogStreamHandler stream = new LogStreamHandler(logger); PumpStreamHandler handler = new PumpStreamHandler(stream); executor.setStreamHandler(handler); int status = executor.execute(commandLine); return new CommandResult(status); } catch (ExecuteException ex) { return new CommandResult(ex.getExitValue()); } catch (IOException ex) { throw new CommandException(ex); } }
From source file:com.netflix.genie.web.jobs.workflow.impl.JobKickoffTaskTest.java
/** * Test the create user method for user already exists. * * @throws IOException If there is any problem. * @throws GenieException If there is any problem. *///from www .ja v a 2 s. co m @Test public void testCreateUserMethodSuccessDoesNotExist1() throws IOException, GenieException { final String user = "user"; final String group = "group"; final CommandLine idCheckCommandLine = new CommandLine("id"); idCheckCommandLine.addArgument("-u"); idCheckCommandLine.addArgument(user); Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenThrow(new IOException()); final ArgumentCaptor<CommandLine> argumentCaptor = ArgumentCaptor.forClass(CommandLine.class); final List<String> command = Arrays.asList("sudo", "useradd", user, "-G", group, "-M"); try { this.jobKickoffTask.createUser(user, group); } catch (GenieException ge) { // ignore } Mockito.verify(this.executor, Mockito.times(3)).execute(argumentCaptor.capture()); Assert.assertArrayEquals(command.toArray(), argumentCaptor.getAllValues().get(2).toStrings()); }
From source file:de.slackspace.wfail2ban.firewall.impl.DefaultFirewallManager.java
private void deleteFirewallRule(int ruleNumber, String filterName) { CommandLine cmdLine = new CommandLine("cmd.exe"); cmdLine.addArgument("/C"); cmdLine.addArgument(System.getenv("WINDIR") + "\\system32\\netsh.exe"); cmdLine.addArgument("advfirewall"); cmdLine.addArgument("firewall"); cmdLine.addArgument("delete"); cmdLine.addArgument("rule"); cmdLine.addArgument(createFinalRuleName(ruleNumber, filterName)); DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog);//from w w w . j a v a 2 s . c o m try { executor.execute(cmdLine); if (logger.isDebugEnabled()) { logger.debug("Deleted firewall rule " + createFinalRuleName(ruleNumber, filterName)); } } catch (ExecuteException e) { logger.error("Could not delete firewall rule. Error was: ", e); } catch (IOException e) { logger.error("Could not delete firewall rule. Error was: ", e); } }
From source file:de.slackspace.wfail2ban.firewall.impl.DefaultFirewallManager.java
private boolean checkFirewallRuleExists(int ruleNumber, String filterName) { CommandLine cmdLine = new CommandLine("cmd.exe"); cmdLine.addArgument("/C"); cmdLine.addArgument(System.getenv("WINDIR") + "\\system32\\netsh.exe"); cmdLine.addArgument("advfirewall"); cmdLine.addArgument("firewall"); cmdLine.addArgument("show"); cmdLine.addArgument("rule"); cmdLine.addArgument(createFinalRuleName(ruleNumber, filterName)); DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog);// w w w .j a v a2s .c o m try { executor.execute(cmdLine); return true; } catch (ExecuteException e) { //rule does not exist return false; } catch (IOException e) { logger.error("Could not list firewall rule. Error was: ", e); } return false; }
From source file:com.adaptris.hpcc.PollThor.java
@Override public AdaptrisMessage request(AdaptrisMessage msg, ProduceDestination destination, long timeoutMs) throws ProduceException { try {/*from w ww .j a va 2s .c o m*/ String dest = destination.getDestination(msg); CommandLine commandLine = retrieveConnection(DfuplusConnection.class).createCommand(); commandLine.addArgument("action=list"); commandLine.addArgument(String.format("name=%s", dest)); log.trace("Executing {}", commandLine); ListOutputParser parser = new ListOutputParser(dest); // lgtm [java/output-resource-leak] fileCheckStatus = executor.submit(new WaitForFile(parser, commandLine, dest)); fileCheckStatus.get(maxWaitMs(), TimeUnit.MILLISECONDS); } catch (AbortJobException | InterruptedException | TimeoutException e) { throw ExceptionHelper.wrapProduceException(generateExceptionMessage(e), e); } catch (Exception e) { throw ExceptionHelper.wrapProduceException(e); } finally { fileCheckStatus = null; } return msg; }
From source file:com.dubture.composer.core.launch.DefaultExecutableLauncher.java
protected void doLaunch(String scriptPath, String[] arguments, final ILaunchResponseHandler handler, boolean async) throws IOException, InterruptedException, CoreException { String phpExe = null;//from w w w. j a v a 2s.c o m try { Logger.debug("Getting default executable"); phpExe = LaunchUtil.getPHPExecutable(); } catch (ExecutableNotFoundException e) { showWarning(); e.printStackTrace(); Logger.logException(e); return; } Logger.debug("Launching workspace php executable: " + phpExe + " using target " + scriptPath); CommandLine cmd = new CommandLine(phpExe); cmd.addArgument(scriptPath); for (int i = 0; i < arguments.length; i++) { cmd.addArgument(arguments[i], false); } DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler() { @Override public void onProcessComplete(int exitValue) { super.onProcessComplete(exitValue); if (handler != null && outputStream != null) { handler.handle(outputStream.toString()); } } @Override public void onProcessFailed(ExecuteException e) { super.onProcessFailed(e); if (handler != null && errStream != null) { handler.handleError(errStream.toString()); } } }; // System.out.println("Command: " + cmd.toString()); executor.setWorkingDirectory(new File(new Path(scriptPath).removeLastSegments(1).toOSString())); executor.execute(cmd, resultHandler); if (async == false) { resultHandler.waitFor(); } }
From source file:com.netflix.genie.core.jobs.workflow.impl.JobKickoffTaskUnitTests.java
/** * Test the create user method for user already exists. * * @throws IOException If there is any problem. * @throws GenieException If there is any problem. *///from w ww.j av a 2 s.c om @Test public void testCreateUserMethodSuccessDoesNotExist1() throws IOException, GenieException { final String user = "user"; final String group = "group"; final CommandLine idCheckCommandLine = new CommandLine("id"); idCheckCommandLine.addArgument("-u"); idCheckCommandLine.addArgument(user); Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenThrow(new IOException()); final ArgumentCaptor<CommandLine> argumentCaptor = ArgumentCaptor.forClass(CommandLine.class); final List<String> command = Arrays.asList("sudo", "useradd", user, "-G", group, "-M"); try { this.jobKickoffTask.createUser(user, group); } catch (GenieException ge) { log.debug("Ignoring exception to capture arguments."); } Mockito.verify(this.executor, Mockito.times(3)).execute(argumentCaptor.capture()); Assert.assertArrayEquals(command.toArray(), argumentCaptor.getAllValues().get(2).toStrings()); }
From source file:de.akquinet.innovation.play.maven.Play2TestMojo.java
public void execute() throws MojoExecutionException { if (isSkipExecution()) { getLog().info("Test phase skipped"); return;/*w w w . jav a2 s. c o m*/ } String line = getPlay2().getAbsolutePath(); CommandLine cmdLine = CommandLine.parse(line); cmdLine.addArguments(getPlay2SystemPropertiesArguments(), false); cmdLine.addArgument("test"); DefaultExecutor executor = new DefaultExecutor(); if (timeout > 0) { ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog); } executor.setWorkingDirectory(project.getBasedir()); executor.setExitValue(0); try { executor.execute(cmdLine, getEnvironment()); } catch (IOException e) { if (testFailureIgnore) { getLog().error("Test execution failures ignored"); } else { throw new MojoExecutionException("Error during compilation", e); } } }
From source file:de.slackspace.wfail2ban.firewall.impl.DefaultFirewallManager.java
private void addDefaultWindowsFirewallRule(int ruleNumber, String filterName, String ipList) { Map<Object, Object> map = new HashMap<Object, Object>(); map.put("name", createFinalRuleName(ruleNumber, filterName)); map.put("direction", "in"); map.put("ipList", ipList); CommandLine cmdLine = new CommandLine("cmd.exe"); cmdLine.addArgument("/C"); cmdLine.addArgument(System.getenv("WINDIR") + "\\system32\\netsh.exe"); cmdLine.addArgument("advfirewall"); cmdLine.addArgument("firewall"); cmdLine.addArgument("add"); cmdLine.addArgument("rule"); cmdLine.addArgument("name=${name}"); cmdLine.addArgument("dir=${direction}"); cmdLine.addArgument("action=block"); cmdLine.addArgument("localip=any"); cmdLine.addArgument("remoteip=${ipList}"); cmdLine.addArgument("description=This is a generated rule from wfail2ban. Do not edit!"); cmdLine.addArgument("profile=any"); cmdLine.addArgument("interfacetype=any"); cmdLine.setSubstitutionMap(map);// w ww . j av a 2 s . c o m DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); try { executor.execute(cmdLine); if (logger.isDebugEnabled()) { logger.debug("Added firewall rule " + createFinalRuleName(ruleNumber, filterName)); } } catch (ExecuteException e) { ConsolePrinter.printError("Could not create firewall rule. Continuing with next one..."); logger.error("", e); } catch (IOException e) { logger.error("Could not create firewall rule. Error was: ", e); } }
From source file:name.martingeisse.webide.features.verilog.compiler.VerilogBuilder.java
private void compile(long workspaceId, final JsonAnalyzer descriptorAnalyzer, ResourcePath inputFilePath, ResourcePath outputFilePath) {/*from www. j av a 2 s. c o m*/ try { // prepare ResourceHandle inputFile = new ResourceHandle(workspaceId, inputFilePath); ResourceHandle outputFile = new ResourceHandle(workspaceId, outputFilePath); // read the input file byte[] inputData = inputFile.readBinaryFile(false); if (inputData == null) { return; } // delete previous output file outputFile.delete(); // build the command line CommandLine commandLine = new CommandLine(Configuration.getIverilogPath()); commandLine.addArgument("-o"); commandLine.addArgument(Configuration.getStdoutPath()); commandLine.addArgument(Configuration.getStdinPath()); // build I/O streams ByteArrayInputStream inputStream = new ByteArrayInputStream(inputData); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); OutputStream errorStream = System.err; ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream, inputStream); // run Icarus Executor executor = new DefaultExecutor(); executor.setStreamHandler(streamHandler); executor.execute(commandLine); // create the output file outputFile.writeFile(outputStream.toByteArray(), true, true); } catch (IOException e) { // TODO error message logger.error(e); return; } }