Java Code Examples for org.apache.commons.exec.DefaultExecutor#setWatchdog()
The following examples show how to use
org.apache.commons.exec.DefaultExecutor#setWatchdog() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BotRunner.java From 2018-TowerDefence with MIT License | 6 votes |
protected String RunSimpleCommandLineCommand(String line, int expectedExitValue) throws IOException, TimeoutException { CommandLine cmdLine = CommandLine.parse(line); DefaultExecutor executor = new DefaultExecutor(); File bot = new File(this.getBotDirectory()); executor.setWorkingDirectory(bot); executor.setExitValue(expectedExitValue); ExecuteWatchdog watchdog = new ExecuteWatchdog(this.timeoutInMilliseconds); executor.setWatchdog(watchdog); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); try { executor.execute(cmdLine); } catch (IOException e) { if (watchdog.killedProcess()) { throw new TimeoutException("Bot process timed out after " + this.timeoutInMilliseconds + "ms of inactivity"); } else { throw e; } } return outputStream.toString(); }
Example 2
Source File: ProcessExecutor.java From vespa with Apache License 2.0 | 6 votes |
/** * 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())); }
Example 3
Source File: DropwizardContractTest.java From moneta with Apache License 2.0 | 6 votes |
@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...."); }
Example 4
Source File: AbstractCppcheckCommand.java From cppcheclipse with Apache License 2.0 | 6 votes |
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); }
Example 5
Source File: ProcessLauncher.java From zeppelin with Apache License 2.0 | 6 votes |
public void launch() { DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(processOutput)); this.watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchdog); try { executor.execute(commandLine, envs, this); transition(State.LAUNCHED); LOGGER.info("Process is launched: {}", commandLine); } catch (IOException e) { this.processOutput.stopCatchLaunchOutput(); LOGGER.error("Fail to launch process: " + commandLine, e); transition(State.TERMINATED); errorMessage = e.getMessage(); } }
Example 6
Source File: LineUtils.java From super-cloudops with Apache License 2.0 | 5 votes |
/** * Execution shell commands * * @param line * @param timeout * @param charset * @return */ public static String execAsString(String line, long timeout, String charset) { // Standard output ByteArrayOutputStream out = new ByteArrayOutputStream(); // Error output ByteArrayOutputStream err = new ByteArrayOutputStream(); CommandLine commandline = CommandLine.parse(line); DefaultExecutor exec = new DefaultExecutor(); exec.setExitValues(null); // Timeout ExecuteWatchdog watch = new ExecuteWatchdog(timeout); exec.setWatchdog(watch); PumpStreamHandler handler = new PumpStreamHandler(out, err); exec.setStreamHandler(handler); try { exec.execute(commandline); // Different operating systems should pay attention to coding, // otherwise the results will be scrambled. String error = err.toString(charset); if (isNotBlank(error)) { throw new IllegalStateException(error.toString()); } return out.toString(charset); } catch (IOException e) { throw new IllegalStateException(e); } }
Example 7
Source File: Store.java From Panako with GNU Affero General Public License v3.0 | 5 votes |
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(); } }
Example 8
Source File: ShellExecutorHelper.java From CodeCheckerEclipsePlugin with Eclipse Public License 1.0 | 5 votes |
private Executor build(Optional<String> workingDirectory, long timeoutInMilliSec) { ExecuteWatchdog ew = new ExecuteWatchdog(timeoutInMilliSec); DefaultExecutor executor = new DefaultExecutor(); //executor.setWorkingDirectory(new File(workingDirectory.or("."))); executor.setWatchdog(ew); return executor; }
Example 9
Source File: KuduLocal.java From geowave with Apache License 2.0 | 5 votes |
private void executeAsyncAndWatch(final CommandLine command) throws ExecuteException, IOException { LOGGER.info("Running async: {}", command.toString()); final ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); final DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(watchdog); executor.setWorkingDirectory(kuduLocalDir); watchdogs.add(watchdog); // Using a result handler makes the local instance run async executor.execute(command, new DefaultExecuteResultHandler()); }
Example 10
Source File: ProcessExecutor.java From frontend-maven-plugin with Apache License 2.0 | 5 votes |
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; }
Example 11
Source File: SounderControl.java From arcusplatform with Apache License 2.0 | 4 votes |
private void play(@Nullable SoundFile sound) { PlayState currentState = state.get(); if (currentState == null) { return; } long currentTimestamp = System.nanoTime(); if (currentState.endTimestamp > Long.MIN_VALUE && currentTimestamp >= currentState.endTimestamp) { log.trace("play duration expired, stopping sounder"); stop(); return; } if (currentState.repeats < 0) { log.trace("play repeats exceeded, stopping sounder"); stop(); return; } if (sound == null) { stop(); return; } DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(PLAYTONES_TIMEOUT_IN_MS); executor.setWatchdog(watchdog); Queue<CommandLine> queue; // Figure out the version we need to play switch (sound.getVersion()) { case IH200: queue = playerV2(sound); ByteArrayInputStream is = new ByteArrayInputStream(currentState.content.getBytes(StandardCharsets.US_ASCII)); executor.setStreamHandler(new PumpStreamHandler(null,null,is)); break; case IH300: case IH304: queue = playerV3(sound); break; default: log.error("No Player Found"); stop(); return; } try { currentState.repeats--; playing.set(true); if (sound != null) { source.set(sound.getMode().toString()); } this.commands.clear(); this.commands.addAll(queue); log.warn("Debug: queue {}, commands {}", queue, commands); log.warn("Debug: playing {}", commands.peek()); executor.execute(commands.poll(), this); } catch (IOException ex) { stop(); } }
Example 12
Source File: ProcessRunner.java From oneops with Apache License 2.0 | 4 votes |
/** * 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); } setTimeoutInSeconds((int)config.getChefTimeout()); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setWatchdog(new ExecuteWatchdog(timeoutInSeconds * 1000)); OutputHandler outputStream = new OutputHandler(logger, logKey, result); ErrorHandler errorStream = new ErrorHandler(logger, logKey, result); executor.setStreamHandler(new PumpStreamHandler(outputStream, errorStream)); 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); } }