Java Code Examples for org.springframework.messaging.MessageChannel

The following examples show how to use org.springframework.messaging.MessageChannel. 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
@Test
public void testCloudProfile() {
	this.context = new SpringApplicationBuilder(SimpleProcessor.class,
			MockCloudConfiguration.class).web(WebApplicationType.NONE)
					.profiles("cloud").run();
	BinderFactory binderFactory = this.context.getBean(BinderFactory.class);
	Binder<?, ?, ?> binder = binderFactory.getBinder(null, MessageChannel.class);
	assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class);
	DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder);
	ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor
			.getPropertyValue("connectionFactory");
	ConnectionFactory connectionFactory = this.context
			.getBean(ConnectionFactory.class);

	assertThat(binderConnectionFactory).isNotSameAs(connectionFactory);

	assertThat(TestUtils.getPropertyValue(connectionFactory, "addresses"))
			.isNotNull();
	assertThat(TestUtils.getPropertyValue(binderConnectionFactory, "addresses"))
			.isNull();

	Cloud cloud = this.context.getBean(Cloud.class);

	verify(cloud).getSingletonServiceConnector(ConnectionFactory.class, null);
}
 
Example 2
@StreamListener
public void receive(@Input(Processor.INPUT) SubscribableChannel input,
		@Output(Processor.OUTPUT) final MessageChannel output1,
		@Output(StreamListenerTestUtils.FooOutboundChannel1.OUTPUT) final MessageChannel output2) {
	input.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			if (message.getHeaders().get("output").equals("output1")) {
				output1.send(org.springframework.messaging.support.MessageBuilder
						.withPayload(
								message.getPayload().toString().toUpperCase())
						.build());
			}
			else if (message.getHeaders().get("output").equals("output2")) {
				output2.send(org.springframework.messaging.support.MessageBuilder
						.withPayload(
								message.getPayload().toString().toLowerCase())
						.build());
			}
		}
	});
}
 
Example 3
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 4
Source Project: xechat   Source File: WebSocketInterceptor.java    License: MIT License 6 votes vote down vote up
/**
 * 绑定用户信息
 *
 * @param message
 * @param channel
 * @return
 */
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
    log.debug("进入拦截器 -> preSend");
    StompHeaderAccessor stompHeaderAccessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

    if (StompCommand.CONNECT.equals(stompHeaderAccessor.getCommand())) {
        User user = new User();
        user.setUserId(UUIDUtils.create());
        user.setUsername(SensitiveWordUtils.loveChina(stompHeaderAccessor.getFirstNativeHeader("username")));
        user.setAvatar(stompHeaderAccessor.getFirstNativeHeader("avatar"));
        user.setAddress(stompHeaderAccessor.getFirstNativeHeader("address"));
        user.setStatus(UserStatusConstant.ONLINE);

        stompHeaderAccessor.setUser(user);
        log.debug("绑定用户信息 -> {}", user);
    }

    return message;
}
 
Example 5
Source Project: spring-analysis-note   Source File: StompSubProtocolHandler.java    License: MIT License 6 votes vote down vote up
private boolean detectImmutableMessageInterceptor(MessageChannel channel) {
	if (this.immutableMessageInterceptorPresent != null) {
		return this.immutableMessageInterceptorPresent;
	}

	if (channel instanceof AbstractMessageChannel) {
		for (ChannelInterceptor interceptor : ((AbstractMessageChannel) channel).getInterceptors()) {
			if (interceptor instanceof ImmutableMessageChannelInterceptor) {
				this.immutableMessageInterceptorPresent = true;
				return true;
			}
		}
	}
	this.immutableMessageInterceptorPresent = false;
	return false;
}
 
