List of usage examples for org.apache.commons.exec DefaultExecutor execute
public int execute(final CommandLine command) throws ExecuteException, IOException
From source file:org.waarp.openr66.context.task.ExecOutputTask.java
@Override public void run() { /*/*from www . ja v a 2 s .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. In case of * an error (> 0), all the line from output will be send back to the partner with the Error * code. No change is made to the file. */ logger.info("ExecOutput 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(); finalize(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); } AllLineReader allLineReader = new AllLineReader(inputStream); Thread thread = new Thread(allLineReader, "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) { finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status, commandLine); return; } catch (IOException e1) { try { outputStream.flush(); } catch (IOException e2) { } 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 { finalizeFromError(outputStream, pumpStreamHandler, inputStream, allLineReader, thread, status, commandLine); 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 = allLineReader.getLastLine().toString(); } finalize(status, newname, commandLine.toString()); }
From source file:org.waarp.openr66.context.task.ExecTask.java
@Override public void run() { /*/*w w w . j a va2s. 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. 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.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/*ww w .j a va 2s.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 *//*from ww w . ja va 2s . com*/ 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.zanata.client.commands.ConfigurableCommand.java
/** * @throws Exception// w w w . j a v a2 s .co m * if any of the commands fail. */ private void runSystemCommands(List<String> commands) throws Exception { for (String command : commands) { log.info("[Running command]$ " + command); try { DefaultExecutor executor = new DefaultExecutor(); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); CommandLine cmdLine = CommandLine.parse(command); int exitValue = executor.execute(cmdLine); if (exitValue != 0) { throw new Exception("Command returned non-zero exit value: " + exitValue); } log.info(" Completed with exit value: " + exitValue); } catch (java.io.IOException e) { throw new Exception("Failed to run command. " + e.getMessage(), e); } catch (InterruptedException e) { throw new Exception("Interrupted while running command. " + e.getMessage(), e); } } }
From source file:processing.app.debug.Compiler.java
/** * Either succeeds or throws a RunnerException fit for public consumption. *//* w w w. j av a 2s .c om*/ 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 www . 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:ro.cosu.vampires.server.resources.local.LocalResourceTest.java
private Resource getFailingResource() throws IOException { DefaultExecutor mock = Mockito.mock(DefaultExecutor.class); when(mock.execute(anyObject())).thenReturn(-1); return getResource(mock); }
From source file:util.Utility.java
/** * command line execution/*from www .j a v a2 s . c o m*/ * * @param line command line * @return output string of running this command line */ public static String exec(String line) { //String line = "wc -l " + "/home/hathitrust/solr/ToVM_Solr_related/test/apache-tomcat-6.0.35/bin/proxy_logs/logfile"; CommandLine command = CommandLine.parse(line); DefaultExecutor executor = new DefaultExecutor(); //int exitValue = executor.execute(command); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler pump_stream_handler = new PumpStreamHandler(stdout); executor.setStreamHandler(pump_stream_handler); int exitValue = 0; try { exitValue = executor.execute(command); } catch (ExecuteException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // System.out.println(exitValue); // System.out.println(stdout.toString()); return stdout.toString(); }
From source file:wf.frk.tilde.sblauncher.SauerbratenExecutor.java
public void startThread(String executable, String[] params, String working_dir) throws ExecuteException, IOException { setDaemon(true);/* w w w . jav a 2s . c o m*/ startThread(); CommandLine cmdLine = CommandLine.parse(executable); for (String p : params) { System.out.println(p); cmdLine.addArgument(p); } DefaultExecutor executor = new DefaultExecutor(); PipedOutputStream output = new PipedOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(output, System.err); SAUER_OUTPUT = new Scanner(new PipedInputStream(output)); executor.setStreamHandler(streamHandler); executor.setWorkingDirectory(new File(working_dir)); executor.execute(cmdLine); }