當前位置: 首頁>>代碼示例>>Java>>正文


Java MessageMapping類代碼示例

本文整理匯總了Java中org.springframework.messaging.handler.annotation.MessageMapping的典型用法代碼示例。如果您正苦於以下問題:Java MessageMapping類的具體用法?Java MessageMapping怎麽用?Java MessageMapping使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


MessageMapping類屬於org.springframework.messaging.handler.annotation包,在下文中一共展示了MessageMapping類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: handleMessages

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
/**
 * Receive and send messages via websockets.
 * <p>
 * Note: public and private chats work the same way. The permission handling is
 * done at the SUBSCRIBE event as part of the AuthenticationInterceptor.
 *
 * @param roomId   String
 * @param message  Message
 * @param traveler Traveler
 * @return Message
 * @throws Exception
 */
@MessageMapping("/chat/{roomId}")
public Message handleMessages(@DestinationVariable("roomId") String roomId, @Payload Message message, Traveler traveler) throws Exception {
	System.out.println("Message received for room: " + roomId);
	System.out.println("User: " + traveler.toString());

	// store message in database
	message.setAuthor(traveler);
	message.setChatRoomId(Integer.parseInt(roomId));
	int id = MessageRepository.getInstance().save(message);
	message.setId(id);

	return message;
}
 
開發者ID:trvlrch,項目名稱:trvlr-backend,代碼行數:26,代碼來源:ChatController.java

示例2: createGame

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
@ApiMethod(description = "Create a new lobby.")
@MessageMapping("/lobby/create")
@SendToUser("/queue/lobby/joined")
public Lobby createGame(@Validated CreateGameAction action, Principal principal) {
    checkThatUserIsNotInAGame(principal, "cannot create another game");

    Player gameOwner = playerRepository.find(principal.getName());
    Lobby lobby = lobbyRepository.create(action.getGameName(), gameOwner);

    logger.info("Game '{}' ({}) created by {} ({})", lobby.getName(), lobby.getId(), gameOwner.getDisplayName(),
            gameOwner.getUsername());

    // notify everyone that a new game exists
    template.convertAndSend("/topic/games", Collections.singletonList(lobby));
    return lobby;
}
 
開發者ID:luxons,項目名稱:seven-wonders,代碼行數:17,代碼來源:GameBrowserController.java

示例3: ready

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
@ApiMethod(description = "Notifies the game that the player is ready to receive his hand.")
@MessageMapping("/game/sayReady")
public void ready(Principal principal) {
    Player player = playerRepository.find(principal.getName());
    player.setReady(true);
    Game game = player.getGame();
    logger.info("Game {}: player {} is ready for the next turn", game.getId(), player);

    Lobby lobby = player.getLobby();
    List<Player> players = lobby.getPlayers();

    boolean allReady = players.stream().allMatch(Player::isReady);
    if (allReady) {
        logger.info("Game {}: all players ready, sending turn info", game.getId());
        players.forEach(p -> p.setReady(false));
        sendTurnInfo(players, game);
    } else {
        sendPlayerReady(game.getId(), player);
    }
}
 
開發者ID:luxons,項目名稱:seven-wonders,代碼行數:21,代碼來源:GameController.java

示例4: prepareMove

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
@ApiMethod(description = "Prepares the player's next move. When all players have prepared their moves, all moves "
        + "are executed.")
@MessageMapping("/game/prepareMove")
public void prepareMove(PrepareMoveAction action, Principal principal) {
    Player player = playerRepository.find(principal.getName());
    Game game = player.getGame();
    CardBack preparedCardBack = game.prepareMove(player.getIndex(), action.getMove());
    PreparedCard preparedCard = new PreparedCard(player, preparedCardBack);
    logger.info("Game {}: player {} prepared move {}", game.getId(), principal.getName(), action.getMove());

    if (game.allPlayersPreparedTheirMove()) {
        logger.info("Game {}: all players have prepared their move, executing turn...", game.getId());
        Table table = game.playTurn();
        sendPlayedMoves(game.getId(), table);
    } else {
        sendPreparedCard(game.getId(), preparedCard);
    }
}
 
開發者ID:luxons,項目名稱:seven-wonders,代碼行數:19,代碼來源:GameController.java

