List of usage examples for org.apache.commons.exec CommandLine CommandLine
public CommandLine(final CommandLine other)
From source file:io.selendroid.builder.SelendroidServerBuilderTest.java
@Test public void testShouldBeAbleToCreateASignedSelendroidServer() throws Exception { SelendroidServerBuilder builder = getDefaultBuilder(); builder.init(new DefaultAndroidApp(new File(APK_FILE))); builder.cleanUpPrebuildServer();//w w w .j a v a 2 s . co m File file = File.createTempFile("testserver", "apk"); builder.signTestServer(builder.createAndAddCustomizedAndroidManifestToSelendroidServer(), file); // Verify that apk is signed CommandLine cmd = new CommandLine(AndroidSdk.aapt()); cmd.addArgument("list", false); cmd.addArgument(file.getAbsolutePath(), false); String output = ShellCommand.exec(cmd); assertResultDoesNotContainFile(output, "META-INF/CERT.RSA"); assertResultDoesNotContainFile(output, "META-INF/CERT.SF"); assertResultDoesContainFile(output, "META-INF/ANDROIDD.SF"); assertResultDoesContainFile(output, "META-INF/ANDROIDD.RSA"); assertResultDoesContainFile(output, "AndroidManifest.xml"); }
From source file:eu.crisis_economics.abm.dashboard.cluster.script.BashScheduler.java
/** {@inheritDoc} * @throws SchedulerException /* w ww .j av a2s .c o m*/ */ @Override public String runParameterSweep(final Model paramSweepConfig, final String timeLimit, final File workDir) throws SchedulerException { File file = null; try { // file = File.createTempFile("paramsweep-", ".xml"); file = new File(workDir, "paramsweep-config.xml"); Marshaller marshaller = JAXBContext.newInstance(Model.class).createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(paramSweepConfig, file); // } catch (IOException e) { // throw new SchedulerException("Could not create temporary parameter-sweep configuration xml.", e); } catch (JAXBException e) { throw new SchedulerException( "Could not write temporary parameter-sweep configuration xml: " + file.toString(), e); } CommandLine cmd = new CommandLine(cmdFile); Map<String, Object> substitutions = new HashMap<String, Object>(); substitutions.put(CMD_SUBSTITUTION_NAME_FILE, file); cmd.setSubstitutionMap(substitutions); if (timeLimit != null && !timeLimit.isEmpty()) { cmd.addArgument("-t", false); cmd.addArgument(timeLimit, false); } // add server port argument cmd.addArgument("-p", false); cmd.addArgument(String.valueOf(serverPort), false); cmd.addArgument("${" + CMD_SUBSTITUTION_NAME_FILE + "}", false); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(workDir); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(byteArrayOutputStream); executor.setStreamHandler(streamHandler); try { executor.execute(cmd); } catch (ExecuteException e) { throw new SchedulerException( paramSweepCmd + " exited with " + e.getExitValue() + ". Output:\n" + byteArrayOutputStream, e); } catch (IOException e) { throw new SchedulerException( "Execution of " + paramSweepCmd + " failed. Output:\n" + byteArrayOutputStream, e); } // the standard output of the script is the job id final String jobId = byteArrayOutputStream.toString(); return jobId; }
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 );/*from ww w . j av a2 s .co m*/ 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:de.slackspace.wfail2ban.firewall.impl.DefaultFirewallManager.java
private void addDefaultWindowsFirewallRule(int ruleNumber, String filterName, String ipList) { Map<Object, Object> map = new HashMap<Object, Object>(); map.put("name", createFinalRuleName(ruleNumber, filterName)); map.put("direction", "in"); map.put("ipList", ipList); 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("add"); cmdLine.addArgument("rule"); cmdLine.addArgument("name=${name}"); cmdLine.addArgument("dir=${direction}"); cmdLine.addArgument("action=block"); cmdLine.addArgument("localip=any"); cmdLine.addArgument("remoteip=${ipList}"); cmdLine.addArgument("description=This is a generated rule from wfail2ban. Do not edit!"); cmdLine.addArgument("profile=any"); cmdLine.addArgument("interfacetype=any"); cmdLine.setSubstitutionMap(map);/* w ww .j a v a2 s .c om*/ DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); try { executor.execute(cmdLine); if (logger.isDebugEnabled()) { logger.debug("Added firewall rule " + createFinalRuleName(ruleNumber, filterName)); } } catch (ExecuteException e) { ConsolePrinter.printError("Could not create firewall rule. Continuing with next one..."); logger.error("", e); } catch (IOException e) { logger.error("Could not create firewall rule. Error was: ", e); } }
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"; }/* www . j av a2 s .com*/ 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:com.tascape.qa.th.android.comm.Adb.java
private static void loadSerialProductMap() { SERIAL_PRODUCT.clear();//from w w w. jav a 2 s . co m String serials = SystemConfiguration.getInstance().getProperty(SYSPROP_SERIALS); if (null != serials) { LOG.info("Use specified devices from system property {}={}", SYSPROP_SERIALS, serials); Lists.newArrayList(serials.split(",")).forEach(s -> SERIAL_PRODUCT.put(s, "na")); } else { CommandLine cmdLine = new CommandLine(ADB); cmdLine.addArgument("devices"); cmdLine.addArgument("-l"); LOG.debug("{}", cmdLine.toString()); List<String> output = new ArrayList<>(); Executor executor = new DefaultExecutor(); executor.setStreamHandler(new ESH(output)); try { if (executor.execute(cmdLine) != 0) { throw new RuntimeException(cmdLine + " failed"); } } catch (IOException ex) { throw new RuntimeException(cmdLine + " failed", ex); } output.stream().map(line -> StringUtils.split(line, " ", 3)) .filter(ss -> ss.length == 3 && ss[1].equals("device")).forEach(ss -> { LOG.info("device {} -> {}", ss[0], ss[2]); SERIAL_PRODUCT.put(ss[0], ss[2]); }); } if (SERIAL_PRODUCT.isEmpty()) { throw new RuntimeException("No device detected."); } SERIALS.addAll(SERIAL_PRODUCT.keySet()); }
From source file:io.selendroid.standalone.builder.SelendroidServerBuilderTest.java
@Test public void testShouldBeAbleToResignAnSignedAppWithCustomKeystore() throws Exception { SelendroidServerBuilder builder = getDefaultBuilderWithCustomKeystore(); File androidApp = File.createTempFile("testapp", ".apk"); System.out.println("App name: " + androidApp.getName()); FileUtils.copyFile(new File(APK_FILE), androidApp); AndroidApp resignedApp = builder.resignApp(androidApp); assertResignedApp(resignedApp, androidApp); // Verify that apk is signed CommandLine cmd = new CommandLine(AndroidSdk.aapt()); cmd.addArgument("list", false); cmd.addArgument(resignedApp.getAbsolutePath(), false); String output = ShellCommand.exec(cmd); String sigFileName = selendroidConfiguration.getKeystoreAlias().toUpperCase(); if (sigFileName.length() > 8) { sigFileName = sigFileName.substring(0, 8); }/*ww w. j a v a 2 s . c o m*/ assertResultDoesNotContainFile(output, "META-INF/CERT.RSA"); assertResultDoesNotContainFile(output, "META-INF/CERT.SF"); assertResultDoesContainFile(output, "META-INF/" + sigFileName + ".SF"); assertResultDoesContainFile(output, "META-INF/" + sigFileName + ".RSA"); assertResultDoesContainFile(output, "AndroidManifest.xml"); }
From source file:io.selendroid.standalone.android.impl.DefaultAndroidEmulator.java
public static List<AndroidEmulator> listAvailableAvds() throws AndroidDeviceException { List<AndroidEmulator> avds = Lists.newArrayList(); CommandLine cmd = new CommandLine(AndroidSdk.android()); cmd.addArgument("list", false); cmd.addArgument("avds", false); String output = null;/* w w w . jav a 2s . c o m*/ try { output = ShellCommand.exec(cmd, 20000); } catch (ShellCommandException e) { throw new AndroidDeviceException(e); } Map<String, Integer> startedDevices = mapDeviceNamesToSerial(); String[] avdsOutput = StringUtils.splitByWholeSeparator(output, "---------"); if (avdsOutput != null && avdsOutput.length > 0) { for (String element : avdsOutput) { if (!element.contains("Name:")) { continue; } DefaultAndroidEmulator emulator = new DefaultAndroidEmulator(element); if (startedDevices.containsKey(emulator.getAvdName())) { emulator.setSerial(startedDevices.get(emulator.getAvdName())); } avds.add(emulator); } } return avds; }
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 av a 2s . c o 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:com.github.stephenc.mongodb.maven.StartMongoMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { if (skip) {/*from www . ja v a 2 s . c o m*/ getLog().info("Skipping mongodb: mongodb.skip==true"); return; } if (installation == null) { getLog().info("Using mongod from PATH"); } else { getLog().info("Using mongod installed in " + installation); } getLog().info("Using database root of " + databaseRoot); final Logger mongoLogger = Logger.getLogger("com.mongodb"); Level mongoLevel = mongoLogger.getLevel(); try { mongoLogger.setLevel(Level.SEVERE); MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = false; opts.connectionsPerHost = 1; opts.connectTimeout = 50; opts.socketTimeout = 50; Mongo instance; try { instance = new Mongo(new ServerAddress("localhost", port), opts); List<String> databaseNames = instance.getDatabaseNames(); throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance with the following databases " + databaseNames); } catch (MongoException.Network e) { // fine... no instance running } catch (MongoException e) { throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance"); } catch (UnknownHostException e) { // ignore... localhost is always known! } } finally { mongoLogger.setLevel(mongoLevel); } CommandLine commandLine = null; if (installation != null && installation.isDirectory()) { File bin = new File(installation, "bin"); File exe = new File(bin, Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod"); if (exe.isFile()) { commandLine = new CommandLine(exe); } else { throw new MojoExecutionException("Could not find mongo executables in specified installation: " + installation + " expected to find " + exe + " but it does not exist."); } } if (commandLine == null) { commandLine = new CommandLine(Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod"); } if (databaseRoot.isFile()) { throw new MojoExecutionException("Database root " + databaseRoot + " is a file and not a directory"); } if (databaseRoot.isDirectory() && cleanDatabaseRoot) { getLog().info("Cleaning database root directory: " + databaseRoot); try { FileUtils.deleteDirectory(databaseRoot); } catch (IOException e) { throw new MojoExecutionException("Could not clean database root directory " + databaseRoot, e); } } if (!databaseRoot.isDirectory()) { getLog().debug("Creating database root directory: " + databaseRoot); if (!databaseRoot.mkdirs()) { throw new MojoExecutionException("Could not create database root directory " + databaseRoot); } } if (!verbose) { commandLine.addArgument("--quiet"); } commandLine.addArgument("--logpath"); commandLine.addArgument(logPath.getAbsolutePath()); if (logAppend) { commandLine.addArgument("--logappend"); } commandLine.addArgument(auth ? "--auth" : "--noauth"); commandLine.addArgument("--port"); commandLine.addArgument(Integer.toString(port)); commandLine.addArgument("--dbpath"); commandLine.addArgument(databaseRoot.getAbsolutePath()); if (additionalArguments != null) { for (String aa : additionalArguments) { commandLine.addArgument(aa); } } Executor exec = new DefaultExecutor(); DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler(); exec.setWorkingDirectory(databaseRoot); ProcessObserver processObserver = new ProcessObserver(new ShutdownHookProcessDestroyer()); exec.setProcessDestroyer(processObserver); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); getLog().info("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr)); try { exec.execute(commandLine, execHandler); getLog().info("Waiting for MongoDB to start..."); long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(120); mongoLevel = mongoLogger.getLevel(); try { mongoLogger.setLevel(Level.SEVERE); while (System.currentTimeMillis() < timeout && !execHandler.hasResult()) { MongoOptions opts = new MongoOptions(); opts.autoConnectRetry = false; opts.connectionsPerHost = 1; opts.connectTimeout = 250; opts.socketTimeout = 250; Mongo instance; try { instance = new Mongo(new ServerAddress("localhost", port), opts); List<String> databaseNames = instance.getDatabaseNames(); getLog().info("MongoDb started."); getLog().info("Databases: " + databaseNames); } catch (MongoException.Network e) { // ignore, wait and try again try { Thread.sleep(50); } catch (InterruptedException e1) { // ignore } continue; } catch (MongoException e) { getLog().info("MongoDb started."); getLog().info("Unable to list databases due to " + e.getMessage()); } break; } } finally { mongoLogger.setLevel(mongoLevel); } if (execHandler.hasResult()) { ExecuteException exception = execHandler.getException(); if (exception != null) { throw new MojoFailureException(exception.getMessage(), exception); } throw new MojoFailureException( "Command " + commandLine + " exited with exit code " + execHandler.getExitValue()); } Map pluginContext = session.getPluginContext(getPluginDescriptor(), project); pluginContext.put(ProcessObserver.class.getName() + ":" + Integer.toString(port), processObserver); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } }