Java Code Examples for org.springframework.messaging.SubscribableChannel

The following examples show how to use org.springframework.messaging.SubscribableChannel. 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
@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 2
Source Project: spring-cloud-consul   Source File: TestProducer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run(ApplicationArguments args) throws Exception {
	/*
	 * if (args.containsOption("partitioned") &&
	 * Boolean.valueOf(args.getOptionValues("partitioned").get(0))) {
	 * binder.setPartitionSelector(stubPartitionSelectorStrategy()); }
	 */
	SubscribableChannel producerChannel = producerChannel();
	ProducerProperties properties = new ProducerProperties();
	properties.setPartitionKeyExpression(
			new SpelExpressionParser().parseExpression("payload"));
	this.binder.bindProducer(ConsulBinderTests.BINDING_NAME, producerChannel,
			properties);

	Message<String> message = new GenericMessage<>(ConsulBinderTests.MESSAGE_PAYLOAD);
	logger.info("Writing message to binder {}", this.binder);
	producerChannel.send(message);
}
 
Example 3
Source Project: messaging   Source File: StreamConsumer.java    License: Apache License 2.0 6 votes vote down vote up
private IntegrationFlow incomingMessageFlow(SubscribableChannel incoming,
 String prefix) {

 Log log = LogFactory.getLog(getClass());

 return IntegrationFlows
  .from(incoming)
  .transform(String.class, String::toUpperCase)
  .handle(
   String.class,
   (greeting, headers) -> {
    log.info("greeting received in IntegrationFlow (" + prefix + "): "
     + greeting);
    return null;
   }).get();
}
 
Example 4
/**
 * Create an instance of SimpAnnotationMethodMessageHandler with the given
 * message channels and broker messaging template.
 * @param clientInboundChannel the channel for receiving messages from clients (e.g. WebSocket clients)
 * @param clientOutboundChannel the channel for messages to clients (e.g. WebSocket clients)
 * @param brokerTemplate a messaging template to send application messages to the broker
 */
public SimpAnnotationMethodMessageHandler(SubscribableChannel clientInboundChannel,
		MessageChannel clientOutboundChannel, SimpMessageSendingOperations brokerTemplate) {

	Assert.notNull(clientInboundChannel, "clientInboundChannel must not be null");
	Assert.notNull(clientOutboundChannel, "clientOutboundChannel must not be null");
	Assert.notNull(brokerTemplate, "brokerTemplate must not be null");

	this.clientInboundChannel = clientInboundChannel;
	this.clientMessagingTemplate = new SimpMessagingTemplate(clientOutboundChannel);
	this.brokerTemplate = brokerTemplate;

	Collection<MessageConverter> converters = new ArrayList<>();
	converters.add(new StringMessageConverter());
	converters.add(new ByteArrayMessageConverter());
	this.messageConverter = new CompositeMessageConverter(converters);
}
 
Example 5
@Override
protected SimpleBrokerMessageHandler getMessageHandler(SubscribableChannel brokerChannel) {
	SimpleBrokerMessageHandler handler = new SimpleBrokerMessageHandler(getClientInboundChannel(),
			getClientOutboundChannel(), brokerChannel, getDestinationPrefixes());
	if (this.taskScheduler != null) {
		handler.setTaskScheduler(this.taskScheduler);
	}
	if (this.heartbeat != null) {
		handler.setHeartbeatValue(this.heartbeat);
	}
	return handler;
}
 
Example 6
@Override
public SubscribableChannel createInput(String name) {
	DirectWithAttributesChannel subscribableChannel = new DirectWithAttributesChannel();
	subscribableChannel.setComponentName(name);
	subscribableChannel.setAttribute("type", Sink.INPUT);
	this.messageChannelConfigurer.configureInputChannel(subscribableChannel, name);
	if (context != null && !context.containsBean(name)) {
		context.registerBean(name, DirectWithAttributesChannel.class, () -> subscribableChannel);
	}
	return subscribableChannel;
}
 
