List of usage examples for org.apache.commons.exec ExecuteWatchdog ExecuteWatchdog
public ExecuteWatchdog(final long timeout)
From source file:edu.stolaf.cs.wmrserver.testjob.TestJobTask.java
public TestJobResult call() throws IOException { // Create the result object TestJobResult result = new TestJobResult(); // Map/*from w w w .j a va2s .com*/ CappedInputStream mapInput = null; try { // List the input files and open a stream FileSystem fs = _inputPath.getFileSystem(_conf); FileStatus[] files = JobServiceHandler.listInputFiles(fs, _inputPath); AggregateInputStream aggregateInput = new AggregateInputStream(fs, files); mapInput = new CappedInputStream(aggregateInput, _inputCap); // Run the mapper result.setMapResult(runTransform(_id, _mapperFile, _packageDir, mapInput)); } finally { IOUtils.closeQuietly(mapInput); } // Return if mapper failed or did not produce output if (result.getMapResult().getExitCode() != 0 || result.getMapResult().getOutputFile() == null) return result; // Sort // While this seems (and is) inefficient for computers, this is //actually probably the shortest way to write this code since // vanilla Java does not provide an equivalent of sort -n. // If you want to write it in Java, use java.util.TreeSet. File intermediateFile = null; FileOutputStream intermediateOutput = null; try { // Create and open temporary file for sorted intermediate output intermediateFile = File.createTempFile("job-" + Long.toString(_id), "-intermediate", _tempDir); intermediateOutput = new FileOutputStream(intermediateFile); // Run the sort CommandLine sortCommand = new CommandLine("sort"); //sortCommand.addArgument("--field-separator=\t"); if (_numericSort) sortCommand.addArgument("-n"); sortCommand.addArgument(result.getMapResult().getOutputFile().getCanonicalPath(), false); DefaultExecutor exec = new DefaultExecutor(); ExecuteWatchdog dog = new ExecuteWatchdog(EXECUTABLE_TIMEOUT); PumpStreamHandler pump = new PumpStreamHandler(intermediateOutput); exec.setWatchdog(dog); exec.setStreamHandler(pump); try { exec.execute(sortCommand); } catch (ExecuteException ex) { throw new IOException("Sort process failed while running test jobs", ex); } } finally { IOUtils.closeQuietly(intermediateOutput); } // Reduce FileInputStream reduceInput = null; try { // Open the intermediate file for reading reduceInput = new FileInputStream(intermediateFile); // Run the reducer result.setReduceResult(runTransform(_id, _reducerFile, _packageDir, reduceInput)); } finally { IOUtils.closeQuietly(reduceInput); // Delete intermediate file intermediateFile.delete(); } return result; }
From source file:com.base.exec.TutorialTest.java
/** * Simulate printing a PDF document.// w ww .ja va 2 s . c om * * @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: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);/*from www . ja v a 2 s .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:modules.NativeProcessIterativeDaemonModule.java
protected String extractNative(String command, String options, Path path) throws NativeExecutionException { if (command == null || command.equals("")) { System.err.println("command null at GeneralNativeCommandModule.extractNative()"); return null; }/*from w w w . ja v a2 s . c om*/ CommandLine commandLine = new CommandLine(command); if (options != null && !options.equals("")) { String[] args = options.split(" "); commandLine.addArguments(args); } if (path != null) { commandLine.addArgument(path.toAbsolutePath().toString(), false); } DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); GeneralExecutableModuleConfig generalExecutableModuleConfig = getConfig(); executor.setWatchdog(new ExecuteWatchdog(generalExecutableModuleConfig.timeout)); if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) { executor.setWorkingDirectory(getConfig().workingDirectory); } try { // System.out.println("Now execute " + commandLine); executor.execute(commandLine); } catch (ExecuteException xs) { NativeExecutionException n = new NativeExecutionException(); n.initCause(xs); if (path != null) { n.path = path.toAbsolutePath().toString(); } n.executionResult = outputStream.toString(); n.exitCode = xs.getExitValue(); throw n; } catch (IOException xs) { NativeExecutionException n = new NativeExecutionException(); n.initCause(xs); if (path != null) { n.path = path.toAbsolutePath().toString(); } n.executionResult = outputStream.toString(); throw n; } return outputStream.toString().trim(); }
From source file:net.robyf.dbpatcher.util.MySqlUtil.java
private static void execute(final CommandLine commandLine) { try {//from www.j av a 2s . c o m DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(new ExecuteWatchdog(300000L)); int returnCode = executor.execute(commandLine); if (returnCode != 0) { throw new UtilException("Error executing: " + commandLine // NOSONAR + ", return code = " + returnCode); //NOSONAR } } catch (IOException ioe) { throw new UtilException("Error executing: " + commandLine, ioe); //NOSONAR } }
From source file:com.tibco.tgdb.test.lib.TGAdmin.java
/** * Invoke TG admin synchronously. //from www . j a va 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:com.boundlessgeo.wps.grass.GrassProcesses.java
@DescribeProcess(title = "GRASS Version", description = "Retreive the version of GRASS used for computation") @DescribeResult(description = "Version") public static String version() { if (EXEC == null) { return "unavailable"; }/* w w w .j ava 2 s . c om*/ CommandLine cmd = new CommandLine(EXEC); cmd.addArgument("-v"); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(outputStream)); LOGGER.info("exec: " + cmd.toString()); int exitValue = executor.execute(cmd); return outputStream.toString(); } catch (ExecuteException huh) { return "exit code: " + huh.getExitValue() + " (" + huh.getMessage() + ")"; } catch (IOException e) { return "unavailable: " + e.getClass().getSimpleName() + ":" + e.getMessage(); } }
From source file:edu.odu.cs.cs350.yellow1.jar.ExecuteJar.java
/** * /*from w w w. j ava 2 s. c o m*/ * {@inheritDoc} * <br>Run all tests in the test suit on the mutant * capturing the output created and if the execution of the mutant with a test exits successfully compare the standard output generated by<br> * the mutant if different stop running tests and return {@link ExecutionResults} * <br> Treats exiting the jvm with error as was not killed continue to run more tests * @return {@link ExecutionResults} */ @Override public ExecutionResults call() throws Exception { //create new Executor for monitoring mutation running executor = new DefaultExecutor(); //get a MessageDigest Instance for use in comparing outputs MessageDigest mDigest = MessageDigest.getInstance("MD5"); //get file object for gold file File f = new File(pathToGold); //get the hash value for the gold file goldHash = mDigest.digest(FileUtils.readFileToByteArray(f)); //reset the MessageDigest mDigest.reset(); int testCount = 0; //Create a new ExecuteWatchdog with timeout at 10 seconds wDog = new ExecuteWatchdog(10000); executor.setWatchdog(wDog); //loop through the tests till empty while (!tests.isEmpty()) { //get the next test File test = tests.poll();//poll removes the test from the queue //prepair captured output files String testName = test.getName(); testName = testName.toUpperCase(Locale.getDefault()).substring(0, testName.indexOf(".")); String outName = jarName + "_" + testName + "_out.txt"; String errOutName = jarName + "_" + testName + "_err.txt"; //create file objects to be written to File standardOut = new File(pathToOutputDir + File.separator + outName); File standardErr = new File(pathToOutputDir + File.separator + errOutName); //file streams create the files for me try { log = new FileOutputStream(standardOut); err = new FileOutputStream(standardErr); } catch (FileNotFoundException e1) { logger.error("log or err file not found for jar " + jarName, e1.getMessage()); } //create new stream handler for each execution streamHandler = new PumpStreamHandler(/* standard out */log, /* error out */err); executor.setStreamHandler(streamHandler); //construct the executable command CommandLine args = new CommandLine(pathToJVM); args.addArgument("-jar"); args.addArgument(jar.getAbsolutePath()); args.addArgument(test.getAbsolutePath()); //new process destroyer per execution ShutDownSpawnedJVMProcess killJVM = new ShutDownSpawnedJVMProcess("java -jar " + jarName, 10000); killJVM.setWaitOnShutdown(true); executor.setProcessDestroyer(killJVM); success = false; try { streamHandler.start(); int result = executor.execute(args); logger.info(jarName + " Sucess with val=[" + result + "] for test[" + testName + "]"); success = true; } catch (ExecuteException ee) { logger.error(jarName + " Execute exception " + ee.getMessage() + " with val=[" + ee.getExitValue() + "] for test[" + testName + "]"); } catch (IOException e) { logger.error(jarName + " IOExecption " + e.getMessage()); } finally { //PumpStreamHandler does not guarantee the closing of stream 100% so to release the locks held by the filestreams //on the created output files so close manually //if the streamhandler was able to close then this will through exception which we ignore try { streamHandler.stop(); //log.flush(); log.close(); //err.flush(); err.close(); } catch (IOException e) { logger.error(e.getMessage()); //ignore nothing I can do } } //if the spawned process exited with success value //check the hash of the output file and delete the empty error file //if the hash is different the mutant was killed otherwise test more //if the spawned process exited with an error value delete empty standard out file and test more if (success) { ++numOfSucesses; standardErr.delete(); outFiles.add(standardOut); if (!Arrays.equals(goldHash, mDigest.digest(FileUtils.readFileToByteArray(standardOut)))) { testMore = false; logger.debug("Different hashes for jar [" + jarName + "] for test [" + testName + "]"); } else { logger.debug("Same hashes for jar [" + jarName + "] for test [" + testName + "]"); } mDigest.reset(); } else { ++numOfFailurs; standardOut.delete(); errFiles.add(standardErr); this.didNotExecute.add(test); } ++testCount; //the mutant was killed so stop testing if (!testMore) { testMore = false; killed = true; testNumKilledME = testCount; break; } } jar.delete(); return new ExecutionResults(numOfSucesses, numOfFailurs, testNumKilledME, jarName, killed, killedMutant, outFiles, errFiles); }
From source file:com.vmware.bdd.service.impl.NodeLdapUserMgmtConfService.java
private void transferFile(String srcFilePath, String ip, String targetFilePath) { CommandLine cmdLine = new CommandLine("scp").addArgument(srcFilePath) .addArgument(ip + ":" + targetFilePath); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(new ExecOutputLogger(LOGGER, false), //output logger new ExecOutputLogger(LOGGER, true)) //error logger );// w w w.j ava 2 s . c om executor.setWatchdog(new ExecuteWatchdog(1000l * 120l)); try { int exitVal = executor.execute(cmdLine); if (exitVal != 0) { throw new RuntimeException("CFG_LDAP_FAIL", null); } } catch (IOException e) { throw new RuntimeException("CFG_LDAP_FAIL", e); } }
From source file:modules.GeneralNativeCommandModule.java
protected KeyValueResult extractNative(String command, String options, Path path) throws NativeExecutionException { if (command == null || command.equals("")) { System.err.println("command null at GeneralNativeCommandModule.extractNative()"); return null; }// w w w .j a v a2 s . c o m CommandLine commandLine = new CommandLine(command); if (options != null && !options.equals("")) { String[] args = options.split(" "); commandLine.addArguments(args); } if (path != null) { commandLine.addArgument(path.toAbsolutePath().toString(), false); } DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); GeneralExecutableModuleConfig generalExecutableModuleConfig = getConfig(); executor.setWatchdog(new ExecuteWatchdog(generalExecutableModuleConfig.timeout)); if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) { executor.setWorkingDirectory(getConfig().workingDirectory); } try { // System.out.println(commandLine); executor.execute(commandLine); } catch (ExecuteException xs) { NativeExecutionException n = new NativeExecutionException(); n.initCause(xs); if (path != null) { n.path = path.toAbsolutePath().toString(); } n.executionResult = outputStream.toString(); n.exitCode = xs.getExitValue(); throw n; } catch (IOException xs) { // System.out.println(commandLine); NativeExecutionException n = new NativeExecutionException(); n.initCause(xs); if (path != null) { n.path = path.toAbsolutePath().toString(); } n.executionResult = outputStream.toString(); throw n; } KeyValueResult t = new KeyValueResult("GeneralNativeCommandResults"); t.add("fullOutput", outputStream.toString().trim()); return t; }