List of usage examples for org.apache.commons.exec DefaultExecutor setStreamHandler
public void setStreamHandler(final ExecuteStreamHandler streamHandler)
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);/* w w w . j a 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 www . j a v a2 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; } }
From source file:nl.tudelft.graphalytics.graphlab.GraphLabPlatform.java
/** * Execute the python script belonging to a given AlgorithmType with the given graph location and extra arguments * and return the Process created by the Java Runtime. * @param job The GraphLab job to execute * @return The exit code of the python subprocess * @throws IOException When an I/O error occurs *///from ww w.j a va 2s. c o m private int executePythonJob(GraphLabJob job) throws IOException { LOG.entry(job); if (job == null) { LOG.warn("GraphLab job set to execute is null, skipping execution."); return LOG.exit(-1); } // Extract the script resource file File scriptFile = extractFile(job.getPythonFile()); if (scriptFile == null) { return LOG.exit(-1); } // Construct the commandline execution pattern starting with the python executable CommandLine commandLine = new CommandLine("python2"); // Add the arguments that are the same for all jobs commandLine.addArgument(scriptFile.getAbsolutePath()); commandLine.addArgument("--target"); commandLine.addArgument(TARGET); if (USE_HADOOP) { commandLine.addArgument("--virtual-cores"); commandLine.addArgument(VIRTUAL_CORES, false); commandLine.addArgument("--heap-size"); commandLine.addArgument(HEAP_SIZE, false); } // Add the save_graph_result parameter is true (default false, but can be set to true for automated testing) if (saveGraphResult) { commandLine.addArgument("--save-result"); } // Let the job format it's arguments and add it to the commandline commandLine.addArguments(job.formatParametersAsStrings(), false); // 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)); int result; try { // Execute the actual command and store the return code result = executor.execute(commandLine); // Print the command output System.out.println(outputStream.toString()); } catch (ExecuteException e) { // Catch the exception thrown when the process exits with result != 0 System.out.println(outputStream.toString()); LOG.catching(Level.ERROR, e); return LOG.exit(e.getExitValue()); } return LOG.exit(result); }
From source file:org.apache.camel.component.exec.impl.DefaultExecCommandExecutor.java
public ExecResult execute(ExecCommand command) { notNull(command, "command"); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); DefaultExecutor executor = prepareDefaultExecutor(command); // handle error and output of the process and write them to the given // out stream PumpStreamHandler handler = new PumpStreamHandler(out, err, command.getInput()); executor.setStreamHandler(handler); CommandLine cl = toCommandLine(command); try {/*from w w w . j a v a 2 s . c o m*/ int exitValue = executor.execute(cl); // if the size is zero, we have no output, so construct the result // with null (required by ExecResult) InputStream stdout = out.size() == 0 ? null : new ByteArrayInputStream(out.toByteArray()); InputStream stderr = err.size() == 0 ? null : new ByteArrayInputStream(err.toByteArray()); ExecResult result = new ExecResult(command, stdout, stderr, exitValue); return result; } catch (ExecuteException ee) { LOG.error("ExecException while executing command: " + command.toString() + " - " + ee.getMessage()); throw new ExecException("Failed to execute command " + command, ee); } catch (IOException ioe) { // invalid working dir LOG.error("IOException while executing command: " + command.toString() + " - " + ioe.getMessage()); throw new ExecException("Unable to execute command " + command, ioe); } finally { // the inputStream must be closed after the execution IOUtils.closeQuietly(command.getInput()); } }
From source file:org.apache.falcon.regression.core.util.ExecUtil.java
public static ExecResult executeCommand(CommandLine commandLine) { LOGGER.info("Command to be executed: " + commandLine); DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(new ExecuteWatchdog(5 * 1000)); //timeout of 5 seconds final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); final ByteArrayOutputStream errStream = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(outStream, errStream)); int exitVal = 1; String exception = ""; try {/*ww w. j a va2s.c o m*/ exitVal = executor.execute(commandLine); } catch (IOException e) { LOGGER.warn("Caught exception: " + e); exception = e.toString(); } final String output = outStream.toString(); String errors = errStream.toString(); errors = errors.isEmpty() ? exception : errors; LOGGER.info("exitVal: " + exitVal); LOGGER.info("output: " + output); LOGGER.info("errors: " + errors); return new ExecResult(commandLine, exitVal, output.trim(), errors.trim()); }
From source file:org.apache.hcatalog.templeton.ExecServiceImpl.java
private ExecBean auxRun(String program, List<String> args, Map<String, String> env) throws NotAuthorizedException, ExecuteException, IOException { DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(null);//from ww w .j a v a 2 s. c o m // Setup stdout and stderr int nbytes = appConf.getInt(AppConfig.EXEC_MAX_BYTES_NAME, -1); ByteArrayOutputStream outStream = new MaxByteArrayOutputStream(nbytes); ByteArrayOutputStream errStream = new MaxByteArrayOutputStream(nbytes); executor.setStreamHandler(new PumpStreamHandler(outStream, errStream)); // Only run for N milliseconds int timeout = appConf.getInt(AppConfig.EXEC_TIMEOUT_NAME, 0); ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog); CommandLine cmd = makeCommandLine(program, args); LOG.info("Running: " + cmd); ExecBean res = new ExecBean(); res.exitcode = executor.execute(cmd, execEnv(env)); String enc = appConf.get(AppConfig.EXEC_ENCODING_NAME); res.stdout = outStream.toString(enc); res.stderr = errStream.toString(enc); return res; }
From source file:org.apache.hive.hcatalog.templeton.StreamOutputWriter.java
private ExecBean auxRun(String program, List<String> args, Map<String, String> env) throws NotAuthorizedException, ExecuteException, IOException { DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(null);/*from w w w . j av a2s. c om*/ // Setup stdout and stderr int nbytes = appConf.getInt(AppConfig.EXEC_MAX_BYTES_NAME, -1); ByteArrayOutputStream outStream = new MaxByteArrayOutputStream(nbytes); ByteArrayOutputStream errStream = new MaxByteArrayOutputStream(nbytes); executor.setStreamHandler(new PumpStreamHandler(outStream, errStream)); // Only run for N milliseconds int timeout = appConf.getInt(AppConfig.EXEC_TIMEOUT_NAME, 0); ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog); CommandLine cmd = makeCommandLine(program, args); LOG.info("Running: " + cmd); ExecBean res = new ExecBean(); res.exitcode = executor.execute(cmd, execEnv(env)); String enc = appConf.get(AppConfig.EXEC_ENCODING_NAME); res.stdout = outStream.toString(enc); res.stderr = errStream.toString(enc); try { watchdog.checkException(); } catch (Exception ex) { LOG.error("Command: " + cmd + " failed. res=" + res, ex); } if (watchdog.killedProcess()) { String msg = " was terminated due to timeout(" + timeout + "ms). See " + AppConfig.EXEC_TIMEOUT_NAME + " property"; LOG.warn("Command: " + cmd + msg + " res=" + res); res.stderr += " Command " + msg; } if (res.exitcode != 0) { LOG.info("Command: " + cmd + " failed. res=" + res); } return res; }
From source file:org.apache.karaf.decanter.collector.system.SystemCollector.java
@Override public void run() { if (properties != null) { String karafName = System.getProperty("karaf.name"); String hostAddress = null; String hostName = null;// w w w .j av a 2s . c om try { hostAddress = InetAddress.getLocalHost().getHostAddress(); hostName = InetAddress.getLocalHost().getHostName(); } catch (Exception e) { // nothing to do } Enumeration<String> keys = properties.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); try { if (key.startsWith("command.")) { HashMap<String, Object> data = new HashMap<>(); String command = (String) properties.get(key); LOGGER.debug("Executing {} ({})", command, key); CommandLine cmdLine = CommandLine.parse(command); DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); data.put("timestamp", System.currentTimeMillis()); data.put("type", "system"); data.put("karafName", karafName); data.put("hostAddress", hostAddress); data.put("hostName", hostName); executor.execute(cmdLine); outputStream.flush(); String output = outputStream.toString(); if (output.endsWith("\n")) { output = output.substring(0, output.length() - 1); } // try to convert to number try { if (output.contains(".")) { Double value = Double.parseDouble(output); data.put(key, value); } else { Integer value = Integer.parseInt(output); data.put(key, value); } } catch (NumberFormatException e) { data.put(key, outputStream.toString()); } streamHandler.stop(); Event event = new Event("decanter/collect/system/" + key.replace(".", "_"), data); eventAdmin.postEvent(event); try { outputStream.close(); } catch (Exception e) { // nothing to do } } } catch (Exception e) { LOGGER.warn("Command {} execution failed", key, e); } } } }
From source file:org.apache.stratos.cartridge.agent.test.JavaCartridgeAgentTest.java
/** * Execute shell command//from w w w .j av a2 s .co m * * @param commandText */ private ByteArrayOutputStreamLocal executeCommand(final String commandText, File workingDir) { final ByteArrayOutputStreamLocal outputStream = new ByteArrayOutputStreamLocal(); try { CommandLine commandline = CommandLine.parse(commandText); DefaultExecutor exec = new DefaultExecutor(); if (workingDir != null) { exec.setWorkingDirectory(workingDir); } PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT); exec.setWatchdog(watchdog); log.info("Executing command: " + commandText + (workingDir == null ? "" : " at " + workingDir.getCanonicalPath())); exec.execute(commandline, new ExecuteResultHandler() { @Override public void onProcessComplete(int i) { log.info(commandText + " process completed"); } @Override public void onProcessFailed(ExecuteException e) { log.error(commandText + " process failed", e); } }); executorList.put(commandText, exec); return outputStream; } catch (Exception e) { log.error(outputStream.toString(), e); throw new RuntimeException(e); } }
From source file:org.apache.stratos.integration.tests.SampleApplicationsTest.java
/** * Execute shell command/*w w w.j ava 2 s .c o m*/ * @param commandText */ private void executeCommand(String commandText) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { CommandLine commandline = CommandLine.parse(commandText); DefaultExecutor exec = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); exec.execute(commandline); log.info(outputStream.toString()); } catch (Exception e) { log.error(outputStream.toString(), e); throw new RuntimeException(e); } }