org.springframework.messaging.MessageChannel Java Examples
The following examples show how to use
org.springframework.messaging.MessageChannel.
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: WebSocketInterceptor.java From xechat with MIT License | 7 votes |
/** * 绑定用户信息 * * @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 #2
Source File: GenericMessagingTemplateTests.java From spring-analysis-note with MIT License | 6 votes |
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: StreamListenerHandlerMethodTests.java From spring-cloud-stream with Apache License 2.0 | 6 votes |
@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 #4
Source File: RabbitBinderModuleTests.java From spring-cloud-stream-binder-rabbit with Apache License 2.0 | 6 votes |
@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 #5
Source File: IntegrationConfiguration.java From building-microservices with Apache License 2.0 | 6 votes |
@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 #6
Source File: GenericMessagingTemplateTests.java From java-technology-stack with MIT License | 6 votes |
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 spring-analysis-note with MIT License | 6 votes |
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 #8
Source File: StreamListenerHandlerMethodTests.java From spring-cloud-stream with Apache License 2.0 | 6 votes |
@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 #9
Source File: GreenfieldFunctionEnableBindingTests.java From spring-cloud-stream with Apache License 2.0 | 6 votes |
@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 #10
Source File: TwoKafkaBindersApplicationTest.java From spring-cloud-stream-samples with Apache License 2.0 | 6 votes |
@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 #11
Source File: RabbitBinderTests.java From spring-cloud-stream-binder-rabbit with Apache License 2.0 | 6 votes |
@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 #12
Source File: KafkaExpressionEvaluatingInterceptor.java From spring-cloud-stream-binder-kafka with Apache License 2.0 | 5 votes |
@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 #13
Source File: GenericMessagingTemplate.java From java-technology-stack with MIT License | 5 votes |
@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 #14
Source File: AbstractTestBinder.java From spring-cloud-stream with Apache License 2.0 | 5 votes |
@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 #15
Source File: GenericMessagingTemplateTests.java From java-technology-stack with MIT License | 5 votes |
@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 #16
Source File: WebSocketStompConfig.java From Project with Apache License 2.0 | 5 votes |
@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 #17
Source File: ProcessorToFunctionsSupportTests.java From spring-cloud-stream with Apache License 2.0 | 5 votes |
@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 #18
Source File: GenericMessagingTemplate.java From java-technology-stack with MIT License | 5 votes |
@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 #19
Source File: StreamListenerWithAnnotatedInputOutputArgsTests.java From spring-cloud-stream with Apache License 2.0 | 5 votes |
@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 #20
Source File: BindingServiceTests.java From spring-cloud-stream with Apache License 2.0 | 5 votes |
@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 #21
Source File: StompSubProtocolHandlerTests.java From java-technology-stack with MIT License | 5 votes |
@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 #22
Source File: TracingChannelInterceptor.java From spring-cloud-sleuth with Apache License 2.0 | 5 votes |
@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 #23
Source File: MessageBusAdapter.java From spring-bus with Apache License 2.0 | 5 votes |
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 #24
Source File: ChannelInterceptorTests.java From spring-analysis-note with MIT License | 5 votes |
@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); }
Example #25
Source File: BindableFunctionProxyFactory.java From spring-cloud-stream with Apache License 2.0 | 5 votes |
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 #26
Source File: SinkBindingWithDefaultsTests.java From spring-cloud-stream with Apache License 2.0 | 5 votes |
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testSourceOutputChannelBound() { Binder binder = this.binderFactory.getBinder(null, MessageChannel.class); verify(binder).bindConsumer(eq("input"), isNull(), eq(this.testSink.input()), Mockito.any()); verifyNoMoreInteractions(binder); }
Example #27
Source File: AbstractBrokerMessageHandler.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * 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 #28
Source File: AbstractMessageChannel.java From spring4-understanding with Apache License 2.0 | 5 votes |
public boolean applyPreReceive(MessageChannel channel) { for (ChannelInterceptor interceptor : interceptors) { if (!interceptor.preReceive(channel)) { triggerAfterReceiveCompletion(null, channel, null); return false; } this.receiveInterceptorIndex++; } return true; }
Example #29
Source File: ImmutableMessageChannelInterceptor.java From java-technology-stack with MIT License | 5 votes |
@Override public Message<?> preSend(Message<?> message, MessageChannel channel) { MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class); if (accessor != null && accessor.isMutable()) { accessor.setImmutable(); } return message; }
Example #30
Source File: AbstractMessageChannel.java From spring-analysis-note with MIT License | 5 votes |
public boolean applyPreReceive(MessageChannel channel) { for (ChannelInterceptor interceptor : interceptors) { if (!interceptor.preReceive(channel)) { triggerAfterReceiveCompletion(null, channel, null); return false; } this.receiveInterceptorIndex++; } return true; }