List of usage examples for org.apache.commons.exec DefaultExecutor DefaultExecutor
public DefaultExecutor()
From source file:org.sonar.plugins.ideainspections.IdeaExecutor.java
/** * Execute Idea Inspections and return the generated XML report. * @return File a directory with the inspection results or null if the project was not found *///from w w w .j a v a2 s. c o m public File execute() { if (!project.exists()) { LOG.info("Cannot find: " + project + ". Skipping..."); return null; } TimeProfiler profiler = new TimeProfiler().start("Execute Idea Inspections " + IdeaVersion.getVersion()); CommandLine cmdLine = new CommandLine(jdkHome + "/bin/java"); cmdLine.addArgument("-XX:-UseGCOverheadLimit"); cmdLine.addArgument("-Xmx" + memory); cmdLine.addArgument("-XX:MaxPermSize=" + permSize); cmdLine.addArgument("-Xbootclasspath/a:" + bootJar.getPath()); cmdLine.addArgument("-Djdk." + jdkName + "=" + jdkHome); cmdLine.addArgument("-cp"); cmdLine.addArgument(buildClassPath()); cmdLine.addArgument(IDEA_MAIN_CLASS_NAME); cmdLine.addArgument("inspect"); cmdLine.addArgument(project.getPath()); cmdLine.addArgument(profile.getPath()); cmdLine.addArgument(reportDirectory.getPath()); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); //ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); //executor.setWatchdog(watchdog); try { LOG.info("About to execute: \n" + cmdLine.toString()); executor.execute(cmdLine); } catch (Exception e) { throw new SonarException("Can not execute Idea Inspections", e); } finally { profiler.stop(); } return reportDirectory; }
From source file:org.sonatype.nexus.yum.internal.task.CommandLineExecutor.java
public int exec(String command) throws IOException { LOG.debug("Execute command : {}", command); CommandLine cmdLine = CommandLine.parse(command); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler()); int exitValue = executor.execute(cmdLine); LOG.debug("Execution finished with exit code : {}", exitValue); return exitValue; }
From source file:org.sonatype.sisu.bl.support.DefaultDropwizardBundle.java
@Override protected void startApplication() { File bundleDirectory = getBundleDirectory(); List<String> javaOptions = getConfiguration().getJavaOptions(); List<String> javaAgentOptions = getJavaAgentOptions(); CommandLine cmdLine = new CommandLine(new File(System.getProperty("java.home"), "/bin/java")); if (javaAgentOptions.size() > 0) { cmdLine.addArguments(javaAgentOptions.toArray(new String[javaAgentOptions.size()])); }/*from www.ja va 2 s . c o m*/ if (javaOptions.size() > 0) { cmdLine.addArguments(javaOptions.toArray(new String[javaOptions.size()])); } cmdLine.addArgument("-jar").addArgument(getJarName()).addArguments(getConfiguration().arguments()) .addArgument("config.yaml"); log.debug("Launching: {}", cmdLine.toString()); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(bundleDirectory); executor.setWatchdog(watchdog = new ExecuteWatchdog(Time.minutes(5).toMillis())); try { executor.setStreamHandler(streamHandler = new PumpStreamHandler( new FileOutputStream(new File(bundleDirectory, "output.log")))); executor.execute(cmdLine, new DefaultExecuteResultHandler()); } catch (IOException e) { throw Throwables.propagate(e); } }
From source file:org.spiffyui.maven.plugins.GwtCompileMojo.java
@Override public void execute() throws MojoExecutionException, MojoFailureException { Properties p = project.getProperties(); if (skip || "pom".equals(project.getPackaging())) { getLog().debug("GWT compilation is skipped"); return;//from ww w . jav a2s .c o m } if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } else if (!force) { String name = gwtModuleName; if (name.endsWith(InitializeMojo.SPIFFY_TMP_SUFFIX)) { name = name.substring(0, name.length() - InitializeMojo.SPIFFY_TMP_SUFFIX.length()); } if (Math.max(getNewestModifiedTime(resources, -1), getNewestModifiedTime(new File(compileSourceRoots.get(0)), -1)) < getOldestModifiedTime( new File(outputDirectory, name), -1)) { /* Then the GWT build is up to date and we can skip it */ getLog().info("GWT files are up to date. Skipping GWT build."); return; } } CommandLine cmd = new CommandLine("java"); ClassBuilder cb = new ClassBuilder(project); cb.add(p.getProperty("spiffyui.generated-source")); cb.add(resources.getAbsolutePath()); for (String sourceRoot : compileSourceRoots) { cb.add(sourceRoot); } cmd.addArgument("-cp").addArgument(cb.toString()).addArgument(extraJvmArgs) .addArgument("com.google.gwt.dev.Compiler").addArgument("-gen").addArgument(gen.getAbsolutePath()) .addArgument("-logLevel").addArgument(logLevel).addArgument("-style").addArgument(style) .addArgument("-war").addArgument(outputDirectory.getAbsolutePath()).addArgument("-localWorkers") .addArgument(String.valueOf(getLocalWorkers())); // optional advanced arguments if (enableAssertions) { cmd.addArgument("-ea"); } if (draftCompile) { cmd.addArgument("-draftCompile"); } if (validateOnly) { cmd.addArgument("-validateOnly"); } if (treeLogger) { cmd.addArgument("-treeLogger"); } if (disableClassMetadata) { cmd.addArgument("-XdisableClassMetadata"); } if (disableCastChecking) { cmd.addArgument("-XdisableCastChecking"); } if (strict) { cmd.addArgument("-strict"); } if (soycDetailed) { cmd.addArgument("-XsoycDetailed"); } if (optimizationLevel >= 0) { cmd.addArgument("-optimize").addArgument(Integer.toString(optimizationLevel)); } if (extraParam || compileReport) { getLog().debug("create extra directory "); if (!extra.exists()) { extra.mkdirs(); } cmd.addArgument("-extra").addArgument(extra.getAbsolutePath()); } else { getLog().debug("NOT create extra directory "); } if (compileReport) { cmd.addArgument("-compileReport"); } if (workDir != null) { cmd.addArgument("-workDir").addArgument(String.valueOf(workDir)); } cmd.addArgument(gwtModuleName); try { DefaultExecutor executor = new DefaultExecutor(); getLog().debug("Exec: " + cmd.toString()); int ret = executor.execute(cmd, CommandLineUtils.getSystemEnvVars()); if (ret != 0) { throw new MojoExecutionException("Exec failed: " + Integer.toString(ret)); } } catch (IOException e) { throw new MojoExecutionException(e.getMessage()); } moveJSDir(); }
From source file:org.springframework.data.release.io.CommonsExecOsCommandOperations.java
private Future<CommandResult> executeCommand(String command, File executionDirectory, boolean silent) throws IOException { StringWriter writer = new StringWriter(); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try (WriterOutputStream outputStream = new WriterOutputStream(writer)) { String outerCommand = "/bin/bash -lc"; CommandLine outer = CommandLine.parse(outerCommand); outer.addArgument(command, false); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(executionDirectory); executor.setStreamHandler(new PumpStreamHandler(silent ? outputStream : System.out, null)); executor.execute(outer, ENVIRONMENT, resultHandler); resultHandler.waitFor();/*from w ww. j a va 2s. co m*/ } catch (InterruptedException e) { throw new IllegalStateException(e); } return new AsyncResult<CommandResult>( new CommandResult(resultHandler.getExitValue(), writer.toString(), resultHandler.getException())); }
From source file:org.stanwood.media.info.MediaFileInfoFetcher.java
private String getCommandOutput(boolean captureStdout, boolean captureStderr, boolean failOnExitCode, String command, Object... args) throws StanwoodException { CommandLine cmdLine = new CommandLine(command); for (Object arg : args) { if (arg instanceof File) { cmdLine.addArgument(((File) arg).getAbsolutePath(), false); } else if (arg instanceof String) { cmdLine.addArgument((String) arg, false); }//from w w w .j a v a 2 s. c o m } if (log.isDebugEnabled()) { log.debug("About to execute: " + cmdLine.toString()); //$NON-NLS-1$ } Executor exec = new DefaultExecutor(); exec.setExitValues(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, -1 }); try { ByteArrayOutputStream capture = new ByteArrayOutputStream(); OutputStream out; if (captureStdout) { out = capture; } else { out = new LoggerOutputStream(Level.INFO); } OutputStream err; ; if (captureStderr) { err = capture; } else { err = new LoggerOutputStream(Level.ERROR); } exec.setStreamHandler(new PumpStreamHandler(out, err)); int exitCode = exec.execute(cmdLine); if (failOnExitCode && exitCode != 0) { log.error(capture.toString()); throw new StanwoodException(MessageFormat .format(Messages.getString("MediaFileInfoFetcher.NON_ZERO"), exitCode, cmdLine.toString())); //$NON-NLS-1$ } return capture.toString(); } catch (IOException e) { throw new StanwoodException(MessageFormat .format(Messages.getString("MediaFileInfoFetcher.UnableExecuteSysCmd"), cmdLine.toString()), e); //$NON-NLS-1$ } }
From source file:org.stem.ExternalNode.java
private DefaultExecuteResultHandler startStemProcess(CommandLine commandLine, Map env) throws MojoExecutionException { try {/*from w ww . j a v a 2s . c o m*/ DefaultExecutor exec = new DefaultExecutor(); DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler(); exec.setWorkingDirectory(nodeDir); exec.setProcessDestroyer(new ShutdownHookProcessDestroyer()); LogOutputStream stdout = new MavenLogOutputStream(log); LogOutputStream stderr = new MavenLogOutputStream(log); log.debug("Executing command line: " + commandLine); PumpStreamHandler streamHandler = new PumpStreamHandler(stdout, stderr); streamHandler.start(); exec.setStreamHandler(streamHandler); exec.execute(commandLine, env, execHandler); // try // { // execHandler.waitFor(); // } // catch (InterruptedException e) // { // e.printStackTrace(); // } return execHandler; } catch (IOException e) { throw new MojoExecutionException("Command execution failed.", e); } }
From source file:org.waarp.commandexec.server.LocalExecServerHandler.java
@Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { answered = false;// w w w .j a va 2 s . c o m String request = msg; // Generate and write a response. String response; response = LocalExecDefaultResult.NoStatus.status + " " + LocalExecDefaultResult.NoStatus.result; ExecuteWatchdog watchdog = null; try { if (request.length() == 0) { // No command response = LocalExecDefaultResult.NoCommand.status + " " + LocalExecDefaultResult.NoCommand.result; } else { String[] args = request.split(" "); int cpt = 0; long tempDelay; try { tempDelay = Long.parseLong(args[0]); cpt++; } catch (NumberFormatException e) { tempDelay = delay; } if (tempDelay < 0) { // Shutdown Order isShutdown = true; logger.warn("Shutdown order received"); response = LocalExecDefaultResult.ShutdownOnGoing.status + " " + LocalExecDefaultResult.ShutdownOnGoing.result; Thread thread = new GGLEThreadShutdown(factory); thread.start(); return; } String binary = args[cpt++]; File exec = new File(binary); if (exec.isAbsolute()) { // If true file, is it executable if (!exec.canExecute()) { logger.error("Exec command is not executable: " + request); response = LocalExecDefaultResult.NotExecutable.status + " " + LocalExecDefaultResult.NotExecutable.result; return; } } // Create command with parameters CommandLine commandLine = new CommandLine(binary); for (; cpt < args.length; cpt++) { commandLine.addArgument(args[cpt]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); ByteArrayOutputStream outputStream; outputStream = new ByteArrayOutputStream(); PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); if (tempDelay > 0) { // If delay (max time), then setup Watchdog watchdog = new ExecuteWatchdog(tempDelay); defaultExecutor.setWatchdog(watchdog); } int status = -1; try { // Execute the command status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(LocalExecDefaultResult.RETRYINMS); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e1) { try { pumpStreamHandler.stop(); } catch (IOException e3) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); response = LocalExecDefaultResult.BadExecution.status + " " + LocalExecDefaultResult.BadExecution.result; try { outputStream.close(); } catch (IOException e2) { } return; } catch (IOException e1) { try { pumpStreamHandler.stop(); } catch (IOException e3) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); response = LocalExecDefaultResult.BadExecution.status + " " + LocalExecDefaultResult.BadExecution.result; try { outputStream.close(); } catch (IOException e2) { } return; } } else { try { pumpStreamHandler.stop(); } catch (IOException e3) { } logger.error( "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); response = LocalExecDefaultResult.BadExecution.status + " " + LocalExecDefaultResult.BadExecution.result; try { outputStream.close(); } catch (IOException e2) { } return; } } catch (IOException e) { try { pumpStreamHandler.stop(); } catch (IOException e3) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); response = LocalExecDefaultResult.BadExecution.status + " " + LocalExecDefaultResult.BadExecution.result; try { outputStream.close(); } catch (IOException e2) { } return; } try { pumpStreamHandler.stop(); } catch (IOException e3) { } if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) logger.error("Exec is in Time Out"); response = LocalExecDefaultResult.TimeOutExecution.status + " " + LocalExecDefaultResult.TimeOutExecution.result; try { outputStream.close(); } catch (IOException e2) { } } else { try { response = status + " " + outputStream.toString(WaarpStringUtils.UTF8.name()); } catch (UnsupportedEncodingException e) { response = status + " " + outputStream.toString(); } try { outputStream.close(); } catch (IOException e2) { } } } } finally { // We do not need to write a ByteBuf here. // We know the encoder inserted at LocalExecInitializer will do the // conversion. ctx.channel().writeAndFlush(response + "\n"); answered = true; if (watchdog != null) { watchdog.stop(); } logger.info("End of Command: " + request + " : " + response); ctx.channel().writeAndFlush(LocalExecDefaultResult.ENDOFCOMMAND + "\n"); } }
From source file:org.waarp.gateway.kernel.exec.ExecuteExecutor.java
public void run() throws Reply421Exception { // Check if the execution will be done through LocalExec daemon if (AbstractExecutor.useLocalExec) { LocalExecClient localExecClient = new LocalExecClient(); if (localExecClient.connect()) { localExecClient.runOneCommand(arg, delay, futureCompletion); localExecClient.disconnect(); return; } // else continue }// w ww . j a v a2s. co m // Execution is done internally File exec = new File(args[0]); if (exec.isAbsolute()) { if (!exec.canExecute()) { logger.error("Exec command is not executable: " + args[0]); throw new Reply421Exception("Pre Exec command is not executable"); } } CommandLine commandLine = new CommandLine(args[0]); for (int i = 1; i < args.length; i++) { commandLine.addArgument(args[i]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(null, null); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); ExecuteWatchdog watchdog = null; if (delay > 0) { watchdog = new ExecuteWatchdog(delay); defaultExecutor.setWatchdog(watchdog); } int status = -1; try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(10); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e2) { try { pumpStreamHandler.stop(); } catch (IOException e1) { } logger.error("System Exception: " + e.getMessage() + "\n Exec cannot execute command " + commandLine.toString()); throw new Reply421Exception("Cannot execute Pre command"); } catch (IOException e2) { try { pumpStreamHandler.stop(); } catch (IOException e1) { } logger.error( "Exception: " + e.getMessage() + "\n Exec in error with " + commandLine.toString()); throw new Reply421Exception("Cannot execute Pre command"); } logger.info("System Exception: " + e.getMessage() + " but finally get the command executed " + commandLine.toString()); } else { try { pumpStreamHandler.stop(); } catch (IOException e1) { } logger.error("Exception: " + e.getMessage() + "\n Exec in error with " + commandLine.toString()); throw new Reply421Exception("Cannot execute Pre command"); } } catch (IOException e) { try { pumpStreamHandler.stop(); } catch (IOException e1) { } logger.error("Exception: " + e.getMessage() + "\n Exec in error with " + commandLine.toString()); throw new Reply421Exception("Cannot execute Pre command"); } try { pumpStreamHandler.stop(); } catch (IOException e1) { } if (watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) logger.error("Exec is in Time Out"); status = -1; } if (status == 0) { futureCompletion.setSuccess(); logger.info("Exec OK with {}", commandLine); } else if (status == 1) { logger.warn("Exec in warning with {}", commandLine); futureCompletion.setSuccess(); } else { logger.debug("Status: " + status + (status == -1 ? " Tiemout" : "") + " Exec in error with " + commandLine.toString()); throw new Reply421Exception("Pre command executed in error"); } }
From source file:org.waarp.openr66.context.task.ExecMoveTask.java
@Override public void run() { /*/*from w w w. j a v a 2s .c om*/ * First apply all replacements and format to argRule from context and argTransfer. Will * call exec (from first element of resulting string) with arguments as the following value * from the replacements. Return 0 if OK, else 1 for a warning else as an error. The last * line of stdout will be the new name given to the R66File in case of status 0. The * previous file should be deleted by the script or will be deleted in case of status 0. If * the status is 1, no change is made to the file. */ logger.info("ExecMove with " + argRule + ":" + argTransfer + " and {}", session); String finalname = argRule; finalname = getReplacedValue(finalname, argTransfer.split(" ")); // Force the WaitForValidation waitForValidation = true; if (Configuration.configuration.isUseLocalExec() && useLocalExec) { LocalExecClient localExecClient = new LocalExecClient(); if (localExecClient.connect()) { localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion); LocalExecResult result = localExecClient.getLocalExecResult(); move(result.getStatus(), result.getResult(), finalname); localExecClient.disconnect(); return; } // else continue } String[] args = finalname.split(" "); File exec = new File(args[0]); if (exec.isAbsolute()) { if (!exec.canExecute()) { logger.error("Exec command is not executable: " + finalname); R66Result result = new R66Result(session, false, ErrorCode.CommandNotFound, session.getRunner()); futureCompletion.setResult(result); futureCompletion.cancel(); return; } } CommandLine commandLine = new CommandLine(args[0]); for (int i = 1; i < args.length; i++) { commandLine.addArgument(args[i]); } DefaultExecutor defaultExecutor = new DefaultExecutor(); PipedInputStream inputStream = new PipedInputStream(); PipedOutputStream outputStream = null; try { outputStream = new PipedOutputStream(inputStream); } catch (IOException e1) { try { inputStream.close(); } catch (IOException e) { } logger.error("Exception: " + e1.getMessage() + " Exec in error with " + commandLine.toString(), e1); futureCompletion.setFailure(e1); return; } PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream, null); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); ExecuteWatchdog watchdog = null; if (delay > 0) { watchdog = new ExecuteWatchdog(delay); defaultExecutor.setWatchdog(watchdog); } LastLineReader lastLineReader = new LastLineReader(inputStream); Thread thread = new Thread(lastLineReader, "ExecRename" + session.getRunner().getSpecialId()); thread.setDaemon(true); Configuration.configuration.getExecutorService().execute(thread); int status = -1; try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e) { if (e.getExitValue() == -559038737) { // Cannot run immediately so retry once try { Thread.sleep(Configuration.RETRYINMS); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e1) { try { outputStream.close(); } catch (IOException e2) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e2) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("ExecuteException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } catch (IOException e1) { try { outputStream.close(); } catch (IOException e2) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e2) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error( "IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } } else { try { outputStream.close(); } catch (IOException e1) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e1) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error( "ExecuteException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } } catch (IOException e) { try { outputStream.close(); } catch (IOException e1) { } thread.interrupt(); try { inputStream.close(); } catch (IOException e1) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("IOException: " + e.getMessage() + " . Exec in error with " + commandLine.toString()); futureCompletion.setFailure(e); return; } try { outputStream.flush(); } catch (IOException e) { } try { outputStream.close(); } catch (IOException e) { } try { pumpStreamHandler.stop(); } catch (IOException e2) { } try { if (delay > 0) { thread.join(delay); } else { thread.join(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } try { inputStream.close(); } catch (IOException e1) { } String newname = null; if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) status = -1; newname = "TimeOut"; } else { newname = lastLineReader.getLastLine(); if (status == 0 && (newname == null || newname.isEmpty())) { status = 1; } } move(status, newname, commandLine.toString()); }