Java Code Examples for org.springframework.messaging.handler.annotation.SendTo

The following examples show how to use org.springframework.messaging.handler.annotation.SendTo. These examples are extracted from open source projects. 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 Project: spring_io_2019   Source File: ScsApplication.java    License: Apache License 2.0 6 votes vote down vote up
@StreamListener
@SendTo(Bindings.RATED_MOVIES)
KStream<Long, RatedMovie> rateMoviesFor(@Input(Bindings.AVG_TABLE) KTable<Long, Double> ratings,
                                        @Input(Bindings.MOVIES) KTable<Long, Movie> movies) {

  ValueJoiner<Movie, Double, RatedMovie> joiner = (movie, rating) ->
      new RatedMovie(movie.getMovieId(), movie.getReleaseYear(), movie.getTitle(), rating);

  movies
      .join(ratings, joiner, Materialized
          .<Long, RatedMovie, KeyValueStore<Bytes, byte[]>>as(Bindings.RATED_MOVIES_STORE)
          .withKeySerde(Serdes.Long())
          .withValueSerde(new JsonSerde<>(RatedMovie.class)));

  return movies.join(ratings, joiner).toStream();
}
 
Example 2
@StreamListener
@SendTo("output")
public KStream<String, Long> process(
		@Input("input") KStream<String, Long> userClicksStream,
		@Input("input-x") KTable<String, String> userRegionsTable) {

	return userClicksStream
			.leftJoin(userRegionsTable,
					(clicks, region) -> new RegionWithClicks(
							region == null ? "UNKNOWN" : region, clicks),
					Joined.with(Serdes.String(), Serdes.Long(), null))
			.map((user, regionWithClicks) -> new KeyValue<>(
					regionWithClicks.getRegion(), regionWithClicks.getClicks()))
			.groupByKey(Serialized.with(Serdes.String(), Serdes.Long()))
			.reduce(Long::sum)
			.toStream();
}
 
Example 3
protected static String getOutboundBindingTargetName(Method method) {
	SendTo sendTo = AnnotationUtils.findAnnotation(method, SendTo.class);
	if (sendTo != null) {
		Assert.isTrue(!ObjectUtils.isEmpty(sendTo.value()),
				StreamListenerErrorMessages.ATLEAST_ONE_OUTPUT);
		Assert.isTrue(sendTo.value().length == 1,
				StreamListenerErrorMessages.SEND_TO_MULTIPLE_DESTINATIONS);
		Assert.hasText(sendTo.value()[0],
				StreamListenerErrorMessages.SEND_TO_EMPTY_DESTINATION);
		return sendTo.value()[0];
	}
	Output output = AnnotationUtils.findAnnotation(method, Output.class);
	if (output != null) {
		Assert.isTrue(StringUtils.hasText(output.value()),
				StreamListenerErrorMessages.ATLEAST_ONE_OUTPUT);
		return output.value();
	}
	return null;
}
 
Example 4
@StreamListener
@SendTo("output")
public KStream<?, WordCount> process(
		@Input("input") KStream<Object, String> input) {

	input.map((k, v) -> {
		System.out.println(k);
		System.out.println(v);
		return new KeyValue<>(k, v);
	});
	return input
			.flatMapValues(
					value -> Arrays.asList(value.toLowerCase().split("\\W+")))
			.map((key, value) -> new KeyValue<>(value, value))
			.groupByKey(Serialized.with(Serdes.String(), Serdes.String()))
			.count(Materialized.as("WordCounts")).toStream()
			.map((key, value) -> new KeyValue<>(null, new WordCount(key, value)));
}
 
Example 5
@StreamListener
@SendTo("output")
public KStream<?, Sensor> process(@Input("input") KStream<Object, Sensor> input) {
	// return the same Sensor object unchanged so that we can do test
	// verifications
	return input.map(KeyValue::new);
}
 