Example 6
@SuppressWarnings("unchecked")
public void testStreamListenerMethodWithTargetBeanFromOutside() throws Exception {
	ConfigurableApplicationContext context = SpringApplication.run(
			TestStreamListenerMethodWithTargetBeanFromOutside.class,
			"--server.port=0", "--spring.jmx.enabled=false",
			"--spring.cloud.stream.bindings.input.contentType=text/plain",
			"--spring.cloud.stream.bindings.output.contentType=text/plain");
	Sink sink = context.getBean(Sink.class);
	final String testMessageToSend = "testing";
	sink.input().send(MessageBuilder.withPayload(testMessageToSend).build());
	DirectChannel directChannel = (DirectChannel) context
			.getBean(testMessageToSend.toUpperCase(), MessageChannel.class);
	MessageCollector messageCollector = context.getBean(MessageCollector.class);
	Message<String> result = (Message<String>) messageCollector
			.forChannel(directChannel).poll(1000, TimeUnit.MILLISECONDS);
	sink.input().send(MessageBuilder.withPayload(testMessageToSend).build());
	assertThat(result).isNotNull();
	assertThat(result.getPayload()).isEqualTo(testMessageToSend.toUpperCase());
	context.close();
}
 
Example 7
@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 8
@Test
public void contextLoads() {
	Binder<MessageChannel, ?, ?> binder1 = binderFactory.getBinder("kafka1", MessageChannel.class);
	KafkaMessageChannelBinder kafka1 = (KafkaMessageChannelBinder) binder1;
	DirectFieldAccessor directFieldAccessor1 = new DirectFieldAccessor(kafka1);
	KafkaBinderConfigurationProperties configuration1 =
			(KafkaBinderConfigurationProperties) directFieldAccessor1.getPropertyValue("configurationProperties");
	Assert.assertThat(configuration1.getBrokers(), arrayWithSize(1));
	Assert.assertThat(configuration1.getBrokers()[0], equalTo(kafkaTestSupport1.getEmbeddedKafka().getBrokersAsString()));

	Binder<MessageChannel, ?, ?> binder2 = binderFactory.getBinder("kafka2", MessageChannel.class);
	KafkaMessageChannelBinder kafka2 = (KafkaMessageChannelBinder) binder2;
	DirectFieldAccessor directFieldAccessor2 = new DirectFieldAccessor(kafka2);
	KafkaBinderConfigurationProperties configuration2 =
			(KafkaBinderConfigurationProperties) directFieldAccessor2.getPropertyValue("configurationProperties");
	Assert.assertThat(configuration2.getBrokers(), arrayWithSize(1));
	Assert.assertThat(configuration2.getBrokers()[0], equalTo(kafkaTestSupport2.getEmbeddedKafka().getBrokersAsString()));
}
 
Example 9
@Test
public void testAnonWithBuiltInExchangeCustomPrefix() throws Exception {
	RabbitTestBinder binder = getBinder();
	ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties();
	properties.getExtension().setDeclareExchange(false);
	properties.getExtension().setQueueNameGroupOnly(true);
	properties.getExtension().setAnonymousGroupPrefix("customPrefix.");

	Binding<MessageChannel> consumerBinding = binder.bindConsumer("amq.topic", null,
			createBindableChannel("input", new BindingProperties()), properties);
	Lifecycle endpoint = extractEndpoint(consumerBinding);
	SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint,
			"messageListenerContainer", SimpleMessageListenerContainer.class);
	String queueName = container.getQueueNames()[0];
	assertThat(queueName).startsWith("customPrefix.");
	assertThat(container.isRunning()).isTrue();
	consumerBinding.unbind();
	assertThat(container.isRunning()).isFalse();
}
 
Example 10
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 11
/**
 * Constructor with destination prefixes to match to destinations of messages.
 * @param inboundChannel the channel for receiving messages from clients (e.g. WebSocket clients)
 * @param outboundChannel the channel for sending messages to clients (e.g. WebSocket clients)
 * @param brokerChannel the channel for the application to send messages to the broker
 * @param destinationPrefixes prefixes to use to filter out messages
 */
