List of usage examples for org.apache.commons.exec CommandLine CommandLine
public CommandLine(final CommandLine other)
From source file:org.apache.maven.plugin.cxx.CoverageMojo.java
@Override protected void postExecute(int resultCode) throws MojoExecutionException { String outputReportName = new String(); if (reportsfileDir.isAbsolute()) { outputReportName = reportsfileDir.getAbsolutePath() + "/" + getReportFileName(); } else {/* www. j a va 2s .c o m*/ outputReportName = basedir.getAbsolutePath() + "/" + reportsfileDir.getPath() + "/" + getReportFileName(); } getLog().info("Coverage report location " + outputReportName); OutputStream outStream = System.out; File file = new File(outputReportName); try { new File(file.getParent()).mkdirs(); file.createNewFile(); outStream = new FileOutputStream(file); } catch (IOException e) { getLog().error("Coverage report redirected to stdout since " + outputReportName + " can't be opened"); } InputStream pyScript = getClass().getResourceAsStream("/gcovr.py"); CommandLine commandLine = new CommandLine("python"); Executor exec = new DefaultExecutor(); String[] args = parseCommandlineArgs("-"); commandLine.addArguments(args, false); args = parseCommandlineArgs(gcovrArgs); commandLine.addArguments(args, false); exec.setWorkingDirectory(getWorkingDir()); try { getLog().info("Executing command line: " + commandLine); int res = ExecutorService.executeCommandLine(exec, commandLine, getEnvs(), outStream/*getOutputStreamOut()*/, getOutputStreamErr(), pyScript/*getInputStream()*/ ); // this is a hugly workaround against a random bugs from hudson cobertura plugin. // hudson cobertura plugin randomly truncat coverage reports file to a 1024 size multiple // while it copy reports from slave to master node for (int j = 0; j < 200; j++) { for (int i = 0; i < 80; i++) { outStream.write(' '); } outStream.write('\n'); } outStream.flush(); if (isResultCodeAFailure(res)) { throw new MojoExecutionException("Result of command line execution is: '" + res + "'."); } } catch (ExecuteException e) { throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } }
From source file:org.apache.maven.plugin.cxx.utils.ExecutorService.java
public static CommandLine getExecutablePath(String executableName, Properties enviro, File dir) { File execFile = new File(executableName); String exec = null;/*from w w w . j a va 2 s.c o m*/ if (execFile.exists() && execFile.isFile() && execFile.canExecute()) { //getLog().debug( "Toolchains are ignored, 'executable' parameter is set to " + execFile.getAbsolutePath() ); exec = execFile.getAbsolutePath(); } else { if (OS.isFamilyWindows()) { String ex = executableName.indexOf(".") < 0 ? executableName + ".bat" : executableName; File f = new File(dir, ex); if (f.exists()) { exec = ex; } else { // now try to figure the path from PATH, PATHEXT env vars // if bat file, wrap in cmd /c String path = (String) enviro.get("PATH"); if (path != null) { String[] elems = StringUtils.split(path, File.pathSeparator); for (int i = 0; i < elems.length; i++) { f = new File(new File(elems[i]), ex); if (f.exists()) { exec = ex; break; } } } } } } if (exec == null) { exec = executableName; } CommandLine toRet; if (OS.isFamilyWindows() && exec.toLowerCase(Locale.getDefault()).endsWith(".bat")) { toRet = new CommandLine("cmd"); toRet.addArgument("/c"); toRet.addArgument(exec); } else { toRet = new CommandLine(exec); } return toRet; }
From source file:org.apache.maven.plugin.cxx.VeraxxMojo.java
@Override protected void preExecute(Executor exec, CommandLine commandLine, Properties enviro) throws MojoExecutionException { OutputStream outStream = /*System.out;*/new ByteArrayOutputStream(); OutputStream errStream = new ByteArrayOutputStream(); CommandLine commandLineCheck = new CommandLine(getExecutable()); Executor execCheck = new DefaultExecutor(); String[] args = parseCommandlineArgs("--version"); commandLineCheck.addArguments(args, false); execCheck.setWorkingDirectory(exec.getWorkingDirectory()); getLog().info("Executing command line: " + commandLineCheck); int res = 0;/* w w w . j a v a 2s . com*/ try { res = ExecutorService.executeCommandLine(execCheck, commandLineCheck, enviro, outStream/*getOutputStreamOut()*/, errStream/*getOutputStreamErr()*/, getInputStream()); } catch (ExecuteException e) { getLog().info("Exec Exception while detecting Vera++ version." + " Assume old Vera++ v1.1.x (and less) output parsing style"); getLog().info("Vera++ err output is : " + errStream.toString()); veraxxVersion = 0; /*throw new MojoExecutionException( "preExecute Command execution failed.", e );*/ return; } catch (IOException e) { getLog().info("Vera++ detected version is : " + outStream.toString()); getLog().info("Vera++ err output is : " + errStream.toString()); // due to jdk8 bug :: https://bugs.openjdk.java.net/browse/JDK-8054565 // we use this dirty try/catch ... // because this quick command line call can close the output stream before jvm does getLog().info("jvm " + System.getProperty("java.version") + " (8u11 - 9) workaround, ignoring a " + e.toString() + " during vera++ test command line."); //throw new MojoExecutionException( "preExecute Command execution failed.", e ); } if (isResultCodeAFailure(res)) { getLog().info("Vera++ returned a failure result code : " + res); //throw new MojoExecutionException( "preExecute Result of " + commandLineCheck // + " execution is: '" + res + "'." ); } DefaultArtifactVersion newFormatMinVersion = new DefaultArtifactVersion("1.2.0"); DefaultArtifactVersion currentVeraVersion = new DefaultArtifactVersion(outStream.toString()); getLog().debug("Vera++ detected version is : " + outStream.toString()); getLog().debug("Vera++ version as ArtefactVersion is : " + currentVeraVersion.toString()); if (currentVeraVersion.compareTo(newFormatMinVersion) < 0) { getLog().info("Use old Vera++ v1.1.x (and less) output parsing style"); veraxxVersion = 0; } else { getLog().info("Use Vera++ v1.2.0 (and more) output parsing style"); veraxxVersion = 1; } }
From source file:org.apache.sling.testing.serversetup.jarexec.JarExecutor.java
/** Start the jar if not done yet, and setup runtime hook * to stop it./*w w w .j ava2s . com*/ */ public void start() throws Exception { final ExecuteResultHandler h = new ExecuteResultHandler() { public void onProcessFailed(ExecuteException ex) { log.error("Process execution failed:" + ex, ex); } public void onProcessComplete(int result) { log.info("Process execution complete, exit code=" + result); } }; final String vmOptions = config.getProperty(PROP_VM_OPTIONS); executor = new DefaultExecutor(); final CommandLine cl = new CommandLine(jvmFullPath); if (vmOptions != null && vmOptions.length() > 0) { cl.addArguments(vmOptions); } cl.addArgument("-jar"); cl.addArgument(jarToExecute.getAbsolutePath()); // Additional options for the jar that's executed. // $JAREXEC_SERVER_PORT$ is replaced our serverPort value String jarOptions = config.getProperty(PROP_JAR_OPTIONS); if (jarOptions != null && jarOptions.length() > 0) { jarOptions = jarOptions.replaceAll("\\$JAREXEC_SERVER_PORT\\$", String.valueOf(serverPort)); log.info("Executable jar options: {}", jarOptions); cl.addArguments(jarOptions); } final String workFolderOption = config.getProperty(PROP_WORK_FOLDER); if (workFolderOption != null && workFolderOption.length() > 0) { final File workFolder = new File(workFolderOption); if (!workFolder.isDirectory()) { throw new IOException("Work dir set by " + PROP_WORK_FOLDER + " option does not exist: " + workFolder.getAbsolutePath()); } log.info("Setting working directory for executable jar: {}", workFolder.getAbsolutePath()); executor.setWorkingDirectory(workFolder); } String tmStr = config.getProperty(PROP_EXIT_TIMEOUT_SECONDS); final int exitTimeoutSeconds = tmStr == null ? DEFAULT_EXIT_TIMEOUT : Integer.valueOf(tmStr); if ("true".equals(config.getProperty(PROP_SYNC_EXEC, ""))) { final long start = System.currentTimeMillis(); log.info("Executing and waiting for result: " + cl); final int result = executor.execute(cl); final int expected = Integer.valueOf(config.getProperty(PROP_SYNC_EXEC_EXPECTED, "0")); log.info("Execution took " + (System.currentTimeMillis() - start) + " msec"); if (result != expected) { throw new ExecutorException("Expected result code " + expected + ", got " + result); } } else { log.info("Executing asynchronously: " + cl); executor.setStreamHandler(new PumpStreamHandler()); final ShutdownHookSingleProcessDestroyer pd = new ShutdownHookSingleProcessDestroyer( "java -jar " + jarToExecute.getName(), exitTimeoutSeconds); final boolean waitOnShutdown = Boolean.valueOf(config.getProperty(PROP_WAIT_ONSHUTDOWN, "false")); log.info("Setting up ProcessDestroyer with waitOnShutdown=" + waitOnShutdown); pd.setWaitOnShutdown(waitOnShutdown); executor.setProcessDestroyer(pd); executor.execute(cl, h); } }
From source file:org.apache.storm.util.CoreUtil.java
@ClojureClass(className = "backtype.storm.util#exec-command!") public static void execCommand(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]);/*from ww w . j a v a2s . co m*/ } DefaultExecutor exec = new DefaultExecutor(); exec.execute(cmd); }
From source file:org.apache.storm.utils.ServerUtils.java
public static int execCommand(String... command) throws ExecuteException, IOException { CommandLine cmd = new CommandLine(command[0]); for (int i = 1; i < command.length; i++) { cmd.addArgument(command[i]);/*from w w w. j a v a 2 s . com*/ } DefaultExecutor exec = new DefaultExecutor(); return exec.execute(cmd); }
From source file:org.apache.tika.parser.geo.topic.GeoParser.java
public HashMap<String, ArrayList<String>> searchGeoNames(ArrayList<String> locationNameEntities) throws ExecuteException, IOException { CommandLine cmdLine = new CommandLine("lucene-geo-gazetteer"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); cmdLine.addArgument("-s"); for (String name : locationNameEntities) { cmdLine.addArgument(name);//w w w.j a v a 2s .c om } LOG.fine("Executing: " + cmdLine); DefaultExecutor exec = new DefaultExecutor(); exec.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); exec.setWatchdog(watchdog); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); int exitValue = exec.execute(cmdLine, EnvironmentUtils.getProcEnvironment()); String outputJson = outputStream.toString("UTF-8"); JSONArray json = (JSONArray) JSONValue.parse(outputJson); HashMap<String, ArrayList<String>> returnHash = new HashMap<String, ArrayList<String>>(); for (int i = 0; i < json.size(); i++) { JSONObject obj = (JSONObject) json.get(i); for (Object key : obj.keySet()) { String theKey = (String) key; JSONArray vals = (JSONArray) obj.get(theKey); ArrayList<String> stringVals = new ArrayList<String>(vals.size()); for (int j = 0; j < vals.size(); j++) { String val = (String) vals.get(j); stringVals.add(val); } returnHash.put(theKey, stringVals); } } return returnHash; }
From source file:org.apache.tika.parser.pot.PooledTimeSeriesParser.java
private String computePoT(File input) throws IOException, TikaException { CommandLine cmdLine = new CommandLine("pooled-time-series"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); cmdLine.addArgument("-f"); cmdLine.addArgument(input.getAbsolutePath()); LOG.trace("Executing: {}", cmdLine); DefaultExecutor exec = new DefaultExecutor(); exec.setExitValue(0);/* w w w . j a v a 2 s . c om*/ ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); exec.setWatchdog(watchdog); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); int exitValue = exec.execute(cmdLine, EnvironmentUtils.getProcEnvironment()); return outputStream.toString("UTF-8"); }
From source file:org.apache.zeppelin.interpreter.launcher.Kubectl.java
public ExecuteWatchdog portForward(String resource, String[] ports) throws IOException { DefaultExecutor executor = new DefaultExecutor(); CommandLine cmd = new CommandLine(kubectlCmd); cmd.addArguments("port-forward"); cmd.addArguments(resource);/*from w ww . ja v a2s . c om*/ cmd.addArguments(ports); ExecuteWatchdog watchdog = new ExecuteWatchdog(-1); executor.setWatchdog(watchdog); executor.execute(cmd, new ExecuteResultHandler() { @Override public void onProcessComplete(int i) { LOGGER.info("Port-forward stopped"); } @Override public void onProcessFailed(ExecuteException e) { LOGGER.debug("port-forward process exit", e); } }); return watchdog; }
From source file:org.apache.zeppelin.interpreter.launcher.Kubectl.java
public int execute(String[] args, InputStream stdin, OutputStream stdout, OutputStream stderr) throws IOException { DefaultExecutor executor = new DefaultExecutor(); CommandLine cmd = new CommandLine(kubectlCmd); cmd.addArguments(args);//from w w w . ja va2 s. com ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); executor.setWatchdog(watchdog); PumpStreamHandler streamHandler = new PumpStreamHandler(stdout, stderr, stdin); executor.setStreamHandler(streamHandler); return executor.execute(cmd); }