Example 6
@Override
public boolean supportsReturnType(MethodParameter returnType) {
	return (returnType.hasMethodAnnotation(SendTo.class) ||
			AnnotatedElementUtils.hasAnnotation(returnType.getDeclaringClass(), SendTo.class) ||
			returnType.hasMethodAnnotation(SendToUser.class) ||
			AnnotatedElementUtils.hasAnnotation(returnType.getDeclaringClass(), SendToUser.class) ||
			!this.annotationRequired);
}
 
Example 7
Source Project: springboot-learn   Source File: ChatController.java    License: MIT License 5 votes vote down vote up
@MessageMapping("/chat/addUser")
@SendTo(WebSocketConstants.CHAT_TOPIC)
public ChatMessage addUser(@Payload ChatMessage chatMessage,
                           SimpMessageHeaderAccessor headerAccessor) {
    headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
    return chatMessage;
}
 
Example 8
@StreamListener("input")
@SendTo("output")
public KStream<Integer, Long> process(KStream<Object, Product> input) {
	return input.filter((key, product) -> product.getId() == 123)
			.map((key, value) -> new KeyValue<>(value, value))
			.groupByKey(Serialized.with(new JsonSerde<>(Product.class),
					new JsonSerde<>(Product.class)))
			.windowedBy(TimeWindows.of(5000))
			.count(Materialized.as("id-count-store-x")).toStream()
			.map((key, value) -> {
				return new KeyValue<>(key.key().id, value);
			});
}
 
Example 9
Source Project: spring-cloud-sleuth   Source File: GreetingController.java    License: Apache License 2.0 5 votes vote down vote up
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
	log.info("Hello: " + message);
	Thread.sleep(3000); // simulated delay
	// Then send back greeting
	return new Greeting("Hello, " + message.getName() + "!");
}
 
Example 10
Source Project: spring-cloud-stream   Source File: ContentTypeTckTests.java    License: Apache License 2.0 5 votes vote down vote up
@StreamListener(Processor.INPUT)
@SendTo(Processor.OUTPUT)
public Message<String> echo(Message<Person> value) {
	return MessageBuilder.withPayload(value.getPayload().toString())
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN)
			.build();
}
 
Example 11
@MessageMapping("/queue/CSM_QUEUE_{queueId}")
  @SendTo("/queue/CSM_QUEUE_{queueId}")
  public List<StockProduct> sendContent(@Payload List<String> tickers, @DestinationVariable("queueId") String queueId) throws Exception {
  	String username = extractUserFromQueueId(queueId);
  	if(!getPrincipal().getUsername().equals(username)){
  		throw new IllegalAccessError("/queue/CSM_QUEUE_"+queueId);
  	}
return stockProductService.gather(username, tickers.toArray(new String[tickers.size()]));
  }
 
Example 12
Source Project: demo-projects   Source File: MessageController.java    License: MIT License 5 votes vote down vote up
@MessageMapping("/send")
@SendTo("/topic/messages")
public Message send(Message message) {
    LOGGER.info(String.format("Received message [%s] on `/app/chat` message mapping!", message.toString()));
    LocalDateTime timestamp = LocalDateTime.now();
    return new Message(message.getFrom(), message.getMessage(), timestamp);
}
 
Example 13
@StreamListener(Processor.INPUT)
@SendTo(Processor.OUTPUT)
public Bar receive(Bar bar) {
	logger.info("******************\nAt the transformer\n******************");
	logger.info("Received value "+ bar.getValue() + " of type " + bar.getClass());
	logger.info("Transforming the value to " + TRANSFORMATION_VALUE + " and with the type " + bar.getClass());
	bar.setValue(TRANSFORMATION_VALUE);
	return bar;
}
 
Example 14
Source Project: code   Source File: ChatController.java    License: Apache License 2.0 5 votes vote down vote up
@MessageMapping("/chat.addUser")
@SendTo("/topic/public")
public ChatMessage addUser(@Payload ChatMessage chatMessage,
                           SimpMessageHeaderAccessor headerAccessor) {
    // Add username in web socket session
    logger.info("User added in Chatroom:" + chatMessage.getSender());
    headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
    return chatMessage;
}
 
