List of usage examples for org.apache.commons.exec DefaultExecutor DefaultExecutor
public DefaultExecutor()
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 ww. j a va2 s.co m 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:name.martingeisse.webide.features.verilog.compiler.VerilogBuilder.java
private void compile(long workspaceId, final JsonAnalyzer descriptorAnalyzer, ResourcePath inputFilePath, ResourcePath outputFilePath) {/* w w w . j a va 2 s. c om*/ try { // prepare ResourceHandle inputFile = new ResourceHandle(workspaceId, inputFilePath); ResourceHandle outputFile = new ResourceHandle(workspaceId, outputFilePath); // read the input file byte[] inputData = inputFile.readBinaryFile(false); if (inputData == null) { return; } // delete previous output file outputFile.delete(); // build the command line CommandLine commandLine = new CommandLine(Configuration.getIverilogPath()); commandLine.addArgument("-o"); commandLine.addArgument(Configuration.getStdoutPath()); commandLine.addArgument(Configuration.getStdinPath()); // build I/O streams ByteArrayInputStream inputStream = new ByteArrayInputStream(inputData); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); OutputStream errorStream = System.err; ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream, inputStream); // run Icarus Executor executor = new DefaultExecutor(); executor.setStreamHandler(streamHandler); executor.execute(commandLine); // create the output file outputFile.writeFile(outputStream.toByteArray(), true, true); } catch (IOException e) { // TODO error message logger.error(e); return; } }
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);//w w w . ja v a 2 s . c om 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; }/* w w w .j a v a2s. 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("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:name.martingeisse.webide.process.CompanionProcess.java
/** * Starts the subprocess./*from www . jav a2 s .c o m*/ * * @throws IOException on I/O errors */ public final synchronized void start() throws IOException { if (started) { throw new IllegalStateException("companion process has already been started"); } started = true; onBeforeStart(); CommandLine commandLine = buildCommandLine(); Map<String, String> environment = buildEnvironment(); Executor executor = new DefaultExecutor(); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); configureExecutor(executor); boolean successfullyStarted = false; try { runningProcesses.put(companionId, this); executor.execute(commandLine, environment, new ExecuteResultHandler() { @Override public void onProcessFailed(ExecuteException e) { messageHandler = null; runningProcesses.remove(companionId); CompanionProcess.this.onProcessFailed(e.getExitValue(), e.getMessage()); } @Override public void onProcessComplete(int exitValue) { messageHandler = null; runningProcesses.remove(companionId); CompanionProcess.this.onProcessComplete(exitValue); } }); successfullyStarted = true; } finally { if (!successfullyStarted) { runningProcesses.remove(companionId); } } onAfterStart(); }
From source file:eu.creatingfuture.propeller.blocklyprop.propeller.PropellerLoad.java
protected boolean loadIntoEeprom(String executable, File eepromFile, String comPort) { try {//from www .j ava 2s .co m Map map = new HashMap(); map.put("eepromFile", eepromFile); CommandLine cmdLine = new CommandLine(executable); cmdLine.addArgument("-r"); cmdLine.addArgument("-e"); if (comPort != null) { cmdLine.addArgument("-p").addArgument(comPort); } cmdLine.addArgument("${eepromFile}"); cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); //executor.setExitValues(new int[]{451, 301}); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); try { exitValue = executor.execute(cmdLine); } catch (ExecuteException ee) { exitValue = ee.getExitValue(); logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue); success = false; return false; } finally { output = outputStream.toString(); } success = true; return true; } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); success = false; return false; } }
From source file:ch.ivyteam.ivy.maven.engine.EngineControl.java
private Executor createEngineExecutor() { DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(context.engineDirectory); return executor; }
From source file:eu.creatingfuture.propeller.blocklyprop.propeller.OpenSpin.java
protected boolean compileForRam(String executable, File sourceFile, File destinationFile) { try {/*from w w w .java 2 s. c o m*/ File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-lib"); Map map = new HashMap(); map.put("sourceFile", sourceFile); map.put("destinationFile", destinationFile); map.put("libDirectory", libDirectory); CommandLine cmdLine = new CommandLine(executable); cmdLine.addArgument("-b"); cmdLine.addArgument("-o").addArgument("${destinationFile}"); cmdLine.addArgument("-L").addArgument("${libDirectory}"); cmdLine.addArgument("${sourceFile}"); cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); // executor.setExitValues(new int[]{402, 101}); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); try { exitValue = executor.execute(cmdLine); } catch (ExecuteException ee) { exitValue = ee.getExitValue(); logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue); success = false; return false; } finally { 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:edu.odu.cs.cs350.yellow1.jar.ExecuteJar.java
/** * /*from w w w . j a v a 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:net.robyf.dbpatcher.util.MySqlUtil.java
private static void execute(final CommandLine commandLine) { try {/*from w ww.ja v a 2 s.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 } }