List of usage examples for org.apache.commons.exec PumpStreamHandler PumpStreamHandler
public PumpStreamHandler(final OutputStream outAndErr)
PumpStreamHandler
. 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 ww. ja v a 2s.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);// w ww. j av a 2s.co m int result; try { psh.start(); result = exec.execute(commandLine, enviro); } finally { psh.stop(); } return result; }
From source file:com.tibco.tgdb.test.lib.TGServer.java
/** * Initialize the TG server synchronously. This Init operation blocks until * it is completed.//from w w w . j ava 2s . c o m * * @param initFile * TG server init config file * @param forceCreation * Force creation. Delete all the data in the db directory first. * @param timeout * Number of milliseconds allowed to initialize the server * @return the output stream of init operation * @throws TGInitException * Init operation fails or timeout occurs */ public String init(String initFile, boolean forceCreation, long timeout) throws TGInitException { File initF = new File(initFile); if (!initF.exists()) throw new TGInitException("TGServer - Init file '" + initFile + "' does not exist"); try { this.setInit(initF); } catch (TGGeneralException e) { throw new TGInitException(e.getMessage()); } //ByteArrayOutputStream output = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream()); Executor tgExec = new DefaultExecutor(); tgExec.setStreamHandler(psh); tgExec.setWorkingDirectory(new File(this.home + "/bin")); CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath()); if (forceCreation) tgCL.addArguments(new String[] { "-i", "-f", "-Y", "-c", initFile, "-l", this.initLogFileBase }); else tgCL.addArguments(new String[] { "-i", "-Y", "-c", initFile, "-l", this.initLogFileBase }); ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout); tgExec.setWatchdog(tgWatch); System.out.println("TGServer - Initializing " + StringUtils.toString(tgCL.toStrings(), " ")); String output = ""; try { tgExec.execute(tgCL); output = new String(Files.readAllBytes(Paths.get(this.getInitLogFile().toURI()))); } catch (IOException ee) { if (tgWatch.killedProcess()) throw new TGInitException("TGServer - Init did not complete within " + timeout + " ms"); else { try { Thread.sleep(1000); // make sure output has time to fill up } catch (InterruptedException ie) { ; } throw new TGInitException("TGServer - Init failed: " + ee.getMessage(), output); } } try { this.setBanner(output); } catch (TGGeneralException tge) { throw new TGInitException(tge.getMessage()); } if (output.contains("TGSuccess")) { System.out.println("TGServer - Initialized successfully"); return output; } else throw new TGInitException("TGServer - Init failed", output); }
From source file:com.tibco.tgdb.test.lib.TGServer.java
/** * Start the TG server synchronously./*from w w w .j a va 2 s . com*/ * * @param timeout * Number of milliseconds allowed to start the server * @throws TGStartException Start operation fails */ public void start(long timeout) throws TGStartException { if (this.configFile == null) throw new TGStartException("TGServer - Config file not set"); if (this.logFile == null) this.setLogFile("tgdb_" + this.dbName); //this.outStream = new ByteArrayOutputStream(); // reset //this.errStream = new ByteArrayOutputStream(); // reset PumpStreamHandler psh = new PumpStreamHandler(new ByteArrayOutputStream()); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); Executor tgExec = new DefaultExecutor(); tgExec.setWorkingDirectory(new File(this.home + "/bin")); tgExec.setStreamHandler(psh); CommandLine tgCL = new CommandLine((new File(this.home + "/bin/" + process)).getAbsolutePath()); tgCL.addArguments(new String[] { "-s", "-c", this.configFile.getAbsolutePath(), "-l", this.logFileBase }); System.out.println("TGServer - Starting " + StringUtils.toString(tgCL.toStrings(), " ")); try { tgExec.execute(tgCL, resultHandler); } catch (IOException ioe) { try { Thread.sleep(1000); // Make sure output/error fill up } catch (InterruptedException ie) { ; } throw new TGStartException(ioe.getMessage()); } if (timeout > 0) { Calendar future = Calendar.getInstance(); future.add(Calendar.MILLISECOND, (int) timeout); boolean started = false; boolean error = false; List<String> acceptedClients = new ArrayList<String>(); String acceptedClient; while (!future.before(Calendar.getInstance())) { try { Thread.sleep(1000); BufferedReader reader = new BufferedReader(new StringReader(this.getOutput())); String line = reader.readLine(); while (line != null) { if (line.contains("Process pid:")) this.setPid(Integer.parseInt(line.substring(line.lastIndexOf("Process pid:") + 12, line.indexOf(",", line.lastIndexOf("Process pid:") + 12)))); if (line.contains("[Error]")) { error = true; } if (line.contains("Accepting clients on")) { started = true; acceptedClient = line.substring(line.indexOf("- Accepting clients on") + 2); if (!acceptedClients.contains(acceptedClient)) acceptedClients.add(acceptedClient); } line = reader.readLine(); } reader.close(); if (started) break; } catch (Exception e) { throw new TGStartException("TGServer - " + e.getMessage()); } } if (!started) throw new TGStartException( "TGServer - Did not start on time (after " + timeout + " msec) - See log " + this.logFile); else { this.running = true; System.out.println("TGServer - Started successfully with pid " + this.pid + " :"); System.out.println("\t\t- Log file: " + this.logFile); if (error) System.out.println("\t\t- With some error(s) - See log"); for (String client : acceptedClients) System.out.println("\t\t- " + client); try { this.setBanner(this.getOutput()); } catch (TGGeneralException tge) { throw new TGStartException(tge.getMessage()); } } } }
From source file:com.tibco.tgdb.test.lib.TGServer.java
/** * <pre>//from w ww. j a v a 2 s . c o m * Kill the TG server. * - taskkill on Windows. * - kill -9 on Unix. * </pre> * * @throws Exception * Kill operation fails */ public void kill() throws Exception { if (this.pid == 0) throw new TGGeneralException( "TG server does not have a PID - Probably due to a previous start-up failure"); ByteArrayOutputStream output = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(output); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(psh); CommandLine cmdLine; if (OS.isFamilyWindows()) cmdLine = CommandLine.parse("taskkill /f /pid " + this.getPid() + " /t"); else cmdLine = CommandLine.parse("kill -9 " + this.getPid() + ""); try { executor.execute(cmdLine); } catch (ExecuteException ee) { // System.out.println("TGServer with pid " + this.getPid() + " not killed :"); // System.out.println("\t- " + output.toString().trim().replace("\n","\n\t- ")); throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message } System.out.println("TGServer - Server with pid " + this.getPid() + " successfully killed :"); if (!output.toString().equals("")) System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- ")); this.running = false; this.pid = 0; }
From source file:com.tibco.tgdb.test.lib.TGServer.java
/** * <pre>//w w w .ja v a2 s . c om * Kill all the TG server processes. * Note that this method blindly tries to kill all the servers of the machine * and do not update the running status of those servers. * - taskkill on Windows. * - kill -9 on Unix. * </pre> * * @throws Exception Kill operation fails */ public static void killAll() throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(output); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(psh); executor.setWorkingDirectory(new File(System.getProperty("java.io.tmpdir"))); CommandLine cmdLine; if (OS.isFamilyWindows()) cmdLine = CommandLine.parse("taskkill /f /im " + process + ".exe"); else { // Unix File internalScriptFile = new File(ClassLoader .getSystemResource( TGServer.class.getPackage().getName().replace('.', '/') + "/TGKillProcessByName.sh") .getFile()); File finalScriptFile = new File(executor.getWorkingDirectory() + "/" + internalScriptFile.getName()); Files.copy(internalScriptFile.toPath(), finalScriptFile.toPath(), StandardCopyOption.REPLACE_EXISTING); cmdLine = CommandLine.parse("sh " + finalScriptFile.getAbsolutePath() + " " + process + ""); } try { Thread.sleep(1000); executor.execute(cmdLine); } catch (ExecuteException ee) { if (output.toString().contains( "ERROR: The process \"" + process + (OS.isFamilyWindows() ? ".exe\"" : "") + " not found")) return; throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message } // Check one more thing : // On Windows when some processes do not get killed taskkill still // returns exit code if (OS.isFamilyWindows()) { if (output.toString().contains("ERROR")) throw new ExecuteException(output.toString().trim(), 1); } else { if (output.toString().contains("ERROR: The process \"" + process + "\" not found")) return; } System.out.println("TGServer - Server(s) successfully killed :"); if (!output.toString().equals("")) System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- ")); }
From source file:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java
/** * This calls a TIBCO binary.//w w w . j a va 2 s. c om * * @param binary, the TIBCO binary file to execute * @param tras, the TRA files associated with the TIBCO binary * @param arguments, command-line arguments * @param workingDir, working directory from where the binary is launched * @param errorMsg, error message to display in case of a failure * @param fork, if true the chiild process will be detached from the caller * * @throws IOException * @throws MojoExecutionException */ protected int launchTIBCOBinary(File binary, List<File> tras, ArrayList<String> arguments, File workingDir, String errorMsg, boolean fork, boolean synchronous) throws IOException, MojoExecutionException { Integer result = 0; if (tras == null) { // no value specified as Mojo parameter, we use the .tra in the same directory as the binary String traPathFileName = binary.getAbsolutePath(); traPathFileName = FilenameUtils.removeExtension(traPathFileName); traPathFileName += ".tra"; tras = new ArrayList<File>(); tras.add(new File(traPathFileName)); } HashMap<File, File> trasMap = new HashMap<File, File>(); for (File tra : tras) { // copy of ".tra" file in the working directory File tmpTRAFile = new File(directory, tra.getName()); trasMap.put(tra, tmpTRAFile); copyFile(tra, tmpTRAFile); } for (File tra : trasMap.keySet()) { if (trasMap.containsKey(tibcoDesignerTRAPath) && ((tibcoBuildEARUseDesignerTRA && tra == tibcoBuildEARTRAPath) || (tibcoBuildLibraryUseDesignerTRA && tra == tibcoBuildLibraryTRAPath))) { if (tras.size() > 1) { ReplaceRegExp replaceRegExp = new ReplaceRegExp(); replaceRegExp.setFile(trasMap.get(tra)); replaceRegExp.setMatch("tibco.include.tra (.*/designer.tra)"); replaceRegExp.setReplace( "tibco.include.tra " + trasMap.get(tibcoDesignerTRAPath).toString().replace('\\', '/')); replaceRegExp.setByLine(true); replaceRegExp.execute(); } } if (tra == tibcoBuildEARTRAPath || tra == tibcoDesignerTRAPath || tra == tibcoBWEngineTRAPath) { // FIXME: should check more properly // append user.home at the end to force the use of custom Designer5.prefs PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(trasMap.get(tra), true))); out.println(""); out.println("java.property.user.home=" + directory.getAbsolutePath().replace("\\", "/")); out.close(); } } CommandLine cmdLine = new CommandLine(binary); for (String argument : arguments) { cmdLine.addArgument(argument); } getLog().debug("launchTIBCOBinary command line : " + cmdLine.toString()); getLog().debug("working dir : " + workingDir); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(workingDir); if (timeOut > 0) { ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut * 1000); executor.setWatchdog(watchdog); } executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); ByteArrayOutputStream stdOutAndErr = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(stdOutAndErr)); if (fork) { CommandLauncher commandLauncher = CommandLauncherFactory.createVMLauncher(); commandLauncher.exec(cmdLine, null, workingDir); } else { try { if (synchronous) { result = executor.execute(cmdLine); } else { executor.execute(cmdLine, new DefaultExecuteResultHandler()); } } catch (ExecuteException e) { // TODO : grer erreurs des excutables (ventuellement parser les erreurs classiques) getLog().info(cmdLine.toString()); getLog().info(stdOutAndErr.toString()); getLog().info(result.toString()); throw new MojoExecutionException(errorMsg, e); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } return result; }
From source file:net.sourceforge.seqware.pipeline.plugins.ITUtility.java
/** * Run an arbitrary command and check it against an expected return value * * @param line//from ww w . jav a2 s. c o m * @param expectedReturnValue * @param dir working directory, can be null if you don't want to change directories * @return * @throws IOException */ public static String runArbitraryCommand(String line, int expectedReturnValue, File dir) throws IOException { Log.info("Running " + line); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine commandline = CommandLine.parse(line); DefaultExecutor exec = new DefaultExecutor(); if (dir != null) { exec.setWorkingDirectory(dir); } PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); exec.setExitValue(expectedReturnValue); try { int exitValue = exec.execute(commandline); Assert.assertTrue( "exit value for full jar with no params should be " + expectedReturnValue + " was " + exitValue, exitValue == expectedReturnValue); String output = outputStream.toString(); return output; } catch (ExecuteException e) { Log.error("Execution failed with:"); Log.error(outputStream.toString()); throw e; } }
From source file:net.spinetrak.rpitft.command.Command.java
Result execute(final Stream stream_) { final CommandLine commandline = CommandLine.parse(_script); final DefaultExecutor exec = new DefaultExecutor(); final ExecuteWatchdog watchdog = new ExecuteWatchdog(500); exec.setWatchdog(watchdog);//ww w. ja v a 2 s. c om final PumpStreamHandler streamHandler = new PumpStreamHandler(stream_.getStream()); exec.setStreamHandler(streamHandler); int result = -1; try { result = exec.execute(commandline); } catch (final IOException ex_) { //LOGGER.error(ex_.getMessage()); } return new Result(stream_, result); }
From source file:nl.tudelft.graphalytics.graphlab.AlgorithmTest.java
protected boolean executeTestScript(File scriptFile, String graphFile, String outputFile) { if (!scriptFile.exists()) { throw new IllegalArgumentException("Cannot find GraphLab Test script: " + scriptFile.getAbsolutePath()); }/*from w w w .j a v a 2 s.c om*/ CommandLine commandLine = new CommandLine("python2"); commandLine.addArgument(scriptFile.getAbsolutePath()); commandLine.addArgument(graphFile); commandLine.addArgument(outputFile); // Set the executor of the command, if desired this can be changed to a custom implementation DefaultExecutor executor = new DefaultExecutor(); // Set the OutputStream to enable printing the output of the algorithm ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(outputStream)); try { // Execute the actual command and store the return code executor.execute(commandLine); // Print the command output System.out.println(outputStream.toString()); return true; } catch (IOException e) { // Catch the exception thrown when the process exits with result != 0 or another IOException occurs System.out.println(outputStream.toString()); return false; } }