use of org.apache.commons.exec.DefaultExecuteResultHandler in project smarthome by eclipse.
the class ExecUtil method executeCommandLineAndWaitResponse.
/**
* <p>
* Executes <code>commandLine</code>. Sometimes (especially observed on MacOS) the commandLine isn't executed
* properly. In that cases another exec-method is to be used. To accomplish this please use the special delimiter '
* <code>@@</code>'. If <code>commandLine</code> contains this delimiter it is split into a String[] array and the
* special exec-method is used.
*
* <p>
* A possible {@link IOException} gets logged but no further processing is done.
*
* @param commandLine the command line to execute
* @param timeout timeout for execution in milliseconds
* @return response data from executed command line
*/
public static String executeCommandLineAndWaitResponse(String commandLine, int timeout) {
String retval = null;
CommandLine cmdLine = null;
if (commandLine.contains(CMD_LINE_DELIMITER)) {
String[] cmdArray = commandLine.split(CMD_LINE_DELIMITER);
cmdLine = new CommandLine(cmdArray[0]);
for (int i = 1; i < cmdArray.length; i++) {
cmdLine.addArgument(cmdArray[i], false);
}
} else {
cmdLine = CommandLine.parse(commandLine);
}
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
Executor executor = new DefaultExecutor();
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(stdout);
executor.setExitValues(null);
executor.setStreamHandler(streamHandler);
executor.setWatchdog(watchdog);
try {
executor.execute(cmdLine, resultHandler);
logger.debug("executed commandLine '{}'", commandLine);
} catch (ExecuteException e) {
logger.warn("couldn't execute commandLine '{}'", commandLine, e);
} catch (IOException e) {
logger.warn("couldn't execute commandLine '{}'", commandLine, e);
}
// can safely request the exit code
try {
resultHandler.waitFor();
int exitCode = resultHandler.getExitValue();
retval = StringUtils.chomp(stdout.toString());
if (resultHandler.getException() != null) {
logger.warn("{}", resultHandler.getException().getMessage());
} else {
logger.debug("exit code '{}', result '{}'", exitCode, retval);
}
} catch (InterruptedException e) {
logger.warn("Timeout occurred when executing commandLine '{}'", commandLine, e);
}
return retval;
}
Aggregations