org.springframework.messaging.handler.annotation.MessageMapping Java Examples

The following examples show how to use org.springframework.messaging.handler.annotation.MessageMapping. 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: PlaylistWSController.java    From airsonic-advanced with GNU General Public License v3.0 6 votes vote down vote up
@MessageMapping("/create/empty")
@SendToUser(broadcast = false)
public int createEmptyPlaylist(Principal p) {
    Locale locale = localeResolver.resolveLocale(p.getName());
    DateTimeFormatter dateFormat = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT).withLocale(locale);

    Instant now = Instant.now();
    Playlist playlist = new Playlist();
    playlist.setUsername(p.getName());
    playlist.setCreated(now);
    playlist.setChanged(now);
    playlist.setShared(false);
    playlist.setName(dateFormat.format(now.atZone(ZoneId.systemDefault())));

    playlistService.createPlaylist(playlist);

    return playlist.getId();
}
 
Example #2
Source File: RSocketServerToClientIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@MessageMapping("connect.echo-channel")
void echoChannel(RSocketRequester requester) {
	runTest(() -> {
		Flux<String> flux = requester.route("echo-channel")
				.data(Flux.range(1, 10).map(i -> "Hello " + i), String.class)
				.retrieveFlux(String.class);

		StepVerifier.create(flux)
				.expectNext("Hello 1 async")
				.expectNextCount(7)
				.expectNext("Hello 9 async")
				.expectNext("Hello 10 async")
				.thenCancel()  // https://github.com/rsocket/rsocket-java/issues/613
				.verify(Duration.ofSeconds(5));
	});
}
 
Example #3
Source File: PlaylistWSController.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@MessageMapping("/update")
public void updatePlaylist(PlaylistUpdateRequest req) {
    Playlist playlist = new Playlist(playlistService.getPlaylist(req.getId()));
    playlist.setName(req.getName());
    playlist.setComment(req.getComment());
    playlist.setShared(req.getShared());
    playlistService.updatePlaylist(playlist);
}
 
Example #4
Source File: SimpAnnotationMethodMessageHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@MessageMapping("/message/{foo}/{name}")
public void messageMappingDestinationVariable(@DestinationVariable("foo") String param1,
		@DestinationVariable("name") String param2) {
	this.method = "messageMappingDestinationVariable";
	this.arguments.put("foo", param1);
	this.arguments.put("name", param2);
}
 
