Java Code Examples for org.springframework.messaging.MessageChannel#send()

The following examples show how to use org.springframework.messaging.MessageChannel#send() . 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: GenericMessagingTemplate.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected final void doSend(MessageChannel channel, Message<?> message, long timeout) {
	Assert.notNull(channel, "MessageChannel is required");

	Message<?> messageToSend = message;
	MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
	if (accessor != null && accessor.isMutable()) {
		accessor.removeHeader(this.sendTimeoutHeader);
		accessor.removeHeader(this.receiveTimeoutHeader);
		accessor.setImmutable();
	}
	else if (message.getHeaders().containsKey(this.sendTimeoutHeader)
			|| message.getHeaders().containsKey(this.receiveTimeoutHeader)) {
		messageToSend = MessageBuilder.fromMessage(message)
				.setHeader(this.sendTimeoutHeader, null)
				.setHeader(this.receiveTimeoutHeader, null)
				.build();
	}

	boolean sent = (timeout >= 0 ? channel.send(messageToSend, timeout) : channel.send(messageToSend));

	if (!sent) {
		throw new MessageDeliveryException(message,
				"Failed to send message to channel '" + channel + "' within timeout: " + timeout);
	}
}
 
Example 2
Source File: GenericMessagingTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private MessageHandler createLateReplier(final CountDownLatch latch, final AtomicReference<Throwable> failure) {
	MessageHandler handler = message -> {
		try {
			Thread.sleep(500);
			MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
			replyChannel.send(new GenericMessage<>("response"));
			failure.set(new IllegalStateException("Expected exception"));
		}
		catch (InterruptedException e) {
			failure.set(e);
		}
		catch (MessageDeliveryException ex) {
			String expected = "Reply message received but the receiving thread has exited due to a timeout";
			String actual = ex.getMessage();
			if (!expected.equals(actual)) {
				failure.set(new IllegalStateException(
						"Unexpected error: '" + actual + "'"));
			}
		}
		finally {
			latch.countDown();
		}
	};
	return handler;
}
 
Example 3
Source File: GreenfieldFunctionEnableBindingTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testPojoReturn() throws IOException {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					FooTransform.class)).web(WebApplicationType.NONE).run(
							"--spring.cloud.function.definition=fooFunction",
							"--spring.jmx" + ".enabled=false",
							"--logging.level.org.springframework.integration=TRACE")) {
		MessageChannel input = context.getBean("input", MessageChannel.class);
		OutputDestination target = context.getBean(OutputDestination.class);

		ObjectMapper mapper = context.getBean(ObjectMapper.class);

		input.send(MessageBuilder.withPayload("bar").build());
		byte[] payload = target.receive(2000).getPayload();

		Foo result = mapper.readValue(payload, Foo.class);

		assertThat(result.getBar()).isEqualTo("bar");
	}
}
 
Example 4
Source File: GenericMessagingTemplate.java    From java-technology-stack with MIT License 6 votes vote down vote up
protected final void doSend(MessageChannel channel, Message<?> message, long timeout) {
	Assert.notNull(channel, "MessageChannel is required");

	Message<?> messageToSend = message;
	MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
	if (accessor != null && accessor.isMutable()) {
		accessor.removeHeader(this.sendTimeoutHeader);
		accessor.removeHeader(this.receiveTimeoutHeader);
		accessor.setImmutable();
	}
	else if (message.getHeaders().containsKey(this.sendTimeoutHeader)
			|| message.getHeaders().containsKey(this.receiveTimeoutHeader)) {
		messageToSend = MessageBuilder.fromMessage(message)
				.setHeader(this.sendTimeoutHeader, null)
				.setHeader(this.receiveTimeoutHeader, null)
				.build();
	}

	boolean sent = (timeout >= 0 ? channel.send(messageToSend, timeout) : channel.send(messageToSend));

	if (!sent) {
		throw new MessageDeliveryException(message,
				"Failed to send message to channel '" + channel + "' within timeout: " + timeout);
	}
}
 