public AbstractBrokerMessageHandler(SubscribableChannel inboundChannel, MessageChannel outboundChannel,
		SubscribableChannel brokerChannel, Collection<String> destinationPrefixes) {

	Assert.notNull(inboundChannel, "'inboundChannel' must not be null");
	Assert.notNull(outboundChannel, "'outboundChannel' must not be null");
	Assert.notNull(brokerChannel, "'brokerChannel' must not be null");

	this.clientInboundChannel = inboundChannel;
	this.clientOutboundChannel = outboundChannel;
	this.brokerChannel = brokerChannel;

	destinationPrefixes = (destinationPrefixes != null) ? destinationPrefixes : Collections.<String>emptyList();
	this.destinationPrefixes = Collections.unmodifiableCollection(destinationPrefixes);
}
 
Example 12
private void createOutput(String name) {
	if (this.functionProperties.getBindings().containsKey(name)) {
		name = this.functionProperties.getBindings().get(name);
	}
	this.outputHolders.put(name,
			new BoundTargetHolder(getBindingTargetFactory(MessageChannel.class)
					.createOutput(name), true));
}
 
Example 13
@SuppressWarnings("unchecked")
@Bean
public Consumer<String> log(OutputDestination out) {
	return x -> {
		DirectFieldAccessor dfa = new DirectFieldAccessor(out);
		MessageChannel channel = ((List<MessageChannel>) dfa.getPropertyValue("channels")).get(0);
		channel.send(new GenericMessage<byte[]>(x.getBytes()));
	};
}
 
Example 14
@Override
public void afterSendCompletion(
		Message<?> message, MessageChannel channel, boolean sent, @Nullable Exception ex) {

	if (!sent) {
		SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(message.getHeaders());
		if (SimpMessageType.DISCONNECT.equals(messageType)) {
			logger.debug("Detected unsent DISCONNECT message. Processing anyway.");
			handleMessage(message);
		}
	}
}
 
Example 15
@Bean
IntegrationFlow batchJobFlow(Job job,
                             JdbcTemplate jdbcTemplate,
                             JobLauncher launcher,
                             MessageChannel files) {

    return IntegrationFlows.from(files)
            .transform((GenericTransformer<Object,JobLaunchRequest>) file -> {
                System.out.println(file.toString());
                System.out.println(file.getClass());
                return null ;
            })
            .transform((GenericTransformer<File, JobLaunchRequest>) file -> {
                JobParameters jp = new JobParametersBuilder()
                        .addString("file", file.getAbsolutePath())
                        .toJobParameters();
                return new JobLaunchRequest(job, jp);
            })
            .handle(new JobLaunchingGateway(launcher))
            .handle(JobExecution.class, (payload, headers) -> {
                System.out.println("job execution status: " + payload.getExitStatus().toString());

                List<Person> personList = jdbcTemplate.query("select * from PEOPLE",
                        (resultSet, i) -> new Person(resultSet.getString("first"),
                                resultSet.getString("last"),
                                resultSet.getString("email")));

                personList.forEach(System.out::println);
                return null;
            })
            .get();

}
 
Example 16
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
	MessageBuilder<?> builder = MessageBuilder.fromMessage(message);
	if (this.messageKeyExpression != null) {
		builder.setHeader(MESSAGE_KEY_HEADER,
				this.messageKeyExpression.getValue(this.evaluationContext, message));
	}
	return builder.build();
}
 
Example 17
@Test
@SuppressWarnings("unchecked")
public void testMessageKeyInPayload() throws Exception {
	Binding<?> producerBinding = null;
	try {
		String testPayload = "test";

		ExtendedProducerProperties<KafkaProducerProperties> producerProperties = createProducerProperties();
		producerProperties.getExtension()
				.setMessageKeyExpression(spelExpressionParser.parseExpression("payload.field.bytes"));
		DirectChannel moduleOutputChannel = createBindableChannel("output",
				createProducerBindingProperties(producerProperties));

		String testTopicName = "existing" + System.currentTimeMillis();
		KafkaTestBinder binder = getBinder();
		producerBinding = binder.bindProducer(testTopicName, moduleOutputChannel,
				producerProperties);
		moduleOutputChannel.addInterceptor(new ChannelInterceptor() {

			@Override
			public Message<?> preSend(Message<?> message, MessageChannel channel) {
				assertThat(message.getHeaders()
						.get(KafkaExpressionEvaluatingInterceptor.MESSAGE_KEY_HEADER))
								.isEqualTo("foo".getBytes());
				return message;
			}

		});
		moduleOutputChannel.send(
				new GenericMessage<>(new Pojo("foo"), Collections.singletonMap(KafkaHeaders.PARTITION_ID, 0)));
	}
	finally {
		if (producerBinding != null) {
			producerBinding.unbind();
		}
	}
}
 
