List of usage examples for org.apache.commons.exec DefaultExecutor setStreamHandler
public void setStreamHandler(final ExecuteStreamHandler streamHandler)
From source file:com.codeabovelab.dm.common.utils.ProcessUtils.java
public static int executeCommand(String command, ExecuteWatchdog watchdog, OutputStream outputStream, OutputStream errorStream, InputStream inputStream, Map<String, String> env) { CommandLine cmdLine = CommandLine.parse(command); DefaultExecutor executor = new DefaultExecutor(); if (outputStream == null) { outputStream = new LogOutputStream() { @Override/* w w w.j av a 2s .co m*/ protected void processLine(String s, int i) { log.error(s); } }; } if (errorStream == null) { errorStream = new LogOutputStream() { @Override protected void processLine(String s, int i) { log.error(s); } }; } executor.setStreamHandler(new PumpStreamHandler(outputStream, errorStream, inputStream)); executor.setExitValues(new int[] { 0, 1 }); if (watchdog != null) { executor.setWatchdog(watchdog); } int exitValue; try { exitValue = executor.execute(cmdLine, env); } catch (IOException e) { exitValue = 1; LOGGER.error("error executing command", e); } return exitValue; }
From source file:com.boundlessgeo.wps.grass.GrassProcesses.java
@DescribeProcess(title = "r.viewshed", description = "Computes the viewshed of a point on an elevation raster map.") @DescribeResult(description = "area visible from provided location") public static GridCoverage2D viewshed( @DescribeParameter(name = "dem", description = "digitial elevation model") GridCoverage2D dem, @DescribeParameter(name = "x", description = "x location in map units") double x, @DescribeParameter(name = "y", description = "y location in map units") double y) throws Exception { String COMMAND = "viewshed"; //Stage files in a temporary location File geodb = Files.createTempDirectory("grassdata").toFile(); geodb.deleteOnExit();//from w w w . ja va2 s . com File location = new File(geodb, COMMAND + Long.toString(random.nextLong()) + "location"); // stage dem file File file = new File(geodb, "dem.tif"); //The file must exist for FileImageOutputStreamExtImplSpi to create the output stream if (!file.exists()) { file.getParentFile().mkdirs(); file.createNewFile(); } final GeoTiffFormat format = new GeoTiffFormat(); GridCoverageWriter writer = format.getWriter(file); writer.write(dem, null); LOGGER.info("Staging file:" + file); // use file to create location with (returns PERMANENT mapset) File mapset = location(location, file); DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(new ExecuteWatchdog(60000)); executor.setStreamHandler(new PumpStreamHandler(System.out)); executor.setWorkingDirectory(mapset); Map<String, String> env = customEnv(geodb, location, mapset); // EXPORT IMPORT DEM // r.in.gdal input=~/grassdata/viewshed/PERMANENT/dem.tif output=dem --overwrite File r_in_gdal = bin("r.in.gdal"); CommandLine cmd = new CommandLine(r_in_gdal); cmd.addArgument("input=${file}"); cmd.addArgument("output=dem"); cmd.addArgument("--overwrite"); cmd.setSubstitutionMap(new KVP("file", file)); try { LOGGER.info(cmd.toString()); executor.setExitValue(0); int exitValue = executor.execute(cmd, env); } catch (ExecuteException fail) { LOGGER.warning(r_in_gdal.getName() + ":" + fail.getLocalizedMessage()); throw fail; } // EXECUTE VIEWSHED File r_viewshed = bin("r.viewshed"); cmd = new CommandLine(r_viewshed); cmd.addArgument("input=dem"); cmd.addArgument("output=viewshed"); cmd.addArgument("coordinates=${x},${y}"); cmd.addArgument("--overwrite"); cmd.setSubstitutionMap(new KVP("x", x, "y", y)); try { LOGGER.info(cmd.toString()); executor.setExitValue(0); int exitValue = executor.execute(cmd, env); } catch (ExecuteException fail) { LOGGER.warning(r_viewshed.getName() + ":" + fail.getLocalizedMessage()); throw fail; } // EXECUTE EXPORT VIEWSHED // r.out.gdal --overwrite input=viewshed@PERMANENT output=/Users/jody/grassdata/viewshed/viewshed.tif format=GTiff File viewshed = new File(location, "viewshed.tif"); File r_out_gdal = bin("r.out.gdal"); cmd = new CommandLine(r_out_gdal); cmd.addArgument("input=viewshed"); cmd.addArgument("output=${viewshed}"); cmd.addArgument("--overwrite"); cmd.addArgument("format=GTiff"); cmd.setSubstitutionMap(new KVP("viewshed", viewshed)); try { LOGGER.info(cmd.toString()); executor.setExitValue(0); int exitValue = executor.execute(cmd, env); } catch (ExecuteException fail) { LOGGER.warning(r_out_gdal.getName() + ":" + fail.getLocalizedMessage()); throw fail; } // STAGE RESULT if (!viewshed.exists()) { throw new IOException("Generated viweshed.tif not found"); } GeoTiffReader reader = format.getReader(viewshed); GridCoverage2D coverage = reader.read(null); cleanup(new File(env.get("GISRC"))); return coverage; }
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 a v 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: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 ww . j a va 2 s. co 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(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:at.treedb.util.Execute.java
public static ExecResult execute(String command, String[] param, Map<String, File> map) { DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine cmdLine = null;/*ww w . j ava 2 s . c o m*/ int exitValue = 0; try { PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); cmdLine = new CommandLine(command); if (param != null) { for (String s : param) { s = s.trim(); if (s.isEmpty()) { continue; } cmdLine.addArgument(s); } } cmdLine.setSubstitutionMap(map); executor.setStreamHandler(streamHandler); exitValue = executor.execute(cmdLine); return new ExecResult(exitValue, outputStream.toString(), null); } catch (Exception e) { return new ExecResult(-1, outputStream.toString(), e); } }
From source file:com.boundlessgeo.wps.grass.GrassProcesses.java
@DescribeProcess(title = "GRASS Version", description = "Retreive the version of GRASS used for computation") @DescribeResult(description = "Version") public static String version() { if (EXEC == null) { return "unavailable"; }/*from w w w . jav a 2s . co m*/ CommandLine cmd = new CommandLine(EXEC); cmd.addArgument("-v"); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(outputStream)); LOGGER.info("exec: " + cmd.toString()); int exitValue = executor.execute(cmd); return outputStream.toString(); } catch (ExecuteException huh) { return "exit code: " + huh.getExitValue() + " (" + huh.getMessage() + ")"; } catch (IOException e) { return "unavailable: " + e.getClass().getSimpleName() + ":" + e.getMessage(); } }
From source file:com.sds.acube.ndisc.mts.xserver.XNDiscServer.java
/** * XNDisc Server ? ? ?// w w w .j av a 2 s. c o m * * @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; }
From source file:com.tupilabs.pbs.PBS.java
/** * Executes a PBS command.//from ww w. j a v a 2 s . c o m * * @param cmdLine command * @param environment env vars * @param out output stream * @param err err stream * @return execute handler * @throws ExecuteException if there is an error executing a command * @throws IOException in case of an IO problem */ static DefaultExecuteResultHandler execute(CommandLine cmdLine, Map<String, String> environment, OutputStream out, OutputStream err) throws ExecuteException, IOException { DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteStreamHandler streamHandler = new PumpStreamHandler(out, err); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setStreamHandler(streamHandler); if (environment != null) { executor.execute(cmdLine, environment, resultHandler); } else { executor.execute(cmdLine, resultHandler); } return resultHandler; }
From source file:com.vmware.bdd.usermgmt.job.ChangeLocalAccountStateExecutor.java
private void changeLocalAccountState(String argument) { //String chefCmd = "sudo /opt/serengeti/sbin/set-password L"; String sudoCmd = CommonUtil.getCustomizedSudoCmd(); CommandLine cmdLine = new CommandLine(sudoCmd).addArgument(SET_PASSWORD_COMMAND).addArgument(argument); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(new ExecOutputLogger(LOGGER, false), //output logger new ExecOutputLogger(LOGGER, true)) //error logger );//from w ww .j a va 2 s . co m executor.setWatchdog(new ExecuteWatchdog(1000l * TIMEOUT)); try { int exitVal = executor.execute(cmdLine); if (exitVal != 0) { throw new UserMgmtExecException("CHANGE_LOCAL_ACCOUNT_STATE_FAIL", null); } } catch (IOException e) { throw new UserMgmtExecException("CHANGE_LOCAL_ACCOUNT_STATE_FAIL", e); } }
From source file:com.creactiviti.piper.core.taskhandler.script.Bash.java
@Override public String handle(Task aTask) throws Exception { File scriptFile = File.createTempFile("_script", ".sh"); File logFile = File.createTempFile("log", null); FileUtils.writeStringToFile(scriptFile, aTask.getRequiredString("script")); try (PrintStream stream = new PrintStream(logFile);) { Process chmod = Runtime.getRuntime().exec(String.format("chmod u+x %s", scriptFile.getAbsolutePath())); int chmodRetCode = chmod.waitFor(); if (chmodRetCode != 0) { throw new ExecuteException("Failed to chmod", chmodRetCode); }//w ww .ja v a 2s . c om CommandLine cmd = new CommandLine(scriptFile.getAbsolutePath()); logger.debug("{}", cmd); DefaultExecutor exec = new DefaultExecutor(); exec.setStreamHandler(new PumpStreamHandler(stream)); exec.execute(cmd); return FileUtils.readFileToString(logFile); } catch (ExecuteException e) { throw new ExecuteException(e.getMessage(), e.getExitValue(), new RuntimeException(FileUtils.readFileToString(logFile))); } finally { FileUtils.deleteQuietly(logFile); FileUtils.deleteQuietly(scriptFile); } }