List of usage examples for org.apache.commons.exec DefaultExecutor setStreamHandler
public void setStreamHandler(final ExecuteStreamHandler streamHandler)
From source file:org.opennms.systemreport.AbstractSystemReportPlugin.java
protected Set<Integer> getOpenNMSProcesses() { LOG.trace("getOpenNMSProcesses()"); final Set<Integer> processes = new HashSet<Integer>(); final String jps = getResourceLocator().findBinary("jps"); LOG.trace("jps = {}", jps); DataInputStream input = null; PsParser parser = null;//from w w w .j av a2 s .c o m PipedInputStream pis = null; PipedOutputStream output = new PipedOutputStream(); DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(new ExecuteWatchdog(5000)); if (jps != null) { CommandLine command = CommandLine.parse(jps + " -v"); PumpStreamHandler streamHandler = new PumpStreamHandler(output, System.err); try { LOG.trace("executing '{}'", command); pis = new PipedInputStream(output); input = new DataInputStream(pis); parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0); parser.start(); executor.setStreamHandler(streamHandler); int exitValue = executor.execute(command); IOUtils.closeQuietly(output); parser.join(); processes.addAll(parser.getProcesses()); LOG.trace("finished '{}'", command); if (exitValue != 0) { LOG.debug("error running '{}': exit value was {}", command, exitValue); } } catch (final Exception e) { LOG.debug("Failed to run '{}'", command, e); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(pis); IOUtils.closeQuietly(output); } } LOG.trace("looking for ps"); final String ps = getResourceLocator().findBinary("ps"); if (ps != null) { // try Linux/Mac style CommandLine command = CommandLine.parse(ps + " aww -o pid -o args"); output = new PipedOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(output, System.err); try { LOG.trace("executing '{}'", command); pis = new PipedInputStream(output); input = new DataInputStream(pis); parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0); parser.start(); executor.setStreamHandler(streamHandler); int exitValue = executor.execute(command); IOUtils.closeQuietly(output); parser.join(MAX_PROCESS_WAIT); processes.addAll(parser.getProcesses()); LOG.trace("finished '{}'", command); if (exitValue != 0) { LOG.debug("error running '{}': exit value was {}", command, exitValue); } } catch (final Exception e) { LOG.debug("error running '{}'", command, e); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(pis); IOUtils.closeQuietly(output); } if (processes.size() == 0) { // try Solaris style command = CommandLine.parse(ps + " -ea -o pid -o args"); output = new PipedOutputStream(); streamHandler = new PumpStreamHandler(output, System.err); try { LOG.trace("executing '{}'", command); pis = new PipedInputStream(output); input = new DataInputStream(pis); parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0); parser.start(); executor.setStreamHandler(streamHandler); int exitValue = executor.execute(command); IOUtils.closeQuietly(output); parser.join(MAX_PROCESS_WAIT); processes.addAll(parser.getProcesses()); LOG.trace("finished '{}'", command); if (exitValue != 0) { LOG.debug("error running '{}': exit value was {}", command, exitValue); } } catch (final Exception e) { LOG.debug("error running '{}'", command, e); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(pis); IOUtils.closeQuietly(output); } } } if (processes.size() == 0) { LOG.warn("Unable to find any OpenNMS processes."); } return processes; }
From source file:org.opennms.systemreport.SystemReportResourceLocator.java
@Override public String slurpOutput(final String commandString, final boolean ignoreExitCode) { final CommandLine command = CommandLine.parse(commandString); LOG.debug("running: {}", commandString); final Map<String, String> environment = new HashMap<String, String>(System.getenv()); environment.put("COLUMNS", "2000"); DataInputStream input = null; PipedInputStream pis = null;//from w w w .j a va 2 s . c o m OutputSuckingParser parser = null; String outputText = null; final DefaultExecutor executor = new DefaultExecutor(); final PipedOutputStream output = new PipedOutputStream(); final PumpStreamHandler streamHandler = new PumpStreamHandler(output, output); executor.setWatchdog(new ExecuteWatchdog(m_maxProcessWait)); executor.setStreamHandler(streamHandler); if (ignoreExitCode) { executor.setExitValues(null); } try { LOG.trace("executing '{}'", commandString); pis = new PipedInputStream(output); input = new DataInputStream(pis); parser = new OutputSuckingParser(input); parser.start(); final int exitValue = executor.execute(command, environment); IOUtils.closeQuietly(output); parser.join(m_maxProcessWait); if (!ignoreExitCode && exitValue != 0) { LOG.debug("error running '{}': exit value was {}", commandString, exitValue); } else { outputText = parser.getOutput(); } LOG.trace("finished '{}'", commandString); } catch (final Exception e) { LOG.debug("Failed to run '{}'", commandString, e); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); IOUtils.closeQuietly(pis); } return outputText; }
From source file:org.opennms.web.rest.measurements.fetch.RrdtoolXportFetchStrategy.java
/** * {@inheritDoc}/* w w w . jav a 2 s. c om*/ */ @Override protected FetchResults fetchMeasurements(long start, long end, long step, int maxrows, Map<Source, String> rrdsBySource, Map<String, Object> constants) throws RrdException { String rrdBinary = System.getProperty("rrd.binary"); if (rrdBinary == null) { throw new RrdException("No RRD binary is set."); } final long startInSeconds = (long) Math.floor(start / 1000); final long endInSeconds = (long) Math.floor(end / 1000); long stepInSeconds = (long) Math.floor(step / 1000); // The step must be strictly positive if (stepInSeconds <= 0) { stepInSeconds = 1; } final CommandLine cmdLine = new CommandLine(rrdBinary); cmdLine.addArgument("xport"); cmdLine.addArgument("--step"); cmdLine.addArgument("" + stepInSeconds); cmdLine.addArgument("--start"); cmdLine.addArgument("" + startInSeconds); cmdLine.addArgument("--end"); cmdLine.addArgument("" + endInSeconds); if (maxrows > 0) { cmdLine.addArgument("--maxrows"); cmdLine.addArgument("" + maxrows); } // Use labels without spaces when executing the xport command // These are mapped back to the requested labels in the response final Map<String, String> labelMap = Maps.newHashMap(); int k = 0; for (final Map.Entry<Source, String> entry : rrdsBySource.entrySet()) { final Source source = entry.getKey(); final String rrdFile = entry.getValue(); final String tempLabel = Integer.toString(++k); labelMap.put(tempLabel, source.getLabel()); cmdLine.addArgument(String.format("DEF:%s=%s:%s:%s", tempLabel, rrdFile, source.getAttribute(), source.getAggregation())); cmdLine.addArgument(String.format("XPORT:%s:%s", tempLabel, tempLabel)); } // Use commons-exec to execute rrdtool final DefaultExecutor executor = new DefaultExecutor(); // Capture stdout/stderr final ByteArrayOutputStream stdout = new ByteArrayOutputStream(); final ByteArrayOutputStream stderr = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, null)); // Fail if we get a non-zero exit code executor.setExitValue(0); // Fail if the process takes too long final ExecuteWatchdog watchdog = new ExecuteWatchdog(XPORT_TIMEOUT_MS); executor.setWatchdog(watchdog); // Export RrdXport rrdXport; try { executor.execute(cmdLine); final XMLReader xmlReader = XMLReaderFactory.createXMLReader(); xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); final SAXSource source = new SAXSource(xmlReader, new InputSource(new StringReader(stdout.toString()))); final JAXBContext jc = JAXBContext.newInstance(RrdXport.class); final Unmarshaller u = jc.createUnmarshaller(); rrdXport = (RrdXport) u.unmarshal(source); } catch (IOException e) { throw new RrdException("An error occured while executing '" + StringUtils.join(cmdLine.toStrings(), " ") + "' with stderr: " + stderr.toString(), e); } catch (SAXException | JAXBException e) { throw new RrdException("The output generated by 'rrdtool xport' could not be parsed.", e); } final int numRows = rrdXport.getRows().size(); final int numColumns = rrdXport.getMeta().getLegends().size(); final long timestamps[] = new long[numRows]; final double values[][] = new double[numColumns][numRows]; // Convert rows to columns int i = 0; for (final XRow row : rrdXport.getRows()) { timestamps[i] = row.getTimestamp() * 1000; for (int j = 0; j < numColumns; j++) { if (row.getValues() == null) { // NMS-7710: Avoid NPEs, in certain cases the list of values may be null throw new RrdException( "The output generated by 'rrdtool xport' was not recognized. Try upgrading your rrdtool binaries."); } values[j][i] = row.getValues().get(j); } i++; } // Map the columns by label // The legend entries are in the same order as the column values final Map<String, double[]> columns = Maps.newHashMapWithExpectedSize(numColumns); i = 0; for (String label : rrdXport.getMeta().getLegends()) { columns.put(labelMap.get(label), values[i++]); } return new FetchResults(timestamps, columns, rrdXport.getMeta().getStep() * 1000, constants); }
From source file:org.owasp.goatdroid.gui.emulator.Emulator.java
static public boolean isAndroidDeviceAvailable() { ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(stdout); try {/*from w w w . java2 s.com*/ CommandLine cmdLine = new CommandLine( Config.getSDKPath() + getSlash() + "platform-tools" + getSlash() + "adb"); cmdLine.addArgument("devices", false); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(psh); executor.execute(cmdLine); String stringy = stdout.toString(); stdout.close(); /* * Shell command response will be 27 characters in length if there * are no devices currently attached. * * Output is: List of devices attached \n\n */ if (stringy.length() > 27) return true; else return false; } catch (CorruptConfigException e) { return false; } catch (IOException e) { return false; } }
From source file:org.owasp.goatdroid.gui.emulator.Emulator.java
static public String[] getAvailableAndroidDevices() { ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(stdout); try {/*from ww w . j a v a 2 s.c om*/ CommandLine cmdLine = new CommandLine( Config.getSDKPath() + getSlash() + "platform-tools" + getSlash() + "adb"); cmdLine.addArgument("devices", false); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(psh); executor.execute(cmdLine); String output = stdout.toString(); /* * Shell command response will be 27 characters in length if there * are no devices currently attached. * * Output is: List of devices attached \n\n */ if (output.length() > 27) { List<String> devices = new ArrayList<String>(Arrays.asList(output.split("\n"))); /* * This removes the first line.. We don't care about the first * one [0] because that's just the first line (List of devices * attached \n) */ devices.remove(0); for (int count = 0; count < devices.size(); count++) { devices.set(count, devices.get(count).replaceAll("\t.*", "").trim()); } return devices.toArray(new String[devices.size()]); /* * If there were no devices, return an empty list */ } else { return new String[0]; } } catch (CorruptConfigException e) { return new String[0]; } catch (IOException e) { return new String[0]; } }
From source file:org.owasp.goatdroid.gui.emulator.EmulatorWorker.java
static public String startEmulator(String deviceName) throws FileNotFoundException, IOException, CorruptConfigException { HashMap<String, String> settings = Config.readConfig(); String emulator = settings.get("sdk_path") + getSlash() + "tools" + getSlash(); if (getOperatingSystem().startsWith("windows")) emulator += "emulator-arm.exe"; else/*from w ww .ja va2 s .c om*/ emulator += "emulator"; CommandLine cmdLine = new CommandLine(emulator); // If the Windows path has spaces, we don't even want to deal with it // will ignore parameters, known issue if (getOperatingSystem().startsWith("windows")) { cmdLine.addArgument("@" + deviceName.toLowerCase().replace(".avd", "")); cmdLine.addArgument("-scale"); if (Config.getAndroidEmulatorScreenSize() == 0) cmdLine.addArgument("1"); else if (Config.getAndroidEmulatorScreenSize() > 3) cmdLine.addArgument("3"); else cmdLine.addArgument(Integer.toString(Config.getAndroidEmulatorScreenSize())); } else { cmdLine.addArgument("-avd", false); cmdLine.addArgument(deviceName.toLowerCase().replace(".avd", ""), false); cmdLine.addArgument("-scale"); if (Config.getAndroidEmulatorScreenSize() < 1) cmdLine.addArgument("1"); else if (Config.getAndroidEmulatorScreenSize() > 3) cmdLine.addArgument("3"); else cmdLine.addArgument(Integer.toString(Config.getAndroidEmulatorScreenSize())); } if (!(settings.get("proxy_host").equals("") || settings.get("proxy_port").equals(""))) { cmdLine.addArgument("-http-proxy"); cmdLine.addArgument("http://" + settings.get("proxy_host") + ":" + settings.get("proxy_port")); } ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(stdout); DefaultExecutor executor = new DefaultExecutor(); try { executor.setStreamHandler(psh); executor.execute(cmdLine); return Constants.SUCCESS; } catch (ExecuteException e) { return stdout.toString(); } catch (IOException e) { return Constants.INVALID_SDK_PATH; } }
From source file:org.owasp.goatdroid.gui.emulator.EmulatorWorker.java
static public String pushAppOntoDevice(String appPath) { ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(stdout); CommandLine cmdLine = new CommandLine(sdkPath + getSlash() + "platform-tools" + getSlash() + "adb"); cmdLine.addArgument("install"); cmdLine.addArgument(appPath, false); DefaultExecutor executor = new DefaultExecutor(); try {/*from w w w . j a v a 2 s. c o m*/ executor.setStreamHandler(psh); executor.execute(cmdLine); return stdout.toString(); } catch (ExecuteException e) { return Constants.UNEXPECTED_ERROR; } catch (IOException e) { return Constants.UNEXPECTED_ERROR; } }
From source file:org.owasp.goatdroid.gui.emulator.EmulatorWorker.java
static public String pushAppOntoDevice(String appPath, String deviceSerial) { ByteArrayOutputStream stdout = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(stdout); CommandLine cmdLine = new CommandLine(sdkPath + getSlash() + "platform-tools" + getSlash() + "adb"); Map<String, String> map = new HashMap<String, String>(); map.put("deviceSerial", deviceSerial); cmdLine.addArgument("-s", false); cmdLine.addArgument("${deviceSerial}", false); cmdLine.addArgument("install", false); cmdLine.addArgument(appPath, false); cmdLine.setSubstitutionMap(map);/* www . j ava 2 s. co m*/ DefaultExecutor executor = new DefaultExecutor(); try { executor.setStreamHandler(psh); executor.execute(cmdLine); return stdout.toString(); } catch (ExecuteException e) { return Constants.UNEXPECTED_ERROR; } catch (IOException e) { return Constants.UNEXPECTED_ERROR; } }
From source file:org.rbr8.script_runner.util.BatchScriptRunner.java
public void processFile(File file) throws IOException { CommandLine cmdLine = new CommandLine(executable); cmdLine.addArguments(arguments);//from w ww .j av a2 s . com Map<String, Object> map = new HashMap<>(); map.put(SubstitutionHelper.FILE, file); cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); // executor.setExitValue(1); // NotifierLogOutputStream outputLog = new NotifierLogOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(logOutputStream); executor.setStreamHandler(psh); // ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); // executor.setWatchdog(watchdog); int exitValue = executor.execute(cmdLine); }
From source file:org.sakuli.actions.environment.CommandLineUtil.java
static public CommandLineResult runCommand(String command, boolean throwException) throws SakuliException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream error = new ByteArrayOutputStream(); CommandLineResult result = new CommandLineResult(); try {// w w w . j av a 2 s. co m DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(outputStream, error)); int exitCode = executor.execute(CommandLine.parse(command)); result.setExitCode(exitCode); result.setOutput(error.toString() + outputStream.toString()); } catch (Exception e) { if (throwException) { throw new SakuliException(e, String.format("Error during execution of command '%s': %s", command, error.toString())); } result.setExitCode(resolveExitCode(e.getMessage())); result.setOutput(e.getMessage()); } return result; }