示例5: addSub

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
@MessageMapping("/subscriptions/add")
/* do no use List<> here due it not support deserialization from string, which is need for back capability */
public void addSub(UiAddSubscription[] uases) {
    //we save absent subscriptions into array for prevent multiple log records
    List<String> absent = new ArrayList<>(0/*usually is no absent ids*/);
    for(UiAddSubscription uas: uases) {
        String id = uas.getSource();
        Subscriptions<?> subs = sources.get(id);
        if(subs == null) {
            absent.add(id);
            continue;
        }
        subscriptions.subscribe(uas, subs);
    }
    if(!absent.isEmpty()) {
        log.warn("Can not find subscriptions with ids: {}", absent);
    }
}
 
開發者ID:codeabovelab,項目名稱:haven-platform,代碼行數:19,代碼來源:EventController.java

示例6: sendMessageToAllUsers

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
/**
 * Send the given message to all users after checking the authorization of the user.
 * @param message The message to be sent.
 * @param accessToken The oauth2 accessToken of the user.
 * @return the message to the topic
 * @throws Exception Thrown if not authorized for instance.
 */
@MessageMapping("/user-messages")
@SendTo("/topic/user-messages")
public MessageDto sendMessageToAllUsers(MessageDto message, 
    @Header("access_token") String accessToken) throws Exception {
  OAuth2AccessToken oauth2accessToken = tokenStore.readAccessToken(accessToken);
  if (oauth2accessToken != null) {
    OAuth2Authentication authentication = tokenStore.readAuthentication(oauth2accessToken);
    if (authentication != null && authentication.getAuthorities().contains(
        new SimpleGrantedAuthority("ROLE_ADMIN"))) {
      message.setSender(authentication.getUserAuthentication().getName());
      log.debug("Sending message from {} to all users", message.getSender()); 
      return message;        
    }
  }
  log.error("Unauthorized message from {} with content: {}", 
      message.getSender(), message.getText());
  throw new SessionAuthenticationException("No valid access token found!");
}
 
開發者ID:dzhw,項目名稱:metadatamanagement,代碼行數:26,代碼來源:UserMessagesController.java

示例7: joinQueue

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
/**
 * Join a queue.
 *
 * @param queueId the queue id
 * @param bindingResult the binding result
 */
@MessageMapping(value = "/joinQueue")
public void joinQueue(final Integer queueId) {

	if (queueId == null) {
		throw new JsonErrorException("Queue id is null");
	}

	final Player player = this.wsUserContext.getPlayer();
	final Queue queue = this.matchmaking.getQueueById(queueId);

	if (queue == null) {
		throw new JsonErrorException("Queue does not exist");
	}
	if (queue.isFull()) {
		throw new JsonErrorException("Queue is full");
	}
	if (queue.containsPlayer(player)) {
		throw new JsonErrorException("Player already in queue");
	}
	if (queue.getState() != QueueState.WAITING_PLAYERS) {
		throw new JsonErrorException("Incorrect queue state");
	}

	this.matchmaking.joinQueue(player, queue);
}
 
開發者ID:TeeFun,項目名稱:TeeFun,代碼行數:32,代碼來源:WebSocketController.java

示例8: quitQueue

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
/**
 * Quit a queue.
 *
 * @param queueId the queue id
 * @param bindingResult the binding result
 */
@MessageMapping(value = "/quitQueue")
public void quitQueue(final Integer queueId) {

	if (queueId == null) {
		throw new JsonErrorException("Queue id is null");
	}

	final Player player = this.wsUserContext.getPlayer();
	final Queue queue = this.matchmaking.getQueueById(queueId);

	if (queue == null) {
		throw new JsonErrorException("Queue does not exist");
	}
	if (queue.isFull()) {
		throw new JsonErrorException("Queue is full");
	}
	if (!queue.containsPlayer(player)) {
		throw new JsonErrorException("Player is not in this queue");
	}
	if (queue.getState() != QueueState.WAITING_PLAYERS) {
		throw new JsonErrorException("Incorrect queue state");
	}

	this.matchmaking.quitQueue(player, queue);
}
 
開發者ID:TeeFun,項目名稱:TeeFun,代碼行數:32,代碼來源:WebSocketController.java

示例9: askPassword

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
/**
 * Player is ready/notready.
 *
 * @param queueId the queue id
 * @param bindingResult the binding result
 * @return the password
 */