Example 18
@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 19
Source Project: spring-cloud-stream   Source File: AbstractTestBinder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Binding<MessageChannel> bindConsumer(String name, String group,
		MessageChannel moduleInputChannel, CP properties) {
	this.checkChannelIsConfigured(moduleInputChannel, properties);
	this.queues.add(name);
	return this.binder.bindConsumer(name, group, moduleInputChannel, properties);
}
 
Example 20
Source Project: java-technology-stack   Source File: GenericMessagingTemplate.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
protected final Message<?> doSendAndReceive(MessageChannel channel, Message<?> requestMessage) {
	Assert.notNull(channel, "'channel' is required");
	Object originalReplyChannelHeader = requestMessage.getHeaders().getReplyChannel();
	Object originalErrorChannelHeader = requestMessage.getHeaders().getErrorChannel();

	long sendTimeout = sendTimeout(requestMessage);
	long receiveTimeout = receiveTimeout(requestMessage);

	TemporaryReplyChannel tempReplyChannel = new TemporaryReplyChannel(this.throwExceptionOnLateReply);
	requestMessage = MessageBuilder.fromMessage(requestMessage).setReplyChannel(tempReplyChannel)
			.setHeader(this.sendTimeoutHeader, null)
			.setHeader(this.receiveTimeoutHeader, null)
			.setErrorChannel(tempReplyChannel).build();

	try {
		doSend(channel, requestMessage, sendTimeout);
	}
	catch (RuntimeException ex) {
		tempReplyChannel.setSendFailed(true);
		throw ex;
	}

	Message<?> replyMessage = this.doReceive(tempReplyChannel, receiveTimeout);
	if (replyMessage != null) {
		replyMessage = MessageBuilder.fromMessage(replyMessage)
				.setHeader(MessageHeaders.REPLY_CHANNEL, originalReplyChannelHeader)
				.setHeader(MessageHeaders.ERROR_CHANNEL, originalErrorChannelHeader)
				.build();
	}

	return replyMessage;
}
 
Example 21
@Test
public void sendAndReceive() {
	SubscribableChannel channel = new ExecutorSubscribableChannel(this.executor);
	channel.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
			replyChannel.send(new GenericMessage<>("response"));
		}
	});

	String actual = this.template.convertSendAndReceive(channel, "request", String.class);
	assertEquals("response", actual);
}
 
Example 22
Source Project: Project   Source File: WebSocketStompConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
	registration.setInterceptors(new ChannelInterceptorAdapter() {

		@Override
		public Message<?> preSend(Message<?> message, MessageChannel channel) {
			System.out.println("configureClientInboundChannel");
			StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
			User user = (User) accessor.getSessionAttributes().get("user");
			return super.preSend(message, channel);
		}
		
	});
}
 
Example 23
Source Project: spring-analysis-note   Source File: AbstractMessageChannel.java    License: MIT License 5 votes vote down vote up
public boolean applyPreReceive(MessageChannel channel) {
	for (ChannelInterceptor interceptor : interceptors) {
		if (!interceptor.preReceive(channel)) {
			triggerAfterReceiveCompletion(null, channel, null);
			return false;
		}
		this.receiveInterceptorIndex++;
	}
	return true;
}
 
