javax.ws.rs.sse.OutboundSseEvent Java Examples
The following examples show how to use
javax.ws.rs.sse.OutboundSseEvent.
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: 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 #3
Source File: SseItemStatesEventBuilder.java From openhab-core with Eclipse Public License 2.0 | 6 votes |
public @Nullable OutboundSseEvent buildEvent(Builder eventBuilder, Set<String> itemNames) { Map<String, StateDTO> payload = new HashMap<>(itemNames.size()); for (String itemName : itemNames) { try { Item item = itemRegistry.getItem(itemName); StateDTO stateDto = new StateDTO(); stateDto.state = item.getState().toString(); String displayState = getDisplayState(item, Locale.getDefault()); // Only include the display state if it's different than the raw state if (stateDto.state != null && !stateDto.state.equals(displayState)) { stateDto.displayState = displayState; } payload.put(itemName, stateDto); } catch (ItemNotFoundException e) { logger.warn("Attempting to send a state update of an item which doesn't exist: {}", itemName); } } if (!payload.isEmpty()) { return eventBuilder.mediaType(MediaType.APPLICATION_JSON_TYPE).data(payload).build(); } return null; }
Example #4
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 #5
Source File: SseResource.java From openhab-core with Eclipse Public License 2.0 | 6 votes |
/** * Alters the list of tracked items for a given state update connection * * @param connectionId the connection Id to change * @param itemNames the list of items to track */ @POST @Path("/states/{connectionId}") @ApiOperation(value = "Changes the list of items a SSE connection will receive state updates to.") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 404, message = "Unknown connectionId") }) public Object updateTrackedItems(@PathParam("connectionId") String connectionId, @ApiParam("items") Set<String> itemNames) { Optional<SseSinkItemInfo> itemStateInfo = itemStatesBroadcaster.getInfoIf(hasConnectionId(connectionId)) .findFirst(); if (!itemStateInfo.isPresent()) { return Response.status(Status.NOT_FOUND).build(); } itemStateInfo.get().updateTrackedItems(itemNames); OutboundSseEvent itemStateEvent = itemStatesEventBuilder.buildEvent(sse.newEventBuilder(), itemNames); if (itemStateEvent != null) { itemStatesBroadcaster.sendIf(itemStateEvent, hasConnectionId(connectionId)); } return Response.ok().build(); }
Example #6
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 #7
Source File: OutboundSseEventImplTest.java From cxf with Apache License 2.0 | 6 votes |
/** * A user should not need to specify a media type when creating an outbound event. The default * should be <code>MediaType.SERVER_SENT_EVENTS_TYPE</code>. */ @Test public void testDefaultMediaType() { Sse sse = new SseImpl(); // test newEvent(data) OutboundSseEvent event = sse.newEvent("myData"); assertNull(event.getName()); assertEquals("myData", event.getData()); assertEquals(MediaType.TEXT_PLAIN_TYPE, event.getMediaType()); // test newEvent(name, data) event = sse.newEvent("myName", "myData2"); assertEquals("myName", event.getName()); assertEquals("myData2", event.getData()); assertEquals(MediaType.TEXT_PLAIN_TYPE, event.getMediaType()); // test newEventBuilder()...build() event = sse.newEventBuilder().comment("myComment").data("myData3").build(); assertEquals("myComment", event.getComment()); assertEquals("myData3", event.getData()); assertEquals(MediaType.TEXT_PLAIN_TYPE, event.getMediaType()); }
Example #8
Source File: SseEventSinkImpl.java From cxf with Apache License 2.0 | 6 votes |
@Override public CompletionStage<?> send(OutboundSseEvent event) { final CompletableFuture<?> future = new CompletableFuture<>(); if (!closed.get() && writer != null) { final Throwable ex = throwable.get(); if (ex != null) { future.completeExceptionally(ex); } else if (buffer.offer(new QueuedEvent(event, future))) { if (dispatching.compareAndSet(false, true)) { ctx.start(this::dequeue); } } else { future.completeExceptionally(new IllegalStateException("The buffer is full (" + bufferSize + "), unable to queue SSE event for send. Please use '" + BUFFER_SIZE_PROPERTY + "' property to increase the limit.")); } } else { future.completeExceptionally(new IllegalStateException( "The sink is already closed, unable to queue SSE event for send")); } return future; }
Example #9
Source File: MCREventHandler.java From mycore with GNU General Public License v3.0 | 6 votes |
@Override public void doHandleEvent(MCREvent evt) throws MCRException { if (!evt.getObjectType().equals(MCREvent.DERIVATE_TYPE)) { return; } MCRDerivate der = (MCRDerivate) evt.get(MCREvent.DERIVATE_KEY); JsonObject jEvent = new JsonObject(); addUserInfo(jEvent); JsonObject newData = getData(der); jEvent.add("current", newData); MCRDerivate oldDer = (MCRDerivate) evt.get(MCREvent.DERIVATE_OLD_KEY); if (oldDer != null) { JsonObject oldData = getData(oldDer); jEvent.add("old", oldData); } OutboundSseEvent event = sse.newEventBuilder() .mediaType(MediaType.APPLICATION_JSON_TYPE) .id(getId(evt)) .name(getName(evt)) .data(jEvent.toString()) .build(); sseBroadcaster.broadcast(event); }
Example #10
Source File: MCREventHandler.java From mycore with GNU General Public License v3.0 | 6 votes |
@Override public void doHandleEvent(MCREvent evt) throws MCRException { if (!evt.getObjectType().equals(MCREvent.OBJECT_TYPE)) { return; } MCRObject obj = (MCRObject) evt.get(MCREvent.OBJECT_KEY); JsonObject jEvent = new JsonObject(); JsonObject newData = getData(obj); addUserInfo(jEvent); jEvent.add("current", newData); MCRObject oldObj = (MCRObject) evt.get(MCREvent.OBJECT_OLD_KEY); if (oldObj != null) { JsonObject oldData = getData(oldObj); jEvent.add("old", oldData); } OutboundSseEvent event = sse.newEventBuilder() .mediaType(MediaType.APPLICATION_JSON_TYPE) .id(getId(evt)) .name(getName(evt)) .data(jEvent.toString()) .build(); sseBroadcaster.broadcast(event); }
Example #11
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 #12
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 #13
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 #14
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 #15
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 #16
Source File: BookStoreClientCloseable.java From cxf with Apache License 2.0 | 5 votes |
protected static OutboundSseEvent createRawEvent(final OutboundSseEvent.Builder builder, final int eventId) { return builder .id(Integer.toString(eventId)) .data("New Book #" + eventId) .mediaType(MediaType.TEXT_PLAIN_TYPE) .build(); }
Example #17
Source File: BookStoreClientCloseable.java From cxf with Apache License 2.0 | 5 votes |
protected static OutboundSseEvent createEvent(final OutboundSseEvent.Builder builder, final int eventId) { return builder .id(Integer.toString(eventId)) .data(Book.class, new Book("New Book #" + eventId, eventId)) .mediaType(MediaType.APPLICATION_JSON_TYPE) .build(); }
Example #18
Source File: OutboundSseEventImpl.java From cxf with Apache License 2.0 | 5 votes |
@Override public OutboundSseEvent build() { return new OutboundSseEventImpl( id, name, comment, reconnectDelay, type, genericType, mediaType, data ); }
Example #19
Source File: SseResource.java From tutorials with MIT License | 5 votes |
@GET @Path("publish") public void broadcast() { Runnable r = new Runnable() { @Override public void run() { int lastEventId = 0; boolean running = true; while (running) { lastEventId++; Stock stock = stockService.getNextTransaction(lastEventId); if (stock != null) { OutboundSseEvent sseEvent = eventBuilder .name("stock") .id(String.valueOf(lastEventId)) .mediaType(MediaType.APPLICATION_JSON_TYPE) .data(Stock.class, stock) .reconnectDelay(3000) .comment("price change") .build(); sseBroadcaster.broadcast(sseEvent); } try { //Wait 5 seconds Thread.currentThread().sleep(5 * 1000); } catch (InterruptedException ex) { // ... } //Simulatae a while boucle break running = lastEventId <= 2000; } } }; new Thread(r).start(); }
Example #20
Source File: SseBroadcasterImpl.java From cxf with Apache License 2.0 | 5 votes |
@Override public CompletionStage<?> broadcast(OutboundSseEvent event) { assertNotClosed(); final Collection<CompletableFuture<?>> futures = new ArrayList<>(); for (SseEventSink sink: subscribers) { try { futures.add(sink.send(event).toCompletableFuture()); } catch (final Exception ex) { exceptioners.forEach(exceptioner -> exceptioner.accept(sink, ex)); } } return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); }
Example #21
Source File: StatsRestServiceImpl.java From cxf with Apache License 2.0 | 5 votes |
private static OutboundSseEvent createStatsEvent(final OutboundSseEvent.Builder builder, final int eventId) { return builder .id("" + eventId) .data(Stats.class, new Stats(new Date().getTime(), RANDOM.nextInt(100))) .mediaType(MediaType.APPLICATION_JSON_TYPE) .build(); }
Example #22
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 #23
Source File: OutboundSseEventImplTest.java From cxf with Apache License 2.0 | 5 votes |
/** * A user should not need to specify the type of data being sent in an outbound * event. In that case the OutboundSseEvent should use the data object's type. Other * types may be specified, but the default (if not specified by the user) should be * the return value from the object's <code>getClass()</code> method. */ @Test public void testDefaultClass() { Sse sse = new SseImpl(); // test newEvent(string) OutboundSseEvent event = sse.newEvent("myData"); assertNull(event.getName()); assertEquals("myData", event.getData()); assertEquals(String.class, event.getType()); // test newEvent(name, data) event = sse.newEvent("myName", "myData2"); assertEquals("myName", event.getName()); assertEquals("myData2", event.getData()); assertEquals(String.class, event.getType()); // test newEventBuilder()...build() event = sse.newEventBuilder().comment("myComment").data("myData3").build(); assertEquals("myComment", event.getComment()); assertEquals("myData3", event.getData()); assertEquals(String.class, event.getType()); // test that object's class is re-enabled when calling different signatures of the data method OutboundSseEvent.Builder builder = sse.newEventBuilder(); builder.data(TestData.class, new TestDataImpl("1", "2")); event = builder.build(); assertEquals(TestData.class, event.getType()); builder.data("myString"); event = builder.build(); assertEquals(String.class, event.getType()); // same thing, but don't build in between calls to data event = sse.newEventBuilder().data(TestDataImpl.class, new TestDataImpl("3")).data("anotherString").build(); assertEquals(String.class, event.getType()); assertEquals("anotherString", event.getData()); }
Example #24
Source File: OutboundSseEventImplTest.java From cxf with Apache License 2.0 | 5 votes |
/** * Test that event built by the builder contains all of the data passed in * to it. */ @Test public void testBuilderAPIs() { SseImpl sse = new SseImpl(); OutboundSseEvent.Builder builder = sse.newEventBuilder(); builder.comment("myComment"); builder.data(new TestDataImpl("dataNoSpecifiedType")); builder.id("id"); builder.mediaType(MediaType.APPLICATION_JSON_TYPE); builder.name("name"); builder.reconnectDelay(5000); OutboundSseEvent event = builder.build(); assertEquals("myComment", event.getComment()); assertEquals(TestDataImpl.class, event.getType()); assertTrue(event.getData() instanceof TestDataImpl); assertEquals("dataNoSpecifiedType", ((TestDataImpl)event.getData()).getData().get(0)); assertEquals("id", event.getId()); assertEquals(MediaType.APPLICATION_JSON_TYPE, event.getMediaType()); assertEquals("name", event.getName()); assertEquals(5000, event.getReconnectDelay()); // now reuse the builder to build a new event builder.comment("myComment2"); builder.data(TestData.class, new TestDataImpl("data1", "data2")); builder.id("id2"); builder.mediaType(MediaType.TEXT_PLAIN_TYPE); builder.name("name2"); builder.reconnectDelay(9000); event = builder.build(); assertEquals("myComment2", event.getComment()); assertEquals(new TestDataImpl("data1", "data2"), event.getData()); assertEquals(TestData.class, event.getType()); assertEquals("id2", event.getId()); assertEquals(MediaType.TEXT_PLAIN_TYPE, event.getMediaType()); assertEquals("name2", event.getName()); assertEquals(9000, event.getReconnectDelay()); }
Example #25
Source File: SseBroadcasterImplTest.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testOnErrorCallbackIsCalled() throws WebApplicationException, IOException { when(writer.isWriteable(any(), any(), any(), any())).thenReturn(true); final LongAdder adder = new LongAdder(); final SseEventSinkImpl sink = new SseEventSinkImpl(writer, null, ctx) { @Override public CompletionStage<?> send(OutboundSseEvent event) { ctx.start(() -> { throw new RuntimeException("Failed to schedule async task"); }); return CompletableFuture.completedFuture(null); } }; broadcaster.register(sink); broadcaster.onError((s, ex) -> { if (s == sink) { adder.increment(); } }); assertThat(adder.intValue(), equalTo(0)); broadcaster.broadcast(new OutboundSseEventImpl.BuilderImpl().build()); broadcaster.close(); assertThat(adder.intValue(), equalTo(1)); }
Example #26
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 #27
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 #28
Source File: SseUtil.java From openhab-core with Eclipse Public License 2.0 | 5 votes |
/** * Creates a new {@link OutboundSseEvent} object containing an {@link EventDTO} created for the given Eclipse * SmartHome {@link Event}. * * @param eventBuilder the builder that should be used * @param event the event data transfer object * @return a new OutboundEvent */ public static OutboundSseEvent buildEvent(OutboundSseEvent.Builder eventBuilder, EventDTO event) { final OutboundSseEvent sseEvent = eventBuilder.name("message") // .mediaType(MediaType.APPLICATION_JSON_TYPE) // .data(event) // .build(); return sseEvent; }
Example #29
Source File: MCREventHandler.java From mycore with GNU General Public License v3.0 | 5 votes |
public void sendEvent(MCREvent evt, Path path, BasicFileAttributes attrs) { if (!(path instanceof MCRPath) || !(attrs instanceof MCRFileAttributes)) { LogManager.getLogger().warn("Cannot handle {} {}", path.getClass(), attrs.getClass()); return; } JsonObject file = new JsonObject(); addUserInfo(file); String derId = ((MCRPath) path).getOwner(); String fPath = ((MCRPath) path).getOwnerRelativePath(); String objId = MCRMetadataManager.getObjectId(MCRObjectID.getInstance(derId), 1, TimeUnit.MINUTES) .toString(); String relPath = String.format(Locale.ROOT, "objects/%s/derivates/%s/contents/%s", objId, derId, fPath); String uri = uriResolver.apply(getPathURI(relPath)).toString(); file.addProperty("uri", uri); file.addProperty("derivate", derId); file.addProperty("object", objId); file.addProperty("size", attrs.size()); file.addProperty("modified", attrs.lastModifiedTime().toInstant().toString()); file.addProperty("md5", ((MCRFileAttributes) attrs).md5sum()); file.addProperty("mimeType", context.getMimeType(path.getFileName().toString())); OutboundSseEvent event = sse.newEventBuilder() .mediaType(MediaType.APPLICATION_JSON_TYPE) .id(getId(evt)) .name(getName(evt)) .data(file.toString()) .build(); sseBroadcaster.broadcast(event); }
Example #30
Source File: PartyQueue.java From liberty-bikes with Eclipse Public License 1.0 | 5 votes |
public void promoteToGame(String roundId) { OutboundSseEvent event = sse.newEventBuilder() .mediaType(MediaType.APPLICATION_JSON_TYPE) .data(new OutboundMessage.RequeueGame(roundId)) .build(); sink.send(event); party.log("Promoted queued client " + playerId + " into round " + roundId); close(); }