@MessageMapping(value = "/askPassword")
public String askPassword(final Integer queueId) {

	if (queueId == null) {
		throw new JsonErrorException("Queue id is null");
	}

	final Queue queue = this.matchmaking.getQueueById(queueId);

	if (queue == null) {
		throw new JsonErrorException("Queue does not exist");
	}
	if (!queue.containsPlayer(this.wsUserContext.getPlayer())) {
		throw new JsonErrorException("Player is not in this queue");
	}
	if (queue.getState() != QueueState.IN_GAME) {
		throw new JsonErrorException("Game not ready");
	}

	return queue.getServer().getConfig().getVariableAsString("password");
}
 
開發者ID:TeeFun,項目名稱:TeeFun,代碼行數:29,代碼來源:WebSocketController.java

示例10: playerReady

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
/**
 * Player is ready/notready.
 *
 * @param playerReadyRequest the request
 * @param bindingResult the binding result
 */
@MessageMapping(value = "/playerReady")
public void playerReady(@RequestBody @Valid final PlayerReadyRequest playerReadyRequest, final BindingResult bindingResult) {

	if (bindingResult.hasErrors()) {
		throw new JsonErrorException("Request validation failed", bindingResult);
	}

	final Queue queue = this.matchmaking.getQueueById(playerReadyRequest.getQueueId());

	if (queue == null) {
		throw new JsonErrorException("Queue does not exist", bindingResult);
	}
	if (!queue.containsPlayer(this.wsUserContext.getPlayer())) {
		throw new JsonErrorException("Player is not in this queue", bindingResult);
	}
	if (queue.getState() != QueueState.WAITING_READY) {
		throw new JsonErrorException("Incorrect queue state", bindingResult);
	}

	queue.setPlayerReady(this.wsUserContext.getPlayer(), playerReadyRequest.getReady());
	this.eventBus.post(new PlayerReadyEvent(this.wsUserContext.getPlayer(), queue));
}
 
開發者ID:TeeFun,項目名稱:TeeFun,代碼行數:29,代碼來源:WebSocketController.java

示例11: join

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
/**
 * direct message handler that receives a join message from a device. When a device joins, a session is attempted to
 * be found within a tolerated geo-proximity. if one is found, the device is added to it and returned, if not, a
 * new session is created.
 *
 * @param   j   a stringified JoinMessage sent from the device seeking to join a session
 * @return      stringified JoinResponse
 *
 * @see     JoinMessage
 * @see     JoinResponse
 */
@MessageMapping("/join")
@SendToUser("/queue/device")
public String join(JoinMessage j) {
    String joinType = j.getType().toString();
    switch(joinType){
        case "enter":
            break;
        case "exit":
            Session session = (Session) this.sessionService.get(j);
            String uuid = session.getUuid().toString();
            //Return join
            String joinResponse = gson.toJson(new JoinResponse(session.getApplicationId(), uuid, session.getDevices(), session.getRoom()), JoinResponse.class);
            if(logger.isDebugEnabled())
                logger.debug(String.format("JOIN RESPONSE: %s", joinResponse));
            return joinResponse;
        default:
            logger.error(String.format("Detected SyncType %s not supported", joinType));
    }
    return null;
}
 
開發者ID:wieden-kennedy,項目名稱:composite-framework,代碼行數:32,代碼來源:CompositeController.java

示例12: pair

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
/**
 * Direct message handler that receives pair message from a device. When device joins, session is found or a new
 * pair session is created.
 *
 * @param p     Stringified PairMessage sent from device seeking to pair up with another device
 * @return      Stringified PairResponse
 *
 * @see         PairResponse
 * @see         PairMessage
 */
@MessageMapping("/pair")
@SendToUser("/queue/device")
public String pair(PairMessage p){
    String pairType = p.getType().toString();
    switch(pairType){
        case "enter":
            break;
        case "exit":
            Session session = this.sessionService.pair(p);
            String uuid = session.getUuid().toString();
            // Return pair
            String pairResponse = gson.toJson(new PairResponse(session.getApplicationId(), uuid,session.getDevices()),PairResponse.class);
            if(logger.isDebugEnabled()){
                logger.debug(String.format("PAIR RESPONSE: %s", pairResponse));
            }
            return pairResponse;
        default:
            logger.error(String.format("Detected SyncType %s not supported", pairType));
    }
    return null;
}
 
