org.springframework.web.servlet.mvc.method.annotation.SseEmitter Java Examples
The following examples show how to use
org.springframework.web.servlet.mvc.method.annotation.SseEmitter.
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: ServerSentEventsController.java From mirrorgate with Apache License 2.0 | 7 votes |
@GetMapping(value = "/emitter/{dashboardId}") public SseEmitter serverSideEmitter(final @PathVariable String dashboardId) throws IOException { LOG.info("Creating SseEmitter for dashboard {}", dashboardId); final SseEmitter sseEmitter = new NotCachedSseEmitter(); sseEmitter.onCompletion(() -> { handler.removeFromSessionsMap(sseEmitter, dashboardId); sseEmitter.complete(); }); sseEmitter.onTimeout(() -> { handler.removeFromSessionsMap(sseEmitter, dashboardId); sseEmitter.complete(); }); handler.addToSessionsMap(sseEmitter, dashboardId); sseEmitter.send(SseEmitter.event().reconnectTime(0L)); return sseEmitter; }
Example #2
Source File: SseEmitterController.java From tutorials with MIT License | 6 votes |
@GetMapping("/stream-sse-mvc") public SseEmitter streamSseMvc() { SseEmitter emitter = new SseEmitter(); ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor(); sseMvcExecutor.execute(() -> { try { for (int i = 0; true; i++) { SseEventBuilder event = SseEmitter.event() .data("SSE MVC - " + LocalTime.now() .toString()) .id(String.valueOf(i)) .name("sse event - mvc"); emitter.send(event); Thread.sleep(1000); } } catch (Exception ex) { emitter.completeWithError(ex); } }); return emitter; }
Example #3
Source File: SseEmitterController.java From tutorials with MIT License | 6 votes |
@GetMapping(Constants.API_SSE) public SseEmitter handleSse() { SseEmitter emitter = new SseEmitter(); nonBlockingService.execute(() -> { try { emitter.send(Constants.API_SSE_MSG + " @ " + new Date()); emitter.complete(); } catch (Exception ex) { System.out.println(Constants.GENERIC_EXCEPTION); emitter.completeWithError(ex); } }); return emitter; }
Example #4
Source File: SpringSseEmitterTest.java From cxf with Apache License 2.0 | 6 votes |
@GetMapping("/sse") public SseEmitter streamSseMvc() { final SseEmitter emitter = new SseEmitter(); final ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor(); sseMvcExecutor.execute(() -> { try { for (int eventId = 1; eventId <= 5; ++eventId) { SseEventBuilder event = SseEmitter.event() .id(Integer.toString(eventId)) .data(new Book("New Book #" + eventId, "Author #" + eventId), MediaType.APPLICATION_JSON) .name("book"); emitter.send(event); Thread.sleep(100); } } catch (Exception ex) { emitter.completeWithError(ex); } }); return emitter; }
Example #5
Source File: SseEventBus.java From sse-eventbus with Apache License 2.0 | 6 votes |
/** * Creates a {@link SseEmitter} and registers the client in the internal database. * Client will be subscribed to the provided events if specified. * @param clientId unique client identifier * @param timeout timeout value in milliseconds * @param unsubscribe if true unsubscribes from all events that are not provided with * the next parameter * @param events events the client wants to subscribe * @return a new SseEmitter instance */ public SseEmitter createSseEmitter(String clientId, Long timeout, boolean unsubscribe, boolean completeAfterMessage, String... events) { SseEmitter emitter = new SseEmitter(timeout); emitter.onTimeout(emitter::complete); registerClient(clientId, emitter, completeAfterMessage); if (events != null && events.length > 0) { if (unsubscribe) { unsubscribeFromAllEvents(clientId, events); } for (String event : events) { subscribe(clientId, event); } } return emitter; }
Example #6
Source File: TemperatureController.java From Hands-On-Reactive-Programming-in-Spring-5 with MIT License | 6 votes |
@Async @EventListener public void handleMessage(Temperature temperature) { log.info(format("Temperature: %4.2f C, active subscribers: %d", temperature.getValue(), clients.size())); List<SseEmitter> deadEmitters = new ArrayList<>(); clients.forEach(emitter -> { try { Instant start = Instant.now(); emitter.send(temperature, MediaType.APPLICATION_JSON); log.info("Sent to client, took: {}", Duration.between(start, Instant.now())); } catch (Exception ignore) { deadEmitters.add(emitter); } }); clients.removeAll(deadEmitters); }
Example #7
Source File: ServerSentEventsHandler.java From mirrorgate with Apache License 2.0 | 6 votes |
public synchronized void removeFromSessionsMap(final SseEmitter session, final String dashboardId) { LOG.debug("Remove SseEmitter {} to sessions map", dashboardId); if (! StringUtils.isEmpty(dashboardId)) { final List<SseEmitter> dashboardEmitters = emittersPerDashboard.get(dashboardId); if (dashboardEmitters != null) { dashboardEmitters.remove(session); if (dashboardEmitters.isEmpty()) { emittersPerDashboard.remove(dashboardId); } } } }
Example #8
Source File: ApplicationEventListener.java From voj with GNU General Public License v3.0 | 6 votes |
/** * 提交事件的处理器. * @param event - 提交记录事件 * @throws IOException */ @EventListener public void submissionEventHandler(SubmissionEvent event) throws IOException { long submissionId = event.getSubmissionId(); String judgeResult = event.getJudgeResult(); String message = event.getMessage(); boolean isCompleted = event.isCompleted(); SseEmitter sseEmitter = sseEmitters.get(submissionId); if ( sseEmitter == null ) { LOGGER.warn(String.format("CANNOT get the SseEmitter for submission #%d.", submissionId)); return; } Map<String, String> mapMessage = new HashMap<>(3, 1); mapMessage.put("judgeResult", judgeResult); mapMessage.put("message", message); sseEmitter.send(mapMessage); if ( isCompleted ) { sseEmitter.complete(); removeSseEmitters(submissionId); } }
Example #9
Source File: SubmissionController.java From voj with GNU General Public License v3.0 | 6 votes |
/** * 获取实时的评测结果. * @param submissionId - 提交记录的唯一标识符 * @return 包含评测结果信息的StreamingResponseBody对象 * @throws IOException */ @RequestMapping("/getRealTimeJudgeResult.action") public SseEmitter getRealTimeJudgeResultAction( @RequestParam(value="submissionId") long submissionId, @RequestParam(value="csrfToken") String csrfToken, HttpServletRequest request, HttpServletResponse response) throws IOException { User currentUser = HttpSessionParser.getCurrentUser(request.getSession()); boolean isCsrfTokenValid = CsrfProtector.isCsrfTokenValid(csrfToken, request.getSession()); Submission submission = submissionService.getSubmission(submissionId); if ( !isCsrfTokenValid || submission == null || !submission.getUser().equals(currentUser) || !submission.getJudgeResult().getJudgeResultSlug().equals("PD") ) { throw new ResourceNotFoundException(); } response.addHeader("X-Accel-Buffering", "no"); SseEmitter sseEmitter = new SseEmitter(); submissionEventListener.addSseEmitters(submissionId, sseEmitter); sseEmitter.send("Established"); return sseEmitter; }
Example #10
Source File: RealTimeStatusController.java From zhcet-web with Apache License 2.0 | 5 votes |
@GetMapping("/management/task/sse/{id}") public SseEmitter realTimeSse(@PathVariable String id) { SseEmitter emitter = new SseEmitter(TIMEOUT); RealTimeStatus status = realTimeStatusService.get(id); Consumer<RealTimeStatus> consumer = statusChange -> { try { emitter.send(statusChange); } catch (IOException e) { log.error("Error sending event", e); emitter.complete(); } }; Runnable completeListener = emitter::complete; Runnable onComplete = () -> { status.removeChangeListener(consumer); status.removeStopListener(completeListener); }; status.addChangeListener(consumer); status.onStop(completeListener); emitter.onCompletion(onComplete); emitter.onTimeout(onComplete); consumer.accept(status); if (status.isInvalid() || status.isFailed() || status.isFinished()) emitter.complete(); return emitter; }
Example #11
Source File: SseEventBus.java From sse-eventbus with Apache License 2.0 | 5 votes |
public void registerClient(String clientId, SseEmitter emitter, boolean completeAfterMessage) { Client client = this.clients.get(clientId); if (client == null) { this.clients.put(clientId, new Client(clientId, emitter, completeAfterMessage)); } else { client.updateEmitter(emitter); } }
Example #12
Source File: OnlineUserUtils.java From youkefu with Apache License 2.0 | 5 votes |
/** * 发送邀请 * @param userid * @throws Exception */ public static void sendWebIMClients(String sessionid , String userid , String msg) throws Exception{ List<WebIMClient> clients = OnlineUserUtils.webIMClients.getClients(userid) ; if(clients!=null && clients.size()>0){ for(WebIMClient client : clients){ try{ client.getSse().send(SseEmitter.event().reconnectTime(0).data(msg)); }catch(Exception ex){ OnlineUserUtils.webIMClients.removeClient(sessionid , userid , client.getClient() , true) ; }finally{ client.getSse().complete(); } } } }
Example #13
Source File: CommentController.java From spring-react-isomorphic with Apache License 2.0 | 5 votes |
@RequestMapping(path = "/", method = RequestMethod.POST, produces = "application/json") @ResponseBody Comment jsonCreate(Comment comment) throws IOException { Comment newComment = this.commentRepository.save(comment); synchronized (this.sseEmitters) { for (SseEmitter sseEmitter : this.sseEmitters) { // Servlet containers don't always detect ghost connection, so we must catch exceptions ... try { sseEmitter.send(newComment, MediaType.APPLICATION_JSON); } catch (Exception e) {} } } return comment; }
Example #14
Source File: WebSocketEventController.java From spring-twitter-stream with MIT License | 5 votes |
@RequestMapping("/tweetLocation") public SseEmitter streamTweets() throws InterruptedException{ SseEmitter sseEmitter = new SseEmitter(); emitters.add(sseEmitter); sseEmitter.onCompletion(() -> emitters.remove(sseEmitter)); streamTweetEventService.streamTweetEvent(emitters); return sseEmitter; }
Example #15
Source File: ControllerBase.java From microservices-sample-project with Apache License 2.0 | 5 votes |
@RequestMapping("/listener/{id}") public SseEmitter listen(@PathVariable("id") String id){ if(this.listenerType == null) throw new ListenerTypeNotFound(); final SseEmitter sseEmitter = new SseEmitter(); applicationEventListener.addSseEmitters(this.listenerType , id, sseEmitter); return sseEmitter; }
Example #16
Source File: CommentController.java From spring-react-isomorphic with Apache License 2.0 | 5 votes |
@RequestMapping("/sse/updates") SseEmitter subscribeUpdates() { SseEmitter sseEmitter = new SseEmitter(); synchronized (this.sseEmitters) { this.sseEmitters.add(sseEmitter); sseEmitter.onCompletion(() -> { synchronized (this.sseEmitters) { this.sseEmitters.remove(sseEmitter); } }); } return sseEmitter; }
Example #17
Source File: SseEmitterApplicationEventListener.java From microservices-sample-project with Apache License 2.0 | 5 votes |
@EventListener public void submissionEventHandler(SubmissionEvent event) throws IOException { String key = event.getKey(); Object message = event.getMessage(); SseEmitter sseEmitter = sseEmitters.get(key); if ( sseEmitter == null ) { return; } sseEmitter.send(message, MediaType.APPLICATION_JSON); }
Example #18
Source File: ApplicationEventListener.java From voj with GNU General Public License v3.0 | 5 votes |
/** * 移除Server Sent Event的发送者对象. * @param submissionId - 提交记录的唯一标识符 */ private void removeSseEmitters(long submissionId) { sseEmitters.remove(submissionId); for ( Entry<Long, SseEmitter> mapEntry : sseEmitters.entrySet() ) { long currentSubmissionId = mapEntry.getKey(); if ( currentSubmissionId < submissionId ) { sseEmitters.remove(currentSubmissionId); } } }
Example #19
Source File: ServerSentEventsHandler.java From mirrorgate with Apache License 2.0 | 5 votes |
@Override public void sendEventUpdateMessage(final EventType event, final String dashboardId) { final List<SseEmitter> emitters = emittersPerDashboard.get(dashboardId); if (emitters != null) { if (event != EventType.PING) { sendEventUpdateMessage(EventType.PING, dashboardId); } LOG.info("Notifying {} dashboards with name {} and event type {}", emitters.size(), dashboardId, event); for (int i = emitters.size(); i > 0; i--) { final SseEmitter sseEmitter = emitters.get(i - 1); try { final String jsonMessage = objectMapper.writeValueAsString( ImmutableMap .<String, String>builder() .put("type", event.getValue()) .build() ); sseEmitter.send(jsonMessage, MediaType.APPLICATION_JSON); } catch (IOException e) { this.removeFromSessionsMap(sseEmitter, dashboardId); LOG.error("Exception while sending message to emitter for dashboard {}", dashboardId); } } } }
Example #20
Source File: LogServiceApplication.java From Hands-On-Reactive-Programming-in-Spring-5 with MIT License | 5 votes |
@RequestMapping("/logs") public SseEmitter mockLogs() { SseEmitter emitter = new SseEmitter(); Flowable.interval(300, TimeUnit.MILLISECONDS) .map(i -> "[" + System.nanoTime() + "] [LogServiceApplication] [Thread " + Thread.currentThread() + "] Some loge here " + i + "\n") .subscribe(emitter::send, emitter::completeWithError, emitter::complete); return emitter; }
Example #21
Source File: TemperatureController.java From Hands-On-Reactive-Programming-in-Spring-5 with MIT License | 5 votes |
@RequestMapping(value = "/temperature-stream", method = RequestMethod.GET) public SseEmitter events(HttpServletRequest request) { log.info("SSE stream opened for client: " + request.getRemoteAddr()); SseEmitter emitter = new SseEmitter(SSE_SESSION_TIMEOUT); clients.add(emitter); // Remove SseEmitter from active clients on error or client disconnect emitter.onTimeout(() -> clients.remove(emitter)); emitter.onCompletion(() -> clients.remove(emitter)); return emitter; }
Example #22
Source File: TemperatureController.java From Hands-On-Reactive-Programming-in-Spring-5 with MIT License | 5 votes |
@RequestMapping(value = "/temperature-stream", method = RequestMethod.GET) public SseEmitter events(HttpServletRequest request) { RxSeeEmitter emitter = new RxSeeEmitter(); log.info("[{}] Rx SSE stream opened for client: {}", emitter.getSessionId(), request.getRemoteAddr()); temperatureSensor.temperatureStream() .subscribe(emitter.getSubscriber()); return emitter; }
Example #23
Source File: SseEventBus.java From sse-eventbus with Apache License 2.0 | 4 votes |
public SseEmitter createSseEmitter(String clientId, boolean unsubscribe, String... events) { return createSseEmitter(clientId, 180_000L, unsubscribe, false, events); }
Example #24
Source File: SseEventBusTest.java From sse-eventbus with Apache License 2.0 | 4 votes |
@Test public void testClientRegisterAndSubscribeOnly() { assertThat(this.eventBus.getAllClientIds()).isEmpty(); SseEmitter se1 = this.eventBus.createSseEmitter("1", "one"); SseEmitter se2 = this.eventBus.createSseEmitter("2", "one", "two", "three"); assertThat(this.eventBus.getAllClientIds()).containsOnly("1", "2"); assertThat(internalClients().get("1").sseEmitter()).isEqualTo(se1); assertThat(internalClients().get("2").sseEmitter()).isEqualTo(se2); assertThat(this.eventBus.getAllEvents()).containsOnly("one", "two", "three"); assertThat(this.eventBus.getSubscribers("one")).containsExactly("1", "2"); assertThat(this.eventBus.getSubscribers("two")).containsExactly("2"); assertThat(this.eventBus.getSubscribers("three")).containsExactly("2"); se1 = this.eventBus.createSseEmitter("1", true, "one"); se2 = this.eventBus.createSseEmitter("2", true, "three", "four", "five"); assertThat(this.eventBus.getAllClientIds()).containsOnly("1", "2"); assertThat(internalClients().get("1").sseEmitter()).isEqualTo(se1); assertThat(internalClients().get("2").sseEmitter()).isEqualTo(se2); assertThat(this.eventBus.getAllEvents()).containsOnly("one", "three", "four", "five"); assertThat(this.eventBus.getSubscribers("one")).containsExactly("1"); assertThat(this.eventBus.getSubscribers("three")).containsExactly("2"); assertThat(this.eventBus.getSubscribers("four")).containsExactly("2"); assertThat(this.eventBus.getSubscribers("five")).containsExactly("2"); se1 = this.eventBus.createSseEmitter("1", true, "one"); se2 = this.eventBus.createSseEmitter("2", true, "one"); assertThat(this.eventBus.getAllClientIds()).containsOnly("1", "2"); assertThat(internalClients().get("1").sseEmitter()).isEqualTo(se1); assertThat(internalClients().get("2").sseEmitter()).isEqualTo(se2); assertThat(this.eventBus.getAllEvents()).containsOnly("one"); assertThat(this.eventBus.getSubscribers("one")).containsExactly("1", "2"); this.eventBus.subscribeOnly("2", "two"); assertThat(this.eventBus.getAllEvents()).containsOnly("one", "two"); assertThat(this.eventBus.getSubscribers("one")).containsExactly("1"); assertThat(this.eventBus.getSubscribers("two")).containsExactly("2"); this.eventBus.subscribeOnly("1", "two"); assertThat(this.eventBus.getAllEvents()).containsOnly("two"); assertThat(this.eventBus.getSubscribers("two")).containsExactly("1", "2"); }
Example #25
Source File: SseEventBusTest.java From sse-eventbus with Apache License 2.0 | 4 votes |
@Test public void testClientRegisterAndSubscribe() { assertThat(this.eventBus.getAllClientIds()).isEmpty(); SseEmitter se1 = this.eventBus.createSseEmitter("1", "one"); SseEmitter se2 = this.eventBus.createSseEmitter("2", "two", "two2"); SseEmitter se3 = this.eventBus.createSseEmitter("3", "one", "three"); assertThat(this.eventBus.getAllClientIds()).containsOnly("1", "2", "3"); assertThat(internalClients().get("1").sseEmitter()).isEqualTo(se1); assertThat(internalClients().get("2").sseEmitter()).isEqualTo(se2); assertThat(internalClients().get("3").sseEmitter()).isEqualTo(se3); assertThat(this.eventBus.getAllEvents()).containsOnly("one", "two", "two2", "three"); assertThat(this.eventBus.getSubscribers("one")).containsExactly("1", "3"); assertThat(this.eventBus.getSubscribers("two")).containsExactly("2"); assertThat(this.eventBus.getSubscribers("two2")).containsExactly("2"); assertThat(this.eventBus.getSubscribers("three")).containsExactly("3"); this.eventBus.unsubscribe("1", "x"); assertThat(this.eventBus.getAllEvents()).containsOnly("one", "two", "two2", "three"); assertThat(this.eventBus.getSubscribers("one")).containsExactly("1", "3"); assertThat(this.eventBus.getSubscribers("two")).containsExactly("2"); assertThat(this.eventBus.getSubscribers("two2")).containsExactly("2"); assertThat(this.eventBus.getSubscribers("three")).containsExactly("3"); this.eventBus.unsubscribe("2", "two2"); assertThat(this.eventBus.getAllEvents()).containsOnly("one", "two", "three"); assertThat(this.eventBus.getSubscribers("one")).containsExactly("1", "3"); assertThat(this.eventBus.getSubscribers("two")).containsExactly("2"); assertThat(this.eventBus.getSubscribers("three")).containsExactly("3"); this.eventBus.unsubscribe("2", "two"); assertThat(this.eventBus.getAllEvents()).containsOnly("one", "three"); assertThat(this.eventBus.getSubscribers("one")).containsExactly("1", "3"); assertThat(this.eventBus.getSubscribers("three")).containsExactly("3"); this.eventBus.unregisterClient("3"); assertThat(this.eventBus.getAllEvents()).containsOnly("one"); assertThat(this.eventBus.getSubscribers("one")).containsExactly("1"); }
Example #26
Source File: TestController.java From sse-eventbus with Apache License 2.0 | 4 votes |
@GetMapping("/registerOnly/{id}/{event}") public SseEmitter eventbusOnly(@PathVariable("id") String id, @PathVariable("event") String event) { return this.eventBus.createSseEmitter(id, 3_000L, true, event.split(",")); }
Example #27
Source File: TestController.java From sse-eventbus with Apache License 2.0 | 4 votes |
@GetMapping("/register/{id}/{event}") public SseEmitter eventbus(@PathVariable("id") String id, @PathVariable("event") String event) { return this.eventBus.createSseEmitter(id, 3_000L, event.split(",")); }
Example #28
Source File: TestController.java From sse-eventbus with Apache License 2.0 | 4 votes |
@GetMapping("/register/{id}") public SseEmitter eventbus(@PathVariable("id") String id) { return this.eventBus.createSseEmitter(id, 3_000L); }
Example #29
Source File: Client.java From sse-eventbus with Apache License 2.0 | 4 votes |
void updateEmitter(SseEmitter emitter) { this.sseEmitter = emitter; }
Example #30
Source File: Client.java From sse-eventbus with Apache License 2.0 | 4 votes |
SseEmitter sseEmitter() { return this.sseEmitter; }