List of usage examples for org.apache.commons.exec DefaultExecutor DefaultExecutor
public DefaultExecutor()
From source file:com.netflix.genie.web.configs.GenieTasksAutoConfiguration.java
/** * Get an {@link Executor} to use for executing processes from tasks. * * @return The executor to use/*from ww w .ja v a 2 s .co m*/ */ @Bean @ConditionalOnMissingBean(Executor.class) public Executor processExecutor() { final Executor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(null, null)); return executor; }
From source file:com.adaptris.core.services.system.SystemCommandExecutorService.java
/** * Invokes the command line executable//from w w w. j a va2 s .c o m * @see com.adaptris.core.Service#doService(com.adaptris.core.AdaptrisMessage) */ @Override public void doService(AdaptrisMessage msg) throws ServiceException { try (OutputStream out = getOutputCapture().startCapture(msg)) { Executor cmd = getCommandBuilder().configure(new DefaultExecutor()); ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMs()); cmd.setWatchdog(watchdog); CommandLine cl = getCommandBuilder().createCommandLine(msg); Map<String, String> env = getCommandBuilder().createEnvironment(msg); PumpStreamHandler pump = new PumpStreamHandler(out); cmd.setStreamHandler(pump); log.trace("Executing {}", cl); int exit = cmd.execute(cl, env); msg.addMetadata(COMMAND_RETURN_VALUE_METADATA_KEY, "" + exit); } catch (Exception e) { throw ExceptionHelper.wrapServiceException(e); } }
From source file:com.tascape.qa.th.android.comm.Adb.java
private static void loadAllSerials() { SERIALS.clear();// w w w . ja va2 s . c o m String serials = SystemConfiguration.getInstance().getProperty(SYSPROP_SERIALS); if (null != serials) { LOG.info("Use specified devices from system property {}={}", SYSPROP_SERIALS, serials); SERIALS.addAll(Lists.newArrayList(serials.split(","))); } else { CommandLine cmdLine = new CommandLine(ADB); cmdLine.addArgument("devices"); LOG.debug("{}", cmdLine.toString()); List<String> output = new ArrayList<>(); Executor executor = new DefaultExecutor(); executor.setStreamHandler(new ESH(output)); try { if (executor.execute(cmdLine) != 0) { throw new RuntimeException(cmdLine + " failed"); } } catch (IOException ex) { throw new RuntimeException(cmdLine + " failed", ex); } output.stream().filter((line) -> (line.endsWith("device"))).forEach((line) -> { String s = line.split("\\t")[0]; LOG.info("serial {}", s); SERIALS.add(s); }); } if (SERIALS.isEmpty()) { throw new RuntimeException("No device detected."); } }
From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java
/** * * * @param executable/* w w w . ja va 2s. com*/ * @param sourceFile * @return */ protected boolean compile(String executable, File sourceFile) { try { List<CLib> libs = new ArrayList<>(); libs.add(cLibs.get("simpletools")); libs.add(cLibs.get("simpletext")); libs.add(cLibs.get("simplei2c")); File temporaryDestinationFile = File.createTempFile("blocklyapp", ".elf"); File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-c-lib"); Map map = new HashMap(); map.put("sourceFile", sourceFile); map.put("destinationFile", temporaryDestinationFile); CommandLine cmdLine = new CommandLine(executable); for (CLib lib : libs) { cmdLine.addArgument("-I").addArgument("${libdir" + lib.getName() + "}"); cmdLine.addArgument("-L").addArgument("${memorymodel" + lib.getName() + "}"); // cmdLine.addArgument("-l" + lib.getName()); map.put("libdir" + lib.getName(), new File(libDirectory, lib.getLibdir())); map.put("memorymodel" + lib.getName(), new File(libDirectory, lib.getMemoryModel().get("cmm"))); } cmdLine.addArgument("-Os"); cmdLine.addArgument("-mcmm"); cmdLine.addArgument("-m32bit-doubles"); cmdLine.addArgument("-fno-exceptions"); cmdLine.addArgument("-std=c99"); cmdLine.addArgument("-o").addArgument("${destinationFile}"); cmdLine.addArgument("${sourceFile}"); cmdLine.addArgument("-lm"); for (CLib lib : libs) { cmdLine.addArgument("-l" + lib.getName()); } cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(new int[] { 0, 1 }); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); try { System.out.println(cmdLine); exitValue = executor.execute(cmdLine); } catch (ExecuteException ee) { exitValue = ee.getExitValue(); logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue); success = false; return false; } finally { temporaryDestinationFile.delete(); output = outputStream.toString(); } // System.out.println("output: " + output); /* Scanner scanner = new Scanner(output); Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?"); Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$"); while (scanner.hasNextLine()) { String portLine = scanner.nextLine(); if (chipFoundPattern.matcher(portLine).matches()) { Matcher portMatch = pattern.matcher(portLine); if (portMatch.find()) { // String port = portMatch.group("comport"); } } } */ // System.out.println("output: " + output); // System.out.println("exitValue: " + exitValue); success = true; return true; } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); success = false; return false; } }
From source file:com.netflix.spinnaker.clouddriver.jobs.local.JobExecutorLocal.java
private Executor buildExecutor(ExecuteStreamHandler streamHandler) { Executor executor = new DefaultExecutor(); executor.setStreamHandler(streamHandler); executor.setWatchdog(new ExecuteWatchdog(timeoutMinutes * 60 * 1000)); // Setting this to null causes the executor to skip verifying exit codes; we'll handle checking the exit status // instead of having the executor throw an exception for non-zero exit codes. executor.setExitValues(null);//ww w . j av a 2s. c o m return executor; }
From source file:com.tibco.tgdb.test.lib.TGAdmin.java
/** * Invoke TG admin synchronously. //from w ww .ja v a 2s. c o m * Admin operation blocks until it is completed. * * @param url Url to connect to TG server * @param user User name * @param pwd User password * @param logFile TG admin log file location - Generated by admin * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire * @param cmdFile TG admin command file - Need to exist before invoking admin * @param memSize Specify the maximum memory usage (MB). -1 for default (8 MB) * @param timeout Number of milliseconds allowed to complete admin operation * * @return Output console of admin operation * @throws TGAdminException Admin execution fails or timeout occurs */ public String invoke(String url, String user, String pwd, String logFile, String logLevel, String cmdFile, int memSize, long timeout) throws TGAdminException { ByteArrayOutputStream output = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(output); Executor tgExec = new DefaultExecutor(); tgExec.setStreamHandler(psh); tgExec.setWorkingDirectory(new File(this.home + "/bin")); CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath()); // Define arguments List<String> args = new ArrayList<String>(); if (url != null) { args.add("--url"); args.add(url); } if (user != null) { args.add("--uid"); args.add(user); } if (pwd != null) { args.add("--pwd"); args.add(pwd); } if (logFile != null) { args.add("--log"); args.add(logFile); } if (logLevel != null) { args.add("--log-level"); args.add(logLevel); } if (memSize >= 0) { args.add("--max-memory"); args.add(Integer.toString(memSize)); } if (cmdFile == null) throw new TGAdminException("TGAdmin - Command file is required."); args.add("--file"); args.add(cmdFile); tgCL.addArguments((String[]) args.toArray(new String[args.size()])); ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout); tgExec.setWatchdog(tgWatch); System.out.println("TGAdmin - Invoking " + StringUtils.toString(tgCL.toStrings(), " ")); long startProcTime = 0; long endProcTime = 0; long totalProcTime = 0; try { startProcTime = System.currentTimeMillis(); tgExec.execute(tgCL); endProcTime = System.currentTimeMillis(); } catch (IOException ee) { if (tgWatch.killedProcess()) throw new TGAdminException("TGAdmin - Operation did not complete within " + timeout + " ms", output.toString()); else { try { Thread.sleep(1000); // make sure output has time to fill up } catch (InterruptedException ie) { ; } throw new TGAdminException("TGAdmin - Execution failed: " + ee.getMessage(), output.toString()); } } if (!output.toString().contains("Successfully connected to server")) throw new TGAdminException("TGAdmin - Admin could not connect to server", output.toString()); if (endProcTime != 0) totalProcTime = endProcTime - startProcTime; System.out.println( "TGAdmin - Operation completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : "")); return output.toString(); }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.svmlib.SVMLibExperimentRunner.java
public static void runCommand(String command) throws IOException { CommandLine cmdLine = CommandLine.parse(command); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0);/* w w w. ja va 2s .c om*/ // set one hour limit for training ExecuteWatchdog watchdog = new ExecuteWatchdog(1000 * 60 * 60); executor.setWatchdog(watchdog); System.out.println("Running\n" + command); int exitValue = executor.execute(cmdLine); }
From source file:com.base.exec.TutorialTest.java
/** * Simulate printing a PDF document./* w w w . jav a2 s . c o m*/ * * @param file * the file to print * @param printJobTimeout * the printJobTimeout (ms) before the watchdog terminates the * print process * @param printInBackground * printing done in the background or blocking * @return a print result handler (implementing a future) * @throws IOException * the test failed */ public PrintResultHandler print(final File file, final long printJobTimeout, final boolean printInBackground) throws IOException { int exitValue; ExecuteWatchdog watchdog = null; PrintResultHandler resultHandler; // build up the command line to using a 'java.io.File' final Map<String, File> map = new HashMap<String, File>(); map.put("file", file); final CommandLine commandLine = new CommandLine(acroRd32Script); // commandLine.addArgument("/p"); // commandLine.addArgument("/h"); // commandLine.addArgument("${file}"); // commandLine.setSubstitutionMap(map); // // create the executor and consider the exitValue '1' as success final Executor executor = new DefaultExecutor(); executor.setExitValue(0); // create a watchdog if requested if (printJobTimeout > 0) { watchdog = new ExecuteWatchdog(printJobTimeout); executor.setWatchdog(watchdog); } // pass a "ExecuteResultHandler" when doing background printing if (printInBackground) { System.out.println("[print] Executing non-blocking print job ..."); resultHandler = new PrintResultHandler(watchdog); executor.execute(commandLine, resultHandler); } else { System.out.println("[print] Executing blocking print job ..."); exitValue = executor.execute(commandLine); resultHandler = new PrintResultHandler(exitValue); } return resultHandler; }
From source file:com.netflix.spinnaker.halyard.deploy.job.v1.JobExecutorLocal.java
@Override public String startJob(JobRequest jobRequest, Map<String, String> env, InputStream stdIn) { List<String> tokenizedCommand = jobRequest.getTokenizedCommand(); if (tokenizedCommand == null || tokenizedCommand.isEmpty()) { throw new IllegalArgumentException("JobRequest must include a tokenized command to run"); }//from w w w . java2 s . co m final long timeoutMillis = jobRequest.getTimeoutMillis() == null ? ExecuteWatchdog.INFINITE_TIMEOUT : jobRequest.getTimeoutMillis(); String jobId = UUID.randomUUID().toString(); log.info("Scheduling job " + jobRequest.getTokenizedCommand() + " with id " + jobId); scheduler.createWorker().schedule(new Action0() { @Override public void call() { ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); ByteArrayOutputStream stdErr = new ByteArrayOutputStream(); PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(stdOut, stdErr, stdIn); CommandLine commandLine; log.info("Executing " + jobId + "with tokenized command: " + tokenizedCommand); // Grab the first element as the command. commandLine = new CommandLine(jobRequest.getTokenizedCommand().get(0)); // Treat the rest as arguments. String[] arguments = Arrays.copyOfRange(tokenizedCommand.toArray(new String[0]), 1, tokenizedCommand.size()); commandLine.addArguments(arguments, false); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis) { @Override public void timeoutOccured(Watchdog w) { // If a watchdog is passed in, this was an actual time-out. Otherwise, it is likely // the result of calling watchdog.destroyProcess(). if (w != null) { log.warn("Job " + jobId + " timed-out after " + timeoutMillis + "ms."); cancelJob(jobId); } super.timeoutOccured(w); } }; Executor executor = new DefaultExecutor(); executor.setStreamHandler(pumpStreamHandler); executor.setWatchdog(watchdog); try { executor.execute(commandLine, env, resultHandler); } catch (IOException e) { throw new RuntimeException("Execution of " + jobId + " failed ", e); } // Give the job some time to spin up. try { Thread.sleep(500); } catch (InterruptedException e) { } jobIdToHandlerMap.put(jobId, new ExecutionHandler().setResultHandler(resultHandler) .setWatchdog(watchdog).setStdOut(stdOut).setStdErr(stdErr)); } }); return jobId; }
From source file:com.github.trecloux.yeoman.YeomanMojo.java
void executeCommand(String command) throws MojoExecutionException { try {// www . ja va2 s. c om if (isWindows()) { command = "cmd /c " + command; } CommandLine cmdLine = CommandLine.parse(command); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(yeomanProjectDirectory); executor.execute(cmdLine); } catch (IOException e) { throw new MojoExecutionException("Error during : " + command, e); } }