開發者ID:wieden-kennedy,項目名稱:composite-framework,代碼行數:32,代碼來源:CompositeController.java

示例13: getMappingForMethod

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
@Override
protected MappingInformation getMappingForMethod(Method method, Class<?> handlerType) {
    SqsListener sqsListenerAnnotation = AnnotationUtils.findAnnotation(method, SqsListener.class);
    if (sqsListenerAnnotation != null && sqsListenerAnnotation.value().length > 0) {
        if (sqsListenerAnnotation.deletionPolicy() == SqsMessageDeletionPolicy.NEVER && hasNoAcknowledgmentParameter(method.getParameterTypes())) {
            this.logger.warn("Listener method '" + method.getName() + "' in type '" + method.getDeclaringClass().getName() +
                    "' has deletion policy 'NEVER' but does not have a parameter of type Acknowledgment.");
        }
        return new MappingInformation(resolveDestinationNames(sqsListenerAnnotation.value()), sqsListenerAnnotation.deletionPolicy());
    }

    MessageMapping messageMappingAnnotation = AnnotationUtils.findAnnotation(method, MessageMapping.class);
    if (messageMappingAnnotation != null && messageMappingAnnotation.value().length > 0) {
        return new MappingInformation(resolveDestinationNames(messageMappingAnnotation.value()), SqsMessageDeletionPolicy.ALWAYS);
    }

    return null;
}
 
開發者ID:spring-cloud,項目名稱:spring-cloud-aws,代碼行數:19,代碼來源:QueueMessageHandler.java

示例14: executeBulbActuation

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
/**
    * Client must call <code>/core/bulbs/actuation</code> due to app destination 
    * prefix is set to <code>core</code> - see WebSocketConfig for more details
    * 
    * @param cmd JSON encoded {@link DtoBulbActuatorCmd} expected here
    * @param principal 
    */
   @ApiOperation(value = "Control a single, specific bulb.", httpMethod = "POST")
   @RequestMapping (method= RequestMethod.POST, value = "/bulbs/actuation")
   @MessageMapping({"/bulbs/actuation"})
public void executeBulbActuation(
           @Valid @Payload @RequestBody @ApiParam DtoBulbActuatorCmd cmd,
           Principal principal) {

       String userApiKey =  ((BulbsContextUser)((Authentication)principal).getPrincipal()).getApiKey();

       BulbActuatorCommand bCmd =
               new ConverterBulbActuatorCmd().reverseConvert(cmd);
       bCmd.setUserApiKey(userApiKey);

       try {
           actuatorService.executeDeferred(bCmd);
       } catch (BulbBridgeHwException ex) {
           log.error(ex.getMessage(), ex);
       }
}
 
開發者ID:datenstrudel,項目名稱:bulbs-core,代碼行數:27,代碼來源:WebSocketBulbsCoreCtrl.java

示例15: executeGroupActuation

import org.springframework.messaging.handler.annotation.MessageMapping; //導入依賴的package包/類
@ApiOperation(value = "Control a group of bulbs.", httpMethod = "POST")
    @RequestMapping (method= RequestMethod.POST, value = "/groups/actuation")
    @MessageMapping({"/groups/actuation"})
	public void executeGroupActuation(
            @Valid @Payload @RequestBody DtoGroupActuatorCmd cmd,
            Principal principal) {

        String userApiKey =  ((BulbsContextUser)((Authentication)principal).getPrincipal()).getApiKey();
//        DtoGroupActuatorCmd cmd = gson.fromJson(
//                new String( (byte[]) body.getPayload()),
//                DtoGroupActuatorCmd.class);
        GroupActuatorCommand gCmd =
                new ConverterGroupActuatorCmd().reverseConvert(cmd);
        gCmd.setUserApiKey(userApiKey);

        try {
            actuatorService.executeDeferred(gCmd);
        } catch (BulbBridgeHwException ex) {
            log.error(ex.getMessage(), ex);
        }
	}
 
開發者ID:datenstrudel,項目名稱:bulbs-core,代碼行數:22,代碼來源:WebSocketBulbsCoreCtrl.java


注:本文中的org.springframework.messaging.handler.annotation.MessageMapping類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。