@Subscribe public void send(RatesUpdatedEvent event) { for (RateEntity re : event.getRates()) { messagingTemplate.convertAndSend( "/topic/latest/" + re.getFromcur().getCode() + "/" + re.getTocur().getCode(), re); } }
@MessageMapping("/jobs") public void countTechnicalJobs(JobStatisticRequest request) { messagingTemplate.convertAndSend( "/topic/jobs/" + request.getTerm().toLowerCase(), new JobStatisticResponse.Builder() .withCount( vietnamWorksJobStatisticService.count( jsonConfigRepository.findByKey(request.getTerm().toUpperCase()))) .build()); }
@Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof SessionSubscribeEvent) { SessionSubscribeEvent connect = (SessionSubscribeEvent) event; StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(connect.getMessage()); HistoryService service = new HistoryService(); String dest = headerAccessor.getDestination(); Long diagramId; try { diagramId = Long.parseLong(dest.substring(dest.lastIndexOf('/') + 1)); HistorySession session = service.insertSession( connect.getUser().getName(), diagramId, headerAccessor.getSubscriptionId()); HistoryModel model = new HistoryModel( connect.getUser().getName(), session.getDiagram().getName(), session.getTimeStart(), session.getTimeFinish()); template.convertAndSend("/topic/diagram/" + diagramId + "/history", model); } catch (NumberFormatException ex) { return; } } else if (event instanceof SessionUnsubscribeEvent) { SessionUnsubscribeEvent connect = (SessionUnsubscribeEvent) event; StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(connect.getMessage()); HistoryService service = new HistoryService(); List<HistorySession> sessions = service.updateSession(connect.getUser().getName(), headerAccessor.getSubscriptionId()); for (HistorySession session : sessions) { HistoryModel model = new HistoryModel( connect.getUser().getName(), session.getDiagram().getName(), session.getTimeStart(), session.getTimeFinish()); template.convertAndSend( "/topic/diagram/" + session.getDiagram().getDiagramId() + "/history", model); } } }
@MessageMapping("/admin_removeUserByEmail") public void deleteUserByEmail(AdminMessage message) throws Exception { logger.info("Attempting to delete user " + message.getValue()); User user = assertAdmin(message.getUserEmail(), message.getUserToken()); userService.deleteUserByEmail(message.getValue()); // tell the user that the game has been created messagingTemplate.convertAndSend( "/queue/" + user.getToken() + "/admin", "User " + message.getValue() + " has been removed"); }
@Override public void onApplicationEvent(AbstractSubProtocolEvent event) { MessageHeaders headers = event.getMessage().getHeaders(); Principal user = SimpMessageHeaderAccessor.getUser(headers); if (event instanceof SessionConnectEvent) { String id = SimpMessageHeaderAccessor.getSessionId(headers); playerManager.addPlayer(id, user.getName()); messagingTemplate.convertAndSend( "/topic/player/join", PlayerEntry.create(user.getName(), PlayerEntry.State.ACTIVE)); } else if (event instanceof SessionDisconnectEvent) { SessionDisconnectEvent disconnectEvent = (SessionDisconnectEvent) event; playerManager.removePlayer(disconnectEvent.getSessionId()); messagingTemplate.convertAndSend( "/topic/player/leave", PlayerEntry.create(user.getName(), PlayerEntry.State.DETACHED)); } }
@Scheduled(cron = "${scheduled.cron}") public void countTechnicalJobs() { jsonConfigRepository .getSkillConfig() .stream() .forEach( term -> { Map<String, Double> avgSalary = vietnamWorksJobStatisticService.getAverageSalaryBySkill(term, JOB_LEVEL_ALL); messagingTemplate.convertAndSend( "/topic/jobs/term/" + term.getKey(), new TechnicalTermResponse.Builder() .withTerm(term.getKey()) .withLabel(term.getLabel()) .withAverageSalaryMin(avgSalary.get("SALARY_MIN")) .withAverageSalaryMax(avgSalary.get("SALARY_MAX")) .withCount(vietnamWorksJobStatisticService.count(term)) .build()); }); }
@RequestMapping("/gameStatus") public ResponseEntity<GameStatus> broadcastGameStatus() { GameStatus gameStatus = new GameStatus(); Iterable<GameStep> gameSteps = gameStepRepository.findAll(); List<GameStep> collect = StreamSupport.stream(gameSteps.spliterator(), false).collect(toList()); Map<String, List<GameStep>> gameStepByUser = StreamSupport.stream(gameSteps.spliterator(), false) .collect(Collectors.groupingBy(GameStep::getUserPseudo)); for (Map.Entry<String, List<GameStep>> gameStepByUserEntry : gameStepByUser.entrySet()) { UserGameStatus userGameStatus = new UserGameStatus(); userGameStatus.setPseudo(gameStepByUserEntry.getKey()); Map<Step, List<GameStep>> gameStepByStep = gameStepByUserEntry.getValue().stream().collect(Collectors.groupingBy(GameStep::getStep)); for (Map.Entry<Step, List<GameStep>> gameStepByStepEntry : gameStepByStep.entrySet()) { gameStepByStepEntry .getValue() .stream() .min(Comparator.comparing(GameStep::getInstant)) .ifPresent( gameStep -> { userGameStatus .getStepInfos() .add(new StepInfo(gameStep.getStep(), gameStep.getInstant())); }); } gameStatus.getUserGameStatus().add(userGameStatus); } webSocketTemplate.convertAndSend("/topic/gameStatus", gameStatus); return new ResponseEntity<GameStatus>(gameStatus, HttpStatus.OK); }
/** * {@inheritDoc} * * @param figureId The id of the {@link Figure}. * @param clientId The id of the {@link Figure}s {@link Client owner}. * @param targetFieldNotation The {@link Field#getNotation() notation} of the {@link Field} the * {@link Figure} wants to move to. * @param simpMessagingTemplate Template for sending websocket messages. * @throws MoveNotAllowedException */ @Override public void performMovement( String figureId, String clientId, String targetFieldNotation, SimpMessagingTemplate simpMessagingTemplate) throws MoveNotAllowedException { // Only the current player is allowed to do moves. // Fixes CCD2015-50 if (!clientId.equals(getCurrentPlayer().getId())) throw new MoveNotAllowedException(); List<Hexagon> possibleMovements = getPossibleFieldsToMove(figureId); // Throw an exception when the client ID does not match the figures owner id // or when the target field is not in the list of possible moves. if (possibleMovements .stream() .filter(hexagon -> hexagon.getNotation().equals(targetFieldNotation)) .count() == 0 || getFigures() .stream() // Only figures, that are sill active. .filter(hexagonFigure -> !hexagonFigure.isRemoved()) // Only figures equals to the given id .filter(hexagonFigure -> hexagonFigure.getId().equals(figureId)) // Only the clients figures .filter(hexagonFigure -> hexagonFigure.getClient().getId().equals(clientId)) .count() == 0) throw new MoveNotAllowedException(); HistoryEntry historyEntry = new HistoryEntry(); historyEntry.setPlayer(getCurrentPlayer()); // Remove a figure from the chessboard if there is a figure on the target field getFigures() .stream() // Only figures, that are sill active. // Fixes CCD2015-52 .filter(hexagonFigure -> !hexagonFigure.isRemoved()) // Only figures on the target hexagon .filter( hexagonFigure -> hexagonFigure.getPosition().getNotation().equals(targetFieldNotation)) .findFirst() .ifPresent( hexagonFigure -> { historyEntry .getChessboardEvents() .add( new FigureEvent() .setFigureId(hexagonFigure.getId()) .setEvent(FigureEvent.Event.REMOVED)); hexagonFigure.setRemoved(true); }); // Move our figure to the target field getFigures() .stream() // Only figures, that are sill active. .filter(hexagonFigure -> !hexagonFigure.isRemoved()) // Only figures on the source hexagon .filter(hexagonFigure -> hexagonFigure.getId().equals(figureId)) .findFirst() .ifPresent( hexagonFigure -> { historyEntry .getChessboardEvents() .add( new MovementEvent() .setFigureId(figureId) .setFromNotation(hexagonFigure.getPosition().getNotation()) .setToNotation(targetFieldNotation)); try { hexagonFigure.setPosition((Hexagon) getFieldByNotation(targetFieldNotation)); } catch (NotationNotFoundException e) { logger.error("", e); } }); // Add action to history getParentGame().getGameHistory().add(historyEntry); // Send event through websocket simpMessagingTemplate.convertAndSend("/game/" + getParentGame().getId(), historyEntry); // Change the active player and send it through websocket setCurrentPlayer(getCurrentPlayer().getNextClient()); checkIfCurrentPlayerIsDefeated(); while (getCurrentPlayer().isDefeated()) { setCurrentPlayer(getCurrentPlayer().getNextClient()); checkIfCurrentPlayerIsDefeated(); } getParentGame() .getPlayerList() .stream() .filter(client -> !client.isDefeated()) .forEach( client -> { PlayerChangedEvent playerChangedEvent = new PlayerChangedEvent().setItYouTurn(client.equals(getCurrentPlayer())); simpMessagingTemplate.convertAndSend( "/game/" + getParentGame().getId() + "/" + client.getId(), playerChangedEvent); }); }
@Async public void broadcast(ApiLogEvent apiLogEvent) { messagingTemplate.convertAndSend(brokerName, apiLogEvent); }