List of usage examples for org.apache.commons.exec CommandLine addArgument
public CommandLine addArgument(final String argument)
From source file:info.pancancer.arch3.test.TestWorkerWithMocking.java
@Test public void testRunWorker() throws ShutdownSignalException, ConsumerCancelledException, InterruptedException, Exception { PowerMockito.whenNew(DefaultExecuteResultHandler.class).withNoArguments().thenReturn(this.handler); Mockito.doAnswer(new Answer<Object>() { @Override//from w ww .j ava2s .co m public Object answer(InvocationOnMock invocation) throws Throwable { for (int i = 0; i < 5; i++) { CommandLine cli = new CommandLine("echo"); cli.addArgument("iteration: " + i); mockExecutor.execute(cli); Thread.sleep(500); } CommandLine cli = new CommandLine("bash"); cli.addArgument("./src/test/resources/err_output.sh"); mockExecutor.execute(cli); // Here we make sure that the Handler that always gets used always returns 0, and then everything completes OK. handler.onProcessComplete(0); return null; } }).when(mockExecutor).execute(any(CommandLine.class), any(ExecuteResultHandler.class)); PowerMockito.whenNew(DefaultExecutor.class).withNoArguments().thenReturn(mockExecutor); setupConfig(); Job j = new Job(); j.setWorkflowPath("/workflows/Workflow_Bundle_HelloWorld_1.0-SNAPSHOT_SeqWare_1.1.0"); j.setWorkflow("HelloWorld"); j.setWorkflowVersion("1.0-SNAPSHOT"); j.setJobHash("asdlk2390aso12jvrej"); j.setUuid("1234567890"); Map<String, String> iniMap = new HashMap<>(3); iniMap.put("param1", "value1"); iniMap.put("param2", "value2"); iniMap.put("param3", "help I'm trapped in an INI file"); j.setIni(iniMap); byte[] body = j.toJSON().getBytes(); Delivery testDelivery = new Delivery(mockEnvelope, mockProperties, body); Mockito.when(mockConsumer.nextDelivery()).thenReturn(testDelivery); PowerMockito.whenNew(QueueingConsumer.class).withArguments(mockChannel).thenReturn(mockConsumer); WorkerRunnable testWorker = new WorkerRunnable("src/test/resources/workerConfig.ini", "vm123456", 1); testWorker.run(); // String testResults = TestWorkerWithMocking.outBuffer.toString();// this.outStream.toString(); Mockito.verify(mockAppender, Mockito.atLeastOnce()).doAppend(argCaptor.capture()); List<LoggingEvent> tmpList = new LinkedList<LoggingEvent>(argCaptor.getAllValues()); String testResults = this.appendEventsIntoString(tmpList); testResults = cleanResults(testResults); // System.out.println("\n===============================\nTest Results: " + testResults); // System.out.println(testResults); String expectedDockerCommand = "docker run --rm -h master -t -v /var/run/docker.sock:/var/run/docker.sock -v /workflows/Workflow_Bundle_HelloWorld_1.0-SNAPSHOT_SeqWare_1.1.0:/workflow -v /tmp/seqware_tmpfile.ini:/ini -v /datastore:/datastore -v /home/$USER/.gnos:/home/$USER/.gnos -v /home/$USER/custom-seqware-settings:/home/seqware/.seqware/settings pancancer/seqware_whitestar_pancancer:1.2.3.4 seqware bundle launch --dir /workflow --ini /ini --no-metadata --engine whitestar"; // System.out.println(expectedDockerCommand); assertTrue("Check for docker command, got " + testResults, testResults.contains(expectedDockerCommand)); assertTrue("Check for sleep message in the following:" + testResults, testResults.contains("Sleeping before executing workflow for 1000 ms.")); assertTrue("Check for workflow complete", testResults.contains("Docker execution result: \"iteration: 0\"\n" + "\"iteration: 1\"\n" + "\"iteration: 2\"\n" + "\"iteration: 3\"\n" + "\"iteration: 4\"\n")); String begining = new String(Files.readAllBytes(Paths.get("src/test/resources/testResult_Start.txt"))); assertTrue("check begining of output:" + StringUtils.difference(begining, testResults), testResults.contains(begining)); assertTrue("check INI: " + testResults, testResults.contains("param1=value1") && testResults.contains("param2=value2") && testResults.contains("param3=help I'm trapped in an INI file")); String ending = new String(Files.readAllBytes(Paths.get("src/test/resources/testResult_End.txt"))); assertTrue("check ending of output", testResults.contains(ending)); String initalHeartbeat = new String( Files.readAllBytes(Paths.get("src/test/resources/testInitialHeartbeat.txt"))); assertTrue("Check for an initial heart beat, found" + testResults, testResults.contains(initalHeartbeat)); assertTrue("check for stderr in heartbeat", testResults.contains("\"stderr\": \"123_err\",")); }
From source file:edu.odu.cs.cs350.yellow1.jar.ExecuteJar.java
/** * /*from w w w . j a v a2 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.tascape.qa.th.android.comm.Adb.java
public List<String> adb(final List<Object> arguments) throws IOException { CommandLine cmdLine = new CommandLine(ADB); if (!this.serial.isEmpty()) { cmdLine.addArgument("-s"); cmdLine.addArgument(serial);/*from w w w . j a v a 2s . c om*/ } arguments.forEach((arg) -> { cmdLine.addArgument(arg + ""); }); LOG.debug("[{} {}]", cmdLine.getExecutable(), StringUtils.join(cmdLine.getArguments(), " ")); List<String> output = new ArrayList<>(); Executor executor = new DefaultExecutor(); executor.setStreamHandler(new ESH(output)); if (executor.execute(cmdLine) != 0) { throw new IOException(cmdLine + " failed"); } return output; }
From source file:com.tascape.qa.th.android.comm.Adb.java
public ExecuteWatchdog adbAsync(final List<Object> arguments, long timeoutMillis) throws IOException { CommandLine cmdLine = new CommandLine(ADB); if (!this.serial.isEmpty()) { cmdLine.addArgument("-s"); cmdLine.addArgument(serial);// w w w.j ava 2 s. c o m } arguments.forEach((arg) -> { cmdLine.addArgument(arg + ""); }); LOG.debug("[{} {}]", cmdLine.getExecutable(), StringUtils.join(cmdLine.getArguments(), " ")); ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMillis); Executor executor = new DefaultExecutor(); executor.setWatchdog(watchdog); executor.setStreamHandler(new ESH()); executor.execute(cmdLine, new DefaultExecuteResultHandler()); return watchdog; }
From source file:com.jaeksoft.searchlib.ocr.OcrManager.java
public void ocerize(File input, File outputFile, LanguageEnum lang, boolean hocr) throws SearchLibException, IOException { rwl.r.lock();// w ww. j ava2 s . co m try { if (!enabled) return; if (tesseractPath == null || tesseractPath.length() == 0) throw new SearchLibException("No path for the OCR"); CommandLine cmdLine = CommandLine.parse(tesseractPath); cmdLine.addArgument(input.getAbsolutePath()); cmdLine.addArgument(checkOutputPath(outputFile, hocr)); TesseractLanguageEnum tle = TesseractLanguageEnum.find(lang); if (tle == null) tle = defaultLanguage; if (tle != null && tle != TesseractLanguageEnum.None) cmdLine.addArgument("-l " + tle.option); if (hocr) cmdLine.addArgument("hocr"); int ev = run(cmdLine, 3600, null, null); if (ev == 3) Logging.warn("Image format not supported by Tesseract (" + input.getName() + ")"); } finally { rwl.r.unlock(); } }
From source file:de.torstenwalter.maven.plugins.SQLPlusMojo.java
private void runScriptWithSqlPlus(File file, Map environment) throws MojoExecutionException, MojoFailureException { checkFileIsReadable(file);//from w w w .ja va 2 s. c om CommandLine commandLine = new CommandLine(sqlplus); // logon only once, without this sql*plus would prompt for // credentials if given ones are not correct commandLine.addArgument("-L"); StringTokenizer stringTokenizer = new StringTokenizer(getConnectionIdentifier()); while (stringTokenizer.hasMoreTokens()) { commandLine.addArgument(stringTokenizer.nextToken()); } commandLine.addArgument("@" + file.getName()); if (arguments != null) { for (Object argument : arguments) { if (argument == null) { throw new MojoExecutionException("Misconfigured argument, value is null. " + "Set the argument to an empty value if this is the required behaviour."); } else { commandLine.addArgument(argument.toString()); } } } getLog().info("Executing command line: " + obfuscateCredentials(commandLine.toString(), getCredentials())); Executor exec = new DefaultExecutor(); exec.setWorkingDirectory(file.getParentFile()); exec.setStreamHandler(new PumpStreamHandler(System.out, System.err)); try { exec.execute(commandLine, environment); } catch (ExecuteException e) { throw new MojoExecutionException("program exited with exitCode: " + e.getExitValue()); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } }
From source file:io.takari.maven.plugins.compile.javac.CompilerJavacLauncher.java
private void compile(File options, File output, final Map<File, Resource<File>> sources) throws IOException { new CompilerConfiguration(getSourceEncoding(), getCompilerOptions(), sources.keySet()).write(options); // use the same JVM as the one used to run Maven (the "java.home" one) String executable = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; if (File.separatorChar == '\\') { executable = executable + ".exe"; }//w ww .j a va 2 s . co m CommandLine cli = new CommandLine(executable); // jvm options cli.addArguments(new String[] { "-cp", jar.getAbsolutePath() }); if (meminitial != null) { cli.addArgument("-Xms" + meminitial); } if (maxmem != null) { cli.addArgument("-Xmx" + maxmem); } // main class and program arguments cli.addArgument(CompilerJavacForked.class.getName()); cli.addArgument(options.getAbsolutePath(), false); cli.addArgument(output.getAbsolutePath(), false); DefaultExecutor executor = new DefaultExecutor(); // ExecuteWatchdog watchdog = null; // if (forkedProcessTimeoutInSeconds > 0) { // watchdog = new ExecuteWatchdog(forkedProcessTimeoutInSeconds * 1000L); // executor.setWatchdog(watchdog); // } // best effort to avoid orphaned child process executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); executor.setWorkingDirectory(basedir); log.debug("External java process command line:\n {}", cli); try { executor.execute(cli); // this throws ExecuteException if process return code != 0 } catch (ExecuteException e) { if (!log.isDebugEnabled()) { log.info("External java process command line:\n {}", cli); } throw e; } final Map<File, Output<File>> outputs = new HashMap<File, Output<File>>(); CompilerOutput.process(output, new CompilerOutputProcessor() { @Override public void processOutput(File inputFile, File outputFile) { outputs.put(outputFile, context.processOutput(outputFile)); } @Override public void addMessage(String path, int line, int column, String message, MessageSeverity kind) { if (".".equals(path)) { context.addPomMessage(message, kind, null); } else { File file = new File(path); Resource<File> resource = sources.get(file); if (resource == null) { resource = outputs.get(file); } if (resource != null) { if (isShowWarnings() || kind != MessageSeverity.WARNING) { resource.addMessage(line, column, message, kind, null); } } else { log.warn("Unexpected java resource {}", file); } } } @Override public void addLogMessage(String message) { log.warn(message); } }); }
From source file:com.adaptris.hpcc.DfuPlusWrapper.java
private CommandLine createQuery(String wuid) throws PasswordException, IOException { CommandLine cmdLine = retrieveConnection(DfuplusConnection.class).createCommand(); if (!isBlank(wuid)) { cmdLine.addArgument(String.format("wuid=%s", wuid)); }/*from w ww. j ava 2s .c om*/ return cmdLine; }
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 v a 2s .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:com.blackducksoftware.tools.scmconnector.core.Connector.java
/** * This performs a check to ensure that whatever executable is being * invoked, actually exists./*from w w w.j a v a 2s.com*/ * * @throws Exception */ protected void validateExecutableInstance(String EXECUTABLE) throws Exception { log.info("Verifying installation"); CommandLine command = CommandLine.parse(EXECUTABLE); command.addArgument("--version"); String workingDir = System.getProperty("user.dir"); if (workingDir != null) { int returnCode = (new CommandLineExecutor()).executeCommand(log, command, new File(workingDir)); if (returnCode == 0) { log.info("Found installation of: " + EXECUTABLE); } else { log.warn("Unable to determine location of: " + EXECUTABLE); log.warn("Please install and add to path."); } } }