Example 5
Source File: OrderEntryProducerConfiguration.java    From event-based-shopping-system with MIT License 6 votes vote down vote up
@Bean
@DependsOn(OUTBOUND_ID)
public CommandLineRunner kickOff(@Qualifier(OUTBOUND_ID + ".input") MessageChannel in) {
	return args -> {
		for (int i = 0; i < 100; i++) {
			Address address = new Address(Locale.GERMANY.getDisplayCountry(), "Colonge", "50667", "Domkloster", "4");
			Recipient recipient = new Recipient("Alexander", "Mustermann", address, address);
			int amount = ThreadLocalRandom.current().nextInt(1, 15);
			Order bestellung = new Order(amount, "movieId-" + i, recipient);
			String bestellungAsJson = ow.writeValueAsString(bestellung);
			in.send(new GenericMessage<String>(bestellungAsJson));
			log.info("ordering movie with movieId-" + i + " " + bestellungAsJson);
			Thread.sleep(5000);
		}
	};
}
 
Example 6
Source File: GenericMessagingTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
private MessageHandler createLateReplier(final CountDownLatch latch, final AtomicReference<Throwable> failure) {
	MessageHandler handler = message -> {
		try {
			Thread.sleep(500);
			MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
			replyChannel.send(new GenericMessage<>("response"));
			failure.set(new IllegalStateException("Expected exception"));
		}
		catch (InterruptedException e) {
			failure.set(e);
		}
		catch (MessageDeliveryException ex) {
			String expected = "Reply message received but the receiving thread has exited due to a timeout";
			String actual = ex.getMessage();
			if (!expected.equals(actual)) {
				failure.set(new IllegalStateException(
						"Unexpected error: '" + actual + "'"));
			}
		}
		finally {
			latch.countDown();
		}
	};
	return handler;
}
 
Example 7
Source File: StompSubProtocolHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void afterSessionEnded(WebSocketSession session, CloseStatus closeStatus, MessageChannel outputChannel) {
	this.decoders.remove(session.getId());

	Message<byte[]> message = createDisconnectMessage(session);
	SimpAttributes simpAttributes = SimpAttributes.fromMessage(message);
	try {
		SimpAttributesContextHolder.setAttributes(simpAttributes);
		if (this.eventPublisher != null) {
			Principal user = getUser(session);
			publishEvent(this.eventPublisher, new SessionDisconnectEvent(this, message, session.getId(), closeStatus, user));
		}
		outputChannel.send(message);
	}
	finally {
		this.stompAuthentications.remove(session.getId());
		SimpAttributesContextHolder.resetAttributes();
		simpAttributes.sessionCompleted();
	}
}
 
Example 8
Source File: SpringJmsApplicationTest.java    From spring-jms with MIT License 6 votes vote down vote up
@Test
public void testIntegration() throws Exception {
  MessageChannel producingChannel = applicationContext
      .getBean("producingChannel", MessageChannel.class);

  Map<String, Object> headers = Collections.singletonMap(
      JmsHeaders.DESTINATION, integrationDestination);

  LOGGER.info("sending 10 messages");
  for (int i = 0; i < 10; i++) {
    GenericMessage<String> message = new GenericMessage<>(
        "Hello Spring Integration JMS " + i + "!", headers);
    producingChannel.send(message);
    LOGGER.info("sent message='{}'", message);
  }

  countDownLatchHandler.getLatch().await(10000,
      TimeUnit.MILLISECONDS);
  assertThat(countDownLatchHandler.getLatch().getCount())
      .isEqualTo(0);
}
 
Example 9
Source File: GenericMessagingTemplate.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected final void doSend(MessageChannel channel, Message<?> message) {
	Assert.notNull(channel, "'channel' is required");

	MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
	if (accessor != null && accessor.isMutable()) {
		accessor.setImmutable();
	}

	long timeout = this.sendTimeout;
	boolean sent = (timeout >= 0 ? channel.send(message, timeout) : channel.send(message));

	if (!sent) {
		throw new MessageDeliveryException(message,
				"failed to send message to channel '" + channel + "' within timeout: " + timeout);
	}
}
 