Example #5
Source File: ChatController.java    From springboot-websocket-demo with Apache License 2.0 5 votes vote down vote up
@MessageMapping("/chat.addUser")
public void addUser(@Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) {

    LOGGER.info("User added in Chatroom:" + chatMessage.getSender());
    try {
        headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
        redisTemplate.opsForSet().add(onlineUsers, chatMessage.getSender());
        redisTemplate.convertAndSend(userStatus, JsonUtil.parseObjToJson(chatMessage));
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
}
 
Example #6
Source File: ChatController.java    From spring-examples with GNU General Public License v3.0 5 votes vote down vote up
@MessageMapping("/chat")
//@SendTo("/topic")
//@SendToUser()
public void chatEndpoint(@Payload WsMessage wsMessage) {
    System.out.println(wsMessage);
    messagingTemplate.convertAndSend("/topic", wsMessage);
}
 
Example #7
Source File: ChatController.java    From springboot-websocket-demo with Apache License 2.0 5 votes vote down vote up
@MessageMapping("/chat.sendMessage")
public void sendMessage(@Payload ChatMessage chatMessage) {
    try {
        redisTemplate.convertAndSend(msgToAll, JsonUtil.parseObjToJson(chatMessage));
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
}
 
Example #8
Source File: RSocketServerToClientIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@MessageMapping("connect.echo-stream")
void echoStream(RSocketRequester requester) {
	runTest(() -> {
		Flux<String> flux = requester.route("echo-stream").data("Hello").retrieveFlux(String.class);

		StepVerifier.create(flux)
				.expectNext("Hello 0")
				.expectNextCount(5)
				.expectNext("Hello 6")
				.expectNext("Hello 7")
				.thenCancel()
				.verify(Duration.ofSeconds(5));
	});
}
 
Example #9
Source File: XeChatController.java    From xechat with MIT License 5 votes vote down vote up
/**
 * 聊天室发布订阅
 *
 * @param messageRO 消息请求对象
 * @param user 发送消息的用户对象
 * @throws Exception
 */
@MessageMapping(StompConstant.PUB_CHAT_ROOM)
public void chatRoom(MessageRO messageRO, User user) throws Exception {
    String message = messageRO.getMessage();

    if (!CheckUtils.checkMessageRo(messageRO) || !CheckUtils.checkUser(user)) {
        throw new ErrorCodeException(CodeEnum.INVALID_PARAMETERS);
    }
    if (CheckUtils.checkMessage(message) && message.startsWith(RobotConstant.prefix)) {
        messageService.sendMessageToRobot(StompConstant.SUB_CHAT_ROOM, message, user);
    }

    messageService.sendMessage(StompConstant.SUB_CHAT_ROOM, new MessageVO(user, message, messageRO.getImage(),
            MessageTypeEnum.USER));
}
 
Example #10
Source File: WebSocketController.java    From Demo with Apache License 2.0 5 votes vote down vote up
@MessageMapping("/chat")
public void handleChat(Principal principal,String msg){
    // 在 SpringMVC 中,可以直接在参数中获得 principal,principal 中包含当前用户信息
    if (principal.getName().equals("nasus")){
        // 硬编码,如果发送人是 nasus 则接收人是 chenzy 反之也成立。
        // 通过 messageingTemplate.convertAndSendToUser 方法向用户发送信息,参数一是接收消息用户,参数二是浏览器订阅地址,参数三是消息本身
        messagingTemplate.convertAndSendToUser("chenzy",
                "/queue/notifications",principal.getName()+"-send:" + msg);
    } else {
        messagingTemplate.convertAndSendToUser("nasus",
                "/queue/notifications",principal.getName()+"-send:" + msg);
    }
}
 
Example #11
Source File: RSocketController.java    From spring-rsocket-demo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This @MessageMapping is intended to be used "stream <--> stream" style.
 * The incoming stream contains the interval settings (in seconds) for the outgoing stream of messages.
 *
 * @param settings
 * @return
 */
@PreAuthorize("hasRole('USER')")
@MessageMapping("channel")
Flux<Message> channel(final Flux<Duration> settings, @AuthenticationPrincipal UserDetails user) {
    log.info("Received channel request...");
    log.info("Channel initiated by '{}' in the role '{}'", user.getUsername(), user.getAuthorities());

    return settings
            .doOnNext(setting -> log.info("Channel frequency setting is {} second(s).", setting.getSeconds()))
            .doOnCancel(() -> log.warn("The client cancelled the channel."))
            .switchMap(setting -> Flux.interval(setting)
                    .map(index -> new Message(SERVER, CHANNEL, index)));
}
 
Example #12
Source File: PlaylistWSController.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@MessageMapping("/files/moveup")
@SendToUser(broadcast = false)
public int up(PlaylistFilesModificationRequest req) {
    // in this context, modifierIds has one element that is the index of the file
    List<MediaFile> files = playlistService.getFilesInPlaylist(req.getId(), true);
    if (req.getModifierIds().size() == 1 && req.getModifierIds().get(0) > 0) {
        Collections.swap(files, req.getModifierIds().get(0), req.getModifierIds().get(0) - 1);
        playlistService.setFilesInPlaylist(req.getId(), files);
    }

    return req.getId();
}
 
Example #13
Source File: PlaylistWSController.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@MessageMapping("/files/movedown")
@SendToUser(broadcast = false)
public int down(PlaylistFilesModificationRequest req) {
    // in this context, modifierIds has one element that is the index of the file
    List<MediaFile> files = playlistService.getFilesInPlaylist(req.getId(), true);
    if (req.getModifierIds().size() == 1 && req.getModifierIds().get(0) < files.size() - 1) {
        Collections.swap(files, req.getModifierIds().get(0), req.getModifierIds().get(0) + 1);
        playlistService.setFilesInPlaylist(req.getId(), files);
    }

    return req.getId();
}
 
Example #14
Source File: PlaylistWSController.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@MessageMapping("/files/rearrange")
@SendToUser(broadcast = false)
public int rearrange(PlaylistFilesModificationRequest req) {
    // in this context, modifierIds are indices
    List<MediaFile> files = playlistService.getFilesInPlaylist(req.getId(), true);
    MediaFile[] newFiles = new MediaFile[files.size()];
    for (int i = 0; i < req.getModifierIds().size(); i++) {
        newFiles[i] = files.get(req.getModifierIds().get(i));
    }
    playlistService.setFilesInPlaylist(req.getId(), Arrays.asList(newFiles));

    return req.getId();
}
 
Example #15
Source File: WebSocketController.java    From torrssen2 with MIT License 5 votes vote down vote up
@MessageMapping("/remove")
public DownloadList remove(DownloadList download) {
    if (downloadService.remove(download) >= 0) {
        return download;
    } else {
        return null;
    }
}
 
Example #16
Source File: MessageMappingMessageHandlerTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@MessageMapping("monoString")
Mono<String> handleMonoString(Mono<String> payload) {
	return payload.map(s -> s + "::response").delayElement(Duration.ofMillis(10));
}
 
Example #17
Source File: LyricsWSController.java    From airsonic-advanced with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns lyrics for the given song and artist.
 *
 * @return The lyrics, never <code>null</code> .
 */
@MessageMapping("/get")
@SendToUser(broadcast = false)
public LyricsInfo getLyrics(LyricsGetRequest req) {
    return getLyrics(req.getArtist(), req.getSong());
}
 
Example #18
Source File: MessageBrokerConfigurationTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@MessageMapping("/foo")
@SendTo("/bar")
public String handleMessage() {
	return "bar";
}
 
Example #19
Source File: ChatController.java    From code with Apache License 2.0 4 votes vote down vote up
@MessageMapping("/chat.sendMessage")
@SendTo("/topic/public")
public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
    //chatMessage.setContent(chatMessage.getContent().replace("<", "%3c").replace(">","%3e"));
    return chatMessage;
}
 
Example #20
Source File: RSocketBufferLeakTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@MessageMapping("request-stream")
Flux<String> stream(String payload) {
	return Flux.range(1,100).delayElements(Duration.ofMillis(10)).map(idx -> payload + "-" + idx);
}
 
Example #21
Source File: MessageMappingMessageHandlerTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@MessageMapping("fluxString")
Flux<String> handleFluxString(Flux<String> payload) {
	return payload.map(s -> s + "::response").delayElements(Duration.ofMillis(10));
}
 
Example #22
Source File: SimpAnnotationMethodMessageHandlerTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@MessageMapping("completable-future")
public CompletableFuture<String> handleCompletableFuture() {
	this.future = new CompletableFuture<>();
	return this.future;
}
 
Example #23
Source File: SimpAnnotationMethodMessageHandlerTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@MessageMapping("/optionalHeaders")
public void optionalHeaders(@Header(name="foo", required=false) String foo1, @Header("foo") Optional<String> foo2) {
	this.method = "optionalHeaders";
	this.arguments.put("foo1", foo1);
	this.arguments.put("foo2", (foo2.isPresent() ? foo2.get() : null));
}
 
Example #24
Source File: RSocketClientToServerIntegrationTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@MessageMapping("void-return-value")
Mono<Void> voidReturnValue(String payload) {
	return !payload.equals("bad") ?
			Mono.delay(Duration.ofMillis(10)).then(Mono.empty()) :
			Mono.error(new IllegalStateException("bad"));
}
 
Example #25
Source File: SimpAnnotationMethodMessageHandlerTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@MessageMapping("/validation/payload")
public void payloadValidation(@Validated @Payload String payload) {
	this.method = "payloadValidation";
	this.arguments.put("message", payload);
}
 
Example #26
Source File: StarWSController.java    From airsonic-advanced with GNU General Public License v3.0 4 votes vote down vote up
@MessageMapping("/unstar")
public void unstar(Principal user, int id) {
    mediaFileDao.unstarMediaFile(id, user.getName());
}
 
Example #27
Source File: SimpAnnotationMethodMessageHandlerTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@MessageMapping("/optionalHeaders")
public void optionalHeaders(@Header(name="foo", required=false) String foo1, @Header("foo") Optional<String> foo2) {
	this.method = "optionalHeaders";
	this.arguments.put("foo1", foo1);
	this.arguments.put("foo2", (foo2.isPresent() ? foo2.get() : null));
}
 
Example #28
Source File: StompWebSocketIntegrationTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@MessageMapping("/increment")
public int handle(int i) {
	return i + 1;
}
 
Example #29
Source File: MediaFileWSController.java    From airsonic-advanced with GNU General Public License v3.0 4 votes vote down vote up
@MessageMapping("/directory/get")
@SendToUser(broadcast = false)
public Object get(Principal user, MediaDirectoryRequest req, SimpMessageHeaderAccessor headers) throws Exception {
    List<MediaFile> mediaFiles = getMediaFiles(req.getIds(), req.getPaths());

    if (mediaFiles.isEmpty()) {
        return ImmutableMap.of("contentType", "notFound");
    }

    MediaFile dir = mediaFiles.get(0);
    if (dir.isFile()) {
        dir = mediaFileService.getParentOf(dir);
    }

    // Redirect if root directory.
    if (mediaFileService.isRoot(dir)) {
        return ImmutableMap.of("contentType", "home");
    }

    if (!securityService.isFolderAccessAllowed(dir, user.getName())) {
        return ImmutableMap.of("contentType", "accessDenied");
    }

    List<MediaFile> children = getChildren(mediaFiles);

    List<MediaFile> files = new ArrayList<>();
    List<MediaFile> subDirs = new ArrayList<>();
    for (MediaFile child : children) {
        if (child.isFile()) {
            files.add(child);
        } else {
            subDirs.add(child);
        }
    }
    MediaFileDirectoryEntry entry = new MediaFileDirectoryEntry(mediaFileService.toMediaFileEntryList(Collections.singletonList(dir), user.getName(), true, true, null, null, null).get(0));
    entry.setFiles(mediaFileService.toMediaFileEntryList(files, user.getName(), true, false, null, null, null));
    entry.setSubDirs(mediaFileService.toMediaFileEntryList(subDirs, user.getName(), false, false, null, null, null));
    entry.setAncestors(mediaFileService.toMediaFileEntryList(getAncestors(dir), user.getName(), false, false, null, null, null));
    entry.setLastPlayed(dir.getLastPlayed());
    entry.setPlayCount(dir.getPlayCount());
    entry.setComment(dir.getComment());
    if (dir.isAlbum()) {
        List<MediaFile> siblingAlbums = getSiblingAlbums(dir);
        entry.setSiblingAlbums(mediaFileService.toMediaFileEntryList(siblingAlbums, user.getName(), false, false, null, null, null));
        entry.setAlbum(guessAlbum(children));
        entry.setArtist(guessArtist(children));
        entry.setMusicBrainzReleaseId(guessMusicBrainzReleaseId(children));
    }

    Integer userRating = Optional.ofNullable(ratingService.getRatingForUser(user.getName(), dir)).orElse(0);
    Double averageRating = Optional.ofNullable(ratingService.getAverageRating(dir)).orElse(0.0D);

    entry.setUserRating(10 * userRating);
    entry.setAverageRating(10.0D * averageRating);

    if (isVideoOnly(children)) {
        entry.setContentType("video");
    } else if (dir.isAlbum()) {
        entry.setContentType("album");
    } else {
        entry.setContentType("artist");
    }

    return entry;
}
 
Example #30
Source File: WebsocketController.java    From demo-projects with MIT License 4 votes vote down vote up
@MessageMapping("/incoming")
@SendTo("/topic/outgoing")
public String incoming(Message message) {
    LOGGER.info(String.format("received message: %s", message));
    return String.format("Application on port %s responded to your message: \"%s\"", port, message.getMessage());
}