List of usage examples for org.apache.commons.exec PumpStreamHandler stop
public void stop() throws IOException
From source file:fr.gouv.culture.vitam.utils.Executor.java
/** * Execute an external command// w w w . j av a 2s. c om * @param cmd * @param tempDelay * @param correctValues * @param showOutput * @param realCommand * @return correctValues if ok, < 0 if an execution error occurs, or other error values */ public static int exec(List<String> cmd, long tempDelay, int[] correctValues, boolean showOutput, String realCommand) { // Create command with parameters CommandLine commandLine = new CommandLine(cmd.get(0)); for (int i = 1; i < cmd.size(); i++) { commandLine.addArgument(cmd.get(i)); } DefaultExecutor defaultExecutor = new DefaultExecutor(); ByteArrayOutputStream outputStream; outputStream = new ByteArrayOutputStream(); PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(outputStream); defaultExecutor.setStreamHandler(pumpStreamHandler); defaultExecutor.setExitValues(correctValues); AtomicBoolean isFinished = new AtomicBoolean(false); ExecuteWatchdog watchdog = null; Timer timer = null; if (tempDelay > 0) { // If delay (max time), then setup Watchdog timer = new Timer(true); watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); defaultExecutor.setWatchdog(watchdog); CheckEndOfExecute endOfExecute = new CheckEndOfExecute(isFinished, watchdog, realCommand); timer.schedule(endOfExecute, tempDelay); } 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(100); } catch (InterruptedException e1) { } try { status = defaultExecutor.execute(commandLine); } catch (ExecuteException e1) { pumpStreamHandler.stop(); System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString()); status = -2; try { outputStream.close(); } catch (IOException e2) { } return status; } catch (IOException e1) { pumpStreamHandler.stop(); System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString()); status = -2; try { outputStream.close(); } catch (IOException e2) { } return status; } } else { pumpStreamHandler.stop(); System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString()); status = -2; try { outputStream.close(); } catch (IOException e2) { } return status; } } catch (IOException e) { pumpStreamHandler.stop(); System.err.println(StaticValues.LBL.error_error.get() + "Exception: " + e.getMessage() + " Exec in error with " + commandLine.toString() + "\n\t" + outputStream.toString()); status = -2; try { outputStream.close(); } catch (IOException e2) { } return status; } finally { isFinished.set(true); if (timer != null) { timer.cancel(); } try { Thread.sleep(200); } catch (InterruptedException e1) { } } pumpStreamHandler.stop(); if (defaultExecutor.isFailure(status) && watchdog != null) { if (watchdog.killedProcess()) { // kill by the watchdoc (time out) if (showOutput) { System.err.println(StaticValues.LBL.error_error.get() + "Exec is in Time Out"); } } status = -3; try { outputStream.close(); } catch (IOException e2) { } } else { if (showOutput) { System.out.println("Exec: " + outputStream.toString()); } try { outputStream.close(); } catch (IOException e2) { } } return status; }
From source file:net.hasor.maven.ExecMojo.java
protected int executeCommandLine(Executor exec, CommandLine commandLine, Map<String, String> enviro, FileOutputStream outputFile) throws ExecuteException, IOException { BufferedOutputStream bos = new BufferedOutputStream(outputFile); PumpStreamHandler psh = new PumpStreamHandler(bos); exec.setStreamHandler(psh);//from w w w . j a v a 2 s . com int result; try { psh.start(); result = exec.execute(commandLine, enviro); } finally { psh.stop(); } return result; }
From source file:net.hasor.maven.ExecMojo.java
protected int executeCommandLine(Executor exec, CommandLine commandLine, Map<String, String> enviro, OutputStream out, OutputStream err) throws ExecuteException, IOException { //note: dont use BufferedOutputStream here since it delays the outputs MEXEC-138 PumpStreamHandler psh = new PumpStreamHandler(out, err, System.in); exec.setStreamHandler(psh);/*w w w . j ava 2 s. co m*/ int result; try { psh.start(); result = exec.execute(commandLine, enviro); } finally { psh.stop(); } return result; }
From source file:kr.motd.maven.exec.ExecMojo.java
protected int executeCommandLine(Executor exec, CommandLine commandLine, Map<String, String> enviro, FileOutputStream outputFile) throws ExecuteException, IOException { BufferedOutputStream bos = new LineBufferedOutputStream(outputFile); PumpStreamHandler psh = new PumpStreamHandler(bos); exec.setStreamHandler(psh);//from w w w . j a v a2 s .co m int result; try { psh.start(); result = exec.execute(commandLine, enviro); } finally { psh.stop(); } return result; }
From source file:kr.motd.maven.exec.ExecMojo.java
protected int executeCommandLine(Executor exec, CommandLine commandLine, Map<String, String> enviro, OutputStream out, OutputStream err) throws ExecuteException, IOException { BufferedOutputStream bosStdOut = new LineBufferedOutputStream(out); BufferedOutputStream bosStdErr = new LineBufferedOutputStream(err); PumpStreamHandler psh = new PumpStreamHandler(bosStdOut, bosStdErr, System.in); exec.setStreamHandler(psh);/*from ww w.j ava2 s . c o m*/ int result; try { psh.start(); result = exec.execute(commandLine, enviro); } finally { psh.stop(); } return result; }
From source file:org.apache.karaf.decanter.collector.system.SystemCollector.java
@Override public void run() { if (properties != null) { String karafName = System.getProperty("karaf.name"); String hostAddress = null; String hostName = null;//from w w w . j a v a 2s . c om try { hostAddress = InetAddress.getLocalHost().getHostAddress(); hostName = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { // nothing to do } Enumeration<String> keys = properties.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); try { if (key.startsWith("command.")) { HashMap<String, Object> data = new HashMap<>(); String command = (String) properties.get(key); LOGGER.debug("Executing {} ({})", command, key); CommandLine cmdLine = CommandLine.parse(command); DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); data.put("timestamp", System.currentTimeMillis()); data.put("type", "system"); data.put("karafName", karafName); data.put("hostAddress", hostAddress); data.put("hostName", hostName); executor.execute(cmdLine); outputStream.flush(); String output = outputStream.toString(); if (output.endsWith("\n")) { output = output.substring(0, output.length() - 1); } // try to convert to number try { if (output.contains(".")) { Double value = Double.parseDouble(output); data.put(key, value); } else { Integer value = Integer.parseInt(output); data.put(key, value); } } catch (NumberFormatException e) { data.put(key, outputStream.toString()); } streamHandler.stop(); Event event = new Event("decanter/collect/system/" + key.replace(".", "_"), data); eventAdmin.postEvent(event); try { outputStream.close(); } catch (Exception e) { // nothing to do } } } catch (Exception e) { LOGGER.warn("Command {} execution failed", key, e); } } } }
From source file:org.codehaus.mojo.exec.ExecMojo.java
protected int executeCommandLine(Executor exec, final CommandLine commandLine, Map<String, String> enviro, final PumpStreamHandler psh) throws ExecuteException, IOException { exec.setStreamHandler(psh);//from www . j a va2s.c o m int result; try { psh.start(); if (async) { if (asyncDestroyOnShutdown) { exec.setProcessDestroyer(getProcessDestroyer()); } exec.execute(commandLine, enviro, new ExecuteResultHandler() { public void onProcessFailed(ExecuteException e) { getLog().error("Async process failed for: " + commandLine, e); } public void onProcessComplete(int exitValue) { getLog().info("Async process complete, exit value = " + exitValue + " for: " + commandLine); try { psh.stop(); } catch (IOException e) { getLog().error("Error stopping async process stream handler for: " + commandLine, e); } } }); result = 0; } else { result = exec.execute(commandLine, enviro); } } finally { if (!async) { psh.stop(); } } return result; }
From source file:org.waarp.commandexec.server.LocalExecServerHandler.java
@Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { answered = false;/*from w w w .ja va 2s . 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. jav a 2s. c o 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() { /*// w w w .ja v a2 s . com * 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()); }