Java Code Examples for javax.ws.rs.core.MediaType#SERVER_SENT_EVENTS

The following examples show how to use javax.ws.rs.core.MediaType#SERVER_SENT_EVENTS . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: quarkus   File: ServerSentEventResource.java    License: Apache License 2.0 6 votes vote down vote up
@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 2
/**
 * 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 3
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public Publisher<String> getQueue() {
    return Multi.createBy().merging()
            .streams(
                    queue.map(b -> json.toJson(b)),
                    getPingStream()
            );
}
 
Example 4
Source Project: Java-EE-8-Sampler   File: SseResource.java    License: MIT License 5 votes vote down vote up
@GET
@Path("subscribe")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void subscribe(@Context SseEventSink eventSink) {
    eventSink.send(sse.newEvent("You are subscribed"));
    broadcaster.register(eventSink);
}
 
Example 5
@GET
@Path("/stream")
@Produces(MediaType.SERVER_SENT_EVENTS)
@SseElementType(MediaType.APPLICATION_JSON)
public Publisher<Book> streamBooks(@QueryParam("sort") String sort) {
    if (sort != null) {
        return reactiveBookRepository.streamAll(Sort.ascending(sort));
    }
    return reactiveBookRepository.streamAll();
}
 
Example 6
Source Project: quarkus   File: SseResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public void subscribe(@Context SseEventSink sink) throws IOException {
    if (sink == null) {
        throw new IllegalStateException("No client connected.");
    }
    SseBroadcaster sseBroadcaster = sse.newBroadcaster();

    sseBroadcaster.register(sink);
    sseBroadcaster.broadcast(sse.newEventBuilder().data("hello").build());
}
 
Example 7
Source Project: cxf   File: StatsRestServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@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 8
@GET
@Path("/update")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void newsUpdate(@Context SseEventSink eventSink, @Context Sse sse) {
	CompletableFuture.runAsync(() -> {
		IntStream.range(1, 6).forEach(c -> {
			JsonObject newsEvent = Json.createObjectBuilder().add("news", String.format("Updated Event %d", newsCounter.incrementAndGet())).build();
			eventSink.send(sse.newEventBuilder().mediaType(MediaType.APPLICATION_JSON_TYPE).data(newsEvent).build());
		});
		//closing only on the client is generating a chunked connection exception that can be troubleshooted at a later date.
		eventSink.close();
	});
}
 
Example 9
@GET
@Lock(READ)
@Produces(MediaType.SERVER_SENT_EVENTS)
public void itemEvents(@HeaderParam(HttpHeaders.LAST_EVENT_ID_HEADER)
                       @DefaultValue("-1") int lastEventId,
                       @Context SseEventSink eventSink) {

    if (lastEventId >= 0)
        replayLastMessages(lastEventId, eventSink);

    sseBroadcaster.register(eventSink);
}
 
Example 10
@Path("register/{id}")
@Produces(MediaType.SERVER_SENT_EVENTS)
@GET
public void register(@PathParam("id") Long id,
        @Context SseEventSink sseEventSink) {
    final UserEvent event = POOL.get(id);

    if (event != null) {
        event.getSseBroadcaster().register(sseEventSink);
    } else {
        throw new NotFoundException();
    }
}
 
Example 11
Source Project: Java-EE-8-and-Angular   File: IssueUpdatesSSE.java    License: MIT License 5 votes vote down vote up
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public void subscribe(@Context Sse sse, @Context SseEventSink eventSink) {
    this.sse = sse;
    if(this.broadcaster == null) {
        this.broadcaster = sse.newBroadcaster();
    }
    this.broadcaster.register(eventSink);
}
 
Example 12
@GET
@Path("/stream")
@Produces(MediaType.SERVER_SENT_EVENTS)
@SseElementType(MediaType.APPLICATION_JSON)
public Publisher<ReactiveBookEntity> streamBooks(@QueryParam("sort") String sort) {
    if (sort != null) {
        return ReactiveBookEntity.streamAll(Sort.ascending(sort));
    }
    return ReactiveBookEntity.streamAll();
}
 
Example 13
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
@SseElementType(MediaType.TEXT_PLAIN)
@Path("/stream/{count}/{name}")
public Multi<String> greetingsAsStream(@PathParam int count, @PathParam String name) {
    return service.greetings(count, name);
}
 
Example 14
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public Publisher<String> get() {
    return Multi.createFrom().resource(
            driver::rxSession,
            session -> session.readTransaction(tx -> {
                RxResult result = tx.run("MATCH (f:Fruit) RETURN f.name as name ORDER BY f.name");
                return Multi.createFrom().publisher(result.records())
                        .map(record -> record.get("name").asString());
            })
    ).withFinalizer(session -> {
        return Uni.createFrom().publisher(session.close());
    });
}
 
Example 15
@Produces(MediaType.SERVER_SENT_EVENTS)
@GET
@Path("/subscribe")
public void subscribe(@Context SseEventSink sink) {
    sink.send(_sse.newEvent("welcome"));

    _sseBroadcaster.register(sink);
}
 
Example 16
Source Project: cxf   File: SseEventSourceImplTest.java    License: Apache License 2.0 4 votes vote down vote up
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public Response event() {
    return Response.status(Status.UNAUTHORIZED).build();
}
 
Example 17
Source Project: mycore   File: MCREvents.java    License: GNU General Public License v3.0 4 votes vote down vote up
@GET
@Path("/objects")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void registerObjectEvents(@Context SseEventSink sseEventSink) {
    objectBroadcaster.register(sseEventSink);
}
 
Example 18
Source Project: javaee8-cookbook   File: SseResource.java    License: Apache License 2.0 4 votes vote down vote up
@GET
@Produces(MediaType.SERVER_SENT_EVENTS)
public void getMessageQueue(@Context SseEventSink sink) {
    SseResource.SINK = sink;
}
 
Example 19
Source Project: mycore   File: MCREvents.java    License: GNU General Public License v3.0 4 votes vote down vote up
@GET
@Path("/derivates")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void registerDerivateEvents(@Context SseEventSink sseEventSink) {
    derivateBroadcaster.register(sseEventSink);
}
 
Example 20
Source Project: if1007   File: ReceiverStreamController.java    License: MIT License 4 votes vote down vote up
@GET
@Path("/stream")
@Produces(MediaType.SERVER_SENT_EVENTS)
public Publisher<String> stream() {
    return names;
}