use of io.undertow.server.handlers.sse.ServerSentEventHandler in project undertow by undertow-io.
the class ServerSentEventsServer method main.
public static void main(final String[] args) {
final ServerSentEventHandler sseHandler = serverSentEvents();
HttpHandler chatHandler = new HttpHandler() {
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
new StringReadChannelListener(exchange.getConnection().getByteBufferPool()) {
@Override
protected void stringDone(String string) {
for (ServerSentEventConnection h : sseHandler.getConnections()) {
h.send(string);
}
}
@Override
protected void error(IOException e) {
}
}.setup(exchange.getRequestChannel());
}
};
Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(path().addPrefixPath("/sse", sseHandler).addPrefixPath("/send", chatHandler).addPrefixPath("/", resource(new ClassPathResourceManager(ServerSentEventsServer.class.getClassLoader(), ServerSentEventsServer.class.getPackage())).addWelcomeFiles("index.html"))).build();
server.start();
}
use of io.undertow.server.handlers.sse.ServerSentEventHandler 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