当前位置: 首页>>代码示例>>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;未经允许,请勿转载。