List of usage examples for org.apache.commons.exec DefaultExecutor setStreamHandler
public void setStreamHandler(final ExecuteStreamHandler streamHandler)
From source file:com.nts.alphamale.shell.AdbShellExecutor.java
/** * @param cmd adb //w ww. j a v a2 s. c o m * @param synch ? ? true: synchronous, false: asynchronous * @param (ms) * @return Executor Standard Output? Map */ public Map<String, Object> execute(CommandLine cmd, boolean synch, long timeoutMilliseconds) { Map<String, Object> executorMap = new HashMap<String, Object>(); DefaultExecutor executor = new DefaultExecutor(); PipedOutputStream pos = new PipedOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(pos, System.err); streamHandler.setStopTimeout(timeoutMilliseconds); DataInputStream dis = null; try { dis = new DataInputStream(new PipedInputStream(pos)); } catch (IOException e) { //log.error(e.getCause() + " : " + e.getMessage()); } executor.setStreamHandler(streamHandler); ExecuteWatchdog watchDog = new ExecuteWatchdog(timeoutMilliseconds); executor.setWatchdog(watchDog); try { if (synch) executor.execute(cmd); else executor.execute(cmd, new DefaultExecuteResultHandler()); log.debug(cmd.toString()); LineIterator li = IOUtils.lineIterator(dis, "UTF-8"); if (li != null) { executorMap.put("executor", executor); executorMap.put("stdOut", li); } } catch (Exception e) { log.error(e.getCause() + ":" + e.getMessage() + "[" + cmd + "]"); } return executorMap; }
From source file:com.jaeksoft.searchlib.ocr.OcrManager.java
private final int run(CommandLine cmdLine, int secTimeOut, Integer expectedExitValue, StringBuilder returnedText) throws IOException, SearchLibException { DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {//from w w w .ja va 2 s.c om Logging.info("LOG OCR: " + cmdLine); PumpStreamHandler streamHandler = new PumpStreamHandler(baos); executor.setStreamHandler(streamHandler); if (expectedExitValue != null) executor.setExitValue(expectedExitValue); ExecuteWatchdog watchdog = new ExecuteWatchdog(secTimeOut * 1000); executor.setWatchdog(watchdog); int ev = executor.execute(cmdLine); if (expectedExitValue != null) if (ev != expectedExitValue) throw new SearchLibException("Bad exit value (" + ev + ") "); if (returnedText != null) returnedText.append(baos.toString("UTF-8")); return ev; } finally { if (baos != null) IOUtils.closeQuietly(baos); } }
From source file:com.k42b3.sacmis.Sacmis.java
private void executeCommand() { out.setText(""); try {// w w w. j a va 2 s. c o m // save file saveFile(); CommandLine commandLine = CommandLine.parse(this.path + " " + this.args.getText()); // set timeout ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); // create executor DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(this.exitCode); this.baos = new ByteArrayOutputStream(); this.baosErr = new ByteArrayOutputStream(); if (this.writerStdIn) { this.bais = new ByteArrayInputStream(in.getText().getBytes()); executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr, this.bais)); } else { executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr)); } executor.setWatchdog(watchdog); executor.execute(commandLine, new ExecuteResultHandler() { public void onProcessComplete(int e) { out.setText(baos.toString()); } public void onProcessFailed(ExecuteException e) { out.setText(baosErr.toString()); } }); } catch (Exception e) { out.setText(e.getMessage()); } }
From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java
protected boolean compileForEeprom(String executable, File sourceFile, File destinationFile) { try {//from w ww . j av a 2 s. c o m List<CLib> libs = new ArrayList<>(); libs.add(cLibs.get("simpletools")); libs.add(cLibs.get("simpletext")); libs.add(cLibs.get("simplei2c")); File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-c-lib"); Map map = new HashMap(); map.put("sourceFile", sourceFile); map.put("destinationFile", destinationFile); CommandLine cmdLine = new CommandLine(executable); for (CLib lib : libs) { cmdLine.addArgument("-I").addArgument("${libdir" + lib.getName() + "}"); cmdLine.addArgument("-L").addArgument("${memorymodel" + lib.getName() + "}"); cmdLine.addArgument("-l" + lib.getName()); map.put("libdir" + lib.getName(), new File(libDirectory, lib.getLibdir())); map.put("memorymodel" + lib.getName(), new File(libDirectory, lib.getMemoryModel().get("cmm"))); } cmdLine.addArgument("-Os"); cmdLine.addArgument("-mcmm"); cmdLine.addArgument("-m32bit-doubles"); cmdLine.addArgument("-std=c99"); cmdLine.addArgument("-o").addArgument("${destinationFile}"); cmdLine.addArgument("${sourceFile}"); cmdLine.addArgument("-lm"); for (CLib lib : libs) { cmdLine.addArgument("-l" + lib.getName()); } cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); // executor.setExitValues(new int[]{402, 101}); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); try { exitValue = executor.execute(cmdLine); } catch (ExecuteException ee) { exitValue = ee.getExitValue(); logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue); success = false; return false; } finally { output = outputStream.toString(); } // System.out.println("output: " + output); /* Scanner scanner = new Scanner(output); Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?"); Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$"); while (scanner.hasNextLine()) { String portLine = scanner.nextLine(); if (chipFoundPattern.matcher(portLine).matches()) { Matcher portMatch = pattern.matcher(portLine); if (portMatch.find()) { // String port = portMatch.group("comport"); } } } */ // System.out.println("output: " + output); // System.out.println("exitValue: " + exitValue); success = true; return true; } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); success = false; return false; } }
From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java
protected boolean compileForRam(String executable, File sourceFile, File destinationFile) { try {/*from w w w . j a v a 2 s . c o m*/ List<CLib> libs = new ArrayList<>(); libs.add(cLibs.get("simpletools")); libs.add(cLibs.get("simpletext")); libs.add(cLibs.get("simplei2c")); File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-c-lib"); Map map = new HashMap(); map.put("sourceFile", sourceFile); map.put("destinationFile", destinationFile); CommandLine cmdLine = new CommandLine(executable); for (CLib lib : libs) { cmdLine.addArgument("-I").addArgument("${libdir" + lib.getName() + "}"); cmdLine.addArgument("-L").addArgument("${memorymodel" + lib.getName() + "}"); // cmdLine.addArgument("-l" + lib.getName()); map.put("libdir" + lib.getName(), new File(libDirectory, lib.getLibdir())); map.put("memorymodel" + lib.getName(), new File(libDirectory, lib.getMemoryModel().get("cmm"))); } cmdLine.addArgument("-Os"); cmdLine.addArgument("-mcmm"); cmdLine.addArgument("-m32bit-doubles"); cmdLine.addArgument("-std=c99"); cmdLine.addArgument("-o").addArgument("${destinationFile}"); cmdLine.addArgument("${sourceFile}"); cmdLine.addArgument("-lm"); for (CLib lib : libs) { cmdLine.addArgument("-l" + lib.getName()); } cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); // executor.setExitValues(new int[]{402, 101}); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); try { exitValue = executor.execute(cmdLine); } catch (ExecuteException ee) { exitValue = ee.getExitValue(); logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue); success = false; return false; } finally { output = outputStream.toString(); } // System.out.println("output: " + output); /* Scanner scanner = new Scanner(output); Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?"); Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$"); while (scanner.hasNextLine()) { String portLine = scanner.nextLine(); if (chipFoundPattern.matcher(portLine).matches()) { Matcher portMatch = pattern.matcher(portLine); if (portMatch.find()) { // String port = portMatch.group("comport"); } } } */ // System.out.println("output: " + output); // System.out.println("exitValue: " + exitValue); success = true; return true; } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); success = false; return false; } }
From source file:eu.creatingfuture.propeller.blocklyprop.propeller.GccCompiler.java
/** * * * @param executable/*from ww w.j a v a 2s . co m*/ * @param sourceFile * @return */ protected boolean compile(String executable, File sourceFile) { try { List<CLib> libs = new ArrayList<>(); libs.add(cLibs.get("simpletools")); libs.add(cLibs.get("simpletext")); libs.add(cLibs.get("simplei2c")); File temporaryDestinationFile = File.createTempFile("blocklyapp", ".elf"); File libDirectory = new File(new File(System.getProperty("user.dir")), "/propeller-c-lib"); Map map = new HashMap(); map.put("sourceFile", sourceFile); map.put("destinationFile", temporaryDestinationFile); CommandLine cmdLine = new CommandLine(executable); for (CLib lib : libs) { cmdLine.addArgument("-I").addArgument("${libdir" + lib.getName() + "}"); cmdLine.addArgument("-L").addArgument("${memorymodel" + lib.getName() + "}"); // cmdLine.addArgument("-l" + lib.getName()); map.put("libdir" + lib.getName(), new File(libDirectory, lib.getLibdir())); map.put("memorymodel" + lib.getName(), new File(libDirectory, lib.getMemoryModel().get("cmm"))); } cmdLine.addArgument("-Os"); cmdLine.addArgument("-mcmm"); cmdLine.addArgument("-m32bit-doubles"); cmdLine.addArgument("-fno-exceptions"); cmdLine.addArgument("-std=c99"); cmdLine.addArgument("-o").addArgument("${destinationFile}"); cmdLine.addArgument("${sourceFile}"); cmdLine.addArgument("-lm"); for (CLib lib : libs) { cmdLine.addArgument("-l" + lib.getName()); } cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(new int[] { 0, 1 }); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); try { System.out.println(cmdLine); exitValue = executor.execute(cmdLine); } catch (ExecuteException ee) { exitValue = ee.getExitValue(); logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue); success = false; return false; } finally { temporaryDestinationFile.delete(); output = outputStream.toString(); } // System.out.println("output: " + output); /* Scanner scanner = new Scanner(output); Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?"); Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$"); while (scanner.hasNextLine()) { String portLine = scanner.nextLine(); if (chipFoundPattern.matcher(portLine).matches()) { Matcher portMatch = pattern.matcher(portLine); if (portMatch.find()) { // String port = portMatch.group("comport"); } } } */ // System.out.println("output: " + output); // System.out.println("exitValue: " + exitValue); success = true; return true; } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); success = false; return false; } }
From source file:com.github.badamowicz.maven.ojdeploy.plugin.executor.OjdeployExecutor.java
/** * Actually execute the ojdeploy command which has been prepared before. * /*from w w w.ja v a2s . c o m*/ * @throws IOException if execution of external process failed. */ private void exec() throws IOException { FileOutputStream fos = null; PumpStreamHandler pStreamHandler = null; DefaultExecutor executor = null; int exitVal = -1; LOG.info("Start executing ojdeploy now with command:"); LOG.info(getCmdLine()); fos = new FileOutputStream(new File(getProps().getProperty("ojdeploy.build.log.file"))); pStreamHandler = new PumpStreamHandler(fos); executor = new DefaultExecutor(); executor.setStreamHandler(pStreamHandler); executor.setExitValue(Integer.valueOf(getProps().getProperty("exit.value"))); exitVal = executor.execute(getCmdLine()); fos.flush(); fos.close(); LOG.info("Finished executing ojdeploy with exit value: " + exitVal); }
From source file:com.jredrain.startup.AgentProcessor.java
@Override public Response execute(final Request request) throws TException { if (!this.password.equalsIgnoreCase(request.getPassword())) { return errorPasswordResponse(request); }/*from w w w. jav a 2s .c o m*/ String command = request.getParams().get("command") + EXITCODE_SCRIPT; String pid = request.getParams().get("pid"); //?? Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L); boolean timeoutFlag = timeout > 0; logger.info("[redrain]:execute:{},pid:{}", command, pid); File shellFile = CommandUtils.createShellFile(command, pid); Integer exitValue; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final Response response = Response.response(request); final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE); final Timer timer = new Timer(); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath()); final DefaultExecutor executor = new DefaultExecutor(); ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream); executor.setStreamHandler(stream); response.setStartTime(new Date().getTime()); //?0,shell executor.setExitValue(0); if (timeoutFlag) { //... executor.setWatchdog(watchdog); // timer.schedule(new TimerTask() { @Override public void run() { //,kill... if (watchdog.isWatching()) { /** * watchdogdestroyProcesskill... * watchdog.destroyProcess(); */ timer.cancel(); watchdog.stop(); //call kill... request.setAction(Action.KILL); try { kill(request); response.setExitCode(RedRain.StatusCode.TIME_OUT.getValue()); } catch (TException e) { e.printStackTrace(); } } } }, timeout * 60 * 1000); // resultHandler = new DefaultExecuteResultHandler() { @Override public void onProcessComplete(int exitValue) { super.onProcessComplete(exitValue); timer.cancel(); } @Override public void onProcessFailed(ExecuteException e) { super.onProcessFailed(e); timer.cancel(); } }; } executor.execute(commandLine, resultHandler); resultHandler.waitFor(); } catch (Exception e) { if (e instanceof ExecuteException) { exitValue = ((ExecuteException) e).getExitValue(); } else { exitValue = RedRain.StatusCode.ERROR_EXEC.getValue(); } if (RedRain.StatusCode.KILL.getValue().equals(exitValue)) { if (timeoutFlag) { timer.cancel(); watchdog.stop(); } logger.info("[redrain]:job has be killed!at pid :{}", request.getParams().get("pid")); } else { logger.info("[redrain]:job execute error:{}", e.getCause().getMessage()); } } finally { exitValue = resultHandler.getExitValue(); if (CommonUtils.notEmpty(outputStream.toByteArray())) { try { outputStream.flush(); String text = outputStream.toString(); if (notEmpty(text)) { try { text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), ""); response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY))); exitValue = Integer.parseInt(text .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim()); } catch (IndexOutOfBoundsException e) { response.setMessage(text); } } outputStream.close(); } catch (Exception e) { logger.error("[redrain]:error:{}", e); } } if (RedRain.StatusCode.TIME_OUT.getValue() == response.getExitCode()) { response.setSuccess(false).end(); } else { response.setExitCode(exitValue) .setSuccess(response.getExitCode() == RedRain.StatusCode.SUCCESS_EXIT.getValue()).end(); } if (shellFile != null) { shellFile.delete();// } } logger.info("[redrain]:execute result:{}", response.toString()); watchdog.stop(); return response; }
From source file:io.selendroid.standalone.android.impl.AbstractDevice.java
private void startLogging() { logoutput = new ByteArrayOutputStream(); DefaultExecutor exec = new DefaultExecutor(); exec.setStreamHandler(new PumpStreamHandler(logoutput)); CommandLine command = adbCommand("logcat", "ResourceType:S", "dalvikvm:S", "Trace:S", "SurfaceFlinger:S", "StrictMode:S", "ExchangeService:S", "SVGAndroid:S", "skia:S", "LoaderManager:S", "ActivityThread:S", "-v", "time"); log.info("starting logcat:"); log.fine(command.toString());/*ww w . j a va2s . c o m*/ try { exec.execute(command, new DefaultExecuteResultHandler()); logcatWatchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); exec.setWatchdog(logcatWatchdog); } catch (IOException e) { log.log(Level.SEVERE, e.getMessage(), e); } }
From source file:cc.arduino.Compiler.java
private void exec(String[] command) throws RunnerException { // eliminate any empty array entries List<String> stringList = new ArrayList<>(); for (String string : command) { string = string.trim();//from w w w .j a v a 2 s .com 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.setName("MyStreamPumper Thread"); 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; } }