Example 7
@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 8
private void destroyErrorInfrastructure(ConsumerDestination destination, String group,
		C properties) {
	try {
		String recoverer = getErrorRecovererName(destination, group, properties);

		destroyBean(recoverer);

		String errorChannelName = errorsBaseName(destination, group, properties);
		String errorMessageHandlerName = getErrorMessageHandlerName(destination,
				group, properties);
		String errorBridgeHandlerName = getErrorBridgeName(destination, group,
				properties);
		MessageHandler bridgeHandler = null;
		if (getApplicationContext().containsBean(errorBridgeHandlerName)) {
			bridgeHandler = getApplicationContext().getBean(errorBridgeHandlerName,
					MessageHandler.class);
		}
		MessageHandler handler = null;
		if (getApplicationContext().containsBean(errorMessageHandlerName)) {
			handler = getApplicationContext().getBean(errorMessageHandlerName,
					MessageHandler.class);
		}
		if (getApplicationContext().containsBean(errorChannelName)) {
			SubscribableChannel channel = getApplicationContext()
					.getBean(errorChannelName, SubscribableChannel.class);
			if (bridgeHandler != null) {
				channel.unsubscribe(bridgeHandler);
				destroyBean(errorBridgeHandlerName);
			}
			if (handler != null) {
				channel.unsubscribe(handler);
				destroyBean(errorMessageHandlerName);
			}
			destroyBean(errorChannelName);
		}
	}
	catch (IllegalStateException e) {
		// context is shutting down.
	}
}
 
Example 9
Source Project: spring-analysis-note   Source File: SockJsWebSocketHandlerTests.java    License: MIT License 5 votes vote down vote up
@Test
public void getSubProtocols() throws Exception {
	SubscribableChannel channel = mock(SubscribableChannel.class);
	SubProtocolWebSocketHandler handler = new SubProtocolWebSocketHandler(channel, channel);
	StompSubProtocolHandler stompHandler = new StompSubProtocolHandler();
	handler.addProtocolHandler(stompHandler);

	TaskScheduler scheduler = mock(TaskScheduler.class);
	DefaultSockJsService service = new DefaultSockJsService(scheduler);
	WebSocketServerSockJsSession session = new WebSocketServerSockJsSession("1", service, handler, null);
	SockJsWebSocketHandler sockJsHandler = new SockJsWebSocketHandler(service, handler, session);

	assertEquals(stompHandler.getSupportedProtocols(), sockJsHandler.getSubProtocols());
}
 
Example 10
@Before
public void setUp() throws Exception {
	this.applicationContext = new StaticApplicationContext();
	this.applicationContext.registerSingleton("controller", TestController.class);
	this.applicationContext.registerSingleton("controllerAdvice", TestControllerAdvice.class);
	this.applicationContext.refresh();

	SubscribableChannel channel = Mockito.mock(SubscribableChannel.class);
	SimpMessageSendingOperations brokerTemplate = new SimpMessagingTemplate(channel);

	this.messageHandler = new TestWebSocketAnnotationMethodMessageHandler(brokerTemplate, channel, channel);
	this.messageHandler.setApplicationContext(this.applicationContext);
	this.messageHandler.afterPropertiesSet();
}
 
Example 11
Source Project: spring-cloud-stream   Source File: PollableConsumerTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRequeueFromErrorFlow() {
	TestChannelBinder binder = createBinder();
	MessageConverterConfigurer configurer = this.context
			.getBean(MessageConverterConfigurer.class);

	DefaultPollableMessageSource pollableSource = new DefaultPollableMessageSource(
			this.messageConverter);
	configurer.configurePolledMessageSource(pollableSource, "foo");
	AcknowledgmentCallback callback = mock(AcknowledgmentCallback.class);
	pollableSource.addInterceptor(new ChannelInterceptor() {

		@Override
		public Message<?> preSend(Message<?> message, MessageChannel channel) {
			return MessageBuilder.fromMessage(message)
					.setHeader(
							IntegrationMessageHeaderAccessor.ACKNOWLEDGMENT_CALLBACK,
							callback)
					.build();
		}

	});
	ExtendedConsumerProperties<Object> properties = new ExtendedConsumerProperties<>(null);
	properties.setMaxAttempts(1);
	binder.bindPollableConsumer("foo", "bar", pollableSource, properties);
	SubscribableChannel errorChannel = new DirectChannel();
	errorChannel.subscribe(msg -> {
		throw new RequeueCurrentMessageException((Throwable) msg.getPayload());
	});
	pollableSource.setErrorChannel(errorChannel);
	try {
		pollableSource.poll(received -> {
			throw new RuntimeException("test requeue from error flow");
		});
	}
	catch (Exception e) {
		// no op
	}
	verify(callback).acknowledge(Status.REQUEUE);
}
 
Example 12
@StreamListener
@Output(StreamListenerTestUtils.FooOutboundChannel1.OUTPUT)
public void receive(@Input(Processor.INPUT) SubscribableChannel input,
		@Output(Processor.OUTPUT) final MessageChannel output1) {
	input.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			output1.send(org.springframework.messaging.support.MessageBuilder
					.withPayload(message.getPayload().toString().toUpperCase())
					.build());
		}
	});
}
 