Example 24
Source Project: java-technology-stack   Source File: GenericMessagingTemplate.java    License: MIT License 5 votes vote down vote up
@Nullable
protected final Message<?> doReceive(MessageChannel channel, long timeout) {
	Assert.notNull(channel, "MessageChannel is required");
	Assert.state(channel instanceof PollableChannel, "A PollableChannel is required to receive messages");

	Message<?> message = (timeout >= 0 ?
			((PollableChannel) channel).receive(timeout) : ((PollableChannel) channel).receive());

	if (message == null && logger.isTraceEnabled()) {
		logger.trace("Failed to receive message from channel '" + channel + "' within timeout: " + timeout);
	}

	return message;
}
 
Example 25
@StreamListener
public void receive(@Input(Processor.INPUT) SubscribableChannel input,
		@Output(Processor.OUTPUT) final MessageChannel output) {
	input.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			output.send(MessageBuilder
					.withPayload(message.getPayload().toString().toUpperCase())
					.build());
		}
	});
}
 
Example 26
Source Project: spring-cloud-stream   Source File: BindingServiceTests.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testExplicitGroup() throws Exception {
	BindingServiceProperties properties = new BindingServiceProperties();
	Map<String, BindingProperties> bindingProperties = new HashMap<>();
	BindingProperties props = new BindingProperties();
	props.setDestination("foo");
	props.setGroup("fooGroup");
	final String inputChannelName = "input";
	bindingProperties.put(inputChannelName, props);
	properties.setBindings(bindingProperties);
	DefaultBinderFactory binderFactory = createMockBinderFactory();
	Binder binder = binderFactory.getBinder("mock", MessageChannel.class);
	BindingService service = new BindingService(properties, binderFactory);
	MessageChannel inputChannel = new DirectChannel();
	Binding<MessageChannel> mockBinding = Mockito.mock(Binding.class);
	when(binder.bindConsumer(eq("foo"), eq("fooGroup"), same(inputChannel),
			any(ConsumerProperties.class))).thenReturn(mockBinding);
	Collection<Binding<MessageChannel>> bindings = service.bindConsumer(inputChannel,
			inputChannelName);
	assertThat(bindings).hasSize(1);
	Binding<MessageChannel> binding = bindings.iterator().next();
	assertThat(binding).isSameAs(mockBinding);

	service.unbindConsumers(inputChannelName);
	verify(binder).bindConsumer(eq("foo"), eq(props.getGroup()), same(inputChannel),
			any(ConsumerProperties.class));
	verify(binding).unbind();
	binderFactory.destroy();
}
 
Example 27
@Before
public void setup() {
	this.protocolHandler = new StompSubProtocolHandler();
	this.channel = Mockito.mock(MessageChannel.class);
	this.messageCaptor = ArgumentCaptor.forClass(Message.class);

	when(this.channel.send(any())).thenReturn(true);

	this.session = new TestWebSocketSession();
	this.session.setId("s1");
	this.session.setPrincipal(new TestPrincipal("joe"));
}
 
Example 28
@Override
public void afterReceiveCompletion(Message<?> message, MessageChannel channel,
		Exception ex) {
	if (emptyMessage(message)) {
		return;
	}
	if (log.isDebugEnabled()) {
		log.debug("Will finish the current span after receive completion "
				+ this.tracer.currentSpan());
	}
	finishSpan(ex);
}
 
Example 29
Source Project: spring-bus   Source File: MessageBusAdapter.java    License: Apache License 2.0 5 votes vote down vote up
private void bindMessageConsumer(MessageChannel inputChannel,
		String inputChannelName, Properties consumerProperties) {
	if (isChannelPubSub(inputChannelName)) {
		this.messageBus.bindPubSubConsumer(inputChannelName, inputChannel, consumerProperties);
	}
	else {
		this.messageBus.bindConsumer(inputChannelName, inputChannel, consumerProperties);
	}
}
 
Example 30
Source Project: spring-analysis-note   Source File: ChannelInterceptorTests.java    License: MIT License 5 votes vote down vote up
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
	super.preSend(message, channel);
	if (this.exceptionToRaise != null) {
		throw this.exceptionToRaise;
	}
	return (this.messageToReturn != null ? this.messageToReturn : message);
}