List of usage examples for org.apache.commons.exec CommandLine CommandLine
public CommandLine(final CommandLine other)
From source file:edu.odu.cs.cs350.yellow1.jar.ExecuteJar.java
/** * //from www. jav 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:eu.creatingfuture.propeller.blocklyprop.propeller.OpenSpin.java
protected boolean compileForEeprom(String executable, File sourceFile, File destinationFile) { try {/*w ww. j av a 2s .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("-e"); 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:com.oneops.inductor.ProcessRunner.java
/** * Creates a process and logs the output * * @param cmd/* w ww . ja v a 2 s . c o m*/ * @param logKey * @param result */ private void executeProcess(String[] cmd, String logKey, ProcessResult result) { Map<String, String> env = getEnvVars(logKey, cmd); logger.info(logKey + " Cmd: " + String.join(" ", cmd) + ", Env: " + env); // run the cmd 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)); 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); } }
From source file:com.netflix.genie.web.tasks.node.DiskCleanupTask.java
/** * Checks the disk for jobs on this host. Deletes any job directories that are older than the desired * retention and are complete.//from w ww . j a v a 2s . c om */ @Override public void run() { log.info("Running disk cleanup task..."); final File[] jobDirs = this.jobsDir.listFiles(); if (jobDirs == null) { log.warn("No job dirs found. Returning."); this.numberOfDeletedJobDirs.set(0); this.numberOfDirsUnableToDelete.set(0); return; } // For each of the directories figure out if we need to delete the files or not long deletedCount = 0; long unableToDeleteCount = 0; for (final File dir : jobDirs) { if (!dir.isDirectory()) { log.info("File {} isn't a directory. Skipping.", dir.getName()); continue; } final String id = dir.getName(); try { final Job job = this.jobSearchService.getJob(id); if (job.getStatus().isActive()) { // Don't want to delete anything still going continue; } // Delete anything with a finish time before today @12 AM UTC - retention final Calendar retentionThreshold = TaskUtils.getMidnightUTC(); TaskUtils.subtractDaysFromDate(retentionThreshold, this.properties.getRetention()); final Optional<Date> finished = job.getFinished(); if (finished.isPresent() && finished.get().before(retentionThreshold.getTime())) { log.info("Attempting to delete job directory for job {}", id); if (this.runAsUser) { final CommandLine commandLine = new CommandLine("sudo"); commandLine.addArgument("rm"); commandLine.addArgument("-rf"); commandLine.addArgument(dir.getAbsolutePath()); this.processExecutor.execute(commandLine); } else { // Save forking a process ourselves if we don't have to FileUtils.deleteDirectory(dir); } deletedCount++; log.info("Successfully deleted job directory for job {}", id); } } catch (final GenieException ge) { log.error("Unable to get job {}. Continuing.", id, ge); this.unableToGetJobCounter.increment(); unableToDeleteCount++; } catch (final IOException ioe) { log.error("Unable to delete job directory for job with id: {}", id, ioe); this.unableToDeleteJobDirCounter.increment(); unableToDeleteCount++; } } this.numberOfDeletedJobDirs.set(deletedCount); this.numberOfDirsUnableToDelete.set(unableToDeleteCount); }
From source file:com.walmart.gatling.commons.ScriptExecutor.java
private Object runJob(Object message) { Master.Job job = (Master.Job) message; TaskEvent taskEvent = (TaskEvent) job.taskEvent; CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand()); log.info("Verified Script worker received task: {}", message); Map<String, Object> map = new HashMap<>(); if (StringUtils.isNotEmpty(agentConfig.getJob().getMainClass())) cmdLine.addArgument(agentConfig.getJob().getCpOrJar()); map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName()))); cmdLine.addArgument("${path}"); if (!StringUtils.isEmpty(agentConfig.getJob().getMainClass())) { cmdLine.addArgument(agentConfig.getJob().getMainClass()); }//from w ww.ja va 2 s .c om //parameters come from the task event for (Pair<String, String> pair : taskEvent.getParameters()) { cmdLine.addArgument(pair.getValue()); } cmdLine.addArgument("-rf").addArgument(agentConfig.getJob().getResultPath(job.roleId, job.jobId)); cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(agentConfig.getJob().getExitValues()); ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchdog); executor.setWorkingDirectory(new File(agentConfig.getJob().getPath())); FileOutputStream outFile = null; FileOutputStream errorFile = null; String outPath = "", errPath = ""; try { outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.jobId); errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.jobId); //create the std and err files outFile = FileUtils.openOutputStream(new File(outPath)); errorFile = FileUtils.openOutputStream(new File(errPath)); PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile), new ExecLogHandler(errorFile)); executor.setStreamHandler(psh); log.info("command: {}", cmdLine); int exitResult = executor.execute(cmdLine); //executor.getWatchdog().destroyProcess(). Worker.Result result = new Worker.Result(exitResult, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath), null, job); log.info("Exit code: {}", exitResult); if (executor.isFailure(exitResult) || exitResult == 1) { log.info("Script Executor Failed, job: " + job.jobId); //getSender().tell(new Worker.WorkFailed(result), getSelf()); return new Worker.WorkFailed(result); } else { result = new Worker.Result(exitResult, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath), agentConfig.getUrl(getMetricsPath(job)), job); log.info("Script Executor Completed, job: " + result); //getSender().tell(new Worker.WorkComplete(result), getSelf()); return new Worker.WorkComplete(result); } } catch (IOException e) { log.error(e.toString()); Worker.Result result = new Worker.Result(-1, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath), null, job); log.info("Executor Encountered run time exception, result: " + result.toString()); //getSender().tell(new Worker.WorkFailed(result), getSelf()); return new Worker.WorkFailed(result); } finally { IOUtils.closeQuietly(outFile); IOUtils.closeQuietly(errorFile); } }
From source file:com.github.badamowicz.maven.ojdeploy.plugin.executor.OjdeployExecutor.java
/** * Prepare the start command for ojdeploy. * /*from w w w. j a v a 2 s . c o m*/ * @param ojdParams The list of parameters available. */ private void prepareJdevCommand(List<MojoParameter> ojdParams) { String executable = null; boolean binPathFound = false; LOG.debug("Start initializing ojdeploy command line."); for (MojoParameter currParam : ojdParams) { if (isJdevBinPath(currParam)) { binPathFound = true; if (!((String) currParam.getParameterValue()).isEmpty()) executable = currParam.getParameterValue() + "/" + getOjdeployBinary(); else executable = getOjdeployBinary(); } if (binPathFound) break; } setCmdLine(new CommandLine(executable)); LOG.debug("Base command initialized with: " + executable); }
From source file:io.selendroid.standalone.android.impl.DefaultAndroidEmulator.java
private static Map<String, Integer> mapDeviceNamesToSerial() { Map<String, Integer> mapping = new HashMap<String, Integer>(); CommandLine command = new CommandLine(AndroidSdk.adb()); command.addArgument("devices"); Scanner scanner;/*from w ww . ja va2 s. c om*/ try { scanner = new Scanner(ShellCommand.exec(command)); } catch (ShellCommandException e) { return mapping; } while (scanner.hasNextLine()) { String line = scanner.nextLine(); Pattern pattern = Pattern.compile("emulator-\\d\\d\\d\\d"); Matcher matcher = pattern.matcher(line); if (matcher.find()) { String serial = matcher.group(0); Integer port = Integer.valueOf(serial.replaceAll("emulator-", "")); TelnetClient client = null; try { client = new TelnetClient(port); String avdName = client.sendCommand("avd name"); mapping.put(avdName, port); } catch (AndroidDeviceException e) { // ignore } finally { if (client != null) { client.close(); } } } } scanner.close(); return mapping; }
From source file:be.tarsos.transcoder.ffmpeg.FFMPEGExecutor.java
public String toString() { CommandLine cmdLine = new CommandLine(ffmpegExecutablePath); int fileNumber = 0; Map<String, File> map = new HashMap<String, File>(); for (int i = 0; i < args.size(); i++) { final String arg = args.get(i); final Boolean isFile = argIsFile.get(i); if (isFile) { String key = "file" + fileNumber; map.put(key, new File(arg)); cmdLine.addArgument("${" + key + "}", false); fileNumber++;//from w ww .j a v a2 s. co m } else { cmdLine.addArgument(arg); } } cmdLine.setSubstitutionMap(map); return cmdLine.toString(); }
From source file:com.alibaba.jstorm.utils.JStormUtils.java
public static void exec_command(String command) throws ExecuteException, IOException { String[] cmdlist = command.split(" "); CommandLine cmd = new CommandLine(cmdlist[0]); for (int i = 1; i < cmdlist.length; i++) { cmd.addArgument(cmdlist[i]);// w w w . j av a2 s . c o m } DefaultExecutor exec = new DefaultExecutor(); exec.execute(cmd); }
From source file:beans.DeployManagerImpl.java
public WidgetInstance fork(ServerNode server, Widget widget) { File unzippedDir = Utils.downloadAndUnzip(widget.getRecipeURL(), widget.getApiKey()); File recipeDir = unzippedDir; if (widget.getRecipeRootPath() != null) { recipeDir = new File(unzippedDir, widget.getRecipeRootPath()); }//from w w w.ja va 2 s. com logger.info("Deploying an instance for recipe at : [{}] ", recipeDir); Recipe.Type recipeType = new Recipe(recipeDir).getRecipeType(); if (alreadyInstalled(server, widget, recipeType)) { logger.info("[{}] [{}] is already installed", recipeType, widget.toInstallName()); WidgetInstance widgetInstance = widget.addWidgetInstance(server, recipeDir); String publicIp = getServicePublicIp(widgetInstance); if (!StringUtils.isEmpty(publicIp)) { logger.info("found service ip at [{}]", publicIp); widgetInstance.setServicePublicIp(publicIp); widgetInstance.save(); } server.createEvent(null, ServerNodeEvent.Type.DONE).save(); return widgetInstance; } else { logger.info("Deploying: [ServerIP={}] [recipe={}] [type={}]", new Object[] { server.getPublicIP(), recipeDir, recipeType.name() }); String recipePath = FilenameUtils.separatorsToSystem(recipeDir.getPath()); CommandLine cmdLine = new CommandLine(conf.cloudify.deployScript); cmdLine.addArgument(server.getPublicIP()); cmdLine.addArgument(recipePath.replaceAll("\\\\", "/")); // support for windows. cmdLine.addArgument(recipeType.commandParam); cmdLine.addArgument(widget.toInstallName()); execute(cmdLine, server); return widget.addWidgetInstance(server, recipeDir); } }