Example 15
Source Project: code   Source File: StreamReceiver.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 接收orderDTO对象 消息
 * @param message
 */
@StreamListener(value = StreamClient.INPUT)
@SendTo(StreamClient.INPUT2)
public String process(OrderDTO message) {
    log.info("StreamReceiver: {}", message);
    return "received.";
}
 
Example 16
@StreamListener
@SendTo("output")
public KStream<?, KafkaStreamsBinderWordCountIntegrationTests.WordCount> process(
		@Input("input") KStream<Object, String> input) {

	return input
			.flatMapValues(
					value -> Arrays.asList(value.toLowerCase().split("\\W+")))
			.map((key, value) -> new KeyValue<>(value, value))
			.groupByKey(Serialized.with(Serdes.String(), Serdes.String()))
			.windowedBy(TimeWindows.of(Duration.ofSeconds(5))).count(Materialized.as("foo-WordCounts"))
			.toStream()
			.map((key, value) -> new KeyValue<>(null, null));
}
 
Example 17
Source Project: exchange-gateway-rest   Source File: GreetingController.java    License: Apache License 2.0 5 votes vote down vote up
@MessageMapping("/hello")
@SendTo("/topic/notifications")
public StompApiNotificationMessage greeting(HelloMessage message) throws Exception {
    log.debug("Greeting 1 {}", message);
    Thread.sleep(200); // simulated delay
    log.debug("Greeting 2 {}", message);
    return new StompApiNotificationMessage("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
 
Example 18
@Override
public boolean supportsReturnType(MethodParameter returnType) {
	return (returnType.hasMethodAnnotation(SendTo.class) ||
			AnnotatedElementUtils.hasAnnotation(returnType.getDeclaringClass(), SendTo.class) ||
			returnType.hasMethodAnnotation(SendToUser.class) ||
			AnnotatedElementUtils.hasAnnotation(returnType.getDeclaringClass(), SendToUser.class) ||
			!this.annotationRequired);
}
 
Example 19
Source Project: spring-websocket-template   Source File: MessageController.java    License: MIT License 5 votes vote down vote up
@MessageMapping("/all")
@SendTo("/topic/all")
public Map<String, String> post(@Payload Map<String, String> message) {
    message.put("timestamp", Long.toString(System.currentTimeMillis()));
    chatHistoryDao.save(message);
    return message;
}
 
Example 20
Source Project: tutorials   Source File: ChatController.java    License: MIT License 5 votes vote down vote up
@MessageMapping("/chat")
@SendTo("/topic/messages")
public OutputMessage send(final Message message) throws Exception {

    final String time = new SimpleDateFormat("HH:mm").format(new Date());
    return new OutputMessage(message.getFrom(), message.getText(), time);
}
 
Example 21
Source Project: ServiceCutter   Source File: ActivityService.java    License: Apache License 2.0 5 votes vote down vote up
@SubscribeMapping("/topic/activity")
@SendTo("/topic/tracker")
public ActivityDTO sendActivity(@Payload ActivityDTO activityDTO, StompHeaderAccessor stompHeaderAccessor, Principal principal) {
    activityDTO.setUserLogin(SecurityUtils.getCurrentLogin());
    activityDTO.setUserLogin(principal.getName());
    activityDTO.setSessionId(stompHeaderAccessor.getSessionId());
    activityDTO.setIpAddress(stompHeaderAccessor.getSessionAttributes().get(IP_ADDRESS).toString());
    activityDTO.setTime(dateTimeFormatter.print(Calendar.getInstance().getTimeInMillis()));
    log.debug("Sending user tracking data {}", activityDTO);
    return activityDTO;
}
 
Example 22
Source Project: rocketmq-binder-demo   Source File: SendToService.java    License: Apache License 2.0 5 votes vote down vote up
/**
    * @SendTo is useful with @StreamListener
    */

@StreamListener(Sink.INPUT)
@SendTo(SendToApplication.TEMP_INPUT)
public String receive(String receiveMsg) {
	System.out.println("receive: " + receiveMsg);
	return "handle by SendTo(" + receiveMsg + ")";
}
 
Example 23
@StreamListener("input")
@SendTo("output")
public KStream<Integer, String> process(KStream<Object, Product> input) {

	return input.filter((key, product) -> product.getId() == 123)
			.map((key, value) -> new KeyValue<>(value, value))
			.groupByKey(Serialized.with(new JsonSerde<>(Product.class),
					new JsonSerde<>(Product.class)))
			.windowedBy(TimeWindows.of(5000))
			.count(Materialized.as("id-count-store")).toStream()
			.map((key, value) -> new KeyValue<>(key.key().id,
					"Count for product with ID 123: " + value));
}
 
Example 24
Source Project: TeamDojo   Source File: ActivityService.java    License: Apache License 2.0 5 votes vote down vote up
@MessageMapping("/topic/activity")
@SendTo("/topic/tracker")
public ActivityDTO sendActivity(@Payload ActivityDTO activityDTO, StompHeaderAccessor stompHeaderAccessor, Principal principal) {
    activityDTO.setUserLogin(principal.getName());
    activityDTO.setSessionId(stompHeaderAccessor.getSessionId());
    activityDTO.setIpAddress(stompHeaderAccessor.getSessionAttributes().get(IP_ADDRESS).toString());
    activityDTO.setTime(Instant.now());
    log.debug("Sending user tracking data {}", activityDTO);
    return activityDTO;
}
 
Example 25
Source Project: tutorial   Source File: SocketController.java    License: MIT License 5 votes vote down vote up
/**
 * SendTo SendToUser两个注解必须和 MessageMapping一起用在有作用;
 * SendToUser只是发给消息来源用户的订阅队列里; SendTo则发送到所有用户的订阅队列里
 * 
 * 不写SendTo/SendToUser注解,只写MessageMapping注解,也能接收客户端发送过来的消息。
 * SendTo注解的作用是给客户端发消息(发送到订阅队列里,不是回接收的客户端的消息,STOMP中无回消息的概念)
 * 
 * MessageMapping注解中配置的接收地址和WebScoketConfig中setApplicationDestinationPrefixes()设置的地址前缀
 * 一起构成了客户端向服务器端发送消息时使用地址
 */
@MessageMapping("/all")
@SendTo("/topic/clockmessage")
public ClockMessage toAll(ClockMessage message, Principal principal) throws Exception {
    if(log.isTraceEnabled()) {
        log.trace("toAll(接受到消息)" + message);
    }
    Thread.sleep(100);
    //这个方法也能发
    this.template.convertAndSend("/topic/clockmessage",  new ClockMessage("Hello, from controller now!"));
    
    //由于使用注解@SendTo,返回结果也会被convertAndSend
    return new ClockMessage("toAll, 来自"  + principal.getName() + "的消息:" + message.getMessage() + " ");
}
 
Example 26
@JmsListener(destination="${myqueue}")
@SendTo("${myotherqueue}")
public String simplerConsumer(String message){
	log.info("Simpler Consumer> " + message);
	return message + " and Spring Messaging too!";
}
 
Example 27
@SendTo({"/dest1", "/dest2"})
@SuppressWarnings("unused")
String handleAndSendTo() {
	return PAYLOAD;
}
 
Example 28
@SendTo("/topic/chat.message.filtered.{roomName}")
@SuppressWarnings("unused")
String handleAndSendToWithPlaceholders() {
	return PAYLOAD;
}
 
Example 29
@SendTo({"/dest1", "/dest2"})
@SendToUser({"/dest1", "/dest2"})
@SuppressWarnings("unused")
String handleAndSendToAndSendToUser() {
	return PAYLOAD;
}
 
Example 30
Source Project: spring-cloud-stream   Source File: ContentTypeTckTests.java    License: Apache License 2.0 4 votes vote down vote up
@StreamListener(Processor.INPUT)
@SendTo(Processor.OUTPUT)
public String echo(Message<Map<?, ?>> value) {
	assertThat(value.getPayload() instanceof Map).isTrue();
	return (String) value.getPayload().get("name");
}