List of usage examples for org.apache.commons.exec CommandLine addArgument
public CommandLine addArgument(final String argument)
From source file:org.opennms.netmgt.integrations.R.RScriptExecutor.java
/** * Executes by given script by:/* ww w .j av a 2s.c om*/ * - Searching both the classpath and the filesystem for the path * - Copying the script at the given path to a temporary file and * performing variable substitution with the arguments using Freemarker. * - Invoking the script with commons-exec * - Converting the input table to CSV and passing this to the process via stdin * - Parsing stdout, expecting CSV output, and converting this to an immutable table */ public RScriptOutput exec(String script, RScriptInput input) throws RScriptException { Preconditions.checkNotNull(script, "script argument"); Preconditions.checkNotNull(input, "input argument"); // Grab the script/template Template template; try { template = m_freemarkerConfiguration.getTemplate(script); } catch (IOException e) { throw new RScriptException("Failed to read the script.", e); } // Create a temporary file File scriptOnDisk; try { scriptOnDisk = File.createTempFile("Rcsript", "R"); scriptOnDisk.deleteOnExit(); } catch (IOException e) { throw new RScriptException("Failed to create a temporary file.", e); } // Perform variable substitution and write the results to the temporary file try (FileOutputStream fos = new FileOutputStream(scriptOnDisk); Writer out = new OutputStreamWriter(fos);) { template.process(input.getArguments(), out); } catch (IOException | TemplateException e) { scriptOnDisk.delete(); throw new RScriptException("Failed to process the template.", e); } // Convert the input matrix to a CSV string which will be passed to the script via stdin. // The table may be large, so we try and avoid writing it to disk StringBuilder inputTableAsCsv; try { inputTableAsCsv = toCsv(input.getTable()); } catch (IOException e) { scriptOnDisk.delete(); throw new RScriptException("Failed to convert the input table to CSV.", e); } // Invoke Rscript against the script (located in a temporary file) CommandLine cmdLine = new CommandLine(RSCRIPT_BINARY); cmdLine.addArgument(scriptOnDisk.getAbsolutePath()); // Use commons-exec to execute the process DefaultExecutor executor = new DefaultExecutor(); // Use the CharSequenceInputStream in order to avoid explicitly converting // the StringBuilder a string and then an array of bytes. InputStream stdin = new CharSequenceInputStream(inputTableAsCsv, Charset.forName("UTF-8")); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, stdin)); // Fail if we get a non-zero exit code executor.setExitValue(0); // Fail if the process takes too long ExecuteWatchdog watchdog = new ExecuteWatchdog(SCRIPT_TIMEOUT_MS); executor.setWatchdog(watchdog); // Execute try { executor.execute(cmdLine); } catch (IOException e) { scriptOnDisk.delete(); throw new RScriptException("An error occured while executing Rscript, or the requested script.", inputTableAsCsv.toString(), stderr.toString(), stdout.toString(), e); } // Parse and return the results try { ImmutableTable<Long, String, Double> table = fromCsv(stdout.toString()); return new RScriptOutput(table); } catch (Throwable t) { throw new RScriptException("Failed to parse the script's output.", inputTableAsCsv.toString(), stderr.toString(), stdout.toString(), t); } finally { scriptOnDisk.delete(); } }
From source file:org.opennms.netmgt.measurements.impl.RrdtoolXportFetchStrategy.java
/** * {@inheritDoc}//ww w . j av a 2 s . co m */ @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, Utils.escapeColons(rrdFile), Utils.escapeColons(source.getEffectiveDataSource()), 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 { LOG.debug("Executing: {}", cmdLine); 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 xportStartInMs = rrdXport.getMeta().getStart() * 1000; final long xportStepInMs = rrdXport.getMeta().getStep() * 1000; 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()) { // Derive the timestamp from the start and step since newer versions // of rrdtool no longer include it as part of the rows timestamps[i] = xportStartInMs + xportStepInMs * i; 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, xportStepInMs, constants); }
From source file:org.opennms.web.rest.measurements.fetch.RrdtoolXportFetchStrategy.java
/** * {@inheritDoc}/*from ww w . j ava 2 s . com*/ */ @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.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// w ww . ja v a2s. co m 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 {/* www . j a va2 s . co 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.sculptor.maven.plugin.GraphvizMojo.java
/** * Builds command line for starting the <code>dot</code>. * /* ww w. j a v a2s. c o m*/ * @param generatedFiles * list of generated files from the * {@link AbstractGeneratorMojo#statusFile} */ protected CommandLine getDotCommandLine(Set<String> generatedFiles) throws MojoExecutionException { CommandLine cl = new CommandLine(command); if (isVerbose()) { cl.addArgument("-v"); } cl.addArgument("-Tpng"); cl.addArgument("-O"); for (String generatedFile : generatedFiles) { if (generatedFile.endsWith(".dot")) { cl.addArgument(generatedFile); } } if (isVerbose()) { getLog().info("Commandline: " + cl); } return cl; }
From source file:org.silverpeas.core.io.media.video.ffmpeg.FFmpegToolManager.java
@Override public void init() throws Exception { // SwfTools settings for (final Map.Entry<String, String> entry : System.getenv().entrySet()) { if ("path".equals(entry.getKey().toLowerCase())) { try { CommandLine commandLine = new CommandLine("ffmpeg"); commandLine.addArgument("-version"); ExternalExecution.exec(commandLine, Config.init().doNotDisplayErrorTrace()); isActivated = true;// w ww . j a va 2 s.co m } catch (final Exception e) { // FFmpeg is not installed System.err.println("ffmpeg is not installed"); } } } }
From source file:org.silverpeas.core.viewer.service.JsonPdfToolManager.java
@Override public void init() throws Exception { // pdf2json settings for (final Map.Entry<String, String> entry : System.getenv().entrySet()) { if ("path".equals(entry.getKey().toLowerCase())) { try { CommandLine commandLine = new CommandLine("pdf2json"); commandLine.addArgument("-v"); ExternalExecution.exec(commandLine, Config.init().successfulExitStatusValueIs(1).doNotDisplayErrorTrace()); isActivated = true;/*from w w w . ja v a 2 s .c om*/ } catch (final Exception e) { // pdf2json is not installed System.err.println("pdf2json is not installed"); } } } }
From source file:org.silverpeas.core.viewer.service.SwfToolManager.java
@Override public synchronized void init() { // SwfTools settings for (final Map.Entry<String, String> entry : System.getenv().entrySet()) { if ("path".equalsIgnoreCase(entry.getKey())) { try { CommandLine commandLine = new CommandLine("pdf2swf"); commandLine.addArgument("--version"); ExternalExecution.exec(commandLine, Config.init().doNotDisplayErrorTrace()); isActivated = true;//from w w w . ja v a 2s . c o m } catch (final Exception e) { // SwfTool is not installed SilverLogger.getLogger(this).warn("pdf2swf is not installed"); } } } }
From source file:org.silverpeas.viewer.util.SwfUtil.java
static CommandLine buildPdfDocumentInfoCommandLine(File file) { Map<String, File> files = new HashMap<String, File>(1); files.put("file", file); CommandLine commandLine = new CommandLine("pdf2swf"); commandLine.addArgument("-qq"); commandLine.addArgument("${file}", false); commandLine.addArgument("--info"); commandLine.setSubstitutionMap(files); return commandLine; }