List of usage examples for org.apache.commons.exec DefaultExecutor DefaultExecutor
public DefaultExecutor()
From source file:org.cloudifysource.utilitydomain.context.blockstorage.VolumeUtils.java
private static String executeSilentCommandLineReturnOutput(final String commandLine, final long timeout) throws LocalStorageOperationException, TimeoutException { Executor executor = new DefaultExecutor(); executor.setExitValue(0);//from ww w . j a v a2 s .c o m ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog); ProcessOutputStream outAndErr = new ProcessOutputStream(); try { PumpStreamHandler streamHandler = new PumpStreamHandler(outAndErr); executor.setStreamHandler(streamHandler); executor.execute(CommandLine.parse(commandLine)); } catch (final Exception e) { if (watchdog.killedProcess()) { throw new TimeoutException("Timed out while executing commandLine : '" + commandLine + "'"); } throw new LocalStorageOperationException("Failed executing commandLine : '" + commandLine + ". Process output was : " + outAndErr.getOutput(), e); } return outAndErr.getOutput(); }
From source file:org.codehaus.mojo.AbstractLaunchMojo.java
public void execute() throws MojoExecutionException { if (isSkip()) { getLog().info("skipping execute as per configuraion"); return;//from w w w. j a va 2 s.com } if (basedir == null) { throw new IllegalStateException("basedir is null. Should not be possible."); } List commandArguments = getCommandLineArgs(); Map enviro = getEnvs(); EnsureExistWorkingDirectory(); CommandLine commandLine = getExecutablePath(enviro, getWorkingDir()); Executor exec = new DefaultExecutor(); commandLine.addArguments((String[]) commandArguments.toArray(new String[commandArguments.size()]), false); exec.setWorkingDirectory(getWorkingDir()); try { getLog().info("Executing command line: " + commandLine); preExecute(exec, commandLine, enviro); int resultCode = executeCommandLine(exec, commandLine, enviro, getOutputStreamOut(), getOutputStreamErr(), getInputStream()); postExecute(resultCode); } catch (ExecuteException e) { throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } }
From source file:org.codehaus.mojo.antlr.AbstractAntlrMojo.java
protected void performGeneration(GenerationPlan plan, Artifact antlrArtifact) throws MojoExecutionException { if (!plan.getGenerationDirectory().getParentFile().exists()) { plan.getGenerationDirectory().getParentFile().mkdirs(); }/*from w w w . ja v a2 s . c o m*/ // ---------------------------------------------------------------------- // Wrap arguments // Note: grammar file should be last // ---------------------------------------------------------------------- List arguments = new LinkedList(); addArgIf(arguments, debug, "-debug"); addArgIf(arguments, diagnostic, "-diagnostic"); addArgIf(arguments, trace, "-trace"); addArgIf(arguments, traceParser, "-traceParser"); addArgIf(arguments, traceLexer, "-traceLexer"); addArgIf(arguments, traceTreeParser, "-traceTreeParser"); addArgs(arguments); arguments.add("-o"); arguments.add(plan.getGenerationDirectory().getPath()); if (plan.getCollectedSuperGrammarIds().size() > 0) { arguments.add("-glib"); StringBuffer buffer = new StringBuffer(); Iterator ids = plan.getCollectedSuperGrammarIds().iterator(); while (ids.hasNext()) { buffer.append(new File(sourceDirectory, (String) ids.next())); if (ids.hasNext()) { buffer.append(';'); } } arguments.add(buffer.toString()); } arguments.add(plan.getSource().getPath()); String[] args = (String[]) arguments.toArray(new String[arguments.size()]); if (plan.getImportVocabTokenTypesDirectory() != null && !plan.getImportVocabTokenTypesDirectory().equals(plan.getGenerationDirectory())) { // we need to spawn a new process to properly set up PWD CommandLine commandLine = new CommandLine("java"); commandLine.addArgument("-classpath", false); commandLine.addArgument(generateClasspathForProcessSpawning(antlrArtifact), true); commandLine.addArgument("antlr.Tool", false); commandLine.addArguments(args, true); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(plan.getImportVocabTokenTypesDirectory()); try { executor.execute(commandLine); } catch (IOException e) { getLog().warn("Error spawning process to execute antlr tool : " + e.getMessage()); } return; } // ---------------------------------------------------------------------- // Call Antlr // ---------------------------------------------------------------------- if (getLog().isDebugEnabled()) { getLog().debug("antlr args=\n" + StringUtils.join(args, "\n")); } boolean failedSetManager = false; SecurityManager oldSm = null; try { oldSm = System.getSecurityManager(); System.setSecurityManager(NoExitSecurityManager.INSTANCE); } catch (SecurityException ex) { // ANTLR-12 oldSm = null; failedSetManager = true; // ignore, in embedded environment the security manager can already be set. // in such a case assume the exit call is handled properly.. getLog().warn("Cannot set custom SecurityManager. " + "Antlr's call to System.exit() can cause application shutdown " + "if not handled by the current SecurityManager."); } String originalUserDir = null; if (plan.getImportVocabTokenTypesDirectory() != null) { originalUserDir = System.getProperty("user.dir"); System.setProperty("user.dir", plan.getImportVocabTokenTypesDirectory().getPath()); } PrintStream oldErr = System.err; OutputStream errOS = new StringOutputStream(); PrintStream err = new PrintStream(errOS); System.setErr(err); try { executeAntlrInIsolatedClassLoader((String[]) arguments.toArray(new String[0]), antlrArtifact); } catch (SecurityException e) { if (e.getMessage().equals("exitVM-0") || e.getClass().getName().equals("org.netbeans.core.execution.ExitSecurityException")) // netbeans // IDE Sec // Manager. { // ANTLR-12 // now basically every secutiry manager could set different message, how to handle in generic way? // probably only by external execution // / in case of NetBeans SecurityManager, it's not possible to distinguish exit codes, rather swallow // than fail. getLog().debug(e); } else { throw new MojoExecutionException( "Antlr execution failed: " + e.getMessage() + "\n Error output:\n" + errOS, e); } } finally { if (originalUserDir != null) { System.setProperty("user.dir", originalUserDir); } if (!failedSetManager) { System.setSecurityManager(oldSm); } System.setErr(oldErr); System.err.println(errOS.toString()); } }
From source file:org.codehaus.mojo.cassandra.CleanupCassandraMojo.java
/** * {@inheritDoc}/*from w ww .j a v a 2s. c o m*/ */ public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Skipping cassandra: cassandra.skip==true"); return; } try { Map environment = createEnvironmentVars(); CommandLine commandLine = newNodetoolCommandLine("cleanup"); Executor exec = new DefaultExecutor(); exec.setWorkingDirectory(cassandraDir); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); try { getLog().debug("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in)); exec.execute(commandLine, environment); getLog().info("Cleanup triggered."); } catch (ExecuteException e) { throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } } catch (IOException e) { throw new MojoExecutionException(e.getLocalizedMessage(), e); } }
From source file:org.codehaus.mojo.cassandra.CompactCassandraMojo.java
/** * {@inheritDoc}/* ww w . j a v a 2 s . c o m*/ */ public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Skipping cassandra: cassandra.skip==true"); return; } try { Map environment = createEnvironmentVars(); CommandLine commandLine = newNodetoolCommandLine("compact"); Executor exec = new DefaultExecutor(); exec.setWorkingDirectory(cassandraDir); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); try { getLog().debug("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in)); exec.execute(commandLine, environment); getLog().info("Compact triggered."); } catch (ExecuteException e) { throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } } catch (IOException e) { throw new MojoExecutionException(e.getLocalizedMessage(), e); } }
From source file:org.codehaus.mojo.cassandra.FlushCassandraMojo.java
/** * {@inheritDoc}/*w ww . ja v a2 s . c o m*/ */ public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Skipping cassandra: cassandra.skip==true"); return; } try { Map environment = createEnvironmentVars(); CommandLine commandLine = newNodetoolCommandLine("flush"); Executor exec = new DefaultExecutor(); exec.setWorkingDirectory(cassandraDir); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); try { getLog().debug("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in)); exec.execute(commandLine, environment); getLog().info("Flush triggered."); } catch (ExecuteException e) { throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } } catch (IOException e) { throw new MojoExecutionException(e.getLocalizedMessage(), e); } }
From source file:org.codehaus.mojo.cassandra.RepairCassandraMojo.java
/** * {@inheritDoc}/* w w w. j a va2s. c o m*/ */ public void execute() throws MojoExecutionException, MojoFailureException { if (skip) { getLog().info("Skipping cassandra: cassandra.skip==true"); return; } try { Map environment = createEnvironmentVars(); CommandLine commandLine = newNodetoolCommandLine("repair"); Executor exec = new DefaultExecutor(); exec.setWorkingDirectory(cassandraDir); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); LogOutputStream stdout = new MavenLogOutputStream(getLog()); LogOutputStream stderr = new MavenLogOutputStream(getLog()); try { getLog().debug("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in)); exec.execute(commandLine, environment); getLog().info("Repair triggered."); } catch (ExecuteException e) { throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } } catch (IOException e) { throw new MojoExecutionException(e.getLocalizedMessage(), e); } }
From source file:org.codehaus.mojo.cassandra.Utils.java
/** * Starts the Cassandra server./* ww w . j av a 2 s .c om*/ * * @param cassandraDir The directory to start the Server process in. * @param commandLine The command line to use to start the Server process. * @param environment The environment to start the Server process with. * @param log The log to send the output to. * @return The {@link ExecuteResultHandler} for the started process. * @throws MojoExecutionException if something went wrong. */ protected static DefaultExecuteResultHandler startCassandraServer(File cassandraDir, CommandLine commandLine, Map environment, Log log) throws MojoExecutionException { try { Executor exec = new DefaultExecutor(); DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler(); exec.setWorkingDirectory(cassandraDir); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); LogOutputStream stdout = new MavenLogOutputStream(log); LogOutputStream stderr = new MavenLogOutputStream(log); log.debug("Executing command line: " + commandLine); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr)); exec.execute(commandLine, environment, execHandler); return execHandler; } catch (ExecuteException e) { throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } }
From source file:org.codehaus.mojo.CoverageMojo.java
protected void postExecute(int resultCode) throws MojoExecutionException { String OutputReportName = new String(); if (reportsfileDir.isAbsolute()) { OutputReportName = reportsfileDir.getAbsolutePath() + "/" + getReportFileName(); } else {/*from ww w . j a va2 s. c om*/ 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 = 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.codehaus.mojo.exec.ExecMojo.java
/** * priority in the execute method will be to use System properties arguments over the pom specification. * * @throws MojoExecutionException if a failure happens */// w w w.j a va 2s. c om public void execute() throws MojoExecutionException { if (executable == null) { if (executableDependency == null) { throw new MojoExecutionException("The parameter 'executable' is missing or invalid"); } executable = findExecutableArtifact().getFile().getAbsolutePath(); getLog().debug("using executable dependency " + executable); } if (isSkip()) { getLog().info("skipping execute as per configuration"); return; } if (basedir == null) { throw new IllegalStateException("basedir is null. Should not be possible."); } try { handleWorkingDirectory(); String argsProp = getSystemProperty("exec.args"); List<String> commandArguments = new ArrayList<String>(); if (hasCommandlineArgs()) { handleCommandLineArgs(commandArguments); } else if (!StringUtils.isEmpty(argsProp)) { handleSystemPropertyArguments(argsProp, commandArguments); } else { if (arguments != null) { handleArguments(commandArguments); } } if (hasAdditionalArgs()) { handleAdditionalArgs(commandArguments); } Map<String, String> enviro = handleSystemEnvVariables(); CommandLine commandLine = getExecutablePath(enviro, workingDirectory); String[] args = commandArguments.toArray(new String[commandArguments.size()]); commandLine.addArguments(args, false); Executor exec = new DefaultExecutor(); exec.setWorkingDirectory(workingDirectory); fillSuccessCodes(exec); getLog().debug("Executing command line: " + commandLine); try { int resultCode; if (outputFile != null) { if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) { getLog().warn( "Could not create non existing parent directories for log file: " + outputFile); } FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(outputFile); resultCode = executeCommandLine(exec, commandLine, enviro, outputStream); } finally { IOUtil.close(outputStream); } } else { resultCode = executeCommandLine(exec, commandLine, enviro, System.out, System.err); } if (isResultCodeAFailure(resultCode)) { String message = "Result of " + commandLine.toString() + " execution is: '" + resultCode + "'."; getLog().error(message); throw new MojoExecutionException(message); } } catch (ExecuteException e) { getLog().error("Command execution failed.", e); throw new MojoExecutionException("Command execution failed.", e); } catch (IOException e) { getLog().error("Command execution failed.", e); throw new MojoExecutionException("Command execution failed.", e); } registerSourceRoots(); } catch (IOException e) { throw new MojoExecutionException("I/O Error", e); } }