Example 10
Source File: StompSubProtocolHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public void afterSessionEnded(WebSocketSession session, CloseStatus closeStatus, MessageChannel outputChannel) {
	this.decoders.remove(session.getId());

	Principal principal = session.getPrincipal();
	if (principal != null && this.userSessionRegistry != null) {
		String userName = getSessionRegistryUserName(principal);
		this.userSessionRegistry.unregisterSessionId(userName, session.getId());
	}

	Message<byte[]> message = createDisconnectMessage(session);
	SimpAttributes simpAttributes = SimpAttributes.fromMessage(message);
	try {
		SimpAttributesContextHolder.setAttributes(simpAttributes);
		if (this.eventPublisher != null) {
			Principal user = session.getPrincipal();
			publishEvent(new SessionDisconnectEvent(this, message, session.getId(), closeStatus, user));
		}
		outputChannel.send(message);
	}
	finally {
		SimpAttributesContextHolder.resetAttributes();
		simpAttributes.sessionCompleted();
	}
}
 
Example 11
Source File: SpringKafkaIntegrationApplicationTest.java    From spring-kafka with MIT License 6 votes vote down vote up
@Test
public void testIntegration() throws Exception {
  MessageChannel producingChannel =
      applicationContext.getBean("producingChannel", MessageChannel.class);

  Map<String, Object> headers =
      Collections.singletonMap(KafkaHeaders.TOPIC, SPRING_INTEGRATION_KAFKA_TOPIC);

  LOGGER.info("sending 10 messages");
  for (int i = 0; i < 10; i++) {
    GenericMessage<String> message =
        new GenericMessage<>("Hello Spring Integration Kafka " + i + "!", headers);
    producingChannel.send(message);
    LOGGER.info("sent message='{}'", message);
  }

  countDownLatchHandler.getLatch().await(10000, TimeUnit.MILLISECONDS);
  assertThat(countDownLatchHandler.getLatch().getCount()).isEqualTo(0);
}
 
Example 12
Source File: MainController.java    From heroku-metrics-spring with MIT License 6 votes vote down vote up
@RequestMapping(value = "/logs", method = RequestMethod.POST)
@ResponseBody
public String logs(@RequestBody String body) throws IOException {

  // "application/logplex-1" does not conform to RFC5424.
  // It leaves out STRUCTURED-DATA but does not replace it with
  // a NILVALUE. To workaround this, we inject empty STRUCTURED-DATA.
  String[] parts = body.split("router - ");
  String log = parts[0] + "router - [] " + (parts.length > 1 ? parts[1] : "");

  RFC6587SyslogDeserializer parser = new RFC6587SyslogDeserializer();
  InputStream is = new ByteArrayInputStream(log.getBytes());
  Map<String, ?> messages = parser.deserialize(is);
  ObjectMapper mapper = new ObjectMapper();

  MessageChannel toKafka = context.getBean("toKafka", MessageChannel.class);
  String json = mapper.writeValueAsString(messages);
  toKafka.send(new GenericMessage<>(json));

  return "ok";
}
 
Example 13
Source File: DemoApplication.java    From spring-and-kafka with Apache License 2.0 5 votes vote down vote up
@Bean
@DependsOn("kafkaOutboundChannelAdapter")
CommandLineRunner kickOff(@Qualifier("inputToKafka") MessageChannel in) {
    return args -> {
        for (int i = 0; i < 1000; i++) {
            in.send(new GenericMessage<>("#" + i));
            log.info("sending message #" + i);
        }
    };
}
 
Example 14
Source File: DemoApplication.java    From spring-and-kafka with Apache License 2.0 5 votes vote down vote up
@Bean
@DependsOn(OUTBOUND_ID)
CommandLineRunner kickOff(@Qualifier(OUTBOUND_ID + ".input") MessageChannel in) {
    return args -> {
        for (int i = 0; i < 1000; i++) {
            in.send(new GenericMessage<>("#" + i));
            log.info("sending message #" + i);
        }
    };
}
 
Example 15
Source File: SpringIntegrationStubMessages.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
public void send(Message<?> message, String destination) {
	try {
		MessageChannel messageChannel = this.context.getBean(destination,
				MessageChannel.class);
		messageChannel.send(message);
	}
	catch (Exception e) {
		log.error("Exception occurred while trying to send a message [" + message
				+ "] " + "to a channel with name [" + destination + "]", e);
		throw e;
	}
}
 
