Java Magazine, Sept/Oct 2016
ORACLE COM JAVAMAGAZINE SEPTEMBER OCTOBER 2016 40 enterprise java @ Path events examples @ Singleton public class EventsResource @ Inject SseContext sseContext private SseBroadcaster sseBroadcaster private int lastEventId private List String messages new ArrayList see methods initSse itemEvents newMessage and createEvent below The EventsResource class is a singleton Enterprise JavaBean EJB It contains the SseBroadcaster which is connected to all clients SseContext is an injectable context object responsible for creating SSE broadcasters outputs and events The messages represent the history of all created messages The sseBroadcaster is initialized and enhanced with optional SseBroadcaster Listeners in the @ PostConstruct method @ PostConstruct public void initSse sseBroadcaster sseContext newBroadcaster sseBroadcaster register new SseBroadcaster Listener @ Override public void onException SseEventOutput output Exception exception @ Override public void onClose SseEventOutput output The clients connect against the following JAX RS resource @ GET @ Produces MediaType SERVER_ SENT_ EVENTS @ Lock LockType READ public SseEventOutput itemEvents @ HeaderParam HttpHeaders LAST_ EVENT_ ID_ HEADER @ DefaultValue 1 int lastEventId final SseEventOutput eventOutput sseContext newOutput if sseBroadcaster register eventOutput try to make the client reconnect after 5 seconds throw new ServiceUnavailableException 5L if lastEventId 0 replay messages try for int i lastEventId i messages size i eventOutput write createEvent messages get i i 1 catch IOException e throw new InternalServerErrorException Could not replay messages e
You must have JavaScript enabled to view digital editions.