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

The following examples show how to use org.springframework.messaging.handler.annotation.SendTo. 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: ScsApplication.java    From spring_io_2019 with Apache License 2.0 7 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
Source File: StreamToTableJoinIntegrationTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
@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
Source File: StreamListenerMethodUtils.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
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
Source File: KafkaStreamsBinderMultipleInputTopicsTest.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
@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
Source File: ChatController.java    From tutorials with 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 #6
Source File: GreetingController.java    From spring-cloud-sleuth with 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 #7
Source File: KafkaStreamsBinderPojoInputAndPrimitiveTypeOutputTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@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 #8
Source File: ChatController.java    From springboot-learn with 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 #9
Source File: PerRecordAvroContentTypeTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@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 #10
Source File: ContentTypeTckTests.java    From spring-cloud-stream with 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
Source File: SocketController.java    From tutorial with 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 #12
Source File: ActivityService.java    From TeamDojo with 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 #13
Source File: StockProductWSController.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
@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 #14
Source File: KafkastreamsBinderPojoInputStringOutputIntegrationTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@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 #15
Source File: SendToService.java    From rocketmq-binder-demo with 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 #16
Source File: MessageController.java    From demo-projects with 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 #17
Source File: SampleTransformer.java    From spring-cloud-stream-samples with Apache License 2.0 5 votes vote down vote up
@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 #18
Source File: ChatController.java    From code with 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 #19
Source File: StreamReceiver.java    From code with 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 #20
Source File: OutboundValueNullSkippedConversionTest.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@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 #21
Source File: GreetingController.java    From exchange-gateway-rest with 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 #22
Source File: SendToMethodReturnValueHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #23
Source File: MessageController.java    From spring-websocket-template with 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 #24
Source File: ActivityService.java    From ServiceCutter with 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 #25
Source File: SendToMethodReturnValueHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #26
Source File: GreetingController.java    From spring-websocket-android-client-demo with MIT License 4 votes vote down vote up
@MessageMapping("/hello")
@SendTo("/topics/event")
public AuditEvent greeting(HelloMessage helloMessage) throws Exception {
    return new AuditEvent("greeting", "Hello," + helloMessage.getName() + "!");
}
 
Example #27
Source File: MessageBrokerConfigurationTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@MessageMapping("/foo")
@SendTo("/bar")
public String handleMessage() {
	return "bar";
}
 
Example #28
Source File: MethodJmsListenerEndpointTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@SendTo("")
public String emptySendTo(String content) {
	invocations.put("emptySendTo", true);
	return content;
}
 
Example #29
Source File: ContentTypeTckTests.java    From spring-cloud-stream with Apache License 2.0 4 votes vote down vote up
@StreamListener(Processor.INPUT)
@SendTo(Processor.OUTPUT)
public byte[] echo(byte[] value) {
	return value;
}
 
Example #30
Source File: WebSocketController.java    From boot-actuator with MIT License 4 votes vote down vote up
/**
 * 类加载相关信息
 * @param name
 * @return
 */
@MessageMapping("/cl")
@SendTo("/topic/cl")
public List<ClassLoadEntity> socketCl(String name){
    return classService.findAllByName(name);
}