javax.ws.rs.sse.SseEventSink Java Examples
The following examples show how to use
javax.ws.rs.sse.SseEventSink.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServerSentEventResource.java From quarkus with Apache License 2.0 | 8 votes |
@GET @Path("/stream-xml") @SseElementType(MediaType.TEXT_XML) @Produces(MediaType.SERVER_SENT_EVENTS) public void sendXmlData(@Context SseEventSink sink) { // send a stream of few events try { for (int i = 0; i < 3; i++) { final OutboundSseEvent.Builder builder = this.sse.newEventBuilder(); builder.id(String.valueOf(i)).mediaType(MediaType.TEXT_XML_TYPE) .data("<settings><foo bar=\"" + i + "\"/></settings>") .name("stream of XML data"); sink.send(builder.build()); } } finally { sink.close(); } }
Example #2
Source File: PartyQueue.java From liberty-bikes with Eclipse Public License 1.0 | 7 votes |
public void add(String playerId, SseEventSink sink, Sse sse) { QueuedClient client = new QueuedClient(playerId, sink, sse); // If this client was already in the queue, remove them and add them at the end if (waitingPlayers.removeFirstOccurrence(client)) { party.log("Removed client " + playerId + " from queue before adding at end"); GameMetrics.counterDec(GameMetrics.currentQueuedPlayersCounter); } party.log("Adding client " + playerId + " into the queue in position " + client.queuePosition()); waitingPlayers.add(client); GameMetrics.counterInc(GameMetrics.currentQueuedPlayersCounter); if (party.getCurrentRound().isOpen()) promoteClients(); else client.notifyPosition(); }
Example #3
Source File: AsynchronousResources.java From servicetalk with Apache License 2.0 | 6 votes |
@Produces(SERVER_SENT_EVENTS) @Path("/sse/broadcast") @GET public void getSseBroadcast(@Context final SseEventSink eventSink, @Context final Sse sse) { eventSink.send(sse.newEvent("bar")); final SseBroadcaster sseBroadcaster = sse.newBroadcaster(); sseBroadcaster.register(eventSink); scheduleSseEventSend(new SseEmitter() { @Override public CompletionStage<?> emit(final OutboundSseEvent event) { return sseBroadcaster.broadcast(event); } @Override public void close() { sseBroadcaster.close(); } }, sse, Refs.of(0), ctx.executionContext().executor()); }
Example #4
Source File: BookStore.java From cxf with Apache License 2.0 | 6 votes |
@GET @Path("/titles/sse") @Produces(MediaType.SERVER_SENT_EVENTS) public void forBookTitlesOnly(@Context SseEventSink sink) { final Builder builder = sse.newEventBuilder(); CompletableFuture .runAsync(() -> { sink.send(createRawEvent(builder.name("book"), 1)); sink.send(createRawEvent(builder.name("book"), 2)); sink.send(createRawEvent(builder.name("book"), 3)); sink.send(createRawEvent(builder.name("book"), 4)); sink.send(createRawEvent(builder.name("book"), 5)); }) .whenComplete((r, ex) -> sink.close()); }
Example #5
Source File: BookStore.java From cxf with Apache License 2.0 | 6 votes |
@GET @Path("nodelay/sse/{id}") @Produces(MediaType.SERVER_SENT_EVENTS) public void forBookNoDelay(@Context SseEventSink sink, @PathParam("id") final String id) { final Builder builder = sse.newEventBuilder(); CompletableFuture .runAsync(() -> { sink.send(createEvent(builder.name("book"), 1)); sink.send(createEvent(builder.name("book"), 2)); sink.send(createEvent(builder.name("book"), 3)); sink.send(createEvent(builder.name("book"), 4)); sink.send(createEvent(builder.name("book"), 5)); }) .whenComplete((r, ex) -> sink.close()); }
Example #6
Source File: ServerSentEventsResource.java From Java-EE-8-Sampler with MIT License | 6 votes |
@POST @Path("progress/{report_id}") @Produces(MediaType.SERVER_SENT_EVENTS) public void eventStream(@PathParam("report_id") final String id, @Context SseEventSink es, @Context Sse sse) { executorService.execute(() -> { try { eventSink.send(sse.newEventBuilder().name("report-progress") .data(String.class, "Commencing process for report " + id + " ...").build()); es.send(sse.newEvent("Progress", "25%")); Thread.sleep(500); es.send(sse.newEvent("Progress", "50%")); Thread.sleep(500); es.send(sse.newEvent("Progress", "75%")); } catch (InterruptedException e) { e.printStackTrace(); } }); }
Example #7
Source File: ServerSentEventsResource.java From Java-EE-8-Sampler with MIT License | 6 votes |
@POST @Path("domains/{id}") @Produces(MediaType.SERVER_SENT_EVENTS) public void startDomain(@PathParam("id") final String id, @Context SseEventSink eventSink) { executorService.submit(() -> { try { eventSink.send(sse.newEventBuilder().name("domain-progress").data(String.class, "starting domain " + id + " ...").build()); Thread.sleep(200); eventSink.send(sse.newEvent("domain-progress", "50%")); Thread.sleep(200); eventSink.send(sse.newEvent("domain-progress", "60%")); Thread.sleep(200); eventSink.send(sse.newEvent("domain-progress", "70%")); Thread.sleep(200); eventSink.send(sse.newEvent("domain-progress", "99%")); Thread.sleep(200); eventSink.send(sse.newEvent("domain-progress", "Done.")); eventSink.close(); } catch (final InterruptedException e) { e.printStackTrace(); } }); }
Example #8
Source File: BookStore2.java From cxf with Apache License 2.0 | 6 votes |
@GET @Path("/titles/sse") @Produces(MediaType.SERVER_SENT_EVENTS) public void forBookTitlesOnly(@Context SseEventSink sink) { final Builder builder = sse.newEventBuilder(); CompletableFuture .runAsync(() -> { sink.send(createRawEvent(builder.name("book"), 1)); sink.send(createRawEvent(builder.name("book"), 2)); sink.send(createRawEvent(builder.name("book"), 3)); sink.send(createRawEvent(builder.name("book"), 4)); sink.send(createRawEvent(builder.name("book"), 5)); }) .whenComplete((r, ex) -> sink.close()); }
Example #9
Source File: SseEventSinkContextProvider.java From cxf with Apache License 2.0 | 6 votes |
@Override public SseEventSink createContext(Message message) { final HttpServletRequest request = (HttpServletRequest)message.get(AbstractHTTPDestination.HTTP_REQUEST); if (request == null) { throw new IllegalStateException("Unable to retrieve HTTP request from the context"); } final MessageBodyWriter<OutboundSseEvent> writer = new OutboundSseEventBodyWriter( ServerProviderFactory.getInstance(message), message.getExchange()); final AsyncResponse async = new AsyncResponseImpl(message); final Integer bufferSize = PropertyUtils.getInteger(message, SseEventSinkImpl.BUFFER_SIZE_PROPERTY); final SseEventSink sink = createSseEventSink(request, writer, async, bufferSize); message.put(SseEventSink.class, sink); return sink; }
Example #10
Source File: SseResource.java From openhab-core with Eclipse Public License 2.0 | 6 votes |
/** * Subscribes the connecting client for state updates. It will initially only send a "ready" event with an unique * connectionId that the client can use to dynamically alter the list of tracked items. * * @return {@link EventOutput} object associated with the incoming connection. */ @GET @Path("/states") @Produces(MediaType.SERVER_SENT_EVENTS) @ApiOperation(value = "Initiates a new item state tracker connection") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK") }) public void getStateEvents(@Context final SseEventSink sseEventSink, @Context final HttpServletResponse response) { final SseSinkItemInfo sinkItemInfo = new SseSinkItemInfo(); itemStatesBroadcaster.add(sseEventSink, sinkItemInfo); addCommonResponseHeaders(response); String connectionId = sinkItemInfo.getConnectionId(); OutboundSseEvent readyEvent = sse.newEventBuilder().id("0").name("ready").data(connectionId).build(); itemStatesBroadcaster.sendIf(readyEvent, hasConnectionId(connectionId)); }
Example #11
Source File: SseEventSinkContextProviderTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testCreateSseEventSinkWithDefaultBufferSize() { final SseEventSink sink = provider.createContext(message); IntStream .range(0, 10000) .mapToObj(i -> sink.send(EVENT)) .map(CompletionStage::toCompletableFuture) // At this point, buffer is full, but nothing has been delivered so far .forEach(f -> assertThat(f.isDone(), equalTo(false))); // The buffer overflow should trigger message rejection and exceptional completion final CompletableFuture<?> overflow = sink.send(EVENT).toCompletableFuture(); assertThat(overflow.isCompletedExceptionally(), equalTo(true)); exception.expect(CompletionException.class); exception.expectMessage("The buffer is full (10000), unable to queue SSE event for send."); overflow.join(); }
Example #12
Source File: SseEventSinkContextProviderTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testCreateSseEventSinkWithCustomBufferSize() { message.put(SseEventSinkImpl.BUFFER_SIZE_PROPERTY, 20000); final SseEventSink sink = provider.createContext(message); IntStream .range(0, 20000) .mapToObj(i -> sink.send(EVENT)) .map(CompletionStage::toCompletableFuture) // At this point, buffer is full, but nothing has been delivered so far .forEach(f -> assertThat(f.isDone(), equalTo(false))); // The buffer overflow should trigger message rejection and exceptional completion final CompletableFuture<?> overflow = sink.send(EVENT).toCompletableFuture(); assertThat(overflow.isCompletedExceptionally(), equalTo(true)); exception.expect(CompletionException.class); exception.expectMessage("The buffer is full (20000), unable to queue SSE event for send."); overflow.join(); }
Example #13
Source File: ServerSentEventResource.java From quarkus with Apache License 2.0 | 6 votes |
@GET @Path("/stream-html") @Produces(MediaType.SERVER_SENT_EVENTS) @SseElementType("text/html") public void sendHtmlData(@Context SseEventSink sink) { // send a stream of few events try { for (int i = 0; i < 3; i++) { final OutboundSseEvent.Builder builder = this.sse.newEventBuilder(); builder.id(String.valueOf(i)).mediaType(MediaType.TEXT_HTML_TYPE) .data("<html><body>" + i + "</body></html>") .name("stream of pages"); sink.send(builder.build()); } } finally { sink.close(); } }
Example #14
Source File: ServerSentEventResource.java From quarkus with Apache License 2.0 | 6 votes |
@GET @Path("/stream") @Produces(MediaType.SERVER_SENT_EVENTS) public void sendData(@Context SseEventSink sink) { // send a stream of few events try { for (int i = 0; i < 3; i++) { final OutboundSseEvent.Builder builder = this.sse.newEventBuilder(); builder.id(String.valueOf(i)).mediaType(MediaType.TEXT_PLAIN_TYPE) .data(Integer.class, i) .name("stream of numbers"); sink.send(builder.build()); } } finally { sink.close(); } }
Example #15
Source File: TestResourceForConstructorProperties.java From quarkus with Apache License 2.0 | 6 votes |
@GET @Path("/sse") @SseElementType(MediaType.APPLICATION_JSON) @Produces(MediaType.SERVER_SENT_EVENTS) public void serverSentEvents(@Context SseEventSink sink) { VanillaJavaImmutableData data = new VanillaJavaImmutableData("sse", "ssevalue"); try { OutboundSseEvent.Builder builder = sse.newEventBuilder(); builder.id(String.valueOf(1)) .mediaType(MediaType.APPLICATION_JSON_TYPE) .data(data) .name("stream of json data"); sink.send(builder.build()); } finally { sink.close(); } }
Example #16
Source File: SseResource.java From openhab-core with Eclipse Public License 2.0 | 6 votes |
@GET @Produces(MediaType.SERVER_SENT_EVENTS) @ApiOperation(value = "Get all events.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 400, message = "Topic is empty or contains invalid characters") }) public void listen(@Context final SseEventSink sseEventSink, @Context final HttpServletResponse response, @QueryParam("topics") @ApiParam(value = "topics") String eventFilter) { if (!SseUtil.isValidTopicFilter(eventFilter)) { response.setStatus(Status.BAD_REQUEST.getStatusCode()); return; } topicBroadcaster.add(sseEventSink, new SseSinkTopicInfo(eventFilter)); addCommonResponseHeaders(response); }
Example #17
Source File: RestSBControllerImplTest.java From onos with Apache License 2.0 | 6 votes |
@GET @Path("server-sent-events") @Produces(MediaType.SERVER_SENT_EVENTS) public void getServerSentEvents(@Context SseEventSink eventSink, @Context Sse sse) throws InterruptedException { new Thread(() -> { try { for (int i = 0; i < 10; i++) { // ... code that waits 0.1 second Thread.sleep(100L); final OutboundSseEvent event = sse.newEventBuilder() .id(String.valueOf(i)) .name("message-to-rest-sb") .data(String.class, "Test message " + i + "!") .build(); eventSink.send(event); System.out.println("Message " + i + " sent"); } } catch (InterruptedException e) { e.printStackTrace(); } }).start(); }
Example #18
Source File: BookStore2.java From cxf with Apache License 2.0 | 6 votes |
@GET @Path("nodelay/sse/{id}") @Produces(MediaType.SERVER_SENT_EVENTS) public void forBookNoDelay(@Context SseEventSink sink, @PathParam("id") final String id) { final Builder builder = sse.newEventBuilder(); CompletableFuture .runAsync(() -> { sink.send(createEvent(builder.name("book"), 1)); sink.send(createEvent(builder.name("book"), 2)); sink.send(createEvent(builder.name("book"), 3)); sink.send(createEvent(builder.name("book"), 4)); sink.send(createEvent(builder.name("book"), 5)); }) .whenComplete((r, ex) -> sink.close()); }
Example #19
Source File: AsynchronousResources.java From servicetalk with Apache License 2.0 | 6 votes |
@Produces(SERVER_SENT_EVENTS) @Path("/sse/stream") @GET public void getSseStream(@Context final SseEventSink eventSink, @Context final Sse sse) { scheduleSseEventSend(new SseEmitter() { @Override public CompletionStage<?> emit(final OutboundSseEvent event) { return eventSink.send(event); } @Override public void close() { eventSink.close(); } }, sse, Refs.of(0), ctx.executionContext().executor()); }
Example #20
Source File: SitemapResource.java From openhab-core with Eclipse Public License 2.0 | 5 votes |
/** * Subscribes the connecting client to the stream of sitemap events. * * @return {@link EventOutput} object associated with the incoming * connection. */ @GET @Path(SEGMENT_EVENTS + "/{subscriptionid: [a-zA-Z_0-9-]+}") @Produces(MediaType.SERVER_SENT_EVENTS) @ApiOperation(value = "Get sitemap events.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 400, message = "Page not linked to the subscription."), @ApiResponse(code = 404, message = "Subscription not found.") }) public void getSitemapEvents(@Context final SseEventSink sseEventSink, @Context final HttpServletResponse response, @PathParam("subscriptionid") @ApiParam(value = "subscription id") String subscriptionId, @QueryParam("sitemap") @ApiParam(value = "sitemap name") @Nullable String sitemapname, @QueryParam("pageid") @ApiParam(value = "page id") @Nullable String pageId) { final SseSinkInfo sinkInfo = knownSubscriptions.get(subscriptionId); if (sinkInfo == null) { logger.debug("Subscription id {} does not exist.", subscriptionId); response.setStatus(Status.NOT_FOUND.getStatusCode()); return; } if (sitemapname != null && pageId != null) { subscriptions.setPageId(subscriptionId, sitemapname, pageId); } if (subscriptions.getSitemapName(subscriptionId) == null || subscriptions.getPageId(subscriptionId) == null) { logger.debug("Subscription id {} is not yet linked to a sitemap/page.", subscriptionId); response.setStatus(Status.BAD_REQUEST.getStatusCode()); return; } logger.debug("Client from IP {} requested sitemap event stream for subscription {}.", request.getRemoteAddr(), subscriptionId); // Disables proxy buffering when using an nginx http server proxy for this response. // This allows you to not disable proxy buffering in nginx and still have working sse response.addHeader(X_ACCEL_BUFFERING_HEADER, "no"); broadcaster.add(sseEventSink, sinkInfo); }
Example #21
Source File: StatsRestServiceImpl.java From cxf with Apache License 2.0 | 5 votes |
@GET @Path("sse") @Produces(MediaType.SERVER_SENT_EVENTS) public void stats(@Context SseEventSink sink) { new Thread() { public void run() { try { final Builder builder = sse.newEventBuilder(); sink.send(createStatsEvent(builder.name("stats"), 1)); Thread.sleep(500); sink.send(createStatsEvent(builder.name("stats"), 2)); Thread.sleep(500); sink.send(createStatsEvent(builder.name("stats"), 3)); Thread.sleep(500); sink.send(createStatsEvent(builder.name("stats"), 4)); Thread.sleep(500); sink.send(createStatsEvent(builder.name("stats"), 5)); Thread.sleep(500); sink.send(createStatsEvent(builder.name("stats"), 6)); Thread.sleep(500); sink.send(createStatsEvent(builder.name("stats"), 7)); Thread.sleep(500); sink.send(createStatsEvent(builder.name("stats"), 8)); sink.close(); } catch (final Exception e) { e.printStackTrace(); } } }.start(); }
Example #22
Source File: EchoHeaders.java From tutorials with MIT License | 5 votes |
@GET @Path("/events") @Produces(MediaType.SERVER_SENT_EVENTS) public void getServerSentEvents(@Context SseEventSink eventSink, @Context Sse sse) { OutboundSseEvent event = sse.newEventBuilder() .name("echo-headers") .data(String.class, headers.getHeaderString(AddHeaderOnRequestFilter.FILTER_HEADER_KEY)) .build(); eventSink.send(event); }
Example #23
Source File: SseEventSinkContextProvider.java From cxf with Apache License 2.0 | 5 votes |
protected SseEventSink createSseEventSink(final HttpServletRequest request, final MessageBodyWriter<OutboundSseEvent> writer, final AsyncResponse async, final Integer bufferSize) { if (bufferSize != null) { return new SseEventSinkImpl(writer, async, request.getAsyncContext(), bufferSize); } else { return new SseEventSinkImpl(writer, async, request.getAsyncContext()); } }
Example #24
Source File: SseEndpoint.java From hammock with Apache License 2.0 | 5 votes |
@GET @Path("/{uuid}") @Produces(SERVER_SENT_EVENTS) public void doSseCall(@PathParam("uuid") String uuid, @Context SseEventSink sink, @Context Sse sse) { final OutboundSseEvent.Builder builder = sse.newEventBuilder(); OutboundSseEvent event = builder.id(uuid) .data(SseModel.class, new SseModel("some model "+uuid)) .build(); sink.send(event); sink.close(); }
Example #25
Source File: StatsRestServiceImpl.java From cxf with Apache License 2.0 | 5 votes |
@GET @Path("sse/{id}") @Produces(MediaType.SERVER_SENT_EVENTS) public void stats(@Context SseEventSink sink, @PathParam("id") final String id) { new Thread() { public void run() { try { final Builder builder = sse.newEventBuilder(); sink.send(createStatsEvent(builder.name("stats"), 1)); Thread.sleep(1000); sink.send(createStatsEvent(builder.name("stats"), 2)); Thread.sleep(1000); sink.send(createStatsEvent(builder.name("stats"), 3)); Thread.sleep(1000); sink.send(createStatsEvent(builder.name("stats"), 4)); Thread.sleep(1000); sink.send(createStatsEvent(builder.name("stats"), 5)); Thread.sleep(1000); sink.send(createStatsEvent(builder.name("stats"), 6)); Thread.sleep(1000); sink.send(createStatsEvent(builder.name("stats"), 7)); Thread.sleep(1000); sink.send(createStatsEvent(builder.name("stats"), 8)); sink.close(); } catch (final Exception e) { e.printStackTrace(); } } }.start(); }
Example #26
Source File: StatsRestServiceImpl.java From cxf with Apache License 2.0 | 5 votes |
@GET @Path("sse/{id}") @Produces(MediaType.SERVER_SENT_EVENTS) public void stats(@Context SseEventSink sink, @PathParam("id") final String id) { new Thread() { public void run() { try { final Builder builder = sse.newEventBuilder(); sink.send(createStatsEvent(builder, 1)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 2)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 3)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 4)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 5)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 6)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 7)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 8)); sink.close(); } catch (final Exception e) { e.printStackTrace(); } } }.start(); }
Example #27
Source File: StatsRestServiceImpl.java From cxf with Apache License 2.0 | 5 votes |
@GET @Path("/sse") @Produces(MediaType.SERVER_SENT_EVENTS) public void stats(@Context SseEventSink sink) { new Thread() { public void run() { try { final Builder builder = sse.newEventBuilder(); sink.send(createStatsEvent(builder, 1)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 2)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 3)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 4)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 5)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 6)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 7)); Thread.sleep(1000); sink.send(createStatsEvent(builder, 8)); sink.close(); } catch (final Exception e) { e.printStackTrace(); } } }.start(); }
Example #28
Source File: BookStore2.java From cxf with Apache License 2.0 | 5 votes |
@GET @Path("/filtered/sse") @Produces(MediaType.SERVER_SENT_EVENTS) public void filtered(@Context SseEventSink sink) { new Thread() { public void run() { try { Thread.sleep(200); sink.close(); } catch (final InterruptedException ex) { LOG.error("Communication error", ex); } } }.start(); }
Example #29
Source File: SseBroadcaster.java From openhab-core with Eclipse Public License 2.0 | 5 votes |
private void close(final SseEventSink sink) { try { sink.close(); } catch (final RuntimeException ex) { logger.debug("Closing a SSE event sink failed. Nothing we can do here...", ex); } }
Example #30
Source File: SseBroadcaster.java From openhab-core with Eclipse Public License 2.0 | 5 votes |
@Override public void close() { final Iterator<Entry<SseEventSink, I>> it = sinks.entrySet().iterator(); while (it.hasNext()) { final Entry<SseEventSink, I> entry = it.next(); it.remove(); close(entry.getKey()); notifyAboutRemoval(entry.getKey(), entry.getValue()); } }