List of usage examples for org.apache.commons.exec DefaultExecutor setStreamHandler
public void setStreamHandler(final ExecuteStreamHandler streamHandler)
From source file:org.waarp.openr66.context.task.ExecTask.java
@Override public void run() { /*// w w w.ja v a 2s .c o m * 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. No change * should be done in the FILENAME */ logger.debug("Exec with " + argRule + ":" + argTransfer + " and {}", session); String finalname = argRule; finalname = getReplacedValue(finalname, argTransfer.split(" ")); // Check if the execution will be done through LocalExec daemon if (Configuration.configuration.isUseLocalExec() && useLocalExec) { LocalExecClient localExecClient = new LocalExecClient(); if (localExecClient.connect()) { localExecClient.runOneCommand(finalname, delay, waitForValidation, futureCompletion); localExecClient.disconnect(); return; } // else continue } // Execution is done internally 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(); PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(null, null); defaultExecutor.setStreamHandler(pumpStreamHandler); int[] correctValues = { 0, 1 }; defaultExecutor.setExitValues(correctValues); ExecuteWatchdog watchdog = null; if (delay > 0 && waitForValidation) { watchdog = new ExecuteWatchdog(delay); defaultExecutor.setWatchdog(watchdog); } if (!waitForValidation) { // Do not wait for validation futureCompletion.setSuccess(); logger.info("Exec will start but no WAIT with {}", commandLine); } 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 { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); if (waitForValidation) { futureCompletion.setFailure(e); } return; } catch (IOException e1) { try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); if (waitForValidation) { futureCompletion.setFailure(e); } return; } } else { try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); if (waitForValidation) { futureCompletion.setFailure(e); } return; } } catch (IOException e) { try { pumpStreamHandler.stop(); } catch (IOException e2) { } logger.error("Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString()); if (waitForValidation) { futureCompletion.setFailure(e); } return; } try { pumpStreamHandler.stop(); } catch (IOException e2) { } if (defaultExecutor.isFailure(status) && watchdog != null && watchdog.killedProcess()) { // kill by the watchdoc (time out) logger.error("Exec is in Time Out"); status = -1; } if (status == 0) { if (waitForValidation) { futureCompletion.setSuccess(); } logger.info("Exec OK with {}", commandLine); } else if (status == 1) { logger.warn("Exec in warning with " + commandLine.toString()); if (waitForValidation) { futureCompletion.setSuccess(); } } else { logger.error("Status: " + status + " Exec in error with " + commandLine.toString()); if (waitForValidation) { futureCompletion.cancel(); } } }
From source file:org.wisdom.maven.node.NPM.java
/** * Executes the current NPM.//from w ww. j av a 2 s . co m * NPM can have several executable attached to them, so the 'binary' argument specifies which * one has to be executed. Check the 'bin' entry of the package.json file to determine which * one you need. 'Binary' is the key associated with the executable to invoke. For example, in * <code> * <pre> * "bin": { * "coffee": "./bin/coffee", * "cake": "./bin/cake" * }, * </pre> * </code> * <p/> * we have two alternatives: 'coffee' and 'cake'. * * @param binary the key of the binary to invoke * @param args the arguments * @return the execution exit status * @throws MojoExecutionException if the execution failed */ public int execute(String binary, String... args) throws MojoExecutionException { File destination = getNPMDirectory(); if (!destination.isDirectory()) { throw new IllegalStateException("The npm module " + this.npmName + " is not installed"); } CommandLine cmdLine = new CommandLine(node.getNodeExecutable()); File npmExec = null; try { npmExec = findExecutable(binary); } catch (IOException | ParseException e) { //NOSONAR log.error(e); } if (npmExec == null) { throw new IllegalStateException( "Cannot execute NPM " + this.npmName + " - cannot find the JavaScript file " + "matching " + binary + " in the " + PACKAGE_JSON + " file"); } // NPM is launched using the main file. cmdLine.addArgument(npmExec.getAbsolutePath(), false); for (String arg : args) { cmdLine.addArgument(arg, this.handleQuoting); } DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); errorStreamFromLastExecution = new LoggedOutputStream(log, true, true); outputStreamFromLastExecution = new LoggedOutputStream(log, false, registerOutputStream); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamFromLastExecution, errorStreamFromLastExecution); executor.setStreamHandler(streamHandler); executor.setWorkingDirectory(node.getWorkDir()); log.info("Executing " + cmdLine.toString() + " from " + executor.getWorkingDirectory().getAbsolutePath()); try { return executor.execute(cmdLine, extendEnvironmentWithNodeInPath(node)); } catch (IOException e) { throw new MojoExecutionException("Error during the execution of the NPM " + npmName, e); } }
From source file:org.wisdom.maven.node.NPM.java
/** * Executes the current NPM using the given binary file. * * @param binary the program to run/* w ww . j a v a2 s . co m*/ * @param args the arguments * @return the execution exit status * @throws MojoExecutionException if the execution failed */ public int execute(File binary, String... args) throws MojoExecutionException { File destination = getNPMDirectory(); if (!destination.isDirectory()) { throw new IllegalStateException("NPM " + this.npmName + " not installed"); } CommandLine cmdLine = new CommandLine(node.getNodeExecutable()); if (binary == null) { throw new IllegalStateException( "Cannot execute NPM " + this.npmName + " - the given binary is 'null'."); } if (!binary.isFile()) { throw new IllegalStateException("Cannot execute NPM " + this.npmName + " - the given binary does not " + "exist: " + binary.getAbsoluteFile() + "."); } // NPM is launched using the main file. cmdLine.addArgument(binary.getAbsolutePath(), false); for (String arg : args) { cmdLine.addArgument(arg, this.handleQuoting); } DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); errorStreamFromLastExecution = new LoggedOutputStream(log, true, true); outputStreamFromLastExecution = new LoggedOutputStream(log, false, registerOutputStream); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamFromLastExecution, errorStreamFromLastExecution); executor.setStreamHandler(streamHandler); executor.setWorkingDirectory(node.getWorkDir()); log.info("Executing " + cmdLine.toString() + " from " + executor.getWorkingDirectory().getAbsolutePath()); try { return executor.execute(cmdLine, extendEnvironmentWithNodeInPath(node)); } catch (IOException e) { throw new MojoExecutionException("Error during the execution of the NPM " + npmName, e); } }
From source file:org.wisdom.maven.utils.WisdomExecutor.java
/** * Launches the Wisdom server. This method blocks until the wisdom server shuts down. * It uses the {@literal Java} executable directly. * * @param mojo the mojo// w w w. jav a2 s .c om * @param interactive enables the shell prompt * @param debug the debug port (0 to disable it) * @param jvmArgs JVM arguments to add to the `java` command (before the -jar argument). * @param destroyer a process destroyer that can be used to destroy the process, if {@code null} * a {@link org.apache.commons.exec.ShutdownHookProcessDestroyer} is used. * @throws MojoExecutionException if the Wisdom instance cannot be started or has thrown an unexpected status * while being stopped. */ public void execute(AbstractWisdomMojo mojo, boolean interactive, int debug, String jvmArgs, ProcessDestroyer destroyer) throws MojoExecutionException { // Get java File java = ExecUtils.find("java", new File(mojo.javaHome, "bin")); if (java == null) { throw new MojoExecutionException("Cannot find the java executable"); } CommandLine cmdLine = new CommandLine(java); if (debug != 0) { cmdLine.addArgument("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=" + debug, false); } if (!Strings.isNullOrEmpty(jvmArgs)) { cmdLine.addArguments(jvmArgs, false); } cmdLine.addArgument("-jar"); cmdLine.addArgument("bin/chameleon-core-" + CHAMELEON_VERSION + ".jar"); if (interactive) { cmdLine.addArgument("--interactive"); } appendSystemPropertiesToCommandLine(mojo, cmdLine); DefaultExecutor executor = new DefaultExecutor(); if (destroyer != null) { executor.setProcessDestroyer(destroyer); } else { executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); } executor.setWorkingDirectory(mojo.getWisdomRootDirectory()); if (interactive) { executor.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in)); //NOSONAR // Using the interactive mode the framework should be stopped using the 'exit' command, // and produce a '0' status. executor.setExitValue(0); } else { executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); // NOSONAR // As the execution is intended to be interrupted using CTRL+C, the status code returned is expected to be 1 // 137 or 143 is used when stopped by the destroyer. executor.setExitValues(new int[] { 1, 137, 143 }); } try { mojo.getLog().info("Launching Wisdom Server"); mojo.getLog().debug("Command Line: " + cmdLine.toString()); // The message is different whether or not we are in the interactive mode. if (interactive) { mojo.getLog().info("You are in interactive mode"); mojo.getLog().info("Hit 'exit' to shutdown"); } else { mojo.getLog().info("Hit CTRL+C to exit"); } if (debug != 0) { mojo.getLog().info("Wisdom launched with remote debugger interface enabled on port " + debug); } // Block execution until ctrl+c executor.execute(cmdLine); } catch (IOException e) { throw new MojoExecutionException("Cannot execute Wisdom", e); } }
From source file:org.wisdom.ractivejs.RactiveJsTemplateCompilerMojo.java
/** * Parse the ractive template into a JavaScript file. * Run the ractive script from the plugin resource with node, and ractive module. * * @param template the ractive template file * @throws WatchingException if the template cannot be parsed *///w w w . j av a 2 s .c om private void parseTemplate(File template) throws WatchingException { File destination = getOutputJSFile(template); // Create the destination folder. if (!destination.getParentFile().isDirectory()) { destination.getParentFile().mkdirs(); } // Parse with Ractive.js CommandLine cmdLine = new CommandLine(getNodeManager().getNodeExecutable()); cmdLine.addArgument(ractiveExec.getAbsolutePath(), false); cmdLine.addArgument(ractiveModule.getAbsolutePath(), false); cmdLine.addArgument(template.getAbsolutePath(), false); cmdLine.addArgument(destination.getAbsolutePath(), false); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); PumpStreamHandler streamHandler = new PumpStreamHandler(new LoggedOutputStream(getLog(), false), new LoggedOutputStream(getLog(), true)); executor.setStreamHandler(streamHandler); getLog().info("Executing " + cmdLine.toString()); try { executor.execute(cmdLine); } catch (IOException e) { throw new WatchingException("Error during the execution of " + RACTIVE_SCRIPT_NPM_NAME, e); } }
From source file:org.wso2.ppaas.configurator.tests.ConfiguratorTestManager.java
/** * Execute shell command/* w w w.j av a 2s . c o m*/ * * @param commandText */ protected int executeCommand(final String commandText, Map<String, String> environment) { final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal(); int result; try { CommandLine commandline = CommandLine.parse(commandText); DefaultExecutor exec = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setWorkingDirectory(new File(ConfiguratorTestManager.class.getResource(PATH_SEP).getPath() + ".." + PATH_SEP + CONFIGURATOR_DIR_NAME)); exec.setStreamHandler(streamHandler); ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); exec.setWatchdog(watchdog); result = exec.execute(commandline, environment); } catch (Exception e) { log.error(outputStream.toString(), e); throw new RuntimeException(e); } return result; }
From source file:org.zanata.rest.service.VirusScanner.java
/** * Builds an Executor which will output to the specified OutputStream. * <p>//from w ww . ja va2 s . c om * The Executor will be configured to return exit values as int, rather than * throwing ExecuteException. * * @param output * @return a configured Executor */ private Executor buildExecutor(OutputStream output) { DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); ExecuteStreamHandler psh = new PumpStreamHandler(output); executor.setStreamHandler(psh); // We want to handle all exit values directly (not as ExecuteException). executor.setExitValues(null); return executor; }
From source file:processing.app.debug.Compiler.java
/** * Either succeeds or throws a RunnerException fit for public consumption. *///from www .j av a 2s . c o m private void execAsynchronously(String[] command) throws RunnerException { // eliminate any empty array entries List<String> stringList = new ArrayList<String>(); for (String string : command) { string = string.trim(); if (string.length() != 0) stringList.add(string); } command = stringList.toArray(new String[stringList.size()]); if (command.length == 0) return; if (verbose) { for (String c : command) System.out.print(c + " "); System.out.println(); } DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler() { @Override protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted) { final Thread result = new Thread(new MyStreamPumper(is, Compiler.this)); result.setDaemon(true); return result; } }); CommandLine commandLine = new DoubleQuotedArgumentsOnWindowsCommandLine(command[0]); for (int i = 1; i < command.length; i++) { commandLine.addArgument(command[i], false); } int result; executor.setExitValues(null); try { result = executor.execute(commandLine); } catch (IOException e) { RunnerException re = new RunnerException(e.getMessage()); re.hideStackTrace(); throw re; } executor.setExitValues(new int[0]); // an error was queued up by message(), barf this back to compile(), // which will barf it back to Editor. if you're having trouble // discerning the imagery, consider how cows regurgitate their food // to digest it, and the fact that they have five stomaches. // //System.out.println("throwing up " + exception); if (exception != null) throw exception; if (result > 1) { // a failure in the tool (e.g. unable to locate a sub-executable) System.err.println(I18n.format(_("{0} returned {1}"), command[0], result)); } if (result != 0) { RunnerException re = new RunnerException(_("Error compiling.")); re.hideStackTrace(); throw re; } }
From source file:processing.app.debug.OldCompiler.java
/** * Either succeeds or throws a RunnerException fit for public consumption. *///from w w w .j a v a 2 s . c o m private void execAsynchronously(String[] command) throws RunnerException { // eliminate any empty array entries List<String> stringList = new ArrayList<String>(); for (String string : command) { string = string.trim(); if (string.length() != 0) stringList.add(string); } command = stringList.toArray(new String[stringList.size()]); if (command.length == 0) return; if (verbose) { for (String c : command) System.out.print(c + " "); System.out.println(); } DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler() { @Override protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted) { final Thread result = new Thread(new MyStreamPumper(is, OldCompiler.this)); result.setDaemon(true); return result; } }); CommandLine commandLine = new DoubleQuotedArgumentsOnWindowsCommandLine(command[0]); for (int i = 1; i < command.length; i++) { commandLine.addArgument(command[i], false); } int result; executor.setExitValues(null); try { result = executor.execute(commandLine); } catch (IOException e) { RunnerException re = new RunnerException(e.getMessage()); re.hideStackTrace(); throw re; } executor.setExitValues(new int[0]); // an error was queued up by message(), barf this back to compile(), // which will barf it back to Editor. if you're having trouble // discerning the imagery, consider how cows regurgitate their food // to digest it, and the fact that they have five stomaches. // //System.out.println("throwing up " + exception); if (exception != null) throw exception; if (result > 1) { // a failure in the tool (e.g. unable to locate a sub-executable) System.err.println(I18n.format(tr("{0} returned {1}"), command[0], result)); } if (result != 0) { RunnerException re = new RunnerException(tr("Error compiling.")); re.hideStackTrace(); throw re; } }
From source file:sce.ProcessExecutor.java
public String executeProcess(String[] processParameters) throws JobExecutionException { try {/*from w ww.j av a 2 s .com*/ //Command to be executed CommandLine command = new CommandLine(processParameters[0]); String[] params = new String[processParameters.length - 1]; for (int i = 0; i < processParameters.length - 1; i++) { params[i] = processParameters[i + 1]; } //Adding its arguments command.addArguments(params); //set timeout in seconds ExecuteWatchdog watchDog = new ExecuteWatchdog( this.timeout == 0 ? ExecuteWatchdog.INFINITE_TIMEOUT : this.timeout * 1000); this.watchdog = watchDog; //Result Handler for executing the process in a Asynch way DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); //MyResultHandler resultHandler = new MyResultHandler(); //Using Std out for the output/error stream //ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); //This is used to end the process when the JVM exits ShutdownHookProcessDestroyer processDestroyer = new ShutdownHookProcessDestroyer(); //Our main command executor DefaultExecutor executor = new DefaultExecutor(); //Setting the properties executor.setStreamHandler(new PumpStreamHandler(null, null)); executor.setWatchdog(watchDog); //executor.setExitValue(1); // this has to be set if the java code contains System.exit(1) to avoid a FAILED status //Setting the working directory //Use of recursion along with the ls makes this a long running process //executor.setWorkingDirectory(new File("/home")); executor.setProcessDestroyer(processDestroyer); //if set, use the java environment variables when running the command if (!this.environment.equals("")) { Map<String, String> procEnv = EnvironmentUtils.getProcEnvironment(); EnvironmentUtils.addVariableToEnvironment(procEnv, this.environment); //Executing the command executor.execute(command, procEnv, resultHandler); } else { //Executing the command executor.execute(command, resultHandler); } //The below section depends on your need //Anything after this will be executed only when the command completes the execution resultHandler.waitFor(); /*int exitValue = resultHandler.getExitValue(); System.out.println(exitValue); if (executor.isFailure(exitValue)) { System.out.println("Execution failed"); } else { System.out.println("Execution Successful"); } System.out.println(outputStream.toString());*/ //return outputStream.toString(); if (watchdog.killedProcess()) { throw new JobExecutionException("Job Interrupted", new InterruptedException()); } if (executor.isFailure(resultHandler.getExitValue())) { ExecuteException ex = resultHandler.getException(); throw new JobExecutionException(ex.getMessage(), ex); } return "1"; } catch (ExecuteException ex) { throw new JobExecutionException(ex.getMessage(), ex); } catch (IOException | InterruptedException | JobExecutionException ex) { throw new JobExecutionException(ex.getMessage(), ex); } }