Example #1
0
 @Subscribe
 public void send(RatesUpdatedEvent event) {
   for (RateEntity re : event.getRates()) {
     messagingTemplate.convertAndSend(
         "/topic/latest/" + re.getFromcur().getCode() + "/" + re.getTocur().getCode(), re);
   }
 }
 @MessageMapping("/chat.private")
 public void handlePrivateMessage(Message<Object> message, @Payload MessageData messageData) {
   Principal principal =
       message.getHeaders().get(SimpMessageHeaderAccessor.USER_HEADER, Principal.class);
   messageData.setSender(principal.getName());
   String recipient = messageData.getRecipient();
   simpMessagingTemplate.convertAndSendToUser(recipient, "/queue/messages", messageData);
 }
 @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());
 }
Example #4
0
  @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));
    }
  }
  @Test
  public void annotationMethodMessageHandler() {
    loadBeanDefinitions("websocket-config-broker-simple.xml");

    SimpAnnotationMethodMessageHandler annotationMethodMessageHandler =
        this.appContext.getBean(SimpAnnotationMethodMessageHandler.class);

    assertNotNull(annotationMethodMessageHandler);
    MessageConverter messageConverter = annotationMethodMessageHandler.getMessageConverter();
    assertNotNull(messageConverter);
    assertTrue(messageConverter instanceof CompositeMessageConverter);

    CompositeMessageConverter compositeMessageConverter =
        this.appContext.getBean(CompositeMessageConverter.class);
    assertNotNull(compositeMessageConverter);

    SimpMessagingTemplate simpMessagingTemplate =
        this.appContext.getBean(SimpMessagingTemplate.class);
    assertNotNull(simpMessagingTemplate);
    assertEquals("/personal/", simpMessagingTemplate.getUserDestinationPrefix());

    List<MessageConverter> converters = compositeMessageConverter.getConverters();
    assertThat(converters.size(), Matchers.is(3));
    assertThat(converters.get(0), Matchers.instanceOf(StringMessageConverter.class));
    assertThat(converters.get(1), Matchers.instanceOf(ByteArrayMessageConverter.class));
    assertThat(converters.get(2), Matchers.instanceOf(MappingJackson2MessageConverter.class));

    ContentTypeResolver resolver =
        ((MappingJackson2MessageConverter) converters.get(2)).getContentTypeResolver();
    assertEquals(
        MimeTypeUtils.APPLICATION_JSON,
        ((DefaultContentTypeResolver) resolver).getDefaultMimeType());

    DirectFieldAccessor handlerAccessor = new DirectFieldAccessor(annotationMethodMessageHandler);
    String pathSeparator =
        (String)
            new DirectFieldAccessor(handlerAccessor.getPropertyValue("pathMatcher"))
                .getPropertyValue("pathSeparator");
    assertEquals(".", pathSeparator);
  }
 @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);
  }
Example #10
0
  /**
   * {@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);
 }