use of org.apache.camel.component.exec.ExecResult in project camel by apache.
the class DefaultExecCommandExecutor method execute.
@Override
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 {
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());
InputStream stdout = out.size() == 0 ? null : new ByteArrayInputStream(out.toByteArray());
InputStream stderr = err.size() == 0 ? null : new ByteArrayInputStream(err.toByteArray());
throw new ExecException("Failed to execute command " + command, stdout, stderr, ee.getExitValue(), ee);
} catch (IOException ioe) {
InputStream stdout = out.size() == 0 ? null : new ByteArrayInputStream(out.toByteArray());
InputStream stderr = err.size() == 0 ? null : new ByteArrayInputStream(err.toByteArray());
// use 0 as exit value as the executor didn't return the value
int exitValue = 0;
if (executor instanceof ExecDefaultExecutor) {
// get the exit value from the executor as it captures this to work around the common-exec bug
exitValue = ((ExecDefaultExecutor) executor).getExitValue();
}
// workaround to ignore if the stream was already closes due some race condition in commons-exec
String msg = ioe.getMessage();
if (msg != null && "stream closed".equals(msg.toLowerCase(Locale.ENGLISH))) {
LOG.debug("Ignoring Stream closed IOException", ioe);
ExecResult result = new ExecResult(command, stdout, stderr, exitValue);
return result;
}
// invalid working dir
LOG.error("IOException while executing command: " + command.toString() + " - " + ioe.getMessage());
throw new ExecException("Unable to execute command " + command, stdout, stderr, exitValue, ioe);
} finally {
// the inputStream must be closed after the execution
IOUtils.closeQuietly(command.getInput());
}
}
Aggregations