Example 16
Source File: StreamFromBinderMappingMessageSender.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
public void send(Message<?> message, String destination) {
	try {
		MessageChannel messageChannel = this.context.getBean(this.resolver
				.resolvedDestination(destination, DefaultChannels.OUTPUT),
				MessageChannel.class);
		messageChannel.send(message);
	}
	catch (Exception e) {
		log.error("Exception occurred while trying to send a message [" + message
				+ "] " + "to a channel with name [" + destination + "]", e);
		throw e;
	}
}
 
Example 17
Source File: StreamStubMessageSender.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Override
public void send(Message<?> message, String destination) {
	try {
		MessageChannel messageChannel = resolver().resolveDestination(destination);
		messageChannel.send(message);
	}
	catch (Exception e) {
		log.error("Exception occurred while trying to send a message [" + message
				+ "] " + "to a channel with name [" + destination + "]", e);
		throw e;
	}
}
 
Example 18
Source File: SpringJmsApplicationTest.java    From spring-jms with MIT License 5 votes vote down vote up
@Test
public void testIntegrationGateway() {
  MessageChannel outboundOrderRequestChannel =
      applicationContext.getBean("outboundOrderRequestChannel",
          MessageChannel.class);
  QueueChannel outboundOrderResponseChannel = applicationContext
      .getBean("outboundOrderResponseChannel", QueueChannel.class);

  outboundOrderRequestChannel
      .send(new GenericMessage<>("order-001"));

  assertThat(
      outboundOrderResponseChannel.receive(5000).getPayload())
          .isEqualTo("Accepted");;
}
 
Example 19
Source File: ProducerOnlyTransactionTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 4 votes vote down vote up
@Transactional
public void DoInTransaction(MessageChannel output) {
	this.isInTx = TransactionSynchronizationManager.isActualTransactionActive();
	output.send(new GenericMessage<>("foo"));
}
 
Example 20
Source File: MessageBrokerConfigurationTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private void testDotSeparator(ApplicationContext context, boolean expectLeadingSlash) {
	MessageChannel inChannel = context.getBean("clientInboundChannel", MessageChannel.class);
	TestChannel outChannel = context.getBean("clientOutboundChannel", TestChannel.class);
	MessageChannel brokerChannel = context.getBean("brokerChannel", MessageChannel.class);

	inChannel.send(createConnectMessage("sess1", new long[] {0,0}));

	// 1. Subscribe to user destination

	StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
	headers.setSessionId("sess1");
	headers.setSubscriptionId("subs1");
	headers.setDestination("/user/queue.q1");
	Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());
	inChannel.send(message);

	// 2. Send message to user via inboundChannel

	headers = StompHeaderAccessor.create(StompCommand.SEND);
	headers.setSessionId("sess1");
	headers.setDestination("/user/sess1/queue.q1");
	message = MessageBuilder.createMessage("123".getBytes(), headers.getMessageHeaders());
	inChannel.send(message);

	assertEquals(2, outChannel.messages.size());
	Message<?> outputMessage = outChannel.messages.remove(1);
	headers = StompHeaderAccessor.wrap(outputMessage);

	assertEquals(SimpMessageType.MESSAGE, headers.getMessageType());
	assertEquals(expectLeadingSlash ? "/queue.q1-usersess1" : "queue.q1-usersess1", headers.getDestination());
	assertEquals("123", new String((byte[]) outputMessage.getPayload()));
	outChannel.messages.clear();

	// 3. Send message via broker channel

	SimpMessagingTemplate template = new SimpMessagingTemplate(brokerChannel);
	SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create();
	accessor.setSessionId("sess1");
	template.convertAndSendToUser("sess1", "queue.q1", "456".getBytes(), accessor.getMessageHeaders());

	assertEquals(1, outChannel.messages.size());
	outputMessage = outChannel.messages.remove(0);
	headers = StompHeaderAccessor.wrap(outputMessage);

	assertEquals(SimpMessageType.MESSAGE, headers.getMessageType());
	assertEquals(expectLeadingSlash ? "/queue.q1-usersess1" : "queue.q1-usersess1", headers.getDestination());
	assertEquals("456", new String((byte[]) outputMessage.getPayload()));

}