org.springframework.messaging.MessageHandler Java Examples
The following examples show how to use
org.springframework.messaging.MessageHandler.
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: QueueMessageHandlerTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@Test void receiveMessage_methodAnnotatedWithSqsListenerAnnotation_methodInvokedForIncomingMessage() { StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton("incomingMessageHandler", IncomingMessageHandler.class); applicationContext.registerSingleton("queueMessageHandler", QueueMessageHandler.class); applicationContext.refresh(); MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class); messageHandler.handleMessage(MessageBuilder.withPayload("testContent") .setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "receive").build()); IncomingMessageHandler messageListener = applicationContext .getBean(IncomingMessageHandler.class); assertThat(messageListener.getLastReceivedMessage()).isEqualTo("testContent"); }
Example #2
Source File: StompBrokerRelayMessageHandlerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void systemSubscription() throws Exception { MessageHandler handler = mock(MessageHandler.class); this.brokerRelay.setSystemSubscriptions(Collections.singletonMap("/topic/foo", handler)); this.brokerRelay.start(); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECTED); accessor.setLeaveMutable(true); MessageHeaders headers = accessor.getMessageHeaders(); this.tcpClient.handleMessage(MessageBuilder.createMessage(new byte[0], headers)); assertEquals(2, this.tcpClient.getSentMessages().size()); assertEquals(StompCommand.CONNECT, this.tcpClient.getSentHeaders(0).getCommand()); assertEquals(StompCommand.SUBSCRIBE, this.tcpClient.getSentHeaders(1).getCommand()); assertEquals("/topic/foo", this.tcpClient.getSentHeaders(1).getDestination()); Message<byte[]> message = message(StompCommand.MESSAGE, null, null, "/topic/foo"); this.tcpClient.handleMessage(message); ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class); verify(handler).handleMessage(captor.capture()); assertSame(message, captor.getValue()); }
Example #3
Source File: RqueueMessageHandlerTest.java From rqueue with Apache License 2.0 | 6 votes |
@Test public void testMethodHavingNameFromPropertyFile() { StaticApplicationContext applicationContext = new StaticApplicationContext(); applicationContext.registerSingleton("messageHandler", MessageHandlersWithProperty.class); applicationContext.registerSingleton("rqueueMessageHandler", RqueueMessageHandler.class); Map<String, Object> map = new HashMap<>(); map.put("slow.queue.name", slowQueue); map.put("smart.queue.name", smartQueue); applicationContext .getEnvironment() .getPropertySources() .addLast(new MapPropertySource("test", map)); applicationContext.registerSingleton("ppc", PropertySourcesPlaceholderConfigurer.class); applicationContext.refresh(); MessageHandler messageHandler = applicationContext.getBean(MessageHandler.class); MessageHandlersWithProperty messageListener = applicationContext.getBean(MessageHandlersWithProperty.class); messageHandler.handleMessage(buildMessage(slowQueue, message)); assertEquals(message, messageListener.getLastReceivedMessage()); messageListener.setLastReceivedMessage(null); messageHandler.handleMessage(buildMessage(smartQueue, message + message)); assertEquals(message + message, messageListener.getLastReceivedMessage()); }
Example #4
Source File: AbstractMessageChannelBinder.java From spring-cloud-stream with Apache License 2.0 | 6 votes |
private void destroyErrorInfrastructure(ProducerDestination destination) { String errorChannelName = errorsBaseName(destination); String errorBridgeHandlerName = getErrorBridgeName(destination); MessageHandler bridgeHandler = null; if (getApplicationContext().containsBean(errorBridgeHandlerName)) { bridgeHandler = getApplicationContext().getBean(errorBridgeHandlerName, MessageHandler.class); } if (getApplicationContext().containsBean(errorChannelName)) { SubscribableChannel channel = getApplicationContext() .getBean(errorChannelName, SubscribableChannel.class); if (bridgeHandler != null) { channel.unsubscribe(bridgeHandler); ((DefaultSingletonBeanRegistry) getApplicationContext().getBeanFactory()) .destroySingleton(errorBridgeHandlerName); } ((DefaultSingletonBeanRegistry) getApplicationContext().getBeanFactory()) .destroySingleton(errorChannelName); } }
Example #5
Source File: QueueMessageHandlerTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@Test void receiveMessage_methodWithMessageAsParameter_parameterIsConverted() { new ApplicationContextRunner() .withConfiguration(UserConfigurations .of(QueueMessageHandlerWithJacksonMappingConfiguration.class)) .withBean(IncomingMessageHandlerWithMessageParameter.class) .run((context) -> { DummyKeyValueHolder messagePayload = new DummyKeyValueHolder("myKey", "A value"); MappingJackson2MessageConverter jsonMapper = context .getBean(MappingJackson2MessageConverter.class); Message<?> message = jsonMapper.toMessage(messagePayload, new MessageHeaders(Collections.singletonMap( QueueMessageHandler.LOGICAL_RESOURCE_ID, "testQueue"))); MessageHandler messageHandler = context.getBean(MessageHandler.class); messageHandler.handleMessage(message); IncomingMessageHandlerWithMessageParameter messageListener = context .getBean(IncomingMessageHandlerWithMessageParameter.class); assertThat(messageListener.getLastReceivedMessage()).isNotNull(); assertThat(messageListener.getLastReceivedMessage().getPayload()) .isEqualTo(messagePayload); }); }
Example #6
Source File: RabbitBinderTests.java From spring-cloud-stream-binder-rabbit with Apache License 2.0 | 6 votes |
@Test public void testPolledConsumer() throws Exception { RabbitTestBinder binder = getBinder(); PollableSource<MessageHandler> inboundBindTarget = new DefaultPollableMessageSource( this.messageConverter); Binding<PollableSource<MessageHandler>> binding = binder.bindPollableConsumer( "pollable", "group", inboundBindTarget, createConsumerProperties()); RabbitTemplate template = new RabbitTemplate( this.rabbitAvailableRule.getResource()); template.convertAndSend("pollable.group", "testPollable"); boolean polled = inboundBindTarget.poll(m -> { assertThat(m.getPayload()).isEqualTo("testPollable"); }); int n = 0; while (n++ < 100 && !polled) { polled = inboundBindTarget.poll(m -> { assertThat(m.getPayload()).isEqualTo("testPollable"); }); } assertThat(polled).isTrue(); binding.unbind(); }
Example #7
Source File: MessageBrokerBeanDefinitionParserTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void customChannels() { loadBeanDefinitions("websocket-config-broker-customchannels.xml"); List<Class<? extends MessageHandler>> subscriberTypes = Arrays.<Class<? extends MessageHandler>>asList(SimpAnnotationMethodMessageHandler.class, UserDestinationMessageHandler.class, SimpleBrokerMessageHandler.class); testChannel("clientInboundChannel", subscriberTypes, 3); testExecutor("clientInboundChannel", 100, 200, 600); subscriberTypes = Collections.singletonList(SubProtocolWebSocketHandler.class); testChannel("clientOutboundChannel", subscriberTypes, 3); testExecutor("clientOutboundChannel", 101, 201, 601); subscriberTypes = Arrays.<Class<? extends MessageHandler>>asList(SimpleBrokerMessageHandler.class, UserDestinationMessageHandler.class); testChannel("brokerChannel", subscriberTypes, 1); testExecutor("brokerChannel", 102, 202, 602); }
Example #8
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 #9
Source File: CassandraSinkConfiguration.java From spring-cloud-stream-app-starters with Apache License 2.0 | 6 votes |
@Bean @ServiceActivator(inputChannel = "toSink") public MessageHandler cassandraSinkMessageHandler() { CassandraMessageHandler<?> cassandraMessageHandler = this.cassandraSinkProperties.getQueryType() != null ? new CassandraMessageHandler<>(this.template, this.cassandraSinkProperties.getQueryType()) : new CassandraMessageHandler<>(this.template); cassandraMessageHandler.setProducesReply(false); if (this.cassandraSinkProperties.getConsistencyLevel() != null || this.cassandraSinkProperties.getRetryPolicy() != null || this.cassandraSinkProperties.getTtl() > 0) { cassandraMessageHandler.setWriteOptions( new WriteOptions(this.cassandraSinkProperties.getConsistencyLevel(), this.cassandraSinkProperties.getRetryPolicy(), this.cassandraSinkProperties.getTtl())); } if (StringUtils.hasText(this.cassandraSinkProperties.getIngestQuery())) { cassandraMessageHandler.setIngestQuery(this.cassandraSinkProperties.getIngestQuery()); } else if (this.cassandraSinkProperties.getStatementExpression() != null) { cassandraMessageHandler.setStatementExpression(this.cassandraSinkProperties.getStatementExpression()); } return cassandraMessageHandler; }
Example #10
Source File: SenderApplication.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Bean @ServiceActivator(inputChannel = "pubSubOutputChannel") public MessageHandler messageSender(PubSubTemplate pubsubTemplate) { PubSubMessageHandler adapter = new PubSubMessageHandler(pubsubTemplate, "exampleTopic"); adapter.setPublishCallback(new ListenableFutureCallback<String>() { @Override public void onFailure(Throwable ex) { LOGGER.info("There was an error sending the message."); } @Override public void onSuccess(String result) { LOGGER.info("Message was sent successfully."); } }); return adapter; }
Example #11
Source File: TracingChannelInterceptorTest.java From java-spring-cloud with Apache License 2.0 | 6 votes |
@Test public void testAfterMessageHandled() { Span span = mock(Span.class); Scope scope = mock(Scope.class); MessageHandler messageHandler = mock(WebSocketAnnotationMethodMessageHandler.class); MessageBuilder<String> messageBuilder = MessageBuilder.withPayload("Hi") .setHeader(TracingChannelInterceptor.SIMP_MESSAGE_TYPE, SimpMessageType.MESSAGE) .setHeader(TracingChannelInterceptor.SIMP_DESTINATION, TEST_DESTINATION) .setHeader(TracingChannelInterceptor.OPENTRACING_SCOPE, scope) .setHeader(TracingChannelInterceptor.OPENTRACING_SPAN, span); TracingChannelInterceptor interceptor = new TracingChannelInterceptor(mockTracer, Tags.SPAN_KIND_CLIENT); interceptor.afterMessageHandled(messageBuilder.build(), null, messageHandler, null); // Verify span is finished and scope is closed verify(span).finish(); verify(scope).close(); }
Example #12
Source File: BinderErrorChannel.java From spring-cloud-stream with Apache License 2.0 | 6 votes |
@Override public boolean subscribe(MessageHandler handler) { this.subscribers.incrementAndGet(); if (handler instanceof LastSubscriberMessageHandler && this.finalHandler != null) { throw new IllegalStateException( "Only one LastSubscriberMessageHandler is allowed"); } if (this.finalHandler != null) { super.unsubscribe(this.finalHandler); } boolean result = super.subscribe(handler); if (this.finalHandler != null) { super.subscribe(this.finalHandler); } if (handler instanceof LastSubscriberMessageHandler && this.finalHandler == null) { this.finalHandler = (LastSubscriberMessageHandler) handler; } return result; }
Example #13
Source File: AbstractMessageBrokerConfiguration.java From java-technology-stack with MIT License | 6 votes |
@Bean @Nullable public AbstractBrokerMessageHandler stompBrokerRelayMessageHandler() { StompBrokerRelayMessageHandler handler = getBrokerRegistry().getStompBrokerRelay(brokerChannel()); if (handler == null) { return null; } Map<String, MessageHandler> subscriptions = new HashMap<>(4); String destination = getBrokerRegistry().getUserDestinationBroadcast(); if (destination != null) { subscriptions.put(destination, userDestinationMessageHandler()); } destination = getBrokerRegistry().getUserRegistryBroadcast(); if (destination != null) { subscriptions.put(destination, userRegistryMessageHandler()); } handler.setSystemSubscriptions(subscriptions); updateUserDestinationResolver(handler); return handler; }
Example #14
Source File: PollableConsumerTests.java From spring-cloud-stream with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Test public void testAutoStartupOn() { TestChannelBinder binder = createBinder(); binder.setMessageSourceDelegate(new LifecycleMessageSource( () -> new GenericMessage<>("{\"foo\":\"bar\"}".getBytes()))); MessageConverterConfigurer configurer = this.context .getBean(MessageConverterConfigurer.class); DefaultPollableMessageSource pollableSource = new DefaultPollableMessageSource( this.messageConverter); configurer.configurePolledMessageSource(pollableSource, "foo"); ExtendedConsumerProperties<Object> properties = new ExtendedConsumerProperties<>( null); properties.setAutoStartup(true); Binding<PollableSource<MessageHandler>> pollableSourceBinding = binder .bindPollableConsumer("foo", "bar", pollableSource, properties); assertThat(pollableSourceBinding.isRunning()).isTrue(); }
Example #15
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 #16
Source File: AmazonS3SinkConfiguration.java From spring-cloud-stream-app-starters with Apache License 2.0 | 6 votes |
@Bean @ServiceActivator(inputChannel = Sink.INPUT) public MessageHandler amazonS3MessageHandler(AmazonS3 amazonS3, ResourceIdResolver resourceIdResolver, AmazonS3SinkProperties s3SinkProperties) { S3MessageHandler s3MessageHandler; if (s3SinkProperties.getBucket() != null) { s3MessageHandler = new S3MessageHandler(amazonS3, s3SinkProperties.getBucket()); } else { s3MessageHandler = new S3MessageHandler(amazonS3, s3SinkProperties.getBucketExpression()); } s3MessageHandler.setResourceIdResolver(resourceIdResolver); s3MessageHandler.setKeyExpression(s3SinkProperties.getKeyExpression()); if (s3SinkProperties.getAcl() != null) { s3MessageHandler.setObjectAclExpression(new ValueExpression<>(s3SinkProperties.getAcl())); } else { s3MessageHandler.setObjectAclExpression(s3SinkProperties.getAclExpression()); } s3MessageHandler.setUploadMetadataProvider(this.uploadMetadataProvider); s3MessageHandler.setProgressListener(this.s3ProgressListener); return s3MessageHandler; }
Example #17
Source File: RedisSinkConfiguration.java From spring-cloud-stream-app-starters with Apache License 2.0 | 6 votes |
@Bean @ServiceActivator(inputChannel = Sink.INPUT) public MessageHandler redisSinkMessageHandler() { if (this.redisSinkProperties.isKey()) { RedisStoreWritingMessageHandler redisStoreWritingMessageHandler = new RedisStoreWritingMessageHandler( this.redisConnectionFactory); redisStoreWritingMessageHandler.setKeyExpression(this.redisSinkProperties.keyExpression()); return redisStoreWritingMessageHandler; } else if (this.redisSinkProperties.isQueue()) { return new RedisQueueOutboundChannelAdapter(this.redisSinkProperties.queueExpression(), this.redisConnectionFactory); } else { // must be topic RedisPublishingMessageHandler redisPublishingMessageHandler = new RedisPublishingMessageHandler( this.redisConnectionFactory); redisPublishingMessageHandler.setTopicExpression(this.redisSinkProperties.topicExpression()); return redisPublishingMessageHandler; } }
Example #18
Source File: MqttSinkConfiguration.java From mqtt with Apache License 2.0 | 5 votes |
@Bean @ServiceActivator(inputChannel = Sink.INPUT) public MessageHandler mqttOutbound() { MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(properties.getClientId(), mqttClientFactory); messageHandler.setAsync(properties.isAsync()); messageHandler.setDefaultTopic(properties.getTopic()); messageHandler.setConverter(pahoMessageConverter()); return messageHandler; }
Example #19
Source File: AbstractPollableConsumerTestBinder.java From spring-cloud-stream with Apache License 2.0 | 5 votes |
@Override public Binding<PollableSource<MessageHandler>> bindPollableConsumer(String name, String group, PollableSource<MessageHandler> inboundBindTarget, CP consumerProperties) { return this.binder.bindPollableConsumer(name, group, inboundBindTarget, consumerProperties); }
Example #20
Source File: MessageBrokerConfigurationTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void clientInboundChannelWithBrokerRelay() { ApplicationContext context = loadConfig(BrokerRelayConfig.class); TestChannel channel = context.getBean("clientInboundChannel", TestChannel.class); Set<MessageHandler> handlers = channel.getSubscribers(); assertEquals(3, handlers.size()); assertTrue(handlers.contains(context.getBean(SimpAnnotationMethodMessageHandler.class))); assertTrue(handlers.contains(context.getBean(UserDestinationMessageHandler.class))); assertTrue(handlers.contains(context.getBean(StompBrokerRelayMessageHandler.class))); }
Example #21
Source File: ExecutorSubscribableChannelTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void failurePropagates() { RuntimeException ex = new RuntimeException(); willThrow(ex).given(this.handler).handleMessage(this.message); MessageHandler secondHandler = mock(MessageHandler.class); this.channel.subscribe(this.handler); this.channel.subscribe(secondHandler); try { this.channel.send(message); } catch (MessageDeliveryException actualException) { assertThat(actualException.getCause(), equalTo(ex)); } verifyZeroInteractions(secondHandler); }
Example #22
Source File: MessageBrokerConfigurationTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void brokerChannelWithBrokerRelay() { ApplicationContext context = loadConfig(BrokerRelayConfig.class); TestChannel channel = context.getBean("brokerChannel", TestChannel.class); Set<MessageHandler> handlers = channel.getSubscribers(); assertEquals(2, handlers.size()); assertTrue(handlers.contains(context.getBean(UserDestinationMessageHandler.class))); assertTrue(handlers.contains(context.getBean(StompBrokerRelayMessageHandler.class))); }
Example #23
Source File: MessageBrokerConfigurationTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void brokerChannelWithBrokerRelay() { TestChannel channel = this.brokerRelayContext.getBean("brokerChannel", TestChannel.class); Set<MessageHandler> handlers = channel.getSubscribers(); assertEquals(2, handlers.size()); assertTrue(handlers.contains(brokerRelayContext.getBean(UserDestinationMessageHandler.class))); assertTrue(handlers.contains(brokerRelayContext.getBean(StompBrokerRelayMessageHandler.class))); }
Example #24
Source File: OpenTracingChannelInterceptor.java From java-specialagent with Apache License 2.0 | 5 votes |
@Override public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) { Span span = tracer.activeSpan(); log.trace(String.format("Continuing span %s before handling message", span)); return message; }
Example #25
Source File: OpenTracingChannelInterceptor.java From java-specialagent with Apache License 2.0 | 5 votes |
@Override public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception ex) { Span span = tracer.activeSpan(); log.trace(String.format("Continuing span %s after message handled", span)); if (span == null) { return; } handleException(ex, span); }
Example #26
Source File: AbstractMessageBrokerConfiguration.java From java-technology-stack with MIT License | 5 votes |
@Bean @Nullable public MessageHandler userRegistryMessageHandler() { if (getBrokerRegistry().getUserRegistryBroadcast() == null) { return null; } SimpUserRegistry userRegistry = userRegistry(); Assert.isInstanceOf(MultiServerUserRegistry.class, userRegistry, "MultiServerUserRegistry required"); return new UserRegistryMessageHandler((MultiServerUserRegistry) userRegistry, brokerMessagingTemplate(), getBrokerRegistry().getUserRegistryBroadcast(), messageBrokerTaskScheduler()); }
Example #27
Source File: MessageBrokerBeanDefinitionParserTests.java From spring-analysis-note with MIT License | 5 votes |
private void testChannel( String channelName, List<Class<? extends MessageHandler>> subscriberTypes, int interceptorCount) { AbstractSubscribableChannel channel = this.appContext.getBean(channelName, AbstractSubscribableChannel.class); for (Class<? extends MessageHandler> subscriberType : subscriberTypes) { MessageHandler subscriber = this.appContext.getBean(subscriberType); assertNotNull("No subscription for " + subscriberType, subscriber); assertTrue(channel.hasSubscription(subscriber)); } List<ChannelInterceptor> interceptors = channel.getInterceptors(); assertEquals(interceptorCount, interceptors.size()); assertEquals(ImmutableMessageChannelInterceptor.class, interceptors.get(interceptors.size()-1).getClass()); }
Example #28
Source File: RabbitTestBinder.java From spring-cloud-stream-binder-rabbit with Apache License 2.0 | 5 votes |
@Override public Binding<PollableSource<MessageHandler>> bindPollableConsumer(String name, String group, PollableSource<MessageHandler> inboundBindTarget, ExtendedConsumerProperties<RabbitConsumerProperties> properties) { captureConsumerResources(name, group, properties); return super.bindPollableConsumer(name, group, inboundBindTarget, properties); }
Example #29
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 #30
Source File: SftpConfig.java From java-examples with MIT License | 5 votes |
@Bean @ServiceActivator(inputChannel = "fromSftpChannel") public MessageHandler resultFileHandler() { return new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { System.err.println(message.getPayload()); } }; }