Example 13
/**
 * Create an instance with the given client and broker channels subscribing
 * to handle messages from each and then sending any resolved messages to the
 * broker channel.
 * @param clientInboundChannel messages received from clients.
 * @param brokerChannel messages sent to the broker.
 * @param resolver the resolver for "user" destinations.
 */
public UserDestinationMessageHandler(SubscribableChannel clientInboundChannel,
		SubscribableChannel brokerChannel, UserDestinationResolver resolver) {

	Assert.notNull(clientInboundChannel, "'clientInChannel' must not be null");
	Assert.notNull(brokerChannel, "'brokerChannel' must not be null");
	Assert.notNull(resolver, "resolver must not be null");

	this.clientInboundChannel = clientInboundChannel;
	this.brokerChannel = brokerChannel;
	this.messagingTemplate = new SimpMessagingTemplate(brokerChannel);
	this.destinationResolver = resolver;
}
 
Example 14
/**
 * Create a new {@code SubProtocolWebSocketHandler} for the given inbound and outbound channels.
 * @param clientInboundChannel the inbound {@code MessageChannel}
 * @param clientOutboundChannel the outbound {@code MessageChannel}
 */
public SubProtocolWebSocketHandler(MessageChannel clientInboundChannel, SubscribableChannel clientOutboundChannel) {
	Assert.notNull(clientInboundChannel, "Inbound MessageChannel must not be null");
	Assert.notNull(clientOutboundChannel, "Outbound MessageChannel must not be null");
	this.clientInboundChannel = clientInboundChannel;
	this.clientOutboundChannel = clientOutboundChannel;
}
 
Example 15
Source Project: java-technology-stack   Source File: SimpleBrokerRegistration.java    License: MIT License 5 votes vote down vote up
@Override
protected SimpleBrokerMessageHandler getMessageHandler(SubscribableChannel brokerChannel) {
	SimpleBrokerMessageHandler handler = new SimpleBrokerMessageHandler(getClientInboundChannel(),
			getClientOutboundChannel(), brokerChannel, getDestinationPrefixes());
	if (this.taskScheduler != null) {
		handler.setTaskScheduler(this.taskScheduler);
	}
	if (this.heartbeat != null) {
		handler.setHeartbeatValue(this.heartbeat);
	}
	handler.setSelectorHeaderName(this.selectorHeaderName);
	return handler;
}
 
Example 16
@Test
@SuppressWarnings({ "rawtypes", "unchecked" })
public void propertyPassthrough() {
	Map<String, BindingProperties> bindings = new HashMap<>();
	BindingProperties genericProperties = new BindingProperties();
	genericProperties.setContentType("text/plain");
	bindings.put("foo", genericProperties);
	this.bindingServiceProperties.setBindings(bindings);
	Binder binder = mock(Binder.class);
	Binder binder2 = mock(Binder.class);
	BinderFactory mockBinderFactory = Mockito.mock(BinderFactory.class);
	Binding<MessageChannel> fooBinding = Mockito.mock(Binding.class);
	Binding<MessageChannel> barBinding = Mockito.mock(Binding.class);
	when(binder.bindProducer(matches("foo"), any(DirectChannel.class),
			any(ProducerProperties.class))).thenReturn(fooBinding);
	when(binder2.bindProducer(matches("bar"), any(DirectChannel.class),
			any(ProducerProperties.class))).thenReturn(barBinding);
	when(mockBinderFactory.getBinder(null, DirectWithAttributesChannel.class))
			.thenReturn(binder);
	when(mockBinderFactory.getBinder("someTransport",
			DirectWithAttributesChannel.class)).thenReturn(binder2);
	BindingService bindingService = new BindingService(this.bindingServiceProperties,
			mockBinderFactory);
	BinderAwareChannelResolver resolver = new BinderAwareChannelResolver(
			bindingService, this.bindingTargetFactory,
			new DynamicDestinationsBindable());
	resolver.setBeanFactory(this.context.getBeanFactory());
	SubscribableChannel resolved = (SubscribableChannel) resolver
			.resolveDestination("foo");
	verify(binder).bindProducer(eq("foo"), any(MessageChannel.class),
			any(ProducerProperties.class));
	assertThat(resolved).isSameAs(this.context.getBean("foo"));
	this.context.close();
}
 
