use of javax.servlet.ServletContextListener in project undertow by undertow-io.
the class ServerSentEventSCI method onStartup.
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
if (c == null || c.isEmpty()) {
return;
}
try {
final Map<String, ServerSentEventConnectionCallback> callbacks = new HashMap<>();
ServletContextImpl servletContext = (ServletContextImpl) ctx;
final List<InstanceHandle<?>> handles = new ArrayList<>();
for (Class<?> clazz : c) {
final ServerSentEvent annotation = clazz.getAnnotation(ServerSentEvent.class);
if (annotation == null) {
continue;
}
String path = annotation.value();
final InstanceHandle<?> instance = servletContext.getDeployment().getDeploymentInfo().getClassIntrospecter().createInstanceFactory(clazz).createInstance();
handles.add(instance);
callbacks.put(path, (ServerSentEventConnectionCallback) instance.getInstance());
}
if (callbacks.isEmpty()) {
return;
}
servletContext.getDeployment().getDeploymentInfo().addInnerHandlerChainWrapper(new HandlerWrapper() {
@Override
public HttpHandler wrap(HttpHandler handler) {
PathTemplateHandler pathTemplateHandler = new PathTemplateHandler(handler, false);
for (Map.Entry<String, ServerSentEventConnectionCallback> e : callbacks.entrySet()) {
pathTemplateHandler.add(e.getKey(), new ServerSentEventHandler(e.getValue()));
}
return pathTemplateHandler;
}
});
servletContext.addListener(new ServletContextListener() {
@Override
public void contextInitialized(ServletContextEvent sce) {
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
for (InstanceHandle<?> h : handles) {
h.release();
}
}
});
} catch (Exception e) {
throw new ServletException(e);
}
}
Aggregations