List of usage examples for org.apache.commons.exec CommandLine CommandLine
public CommandLine(final CommandLine other)
From source file:com.netflix.genie.web.jobs.workflow.impl.JobKickoffTaskTest.java
/** * Test the create user method for user already exists. * * @throws IOException If there is any problem. * @throws GenieException If there is any problem. *///from w w w. j a va 2 s.co m @Test public void testCreateUserMethodSuccessDoesNotExist1() throws IOException, GenieException { final String user = "user"; final String group = "group"; final CommandLine idCheckCommandLine = new CommandLine("id"); idCheckCommandLine.addArgument("-u"); idCheckCommandLine.addArgument(user); Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenThrow(new IOException()); final ArgumentCaptor<CommandLine> argumentCaptor = ArgumentCaptor.forClass(CommandLine.class); final List<String> command = Arrays.asList("sudo", "useradd", user, "-G", group, "-M"); try { this.jobKickoffTask.createUser(user, group); } catch (GenieException ge) { // ignore } Mockito.verify(this.executor, Mockito.times(3)).execute(argumentCaptor.capture()); Assert.assertArrayEquals(command.toArray(), argumentCaptor.getAllValues().get(2).toStrings()); }
From source file:com.tupilabs.pbs.PBS.java
/** * PBS qstat command./*w w w. j a v a 2s. co m*/ * <p> * Equivalent to qstat -Q -f [name] * * @param name queue name * @return list of queues */ public static List<Queue> qstatQueues(String name) { final CommandLine cmdLine = new CommandLine(COMMAND_QSTAT); cmdLine.addArgument(PARAMETER_FULL_STATUS); cmdLine.addArgument(PARAMETER_QUEUE); if (StringUtils.isNotBlank(name)) { cmdLine.addArgument(name); } final OutputStream out = new ByteArrayOutputStream(); final OutputStream err = new ByteArrayOutputStream(); DefaultExecuteResultHandler resultHandler; try { resultHandler = execute(cmdLine, null, out, err); resultHandler.waitFor(DEFAULT_TIMEOUT); } catch (ExecuteException e) { throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e); } catch (IOException e) { throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e); } catch (InterruptedException e) { throw new PBSException("Failed to execute qstat command: " + e.getMessage(), e); } final int exitValue = resultHandler.getExitValue(); LOGGER.info("qstat exit value: " + exitValue); final List<Queue> queues; try { queues = QSTAT_QUEUES_PARSER.parse(out.toString()); } catch (ParseException pe) { throw new PBSException("Failed to parse qstat queues output: " + pe.getMessage(), pe); } return (queues == null ? new ArrayList<Queue>(0) : queues); }
From source file:com.tibco.tgdb.test.lib.TGAdmin.java
/** * Invoke TG admin synchronously. /*from w w w.j ava 2 s. 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:eu.creatingfuture.propeller.blocklyprop.propeller.OpenSpin.java
protected boolean compileForRam(String executable, File sourceFile, File destinationFile) { try {/*from www . j ava 2s. co 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:com.devesion.maven.jsr308.CheckersPlugin.java
/** * Plugin Entry point./*from ww w . j a v a 2 s.c om*/ * * @throws MojoExecutionException exception * @throws MojoFailureException exception */ @Override public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("Executing JSR-308 Checkers"); if (checkers.size() <= 0) { getLog().info("No checkers found, omitting checkers execution"); return; } final SourceContext sourceCtx = new SourceContext(compileSourceDirs, includes, excludes); final List<String> sources = SourceUtils.getProjectSources(sourceCtx); if (sources.isEmpty()) { getLog().info("The project does not contains any sources, omitting checkers execution"); return; } final CommandLine cl = new CommandLine("java"); if (checkerJar == null || checkerJar.isEmpty()) { checkerJar = ArtifactUtils.getArtifactPath(JSR308_ALL_GROUP_ID, JSR308_ALL_ARTIFACT_ID, dependencies); if (checkerJar == null) { throw new MojoExecutionException("Cannot find " + JSR308_ALL_GROUP_ID + ":" + JSR308_ALL_ARTIFACT_ID + " artifact jar in the local repository."); } } cl.addArgument("-Xbootclasspath/p:" + checkerJar); cl.addArgument("-ea:com.sun.tools"); if (userJavaParams != null) { cl.addArgument(userJavaParams); } cl.addArgument("-jar"); cl.addArgument(checkerJar); cl.addArgument("-proc:only"); // adding checkers for (String checker : checkers) { cl.addArgument("-processor"); cl.addArgument(checker); } // adding project sources cl.addArguments(sources.toArray(new String[sources.size()])); // adding classpath final StringBuilder sb = new StringBuilder(); for (String element : compileClasspathElements) { sb.append(element); sb.append(File.pathSeparator); } cl.addArgument("-classpath"); cl.addArgument(sb.toString()); if (userJavacParams != null) { cl.addArgument(userJavacParams); } // executing compiler final DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(EXIT_CODE_OK); try { executor.execute(cl); } catch (ExecuteException ex) { if (failOnError) { throw new MojoExecutionException( "Unable to continue because of some errors reported by checkers - " + ex.getMessage()); } else { getLog().error("Some errors has been reported by checkers - " + ex.getMessage()); } } catch (IOException ex) { throw new MojoExecutionException("cannot execute checkers", ex); } }
From source file:de.tu_dresden.psy.fca.ConexpCljBridge.java
public ConexpCljBridge() { this.b = new byte[1]; /**/*from w ww . j a v a 2 s . co m*/ * build the command line (see conexp-clj/bin/conexp-clj) */ String java_bin = Launcher.getJavaCommand(); CommandLine conexp_cmd = new CommandLine(java_bin); conexp_cmd.addArgument("-server"); conexp_cmd.addArgument("-cp"); conexp_cmd.addArgument("./conexp-clj/lib/conexp-clj-0.0.7-alpha-SNAPSHOT-standalone.jar"); conexp_cmd.addArgument("clojure.main"); conexp_cmd.addArgument("-e"); conexp_cmd.addArgument(""); conexp_cmd.addArgument("./conexp-clj/lib/conexp-clj.clj"); /** * open the pipes */ this.to_conexp = new PipedOutputStream(); try { this.stream_to_conexp = new PipedInputStream(this.to_conexp, 2048); } catch (IOException e2) { e2.printStackTrace(); } this.stream_error_conexp = new PipedOutputStream(); this.stream_from_conexp = new PipedOutputStream(); try { this.from_conexp = new PipedInputStream(this.stream_from_conexp, 2048); } catch (IOException e1) { e1.printStackTrace(); } try { this.error_conexp = new PipedInputStream(this.stream_error_conexp, 2048); } catch (IOException e1) { e1.printStackTrace(); } /** * setup apache commons exec */ this.result = new DefaultExecuteResultHandler(); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setStreamHandler( new PumpStreamHandler(this.stream_from_conexp, this.stream_error_conexp, this.stream_to_conexp)); /** * run in non-blocking mode */ try { executor.execute(conexp_cmd, this.result); } catch (ExecuteException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } this.output_buffer = ""; }
From source file:com.netflix.genie.core.jobs.workflow.impl.JobKickoffTaskUnitTests.java
/** * Test the create user method for user already exists. * * @throws IOException If there is any problem. * @throws GenieException If there is any problem. *//* w w w . j a va 2 s . c o m*/ @Test public void testCreateUserMethodSuccessDoesNotExist1() throws IOException, GenieException { final String user = "user"; final String group = "group"; final CommandLine idCheckCommandLine = new CommandLine("id"); idCheckCommandLine.addArgument("-u"); idCheckCommandLine.addArgument(user); Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenThrow(new IOException()); final ArgumentCaptor<CommandLine> argumentCaptor = ArgumentCaptor.forClass(CommandLine.class); final List<String> command = Arrays.asList("sudo", "useradd", user, "-G", group, "-M"); try { this.jobKickoffTask.createUser(user, group); } catch (GenieException ge) { log.debug("Ignoring exception to capture arguments."); } Mockito.verify(this.executor, Mockito.times(3)).execute(argumentCaptor.capture()); Assert.assertArrayEquals(command.toArray(), argumentCaptor.getAllValues().get(2).toStrings()); }
From source file:com.adaptris.hpcc.SprayToThorTest.java
@Test public void testFixed() throws Exception { SprayToThor sprayToThor = new SprayToThor(); sprayToThor.setSprayFormat(new FixedSprayFormat(125)); CommandLine cmdLine = new CommandLine("/bin/dfuplus"); sprayToThor.addFormatArguments(cmdLine); assertEquals(2, cmdLine.getArguments().length); assertEquals("format=fixed", cmdLine.getArguments()[0]); assertEquals("recordsize=125", cmdLine.getArguments()[1]); }
From source file:io.selendroid.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;// w ww . j a va 2 s . c o m 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(); } } Socket socket = null; PrintWriter out = null; BufferedReader in = null; try { socket = new Socket("127.0.0.1", port); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); if (in.readLine() == null) { throw new AndroidDeviceException("error"); } out.write("avd name\r\n"); out.flush(); in.readLine();// OK String avdName = in.readLine(); mapping.put(avdName, port); } catch (Exception e) { // ignore } finally { try { out.close(); in.close(); socket.close(); } catch (Exception e) { // do nothing } } } } scanner.close(); return mapping; }
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; }//from w w w .j a v a2s.co 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; }