public void sse(@PathVariable("beanName") String beanName, @PathVariable("method") String method,
HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
MethodInfo methodInfo = MethodInfoCache.INSTANCE.get(beanName, method);
SSEvent result = null;
if (methodInfo != null) {
try {
Object[] parameters = prepareParameters(request, response, locale, methodInfo);
Object methodReturnValue = null;
if (configuration.isSynchronizeOnSession() || methodInfo.isSynchronizeOnSession()) {
HttpSession session = request.getSession(false);
if (session != null) {
Object mutex = WebUtils.getSessionMutex(session);
synchronized (mutex) {
methodReturnValue = ExtDirectSpringUtil.invoke(context, beanName, methodInfo, parameters);
}
} else {
methodReturnValue = ExtDirectSpringUtil.invoke(context, beanName, methodInfo, parameters);
}
} else {
methodReturnValue = ExtDirectSpringUtil.invoke(context, beanName, methodInfo, parameters);
}
if (methodReturnValue instanceof SSEvent) {
result = (SSEvent) methodReturnValue;
} else {
result = new SSEvent();
if (methodReturnValue != null) {
result.setData(methodReturnValue.toString());
}
}
} catch (Exception e) {
log.error("Error polling method '" + beanName + "." + method + "'", e.getCause() != null ? e.getCause()
: e);
Throwable cause;
if (e.getCause() != null) {
cause = e.getCause();
} else {
cause = e;
}
result = new SSEvent();
result.setEvent("error");
result.setData(configuration.getMessage(cause));
if (configuration.isSendStacktrace()) {
result.setComment(ExtDirectSpringUtil.getStackTrace(cause));
}
}
} else {
log.error("Error invoking method '" + beanName + "." + method + "'. Method or Bean not found");
result = new SSEvent();
result.setEvent("error");
result.setData(configuration.getDefaultExceptionMessage());
if (configuration.isSendStacktrace()) {
result.setComment("Bean or Method '" + beanName + "." + method + "' not found");
}
}
response.setContentType(EVENT_STREAM.toString());
response.setCharacterEncoding(EVENT_STREAM.getCharSet().name());
StringBuilder sb = new StringBuilder(32);
if (StringUtils.hasText(result.getComment())) {
for (String line : result.getComment().split("\\r?\\n|\\r")) {
sb.append(":").append(line).append("\n");
}
}
if (StringUtils.hasText(result.getId())) {
sb.append("id:").append(result.getId()).append("\n");
}
if (StringUtils.hasText(result.getEvent())) {
sb.append("event:").append(result.getEvent()).append("\n");
}
if (StringUtils.hasText(result.getData())) {
for (String line : result.getData().split("\\r?\\n|\\r")) {
sb.append("data:").append(line).append("\n");
}
}
if (result.getRetry() != null) {
sb.append("retry:").append(result.getRetry()).append("\n");
}
sb.append("\n");
FileCopyUtils.copy(sb.toString().getBytes(UTF8_CHARSET), response.getOutputStream());
}