use of org.codelibs.fess.exception.CommandExecutionException in project fess by codelibs.
the class CommandChain method executeCommand.
protected int executeCommand(final String[] commands, final String username, final String password) {
if (commands == null || commands.length == 0) {
throw new CommandExecutionException("command is empty.");
}
if (logger.isInfoEnabled()) {
logger.info("Command: " + String.join(" ", commands));
}
final String[] cmds = stream(commands).get(stream -> stream.map(s -> {
if ("$USERNAME".equals(s)) {
return username;
} else if ("$PASSWORD".equals(s)) {
return password;
} else {
return s;
}
}).toArray(n -> new String[n]));
final ProcessBuilder pb = new ProcessBuilder(cmds);
if (workingDirectory != null) {
pb.directory(workingDirectory);
}
pb.redirectErrorStream(true);
Process currentProcess = null;
MonitorThread mt = null;
try {
currentProcess = pb.start();
// monitoring
mt = new MonitorThread(currentProcess, executionTimeout);
mt.start();
final InputStreamThread it = new InputStreamThread(currentProcess.getInputStream(), commandOutputEncoding, maxOutputLine);
it.start();
currentProcess.waitFor();
it.join(5000);
if (mt.isTeminated()) {
throw new CommandExecutionException("The command execution is timeout: " + String.join(" ", commands));
}
final int exitValue = currentProcess.exitValue();
if (logger.isInfoEnabled()) {
logger.info("Exit Code: " + exitValue + " - Process Output:\n" + it.getOutput());
}
if (exitValue == 143 && mt.isTeminated()) {
throw new CommandExecutionException("The command execution is timeout: " + String.join(" ", commands));
}
return exitValue;
} catch (final CrawlerSystemException e) {
throw e;
} catch (final InterruptedException e) {
if (mt != null && mt.isTeminated()) {
throw new CommandExecutionException("The command execution is timeout: " + String.join(" ", commands), e);
}
throw new CommandExecutionException("Process terminated.", e);
} catch (final Exception e) {
throw new CommandExecutionException("Process terminated.", e);
} finally {
if (mt != null) {
mt.setFinished(true);
try {
mt.interrupt();
} catch (final Exception e) {
// ignore
}
}
if (currentProcess != null) {
try {
currentProcess.destroy();
} catch (final Exception e) {
// ignore
}
}
currentProcess = null;
}
}
Aggregations