@Override public Long call() throws Exception { Executor executor = new DefaultExecutor(); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); ExecuteWatchdog watchDog = new ExecuteWatchdog(watchdogTimeout); executor.setWatchdog(watchDog); executor.setStreamHandler(new PumpStreamHandler(new MyLogOutputStream(handler, true), new MyLogOutputStream(handler, false))); Long exitValue; try { exitValue = new Long(executor.execute(commandline)); } catch (ExecuteException e) { exitValue = new Long(e.getExitValue()); } if (watchDog.killedProcess()) { exitValue = WATCHDOG_EXIST_VALUE; } return exitValue; }
public static void main(String[] args) throws Exception { String cmd = "/tmp/test.sh"; CommandLine cmdLine = CommandLine.parse("/bin/bash " + cmd); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(stdout, stderr); psh.setStopTimeout(TIMEOUT_FIVE_MINUTES); ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT_TEN_MINUTES); // timeout in milliseconds Executor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setStreamHandler(psh); executor.setWatchdog(watchdog); int exitValue = executor.execute(cmdLine, Collections.emptyMap()); System.out.println(exitValue); }
public int execute(String[] args, @Nullable Path workingDir, Map<String, String> addEnv) throws IOException { if (!Files.isExecutable(file)) { Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_EXECUTE); Files.setPosixFilePermissions(file, perms); } ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); CommandLine cmd = new CommandLine(file.toFile()); cmd.addArguments(args); DefaultExecutor exec = new DefaultExecutor(); exec.setWatchdog(watchdog); exec.setStreamHandler(createStreamHandler()); exec.setExitValues(null); if (workingDir != null) { exec.setWorkingDirectory(workingDir.toFile()); } in.close(); LOG.info("Executing: {}", cmd.toString()); Map<String, String> env = new HashMap<>(System.getenv()); env.putAll(addEnv); return exec.execute(cmd, env); }
/** * Runs docker command asynchronously. * * @param arguments command line arguments * @param out stdout will be written in to this file * * @return a handle used to stop the command process * * @throws IOException when command has error */ public ExecuteWatchdog dockerAsync(final List<Object> arguments, OutputStream out) throws IOException { CommandLine cmdLine = new CommandLine(DOCKER); arguments.forEach((arg) -> { cmdLine.addArgument(arg + ""); }); LOG.debug("[{} {}]", cmdLine.getExecutable(), StringUtils.join(cmdLine.getArguments(), " ")); List<String> output = new ArrayList<>(); ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); Executor executor = new DefaultExecutor(); executor.setWatchdog(watchdog); PrintWriter writer = new PrintWriter(out); ESH esh = new ESH(writer); executor.setStreamHandler(esh); executor.execute(cmdLine, new DefaultExecuteResultHandler()); return watchdog; }
private ExecuteWatchdog runJar(InvocationOutputHandler buildLogHandler, InvocationOutputHandler consoleLogHandler, Map<String, String> envVarsForApp, Waiter startupWaiter) { Path libsPath = Paths.get(projectRoot.getPath(), "build", "libs"); File libsFolder = libsPath.toFile(); // To simplify implementation, now I assume only 1 uberjar named "artifact-version-all.jar" under libs folder // As we clean the project every time, I can't foresee any possibility that will mix up other uberjars. File[] files = libsFolder.listFiles(); if(files == null) { throw new ProjectCannotStartException(libsFolder.getPath() + " doesn't exist"); } Optional<File> jar = Stream.of(files).filter((f) -> f.getName().contains("all")).findFirst(); if (!jar.isPresent() || !jar.get().isFile()) { throw new ProjectCannotStartException("Could not find the jar file at " + jar.get().getPath()); } CommandLine command = javaHomeProvider.commandLine(envVarsForApp) .addArgument("-Djava.io.tmpdir=" + envVarsForApp.get("TEMP")) .addArgument("-jar") .addArgument(fullPath(jar.get())); return ProcessStarter.startDaemon(buildLogHandler, consoleLogHandler, envVarsForApp, command, projectRoot, startupWaiter); }
private void runCancelJob(Master.Job message) { if (getAbortStatus(message.abortUrl, message.trackingId)) { CommandLine cmdLine = new CommandLine("/bin/bash"); cmdLine.addArgument(agentConfig.getJob().getJobArtifact("cancel")); cmdLine.addArgument(message.jobId); DefaultExecutor killExecutor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); killExecutor.setWatchdog(watchdog); try { log.info("Cancel command: {}", cmdLine); killExecutor.execute(cmdLine); TaskEvent taskEvent = (TaskEvent) message.taskEvent; String outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), message.jobId); String errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), message.jobId); Worker.Result result = new Worker.Result(-9, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath), null, message); getSender().tell(new Worker.WorkFailed(result), getSelf()); } catch (IOException e) { log.error(e, "Error cancelling job"); } } }
private void runCancelJob(Master.Job message) { if (getAbortStatus(message.abortUrl, message.trackingId)) { CommandLine cmdLine = new CommandLine("/bin/bash"); cmdLine.addArgument(agentConfig.getJob().getJobArtifact("cancel")); cmdLine.addArgument(message.jobId); DefaultExecutor killExecutor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); killExecutor.setWatchdog(watchdog); try { log.info("Cancel command: {}", cmdLine); killExecutor.execute(cmdLine); } catch (IOException e) { log.error(e, "Error cancelling job"); } } }
/** * Executes the given command synchronously. * * @param command The command to execute. * @param processInput Input provided to the process. * @return The result of the execution, or empty if the process does not terminate within the timeout set for this executor. * @throws IOException if the process execution failed. */ public Optional<ProcessResult> execute(String command, String processInput) throws IOException { ByteArrayOutputStream processErr = new ByteArrayOutputStream(); ByteArrayOutputStream processOut = new ByteArrayOutputStream(); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(createStreamHandler(processOut, processErr, processInput)); ExecuteWatchdog watchDog = new ExecuteWatchdog(TimeUnit.SECONDS.toMillis(timeoutSeconds)); executor.setWatchdog(watchDog); executor.setExitValues(successExitCodes); int exitCode; try { exitCode = executor.execute(CommandLine.parse(command)); } catch (ExecuteException e) { exitCode = e.getExitValue(); } return (watchDog.killedProcess()) ? Optional.empty() : Optional.of(new ProcessResult(exitCode, processOut.toString(), processErr.toString())); }
@BeforeClass public static void setUpBeforeClass() throws Exception { System.out.println("Java Temp Dir: " +System.getProperty("java.io.tmpdir")); executor = new DefaultExecutor(); resultHandler = new DefaultExecuteResultHandler(); String javaHome = System.getProperty("java.home"); String userDir = System.getProperty("user.dir"); executor.setStreamHandler(new PumpStreamHandler(System.out)); watchdog = new ExecuteWatchdog(10000); executor.setWatchdog(watchdog); executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR + "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe").addArgument("-version")); executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR + "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe") .addArgument("-jar") .addArgument(userDir + "/../moneta-dropwizard/target/moneta-dropwizard-" + ContractTestSuite.getProjectVersion() + ".jar") .addArgument("server") .addArgument("src/main/resources/dropwizard/moneta-dropwizard.yaml"), resultHandler); Thread.sleep(3000); System.out.println("Test sequence starting...."); }
public void run() { try { executor = new DaemonExecutor(); resultHandler = new DefaultExecuteResultHandler(); String javaHome = System.getProperty("java.home"); String userDir = System.getProperty("user.dir"); executor.setStreamHandler(new PumpStreamHandler(System.out)); watchdog = new ExecuteWatchdog(15000); executor.setWatchdog(watchdog); executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR + "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe").addArgument("-version")); executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR + "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe") .addArgument("-jar") .addArgument(userDir + "/../moneta-springboot/target/moneta-springboot-" + ContractTestSuite.getProjectVersion() + ".jar")); } catch (Exception e) { e.printStackTrace(); } }
/** * Verify if dot can be started and print out the version to stdout. * * @return True if "dot -V" ran successfully, false otherwise * * @throws IOException If running dot fails. */ public static boolean checkDot() throws IOException { // call graphviz-dot via commons-exec CommandLine cmdLine = new CommandLine(DOT_EXE); cmdLine.addArgument("-V"); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); int exitValue = executor.execute(cmdLine); if(exitValue != 0) { System.err.println("Could not run '" + DOT_EXE + "', had exit value: " + exitValue + "!"); return false; } return true; }
public AbstractCppcheckCommand(IConsole console, String[] defaultArguments, long timeout, String binaryPath) { this.binaryPath = binaryPath; this.console = console; this.defaultArguments = defaultArguments; executor = new DefaultExecutor(); // all modes of operation returns 0 when no error occured, executor.setExitValue(0); watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog); out = new ByteArrayOutputStream(); err = new ByteArrayOutputStream(); processStdOut = new LineFilterOutputStream(new TeeOutputStream(out, console.getConsoleOutputStream(false)), DEFAULT_CHARSET); processStdErr = new LineFilterOutputStream(new TeeOutputStream(err, console.getConsoleOutputStream(true)), DEFAULT_CHARSET); }
private Session(Builder builder) { Session.id++; this.config = builder.config; this.source = builder.input; this.cmdLine = builder.cmdLine; this.cleanUpOnExit = builder.cleanUpOnExit; this.setOutputs(builder.outputs); this.executor = new DefaultExecutor(); // set this locally not globally -| this.workingDirectoryPath = (builder.workingDirectoryPath == null || builder.workingDirectoryPath == "")?Globals.getEnv(Globals.Vars.WORKING_DIRECTORY):builder.workingDirectoryPath; this.executonTimeout = ExecuteWatchdog.INFINITE_TIMEOUT; this.watchdog = new ExecuteWatchdog(executonTimeout); this.observers = new ArrayList<ISessionObserver>(); logger.info("Command :" + this.cmdLine.toString()); }
@Override public void onTranscodeProcessFailed(ExecuteException e, ExecuteWatchdog watchdog, long timestamp) { // TODO Auto-generated method stub String cause = null; if(watchdog != null && watchdog.killedProcess()) cause = FAILURE_BY_TIMEOUT; else cause = GENERIC_FAILURE; if(timestamp - this.resultHandler.getAbortRequestTimestamp()>ABORT_TIMEOUT) { logger.warn("onTranscodeProcessFailed cause: " + cause); notifyObservers(SessionEvent.FAILED, new TranscoderExecutionError(e, cause, timestamp)); } else { logger.warn("Probable force abort"); doCleanUp(); } }
public static int executeCommand(String command,ExecuteWatchdog watchdog) { CommandLine cmdLine = CommandLine.parse(command); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(System.out,System.err, null)); executor.setExitValues(new int[]{0, 1}); if(watchdog != null){ executor.setWatchdog(watchdog); } int exitValue = 0; try { exitValue = executor.execute(cmdLine); } catch (IOException e) { exitValue = 1; log.error("error executing command", e); } return exitValue; }
public static boolean testExecutable() { CommandLine commandLine = CommandLine.parse(PythonCLIProcessor.pythonExecutable + " --version"); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); Executor executor = new DefaultExecutor(); // put a watchdog with a timeout ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(timeout_seconds) * 1000); executor.setWatchdog(watchdog); try { executor.execute(commandLine, resultHandler); resultHandler.waitFor(); int exitVal = resultHandler.getExitValue(); if (exitVal != 0) { return false; } return true; } catch (Exception e) { return false; } }
private static boolean testExecutable() { CommandLine commandLine = CommandLine.parse(RCLIProcessor.rExecutable + " " + VERSION_CALL); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); Executor executor = new DefaultExecutor(); // put a watchdog with a timeout ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(TIMEOUT_SECONDS) * 1000); executor.setWatchdog(watchdog); try { executor.execute(commandLine, resultHandler); resultHandler.waitFor(); int exitVal = resultHandler.getExitValue(); if (exitVal != 0) { return false; } return true; } catch (Exception e) { return false; } }
public static void learn(String path, String factsForLearningFile, String rulesDefinitionFile, String learnedWeightsFile) throws Exception { CommandLine cmdLine = new CommandLine(path + "/learnwts"); cmdLine.addArgument("-i"); cmdLine.addArgument(factsForLearningFile); cmdLine.addArgument("-o"); cmdLine.addArgument(rulesDefinitionFile); cmdLine.addArgument("-t"); cmdLine.addArgument(learnedWeightsFile); cmdLine.addArgument("-g -multipleDatabases"); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); executor.execute(cmdLine, resultHandler); resultHandler.waitFor(); }
public static ExecuteWatchdog execASync(String line, File workDir, Map<String, String> environment, OutputStream output, ExecuteResultHandler erh, long timeout) throws IOException { if (environment != null) { Map<String, String> sysenv = System.getenv(); for (String key : sysenv.keySet()) { boolean contains = false; for (String k : environment.keySet()) { if (k.equalsIgnoreCase(key)) { contains = true; break; } } if (!contains) environment.put(key, sysenv.get(key)); } } DefaultExecutor executor = new DefaultExecutor(); if (workDir != null) executor.setWorkingDirectory(workDir); PumpStreamHandler sh = new PumpStreamHandler(output, output, null); executor.setStreamHandler(sh); ExecuteWatchdog watchdog = new ProcessTreeWatchDog(timeout); executor.setWatchdog(watchdog); executor.execute(CommandLine.parse(line), environment, erh); return watchdog; }
public static ExecuteWatchdog execASync(String line, File workDir, Map<String, String> environment, OutputStream output, ExecuteResultHandler erh, long timeout, Logger log) throws IOException { if (environment != null) { Map<String, String> sysenv = System.getenv(); for (String key : sysenv.keySet()) { boolean contains = false; for (String k : environment.keySet()) { if (k.equalsIgnoreCase(key)) { contains = true; break; } } if (!contains) environment.put(key, sysenv.get(key)); } } DefaultExecutor executor = new DefaultExecutor(); if (workDir != null) executor.setWorkingDirectory(workDir); PumpStreamHandler sh = new PumpStreamHandler(output, output, null); executor.setStreamHandler(sh); ExecuteWatchdog watchdog = new ProcessTreeWatchDog(timeout, log); executor.setWatchdog(watchdog); executor.execute(CommandLine.parse(line), environment, erh); return watchdog; }
private void triggerThreadDump() { String kill = findBinary("kill"); if (kill != null) { for (final Integer pid : getOpenNMSProcesses()) { LogUtils.debugf(this, "pid = " + pid); CommandLine command = CommandLine.parse(kill + " -3 " + pid.toString()); try { LogUtils.tracef(this, "running '%s'", command.toString()); DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(new ExecuteWatchdog(5000)); int exitValue = executor.execute(command); LogUtils.tracef(this, "finished '%s'", command.toString()); if (exitValue != 0) { LogUtils.warnf(this, "'%s' exited non-zero: %d", command.toString(), exitValue); } } catch (final Exception e) { LogUtils.warnf(this, e, "Unable to run kill -3 on '%s': you might need to run system-report as root.", pid.toString()); } } } }
private void extractMetaData(File audioFile){ Strategy strategy = Strategy.getInstance(); String identifier = strategy.resolve(file.getAbsolutePath()); String dir = Config.get(Key.META_DATA_DIRECTORY); File metaDataFile = new File(dir,identifier+".json"); String command = Config.get(Key.META_DATA_COMMAND); Map<String,File> map = new HashMap<String,File>(); map.put("audiofile", audioFile); map.put("metadatafile", metaDataFile); CommandLine cmdLine = new CommandLine(command); cmdLine.addArgument("${audiofile}"); cmdLine.addArgument("${metadatafile}"); cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); //executor.setExitValue(1); ExecuteWatchdog watchdog = new ExecuteWatchdog(1000000); executor.setWatchdog(watchdog); try { int exitValue = executor.execute(cmdLine); if(exitValue==0){ System.out.println("Extracted metadata successfully"); }else{ System.err.println("Failed to extract metadata for:" + audioFile); } } catch (IOException e) { e.printStackTrace(); } }
/** * Creates a process and logs the output */ public void executeProcess(String[] cmd, String logKey, ProcessResult result, Map<String, String> additionalEnvVars, File workingDir) { Map<String, String> env = getEnvVars(cmd, additionalEnvVars); logger.info(format("%s Cmd: %s, Additional Env Vars: %s", logKey, String.join(" ", cmd), additionalEnvVars)); try { CommandLine cmdLine = new CommandLine(cmd[0]); // add rest of cmd string[] as arguments for (int i = 1; i < cmd.length; i++) { // needs the quote handling=false or else doesn't work // http://www.techques.com/question/1-5080109/How-to-execute--bin-sh-with-commons-exec? cmdLine.addArgument(cmd[i], false); } DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setWatchdog(new ExecuteWatchdog(timeoutInSeconds * 1000)); executor.setStreamHandler(new OutputHandler(logger, logKey, result)); if (workingDir != null) { executor.setWorkingDirectory(workingDir); } result.setResultCode(executor.execute(cmdLine, env)); // set fault to last error if fault map is empty if (result.getResultCode() != 0 && result.getFaultMap().keySet().size() < 1) { result.getFaultMap().put("ERROR", result.getLastError()); } } catch (ExecuteException ee) { logger.error(logKey + ee); result.setResultCode(ee.getExitValue()); } catch (IOException e) { logger.error(e); result.setResultCode(1); } }
public void compile(String cwd, Submission submission) throws RuntimeException { ByteArrayOutputStream stderr = new ByteArrayOutputStream(); ExecuteWatchdog watchdog = new ExecuteWatchdog(watchdogTimeout); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(new File(cwd)); executor.setStreamHandler(new PumpStreamHandler(null, stderr, null)); executor.setWatchdog(watchdog); CommandLine cmd = new CommandLine(javac); cmd.addArgument("-J-Duser.language=en"); // force using English cmd.addArgument("-classpath"); cmd.addArgument(cwd); cmd.addArgument(fileName + ".java"); logger.info("Compiler cmd:\t" + cmd.toString()); try { executor.execute(cmd); logger.info("Compile OK"); } catch (IOException e) { if (watchdog.killedProcess()) { submission.setStatus(Submission.STATUS_CE); submission.setError("Compile Time Exceeded"); logger.warn("Compile Time Exceeded:\t" + e.getMessage()); } else { submission.setStatus(Submission.STATUS_CE); submission.setError("Compile error"); logger.warn("Compile error:\t" + e.getMessage()); } logger.warn(stderr.toString()); throw new RuntimeException("Compile Aborted."); } }
public static void main(String[] args) throws Exception { DockerClient dc = new DockerClient(); String v = dc.getVersion(); LOG.info(v); ExecuteWatchdog dog = dc.tailServiceLogs("msc_siteservice"); dc.delay(3000); dog.killedProcess(); System.exit(0); }
private void stopProcess(String paragraphId) { if (runningProcesses.containsKey(paragraphId)) { final Executor executor = runningProcesses.get(paragraphId); final ExecuteWatchdog watchdog = executor.getWatchdog(); watchdog.destroyProcess(); } }
protected DefaultExecutor prepareDefaultExecutor(ExecCommand execCommand) { DefaultExecutor executor = new ExecDefaultExecutor(); executor.setExitValues(null); if (execCommand.getWorkingDir() != null) { executor.setWorkingDirectory(new File(execCommand.getWorkingDir()).getAbsoluteFile()); } if (execCommand.getTimeout() != ExecEndpoint.NO_TIMEOUT) { executor.setWatchdog(new ExecuteWatchdog(execCommand.getTimeout())); } executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); return executor; }
public Executor start() throws Exception { CommandLine startCmd = toEngineCommand(Command.start); context.log.info("Start Axon.ivy Engine in folder: " + context.engineDirectory); Executor executor = createEngineExecutor(); executor.setStreamHandler(createEngineLogStreamForwarder(logLine -> findStartEngineUrl(logLine))); executor.setWatchdog(new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT)); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); executor.execute(startCmd, asynchExecutionHandler()); waitForEngineStart(executor); return executor; }
private void generateThumbnailWithImageMagickConvert(File source, File destination, ImageThumbnailFormat thumbnailFormat) throws ImageThumbnailGenerationException { try { CommandLine commandLine = new CommandLine(imageMagickConvertBinary); commandLine.addArgument("-auto-orient"); commandLine.addArgument("-thumbnail"); if (thumbnailFormat.isAllowEnlarge()) { commandLine.addArgument("${width}x${height}"); } else { commandLine.addArgument("${width}x${height}>"); } commandLine.addArgument("-quality"); commandLine.addArgument("${quality}"); commandLine.addArgument("${originalFilePath}"); commandLine.addArgument("${targetFilePath}"); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("width", String.valueOf(thumbnailFormat.getWidth())); parameters.put("height", String.valueOf(thumbnailFormat.getHeight())); parameters.put("quality", String.valueOf(thumbnailFormat.getQuality())); parameters.put("originalFilePath", source.getAbsolutePath()); parameters.put("targetFilePath", destination.getAbsolutePath()); commandLine.setSubstitutionMap(parameters); DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(IMAGE_MAGICK_CONVERT_TIMEOUT); executor.setWatchdog(watchdog); executor.execute(commandLine); } catch (RuntimeException | IOException e) { throw new ImageThumbnailGenerationException(String.format("Unable to generate a thumbnail for file %1$s", source.getAbsolutePath()), e); } }
/** * Call graphviz-dot to convert the .dot-file to a rendered graph. * * The file extension of the specified result file is being used as the filetype * of the rendering. * * @param dotfile The dot {@code File} used for the graph generation * @param resultfile The {@code File} to which should be written * * @throws IOException if writing the resulting graph fails or other I/O * problems occur */ public static void renderGraph(File dotfile, File resultfile) throws IOException { // call graphviz-dot via commons-exec CommandLine cmdLine = new CommandLine(DOT_EXE); cmdLine.addArgument("-T" + StringUtils.substringAfterLast(resultfile.getAbsolutePath(), ".")); cmdLine.addArgument(dotfile.getAbsolutePath()); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); try { try (FileOutputStream out2 = new FileOutputStream(resultfile)) { executor.setStreamHandler(new PumpStreamHandler(out2, System.err)); int exitValue = executor.execute(cmdLine); if(exitValue != 0) { throw new IOException("Could not convert graph to dot, had exit value: " + exitValue + "!"); } } } catch (IOException e) { // if something went wrong the file should not be left behind... if(!resultfile.delete()) { System.out.println("Could not delete file " + resultfile); } throw e; } }
private static DefaultExecutor getDefaultExecutor(File dir, int expectedExit, long timeout) { DefaultExecutor executor = new DefaultExecutor(); if(expectedExit != -1) { executor.setExitValue(expectedExit); } else { executor.setExitValues(null); } ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog); executor.setWorkingDirectory(dir); return executor; }
/** * Runs the specified command on a file. * @param file to run the command on. */ private void runComandOnFile(File file) { try { CommandLine cmdLine = new CommandLine(getCommandToRun()); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(stdout); for (String argument : arguments) { cmdLine.addArgument(argument); } Map<String, File> fileMap = new HashMap<String, File>(); fileMap.put("file", file); cmdLine.setSubstitutionMap(fileMap); Logger.getLogger(FolderOptions.class).info("[Running command] " + cmdLine.toString()); DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(6000); executor.setWatchdog(watchdog); executor.setStreamHandler(psh); executor.execute(cmdLine); Logger.getLogger(FolderOptions.class).info(stdout.toString()); commandsRunning.put(file.getAbsolutePath(), executor); } catch (Exception ex) { Logger.getLogger(FolderOptions.class).error(ex.toString()); } }
public static String getVersion() { try { URL scriptURL = PythonCLIProbe.class.getResource(versionScriptFile); File sf = new File(scriptURL.toURI()); String scriptPath = sf.getAbsolutePath(); CommandLine commandLine = CommandLine.parse(PythonCLIProcessor.pythonExecutable + " " + scriptPath); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); Executor executor = new DefaultExecutor(); // put a watchdog with a timeout ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(timeout_seconds) * 1000); executor.setWatchdog(watchdog); ByteArrayOutputStream os = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(os); executor.setStreamHandler(psh); executor.execute(commandLine, resultHandler); resultHandler.waitFor(); int exitVal = resultHandler.getExitValue(); if (exitVal != 0) { return null; } return (os.toString()); } catch (Exception e) { return null; } }
private static String getVersion() { try { CommandLine commandLine = CommandLine.parse(RCLIProcessor.rExecutable + " " + VERSION_CALL); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); Executor executor = new DefaultExecutor(); // put a watchdog with a timeout ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(TIMEOUT_SECONDS) * 1000); executor.setWatchdog(watchdog); ByteArrayOutputStream os = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(os); executor.setStreamHandler(psh); executor.execute(commandLine, resultHandler); resultHandler.waitFor(); int exitVal = resultHandler.getExitValue(); if (exitVal != 0) { return null; } String osString = os.toString(); String versionString = osString.substring(osString.lastIndexOf(": ") + 2); versionString = versionString.substring(0, versionString.indexOf('\n')); return (versionString); } catch (Exception e) { LOGGER.error("Could not get version string.", e); return null; } }
public static void main(String[] args) throws ExecuteException, IOException, InterruptedException { CommandLine command = new CommandLine("/bin/bash"); command.addArgument("-c", false); command.addArgument("iperf3 -t 30 -c iperf.scottlinux.com >> output.txt", false); //Process process = Runtime.getRuntime().exec(new String[]{"bash", "-c", "iperf3 -t 60 -c localhost"}); // System.out.println(new Mirror().on(process).get().field("pid")); //process.waitFor(); // System.out.println(process.exitValue()); // ManagementFactory.getRuntimeMXBean().getName(); // System.out.println(IOUtils.readLines(process.getInputStream())); //String command = "iperf3 -t 30 -c iperf.scottlinux.com"; ExecuteWatchdog watchdog = new ExecuteWatchdog(10); final DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler()); executor.setExitValue(1); executor.execute(command, new ExecuteResultHandler() { @Override public void onProcessFailed(ExecuteException e) { e.printStackTrace(); } @Override public void onProcessComplete(int exitValue) { System.out.println(exitValue); } }); }
public static int execBlocking(String line, File workDir, Map<String, String> environment, StringBuilder output, long timeout, String charset) throws IOException { charset = (charset == null) ? Charset.defaultCharset().name() : charset; if (environment != null) { Map<String, String> sysenv = System.getenv(); for (String key : sysenv.keySet()) { boolean contains = false; for (String k : environment.keySet()) { if (k.equalsIgnoreCase(key)) { contains = true; break; } } if (!contains) environment.put(key, sysenv.get(key)); } } DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(baos, baos, null)); ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog); if (workDir != null) executor.setWorkingDirectory(workDir); int exitVal = executor.execute(CommandLine.parse(line), environment); if (output != null) { output.append(baos.toString(charset)); } else { System.out.println(baos.toString(charset)); } return exitVal; }
public static void main(String[] args) { StringBuilder output = new StringBuilder(); try { ExecuteWatchdog dog = CommonUtils.execASync("sleep 300", (File) null, (Map<String, String>) null, null, null, 3000); dog.destroyProcess(); } catch (IOException e) { e.printStackTrace(); } System.out.println(output); // CommonUtils.killProcess(pid, false); }
/** * Using apache commons exec for cmd line execution * * @param command * @return exitCode * @throws ExecuteException * @throws IOException * @throws InterruptedException */ private void startEmulator() throws ExecuteException, IOException, InterruptedException { CommandLine cmdLine = new CommandLine( sdkDir + "/" + GCLOUD_EXE); cmdLine.addArgument("beta"); cmdLine.addArgument("emulators"); cmdLine.addArgument("bigtable"); cmdLine.addArgument("start"); cmdLine.addArgument("--quiet"); cmdLine.addArgument("--host-port"); cmdLine.addArgument(HOST_PORT); // Using a result handler makes the emulator run async DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); // watchdog shuts down the emulator, later watchdog = new ExecuteWatchdog( ExecuteWatchdog.INFINITE_TIMEOUT); Executor executor = new DefaultExecutor(); executor.setWatchdog(watchdog); executor.execute( cmdLine, resultHandler); // we need to wait here for a bit, in case the emulator needs to update // itself Thread.sleep(EMULATOR_SPINUP_DELAY_MS); }
private Executor createExecutor(File workingDirectory, long timeoutInSeconds) { DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(workingDirectory); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); // Fixes #41 if (timeoutInSeconds > 0) { executor.setWatchdog(new ExecuteWatchdog(timeoutInSeconds * 1000)); } return executor; }