List of usage examples for org.apache.commons.exec PumpStreamHandler PumpStreamHandler
public PumpStreamHandler(final OutputStream outAndErr)
PumpStreamHandler
. From source file:hr.fer.zemris.vhdllab.service.impl.GhdlSimulator.java
private List<String> executeProcess(CommandLine cl, java.io.File tempDirectory) throws ExecuteException, IOException { if (LOG.isDebugEnabled()) { LOG.debug("Executing process: " + cl.toString()); }//from ww w . j a v a2 s. c om ByteArrayOutputStream bos = new ByteArrayOutputStream(); ExecuteStreamHandler handler = new PumpStreamHandler(bos); ExecuteWatchdog watchdog = new ExecuteWatchdog(PROCESS_TIMEOUT); Executor executor = new DefaultExecutor(); executor.setWorkingDirectory(tempDirectory); executor.setWatchdog(watchdog); executor.setStreamHandler(handler); /* * It seems that when ExecuteWatchdog terminates process by invoking * destroy method, process terminates with exit code 143. And since we * manually ask watchdog if he killed the process, exit code 143 is * marked as successful (just so our code can be executed). * * Exit code 1 in case of compilation error(s). */ executor.setExitValues(new int[] { 0, 1, 143 }); try { executor.execute(cl); } catch (ExecuteException e) { LOG.warn("Process output dump:\n" + bos.toString()); throw e; } if (watchdog.killedProcess()) { throw new SimulatorTimeoutException(PROCESS_TIMEOUT); } String output; try { output = bos.toString(IOUtil.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new UnhandledException(e); } if (StringUtils.isBlank(output)) { return Collections.emptyList(); } return Arrays.asList(StringUtil.splitToNewLines(output)); }
From source file:edu.stolaf.cs.wmrserver.TransformProcessor.java
private File compile(SubnodeConfiguration languageConf, String transformTypeString, File srcTransformFile, File jobTransformDir) throws CompilationException, IOException { // Determine correct compiler, returning if none specified String compiler = languageConf.getString("compiler-" + transformTypeString, ""); if (compiler.isEmpty()) compiler = languageConf.getString("compiler", ""); if (compiler.isEmpty()) return srcTransformFile; // Determine destination filename File compiledTransformFile = new File(jobTransformDir, "compiled-job-" + transformTypeString); // Create map to replace ${wmr:...} variables. // NOTE: Commons Configuration's built-in interpolator does not work here // for some reason. File jobTempDir = getJobTempDir(); Hashtable<String, String> variableMap = new Hashtable<String, String>(); File libDir = getLibraryDirectory(languageConf); variableMap.put("wmr:lib.dir", (libDir != null) ? libDir.toString() : ""); variableMap.put("wmr:src.dir", relativizeFile(srcTransformFile.getParentFile(), jobTempDir).toString()); variableMap.put("wmr:src.file", relativizeFile(srcTransformFile, jobTempDir).toString()); variableMap.put("wmr:dest.dir", relativizeFile(jobTransformDir, jobTempDir).toString()); variableMap.put("wmr:dest.file", relativizeFile(compiledTransformFile, jobTempDir).toString()); // Replace variables in compiler string compiler = StrSubstitutor.replace(compiler, variableMap); // Run the compiler CommandLine compilerCommand = CommandLine.parse(compiler); DefaultExecutor exec = new DefaultExecutor(); ExecuteWatchdog dog = new ExecuteWatchdog(60000); // 1 minute ByteArrayOutputStream output = new ByteArrayOutputStream(); PumpStreamHandler pump = new PumpStreamHandler(output); exec.setWorkingDirectory(jobTempDir); exec.setWatchdog(dog);/*from w w w . j a va2 s . c o m*/ exec.setStreamHandler(pump); exec.setExitValues(null); // Can't get the exit code if it throws exception int exitStatus = -1; try { exitStatus = exec.execute(compilerCommand); } catch (IOException ex) { // NOTE: Exit status is still -1 in this case, since exception was thrown throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus, new String(output.toByteArray())); } // Check for successful exit if (exitStatus != 0) throw new CompilationException("Compiling failed for " + transformTypeString, exitStatus, new String(output.toByteArray())); // Check that output exists and is readable, and make it executable if (!compiledTransformFile.isFile()) throw new CompilationException( "Compiler did not output a " + transformTypeString + " executable (or it was not a regular file).", exitStatus, new String(output.toByteArray())); if (!compiledTransformFile.canRead()) throw new IOException(StringUtils.capitalize(transformTypeString) + " executable output from compiler was not readable: " + compiledTransformFile.toString()); if (!compiledTransformFile.canExecute()) compiledTransformFile.setExecutable(true, false); return compiledTransformFile; }
From source file:com.boundlessgeo.wps.grass.GrassProcesses.java
/** * Define a GISBASE/LOCATION_NAME/PERMANENT for the provided dem. * * The dem is staged in GISBASE/dem.tif and then moved to * GISBASE/LOCATION_NAME/PERMANENT/dem.tif * * @param operation/*from w w w.j av a 2 s.c o m*/ * Name used for the location on disk * @param dem * File used to establish CRS and Bounds for the location * @return Array of files consisting of {GISBASE, LOCATION, MAPSET, dem.tif} * @throws Exception */ static File location(File location, File raster) throws Exception { // grass70 + ' -c ' + myfile + ' -e ' + location_path CommandLine cmd = new CommandLine(EXEC); cmd.addArgument("-c"); cmd.addArgument("${raster}"); cmd.addArgument("-e"); cmd.addArgument("${location}"); cmd.setSubstitutionMap(new KVP("raster", raster, "location", location)); LOGGER.info(cmd.toString()); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); executor.setStreamHandler(new PumpStreamHandler(System.out)); LOGGER.info(cmd.toString()); try { int exitValue = executor.execute(cmd); } catch (ExecuteException fail) { LOGGER.warning("grass70:" + fail.getLocalizedMessage()); throw fail; } File mapset = new File(location, "PERMANENT"); if (!mapset.exists()) { throw new IllegalStateException("Did not create mapset " + mapset); } return location; }
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());/* w w w. j a v a 2 s.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:Logi.GSeries.Service.LogiGSKService.java
public String execToString(String command) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine commandline = CommandLine.parse(command); DefaultExecutor exec = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); exec.execute(commandline);/*from w ww . ja v a 2 s . c om*/ return (outputStream.toString()); }
From source file:com.github.cshubhamrao.MediaConverter.MainUI.java
/** Runs ffmpeg -version */ @Override//w w w. ja v a 2 s. c om protected Void doInBackground() { ffmpeg = FFMpegLoader.getFFMpegExecutable(); if (ffmpeg != null) { try { cmd = new CommandLine(ffmpeg); cmd.addArgument("-version"); OutputStream outputStream = new ByteArrayOutputStream(); DefaultExecutor exec = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); ExecuteWatchdog watchdog = new ExecuteWatchdog(10000); exec.setWatchdog(watchdog); exec.execute(cmd); publish(outputStream.toString()); } catch (ExecuteException ex) { Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex); } } else { try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(DisplayVersion.class.getName()).log(Level.SEVERE, null, ex); } } return null; }
From source file:com.boundlessgeo.wps.grass.GrassProcesses.java
/** * Define a GISBASE/LOCATION_NAME/PERMANENT for the provided dem. * * The dem is staged in GISBASE/dem.tif and then moved to * GISBASE/LOCATION_NAME/PERMANENT/dem.tif * * @param operation//from w w w .j av a 2s . c om * Name used for the location on disk * @param dem * File used to establish CRS and Bounds for the location * @return Array of files consisting of {GISBASE, LOCATION, MAPSET, dem.tif} * @throws Exception */ static File[] location(String operation, GridCoverage2D dem) throws Exception { File geodb = new File(System.getProperty("user.home"), "grassdata"); //File location = Files.createTempDirectory(geodb.toPath(),operation).toFile(); File location = new File(geodb, operation); File mapset = new File(location, "PERMANENT"); File file = new File(geodb, "dem.tif"); final GeoTiffFormat format = new GeoTiffFormat(); GridCoverageWriter writer = format.getWriter(file); writer.write(dem, null); System.out.println("Staging file:" + file); // grass70 + ' -c ' + myfile + ' -e ' + location_path CommandLine cmd = new CommandLine(EXEC); cmd.addArgument("-c"); cmd.addArgument("${file}"); cmd.addArgument("-e"); cmd.addArgument("${location}"); cmd.setSubstitutionMap(new KVP("file", file, "location", location)); LOGGER.info(cmd.toString()); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); executor.setStreamHandler(new PumpStreamHandler(System.out)); int exitValue = executor.execute(cmd); File origional = file; file = new File(mapset, file.getName()); Files.move(origional.toPath(), file.toPath()); return new File[] { geodb, location, mapset, file }; }
From source file:com.tibco.tgdb.test.lib.TGAdmin.java
/** * Invoke TG admin synchronously. /*from ww w .j a v a 2s .co m*/ * Admin operation blocks until it is completed. * * @param tgHome TG admin home * @param url Url to connect to TG server * @param user System User name * @param pwd System User password * @param logFile TG admin log file location - Generated by admin * @param logLevel Specify the log level: info/user1/user2/user3/debug/debugmemory/debugwire * @param cmd TG admin command file or command string * @param memSize Specify the maximum memory usage (MB). -1 for default (8 MB) * @param timeout Number of milliseconds allowed to complete admin operation * * @return Output console of admin operation * @throws TGAdminException Admin execution fails or timeout occurs */ public static String invoke(String tgHome, String url, String user, String pwd, String logFile, String logLevel, String cmd, int memSize, long timeout) throws TGAdminException { if (tgHome == null) throw new TGAdminException("TGAdmin - TGDB home is not defined"); File ftgHome = new File(tgHome); if (!ftgHome.exists()) throw new TGAdminException("TGAdmin - TGDB home '" + tgHome + "' does not exist"); ByteArrayOutputStream output = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(output); Executor tgExec = new DefaultExecutor(); tgExec.setStreamHandler(psh); tgExec.setWorkingDirectory(new File(tgHome + "/bin")); CommandLine tgCL = new CommandLine((new File(tgHome + "/bin/" + process)).getAbsolutePath()); // Define arguments List<String> args = new ArrayList<String>(); if (url != null) { args.add("--url"); args.add(url); } if (user != null) { args.add("--uid"); args.add(user); } if (pwd != null) { args.add("--pwd"); args.add(pwd); } if (logFile != null) { args.add("--log"); args.add(logFile); } if (logLevel != null) { args.add("--log-level"); args.add(logLevel); } if (memSize >= 0) { args.add("--max-memory"); args.add(Integer.toString(memSize)); } File cmdFile = null; if (cmd == null) throw new TGAdminException("TGAdmin - Command is required."); if (cmd.matches( "(?s)^(kill|show|describe|create|stop|info|checkpoint|dump|set|connect|disconnect|export|import|exit).*$")) { try { cmdFile = new File(tgHome + "/invokeAdminScript.txt"); Files.write(Paths.get(cmdFile.toURI()), cmd.getBytes(StandardCharsets.UTF_8)); } catch (IOException ioe) { throw new TGAdminException("TGAdmin - " + ioe.getMessage()); } } else { cmdFile = new File(cmd); } if (!cmdFile.exists()) { throw new TGAdminException("TGAdmin - Command file '" + cmdFile + "' does not exist"); } args.add("--file"); args.add(cmdFile.getAbsolutePath()); tgCL.addArguments((String[]) args.toArray(new String[args.size()])); ExecuteWatchdog tgWatch = new ExecuteWatchdog(timeout); tgExec.setWatchdog(tgWatch); System.out.println("TGAdmin - Invoking " + StringUtils.toString(tgCL.toStrings(), " ")); long endProcTime = 0; long totalProcTime = 0; try { TGAdmin.startProcTime = System.currentTimeMillis(); tgExec.execute(tgCL); endProcTime = System.currentTimeMillis(); } catch (IOException ee) { if (tgWatch.killedProcess()) throw new TGAdminException("TGAdmin - Operation did not complete within " + timeout + " ms", output.toString()); else { try { Thread.sleep(1000); // make sure output has time to fill up } catch (InterruptedException ie) { ; } throw new TGAdminException("TGAdmin - Execution failed: " + ee.getMessage(), output.toString()); } } if (url != null && !output.toString().contains("Successfully connected to server")) throw new TGAdminException("TGAdmin - Admin could not connect to server " + url + " with user " + user, output.toString()); if (endProcTime != 0) totalProcTime = endProcTime - TGAdmin.startProcTime; if (TGAdmin.showOperationBanner) System.out.println( "TGAdmin - Operation completed" + (totalProcTime > 0 ? " in " + totalProcTime + " msec" : "")); return output.toString(); }
From source file:com.boundlessgeo.wps.grass.GrassProcesses.java
/** * Define a GISBASE/LOCATION_NAME for the provided dem. * * @param operation Name used for the location on disk * @param dem File used to establish CRS and Bounds for the location * @return// ww w. ja va 2 s . c om * @throws Exception */ static File location(CoordinateReferenceSystem crs) throws Exception { String code = CRS.toSRS(crs, true); File geodb = new File(System.getProperty("user.home"), "grassdata"); File location = Files.createTempDirectory(geodb.toPath(), code).toFile(); KVP kvp = new KVP("geodb", geodb, "location", location); // grass70 + ' -c epsg:' + myepsg + ' -e ' + location_path CommandLine cmd = new CommandLine(EXEC); cmd.addArgument("-c"); cmd.addArgument("epsg:" + code); cmd.addArgument("-e"); cmd.addArgument("${location}"); cmd.setSubstitutionMap(kvp); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setWatchdog(new ExecuteWatchdog(60000)); executor.setStreamHandler(new PumpStreamHandler(System.out)); int exitValue = executor.execute(cmd); return location; }
From source file:com.sds.acube.ndisc.mts.xserver.XNDiscServer.java
/** * XNDisc Server ? ? ?//from w w w.j a v a 2s . c om * * @return ?? true, false */ private static boolean isXNDiscServerAlive() { boolean isAlive = false; String HOST = XNDiscConfig.getString(XNDiscConfig.HOST, XNDiscConfig.LOCAL_HOST); String PORT = XNDiscConfig.getString(XNDiscConfig.PORT); Scanner scanner = null; ByteArrayOutputStream baos = null; try { String os = System.getProperty("os.name").toLowerCase(); String ostype = (os.contains("windows")) ? "W" : "U"; CommandLine cmdline = new CommandLine("netstat"); cmdline.addArgument("-an"); if (ostype.equals("W")) { cmdline.addArgument("-p"); cmdline.addArgument("\"TCP\""); } else { // UNIX ? ? -an ? ? ? if (XNDiscUtils.isSolaris()) { cmdline.addArgument("-P"); cmdline.addArgument("tcp"); } else if (XNDiscUtils.isAix()) { cmdline.addArgument("-p"); cmdline.addArgument("TCP"); } } DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); baos = new ByteArrayOutputStream(); PumpStreamHandler sh = new PumpStreamHandler(baos); executor.setStreamHandler(sh); executor.execute(cmdline); String str = baos.toString(); if (str != null && str.length() > 0) { // ? XNDisc alive ?(XNDisc Server ? ?) scanner = new Scanner(str); while (scanner.hasNextLine()) { String readline = scanner.nextLine(); if (readline.contains(HOST) && readline.contains(PORT) && readline.contains(XNDISC_LISTEN_STATUS)) { isAlive = true; break; } } } } catch (Exception e) { e.printStackTrace(); isAlive = false; } finally { try { if (scanner != null) { scanner.close(); } if (baos != null) { baos.close(); } } catch (IOException e) { e.printStackTrace(); } } return isAlive; }