Example 17
protected StompBrokerRelayMessageHandler getMessageHandler(SubscribableChannel brokerChannel) {

		StompBrokerRelayMessageHandler handler = new StompBrokerRelayMessageHandler(
				getClientInboundChannel(), getClientOutboundChannel(),
				brokerChannel, getDestinationPrefixes());

		handler.setRelayHost(this.relayHost);
		handler.setRelayPort(this.relayPort);

		handler.setClientLogin(this.clientLogin);
		handler.setClientPasscode(this.clientPasscode);

		handler.setSystemLogin(this.systemLogin);
		handler.setSystemPasscode(this.systemPasscode);

		if (this.systemHeartbeatSendInterval != null) {
			handler.setSystemHeartbeatSendInterval(this.systemHeartbeatSendInterval);
		}
		if (this.systemHeartbeatReceiveInterval != null) {
			handler.setSystemHeartbeatReceiveInterval(this.systemHeartbeatReceiveInterval);
		}
		if (this.virtualHost != null) {
			handler.setVirtualHost(this.virtualHost);
		}
		if (this.tcpClient != null) {
			handler.setTcpClient(this.tcpClient);
		}

		handler.setAutoStartup(this.autoStartup);

		return handler;
	}
 
Example 18
@Override
public SubscribableChannel createOutput(String name) {
	DirectWithAttributesChannel subscribableChannel = new DirectWithAttributesChannel();
	subscribableChannel.setComponentName(name);
	subscribableChannel.setAttribute("type", Source.OUTPUT);
	this.messageChannelConfigurer.configureOutputChannel(subscribableChannel, name);
	if (context != null && !context.containsBean(name)) {
		context.registerBean(name, DirectWithAttributesChannel.class, () -> subscribableChannel);
	}
	return subscribableChannel;
}
 
Example 19
protected SimpleBrokerMessageHandler getSimpleBroker(SubscribableChannel brokerChannel) {
	if (this.simpleBrokerRegistration == null && this.brokerRelayRegistration == null) {
		enableSimpleBroker();
	}
	if (this.simpleBrokerRegistration != null) {
		SimpleBrokerMessageHandler handler = this.simpleBrokerRegistration.getMessageHandler(brokerChannel);
		handler.setPathMatcher(this.pathMatcher);
		return handler;
	}
	return null;
}
 
Example 20
/**
 * Will provision consumer destination as SI {@link DirectChannel}.
 */
@Override
public ConsumerDestination provisionConsumerDestination(String name, String group,
		ConsumerProperties properties) throws ProvisioningException {
	SubscribableChannel destination = this.provisionDestination(name, false);
	if (this.source != null) {
		this.source.setChannel(destination);
	}
	return new SpringIntegrationConsumerDestination(name, destination);
}
 
Example 21
@Before
public void setup() {
	SubscribableChannel inChannel = mock(SubscribableChannel.class);
	SubscribableChannel outChannel = mock(SubscribableChannel.class);
	this.webSocketHandler = new SubProtocolWebSocketHandler(inChannel, outChannel);

	WebSocketTransportRegistration transport = new WebSocketTransportRegistration();
	TaskScheduler scheduler = mock(TaskScheduler.class);
	this.endpointRegistry = new WebMvcStompEndpointRegistry(this.webSocketHandler, transport, scheduler);
}
 
Example 22
Source Project: spring-cloud   Source File: CustomSink.java    License: Apache License 2.0 4 votes vote down vote up
@Input(INPUT0)
SubscribableChannel input0();
 
Example 23
@Input(APPLICATIONS_IN)
SubscribableChannel sourceOfLoanApplications();
 
Example 24
Source Project: MyShopPlus   Source File: AdminLoginLogSink.java    License: Apache License 2.0 4 votes vote down vote up
@Input("admin-login-log-topic")
SubscribableChannel adminLoginLog();
 
Example 25
@Input(BROKER_TO_CLIENT)
SubscribableChannel brokerToClient();
 
Example 26
@Input(UserSink.INPUT)
SubscribableChannel user();
 
Example 27
@Input
SubscribableChannel subscriptionOnMoneyTransferredChannel();
 
Example 28
public SubscribableChannel getClientInboundChannel() {
	return this.clientInboundChannel;
}
 
Example 29
public SubscribableChannel getBrokerChannel() {
	return this.brokerChannel;
}
 
Example 30
Source Project: myfeed   Source File: FeedBinder.java    License: Apache License 2.0 4 votes vote down vote up
@Input(FeedBinder.USER_INITIALIZED)
SubscribableChannel userInitialized();