List of usage examples for org.apache.commons.exec CommandLine CommandLine
public CommandLine(final CommandLine other)
From source file:com.creactiviti.piper.core.taskhandler.script.Bash.java
@Override public String handle(Task aTask) throws Exception { File scriptFile = File.createTempFile("_script", ".sh"); File logFile = File.createTempFile("log", null); FileUtils.writeStringToFile(scriptFile, aTask.getRequiredString("script")); try (PrintStream stream = new PrintStream(logFile);) { Process chmod = Runtime.getRuntime().exec(String.format("chmod u+x %s", scriptFile.getAbsolutePath())); int chmodRetCode = chmod.waitFor(); if (chmodRetCode != 0) { throw new ExecuteException("Failed to chmod", chmodRetCode); }/* w ww .ja v a 2 s. co m*/ CommandLine cmd = new CommandLine(scriptFile.getAbsolutePath()); logger.debug("{}", cmd); DefaultExecutor exec = new DefaultExecutor(); exec.setStreamHandler(new PumpStreamHandler(stream)); exec.execute(cmd); return FileUtils.readFileToString(logFile); } catch (ExecuteException e) { throw new ExecuteException(e.getMessage(), e.getExitValue(), new RuntimeException(FileUtils.readFileToString(logFile))); } finally { FileUtils.deleteQuietly(logFile); FileUtils.deleteQuietly(scriptFile); } }
From source file:com.vmware.bdd.usermgmt.job.ChangeLocalAccountStateExecutor.java
private void changeLocalAccountState(String argument) { //String chefCmd = "sudo /opt/serengeti/sbin/set-password L"; String sudoCmd = CommonUtil.getCustomizedSudoCmd(); CommandLine cmdLine = new CommandLine(sudoCmd).addArgument(SET_PASSWORD_COMMAND).addArgument(argument); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(new ExecOutputLogger(LOGGER, false), //output logger new ExecOutputLogger(LOGGER, true)) //error logger );// w ww .j a v a2s . com executor.setWatchdog(new ExecuteWatchdog(1000l * TIMEOUT)); try { int exitVal = executor.execute(cmdLine); if (exitVal != 0) { throw new UserMgmtExecException("CHANGE_LOCAL_ACCOUNT_STATE_FAIL", null); } } catch (IOException e) { throw new UserMgmtExecException("CHANGE_LOCAL_ACCOUNT_STATE_FAIL", e); } }
From source file:com.walmart.gatling.commons.ReportExecutor.java
private void runJob(Master.GenerateReport job) { TaskEvent taskEvent = job.reportJob.taskEvent; CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand()); Map<String, Object> map = new HashMap<>(); map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName()))); cmdLine.addArgument("${path}"); //parameters come from the task event for (Pair<String, String> pair : taskEvent.getParameters()) { cmdLine.addArgument(pair.getValue()); }/*from w w w. j a v a2 s.c om*/ String dir = agentConfig.getJob().getLogDirectory() + "reports/" + job.reportJob.trackingId + "/"; cmdLine.addArgument(dir); cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(agentConfig.getJob().getExitValues()); ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchdog); executor.setWorkingDirectory(new File(agentConfig.getJob().getPath())); FileOutputStream outFile = null; FileOutputStream errorFile = null; try { List<String> resultFiles = new ArrayList<>(job.results.size()); //download all files adn /*int i=0; for (Worker.Result result : job.results) { String destFile = dir + i++ + ".log"; resultFiles.add(destFile); DownloadFile.downloadFile(result.metrics,destFile); }*/ AtomicInteger index = new AtomicInteger(); job.results.parallelStream().forEach(result -> { String destFile = dir + index.incrementAndGet() + ".log"; resultFiles.add(destFile); DownloadFile.downloadFile(result.metrics, destFile); }); String outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.reportJob.trackingId); String errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.reportJob.trackingId); //create the std and err files outFile = FileUtils.openOutputStream(new File(outPath)); errorFile = FileUtils.openOutputStream(new File(errPath)); PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile), new ExecLogHandler(errorFile)); executor.setStreamHandler(psh); System.out.println(cmdLine); int exitResult = executor.execute(cmdLine); ReportResult result; if (executor.isFailure(exitResult)) { result = new ReportResult(dir, job.reportJob, false); log.info("Report Executor Failed, result: " + job.toString()); } else { result = new ReportResult(job.reportJob.getHtml(), job.reportJob, true); log.info("Report Executor Completed, result: " + result.toString()); } for (String resultFile : resultFiles) { FileUtils.deleteQuietly(new File(resultFile)); } getSender().tell(result, getSelf()); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { IOUtils.closeQuietly(outFile); IOUtils.closeQuietly(errorFile); } }
From source file:net.ladenthin.snowman.imager.run.streamer.Streamer.java
@Override public void run() { final CImager conf = ConfigurationSingleton.ConfigurationSingleton.getImager(); for (;;) {//from www. j a va 2 s . c o m if (WatchdogSingleton.WatchdogSingleton.getWatchdog().getKillFlag() == true) { LOGGER.trace("killFlag == true"); return; } final CommandLine cmdLine = new CommandLine(streamer); // final CommandLine cmdLine = new CommandLine("sleep"); // cmdLine.addArgument("200"); cmdLine.addArgument("-c"); cmdLine.addArgument(conf.getStreamer().getDevice()); cmdLine.addArgument("-t"); cmdLine.addArgument( String.valueOf(conf.getStreamer().getFramesPerSecond() * conf.getStreamer().getRecordTime())); cmdLine.addArgument("-r"); cmdLine.addArgument(String.valueOf(conf.getStreamer().getFramesPerSecond())); cmdLine.addArgument("-s"); cmdLine.addArgument(conf.getStreamer().getResolutionX() + "x" + conf.getStreamer().getResolutionY()); cmdLine.addArgument("-o"); cmdLine.addArgument(conf.getStreamer().getPath() + File.separator + conf.getSnowmanServer().getCameraname() + "_" + (long) (System.currentTimeMillis() / 1000) + "_" + conf.getStreamer().getFramesPerSecond() + "_00000000.jpeg"); LOGGER.trace("cmdLine: {}", cmdLine); // 10 seconds should be more than enough final long safetyTimeWindow = 10000; final DefaultExecutor executor = new DefaultExecutor(); final long timeout = 1000 * (conf.getStreamer().getRecordTime() + safetyTimeWindow); // final long timeout = 5000; LOGGER.trace("timeout: {}", timeout); final ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog); try { LOGGER.debug("start process"); final int exitValue = executor.execute(cmdLine); LOGGER.debug("process executed"); LOGGER.trace("exitValue: {}", exitValue); } catch (IOException e) { if (watchdog.killedProcess()) { LOGGER.warn("Process was killed on purpose by the watchdog "); } else { LOGGER.error("Process exited with an error."); Imager.waitALittleBit(5000); } } LOGGER.trace("loop end"); } }
From source file:com.netflix.genie.web.util.UnixProcessChecker.java
/** * Constructor./* w ww . j ava 2s . c om*/ * * @param pid The process id to check. * @param executor The executor to use for generating system commands. * @param timeout The time which after this job should be killed due to timeout * @param checkWithSudo Whether the checker requires sudo */ UnixProcessChecker(@Min(1) final int pid, @NotNull final Executor executor, @NotNull final Instant timeout, final boolean checkWithSudo) { if (!SystemUtils.IS_OS_UNIX) { throw new IllegalArgumentException("Not running on a Unix system."); } this.executor = executor; // Use POSIX compliant 'kill -0 <PID>' to check if process is still running. if (checkWithSudo) { this.commandLine = new CommandLine("sudo"); this.commandLine.addArgument("kill"); this.commandLine.addArgument("-0"); this.commandLine.addArgument(Integer.toString(pid)); } else { this.commandLine = new CommandLine("kill"); this.commandLine.addArgument("-0"); this.commandLine.addArgument(Integer.toString(pid)); } this.timeout = timeout; }
From source file:com.netflix.genie.core.util.UnixProcessChecker.java
/** * Constructor.//from w w w . j av a 2s. c o m * * @param pid The process id to check. * @param executor The executor to use for generating system commands. * @param timeout The time which after this job should be killed due to timeout */ public UnixProcessChecker(@Min(1) final int pid, @NotNull final Executor executor, @NotNull final Date timeout) { if (!SystemUtils.IS_OS_UNIX) { throw new IllegalArgumentException("Not running on a Unix system."); } this.executor = executor; // Using PS for now but could instead check for existence of done file if this proves to have bad performance // send output to /dev/null so it doesn't print to the logs this.commandLine = new CommandLine("ps"); this.commandLine.addArgument("-p"); this.commandLine.addArgument(Integer.toString(pid)); this.timeout = new Date(timeout.getTime()); this.dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); }
From source file:ch.vorburger.exec.ManagedProcessBuilder.java
public ManagedProcessBuilder(String executable) throws ManagedProcessException { commonsExecCommandLine = new CommandLine(executable); this.environment = initialEnvironment(); }
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./*from w w w . j ava2 s . c o m*/ */ 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:ca.unbsj.cbakerlab.sqltemplate.schematicanswers.ExecutionEngine.java
public String run(String input) { File req = tmpFile("request-", ".tptp"); writeStringToFile(req, input);//from w ww . jav a 2s .c o m CommandLine cl = new CommandLine(m_binPath); cl.addArguments(m_commBuilder.buildCommandLine(m_resourcePaths, req.getPath())); //System.out.println("--"+ cl.toString()); ByteArrayOutputStream out = new ByteArrayOutputStream(); execute(cl, out, m_exeTimeout); req.delete(); File schematic_answer = new File( System.getProperty("java.io.tmpdir").concat("/SQLTemplateDir") + "/schematic_answers.xml"); writeStringToFile(schematic_answer, out.toString()); return m_resultHandler.parse(out.toString()); }
From source file:de.simu.decomap.messaging.resultprocessor.impl.helper.RulesExecutor.java
/** * Executing a predefined Rule/* w ww . j a v a 2 s . c o m*/ * @param ruleType RuleType * @param arg args for Rule * @return Success */ public boolean executePredefinedRule(byte ruleType, String arg) { logger.info("[IPTABLES] -> executing predefined command..."); // use apache's commons-exec for executing command! CommandLine cmdLine = new CommandLine(command); // get the predefined rule-parameters String[] ruleParams = Rules.getPredefindedRuleParameters(ruleType, arg); if (ruleParams != null) { // add rule-parameters to CommanLine-Object for (int i = 0; i < ruleParams.length; i++) { cmdLine.addArgument(ruleParams[i]); } // execute command DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(mTimeout); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); try { executor.execute(cmdLine, resultHandler); } catch (ExecuteException e) { logger.warn("[IPTABLES] -> error while executing predefined command: execute-exception occured!"); return false; } catch (IOException e) { logger.warn("[IPTABLES] -> error while executing predefined command: io-exception occured!"); return false; } try { // some time later the result handler callback was invoked so we // can safely request the exit value resultHandler.waitFor(); int exitCode = resultHandler.getExitValue(); logger.info("[IPTABLES] -> command " + ruleType + " executed, exit-code is: " + exitCode); switch (exitCode) { case EXIT_CODE_SUCCESS: return true; case EXIT_CODE_ERROR: return false; default: return false; } } catch (InterruptedException e) { logger.warn( "[IPTABLES] -> error while executing predefined command: interrupted-exception occured!"); return false; } } else { logger.warn("[IPTABLES] -> error while excuting predefined command: rule-parameters-list is null!"); return false; } }