org.springframework.messaging.support.ChannelInterceptor Java Examples

The following examples show how to use org.springframework.messaging.support.ChannelInterceptor. 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: WebSocketMessageBrokerConfigurationSupportTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void clientInboundChannelSendMessage() throws Exception {
	ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class);
	TestChannel channel = config.getBean("clientInboundChannel", TestChannel.class);
	SubProtocolWebSocketHandler webSocketHandler = config.getBean(SubProtocolWebSocketHandler.class);

	List<ChannelInterceptor> interceptors = channel.getInterceptors();
	assertEquals(ImmutableMessageChannelInterceptor.class, interceptors.get(interceptors.size()-1).getClass());

	TestWebSocketSession session = new TestWebSocketSession("s1");
	session.setOpen(true);
	webSocketHandler.afterConnectionEstablished(session);

	TextMessage textMessage = StompTextMessageBuilder.create(StompCommand.SEND).headers("destination:/foo").build();
	webSocketHandler.handleMessage(session, textMessage);

	Message<?> message = channel.messages.get(0);
	StompHeaderAccessor accessor = StompHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertNotNull(accessor);
	assertFalse(accessor.isMutable());
	assertEquals(SimpMessageType.MESSAGE, accessor.getMessageType());
	assertEquals("/foo", accessor.getDestination());
}
 
Example #2
Source File: StompSubProtocolHandler.java    From spring-analysis-note with 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 #3
Source File: WebSocketMessageBrokerConfigurationSupportTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void clientInboundChannelSendMessage() throws Exception {
	ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class);
	TestChannel channel = config.getBean("clientInboundChannel", TestChannel.class);
	SubProtocolWebSocketHandler webSocketHandler = config.getBean(SubProtocolWebSocketHandler.class);

	List<ChannelInterceptor> interceptors = channel.getInterceptors();
	assertEquals(ImmutableMessageChannelInterceptor.class, interceptors.get(interceptors.size()-1).getClass());

	TestWebSocketSession session = new TestWebSocketSession("s1");
	session.setOpen(true);
	webSocketHandler.afterConnectionEstablished(session);

	webSocketHandler.handleMessage(session,
			StompTextMessageBuilder.create(StompCommand.SEND).headers("destination:/foo").build());

	Message<?> message = channel.messages.get(0);
	StompHeaderAccessor accessor = StompHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertNotNull(accessor);
	assertFalse(accessor.isMutable());
	assertEquals(SimpMessageType.MESSAGE, accessor.getMessageType());
	assertEquals("/foo", accessor.getDestination());
}
 
Example #4
Source File: StompSubProtocolHandler.java    From spring4-understanding with Apache License 2.0 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 #5
Source File: StompSubProtocolHandler.java    From java-technology-stack with 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
Source File: WebSocketMessageBrokerConfigurationSupportTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void clientInboundChannelSendMessage() throws Exception {
	ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class);
	TestChannel channel = config.getBean("clientInboundChannel", TestChannel.class);
	SubProtocolWebSocketHandler webSocketHandler = config.getBean(SubProtocolWebSocketHandler.class);

	List<ChannelInterceptor> interceptors = channel.getInterceptors();
	assertEquals(ImmutableMessageChannelInterceptor.class, interceptors.get(interceptors.size()-1).getClass());

	TestWebSocketSession session = new TestWebSocketSession("s1");
	session.setOpen(true);
	webSocketHandler.afterConnectionEstablished(session);

	webSocketHandler.handleMessage(session,
			StompTextMessageBuilder.create(StompCommand.SEND).headers("destination:/foo").build());

	Message<?> message = channel.messages.get(0);
	StompHeaderAccessor accessor = StompHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertNotNull(accessor);
	assertFalse(accessor.isMutable());
	assertEquals(SimpMessageType.MESSAGE, accessor.getMessageType());
	assertEquals("/foo", accessor.getDestination());
}
 
Example #7
Source File: SpringWebSocketAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void messageChannelSend(final Object thiz) {
  final AbstractMessageChannel channel = (AbstractMessageChannel)thiz;
  for (final ChannelInterceptor interceptor : channel.getInterceptors())
    if (interceptor instanceof TracingChannelInterceptor)
      return;

  final TracingChannelInterceptor tracingChannelInterceptor;
  if (channel.getBeanName().equals("clientOutboundChannel"))
    tracingChannelInterceptor = new TracingChannelInterceptor(GlobalTracer.get(), Tags.SPAN_KIND_CLIENT);
  else if (channel.getBeanName().equals("clientInboundChannel"))
    tracingChannelInterceptor = new TracingChannelInterceptor(GlobalTracer.get(), Tags.SPAN_KIND_SERVER);
  else
    return;

  channel.addInterceptor(tracingChannelInterceptor);
}
 
Example #8
Source File: SpringMessagingAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static void enter(final Object thiz) {
  try {
    // Reflection is used because
    // org.springframework.integration.channel.AbstractMessageChannel$ChannelInterceptorList
    // is protected static class
    final Method getInterceptors = thiz.getClass().getMethod("getInterceptors");
    final List<ChannelInterceptor> interceptors = (List<ChannelInterceptor>)getInterceptors.invoke(thiz);

    for (final ChannelInterceptor interceptor : interceptors)
      if (interceptor instanceof OpenTracingChannelInterceptor)
        return;

    final Method addInterceptor = thiz.getClass().getMethod("add", ChannelInterceptor.class);
    addInterceptor.invoke(thiz, new OpenTracingChannelInterceptor(GlobalTracer.get()));
  }
  catch (final Exception e) {
    logger.log(Level.FINE, e.getMessage(), e);
  }
}
 
Example #9
Source File: PollableConsumerTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequeue() {
	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(2);
	properties.setBackOffInitialInterval(0);
	binder.bindPollableConsumer("foo", "bar", pollableSource, properties);
	final AtomicInteger count = new AtomicInteger();
	try {
		assertThat(pollableSource.poll(received -> {
			count.incrementAndGet();
			throw new RequeueCurrentMessageException("test retry");
		})).isTrue();
	}
	catch (Exception e) {
		// no op
	}
	assertThat(count.get()).isEqualTo(2);
	verify(callback).acknowledge(Status.REQUEUE);
}
 
Example #10
Source File: WebSocketMessageBrokerConfigurationSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void brokerChannel() {
	ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class);
	TestChannel channel = config.getBean("brokerChannel", TestChannel.class);
	Set<MessageHandler> handlers = channel.getSubscribers();

	List<ChannelInterceptor> interceptors = channel.getInterceptors();
	assertEquals(ImmutableMessageChannelInterceptor.class, interceptors.get(interceptors.size()-1).getClass());

	assertEquals(2, handlers.size());
	assertTrue(handlers.contains(config.getBean(SimpleBrokerMessageHandler.class)));
	assertTrue(handlers.contains(config.getBean(UserDestinationMessageHandler.class)));
}
 
Example #11
Source File: MessageBrokerBeanDefinitionParserTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
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 subsription 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 #12
Source File: KafkaBinderTests.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@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 #13
Source File: PollableConsumerTests.java    From spring-cloud-stream with 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 #14
Source File: PollableConsumerTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequeueWithNoAcknowledgementCallback() {
	TestChannelBinder binder = createBinder();
	MessageConverterConfigurer configurer = this.context
			.getBean(MessageConverterConfigurer.class);

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

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

	});
	ExtendedConsumerProperties<Object> properties = new ExtendedConsumerProperties<>(null);
	properties.setMaxAttempts(2);
	properties.setBackOffInitialInterval(0);
	binder.bindPollableConsumer("foo", "bar", pollableSource, properties);
	final AtomicInteger count = new AtomicInteger();

	assertThat(pollableSource.poll(received -> {
		count.incrementAndGet();
		throw new RequeueCurrentMessageException("test retry");
	})).isTrue();

	assertThat(count.get()).isEqualTo(2);

}
 
Example #15
Source File: DefaultPollableMessageSource.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
public void setSource(MessageSource<?> source) {
	ProxyFactory pf = new ProxyFactory(source);
	class ReceiveAdvice implements MethodInterceptor {

		private final List<ChannelInterceptor> interceptors = new ArrayList<>();

		@Override
		public Object invoke(MethodInvocation invocation) throws Throwable {
			Object result = invocation.proceed();
			if (result instanceof Message) {
				Message<?> received = (Message<?>) result;
				for (ChannelInterceptor interceptor : this.interceptors) {
					received = interceptor.preSend(received, dummyChannel);
					if (received == null) {
						return null;
					}
				}
				return received;
			}
			return result;
		}

	}
	final ReceiveAdvice advice = new ReceiveAdvice();
	advice.interceptors.addAll(this.interceptors);
	NameMatchMethodPointcutAdvisor sourceAdvisor = new NameMatchMethodPointcutAdvisor(
			advice);
	sourceAdvisor.addMethodName("receive");
	pf.addAdvisor(sourceAdvisor);
	this.source = (MessageSource<?>) pf.getProxy();
}
 
Example #16
Source File: ChannelRegistration.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Configure interceptors for the message channel.
 */
public ChannelRegistration setInterceptors(ChannelInterceptor... interceptors) {
	if (interceptors != null) {
		this.interceptors.addAll(Arrays.asList(interceptors));
	}
	return this;
}
 
Example #17
Source File: PollableConsumerTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testErrorsNoRetry() {
	TestChannelBinder binder = createBinder();
	MessageConverterConfigurer configurer = this.context
			.getBean(MessageConverterConfigurer.class);

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

		@Override
		public Message<?> preSend(Message<?> message, MessageChannel channel) {
			return MessageBuilder
					.withPayload(((String) message.getPayload()).toUpperCase())
					.copyHeaders(message.getHeaders()).build();
		}

	});
	ExtendedConsumerProperties<Object> properties = new ExtendedConsumerProperties<>(
			null);
	properties.setMaxAttempts(1);
	binder.bindPollableConsumer("foo", "bar", pollableSource, properties);
	final CountDownLatch latch = new CountDownLatch(1);
	this.context.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME,
			SubscribableChannel.class).subscribe(m -> {
				latch.countDown();
			});
	final AtomicInteger count = new AtomicInteger();
	assertThat(pollableSource.poll(received -> {
		count.incrementAndGet();
		throw new RuntimeException("test recoverer");
	})).isTrue();
	assertThat(count.get()).isEqualTo(1);
}
 
Example #18
Source File: CustomPartitionedProducerTest.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomPartitionedProducer() {
	ApplicationContext context = SpringApplication.run(
			CustomPartitionedProducerTest.TestSource.class,
			"--spring.jmx.enabled=false", "--spring.main.web-application-type=none",
			"--spring.cloud.stream.bindings.output.producer.partitionKeyExtractorClass="
					+ "org.springframework.cloud.stream.partitioning.CustomPartitionKeyExtractorClass",
			"--spring.cloud.stream.bindings.output.producer.partitionSelectorClass="
					+ "org.springframework.cloud.stream.partitioning.CustomPartitionSelectorClass",
			"--spring.cloud.stream.default-binder=mock");
	Source testSource = context.getBean(Source.class);
	DirectChannel messageChannel = (DirectChannel) testSource.output();
	for (ChannelInterceptor channelInterceptor : messageChannel
			.getInterceptors()) {
		if (channelInterceptor instanceof MessageConverterConfigurer.PartitioningInterceptor) {
			Field partitionHandlerField = ReflectionUtils.findField(
					MessageConverterConfigurer.PartitioningInterceptor.class,
					"partitionHandler");
			ReflectionUtils.makeAccessible(partitionHandlerField);
			PartitionHandler partitionHandler = (PartitionHandler) ReflectionUtils
					.getField(partitionHandlerField, channelInterceptor);
			Field partitonKeyExtractorField = ReflectionUtils.findField(
					PartitionHandler.class, "partitionKeyExtractorStrategy");
			ReflectionUtils.makeAccessible(partitonKeyExtractorField);
			Field partitonSelectorField = ReflectionUtils
					.findField(PartitionHandler.class, "partitionSelectorStrategy");
			ReflectionUtils.makeAccessible(partitonSelectorField);
			assertThat(((PartitionKeyExtractorStrategy) ReflectionUtils
					.getField(partitonKeyExtractorField, partitionHandler)).getClass()
							.equals(CustomPartitionKeyExtractorClass.class)).isTrue();
			assertThat(((PartitionSelectorStrategy) ReflectionUtils
					.getField(partitonSelectorField, partitionHandler)).getClass()
							.equals(CustomPartitionSelectorClass.class)).isTrue();
		}
	}
}
 
Example #19
Source File: CustomPartitionedProducerTest.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomPartitionedProducerByName() {
	ApplicationContext context = SpringApplication.run(
			CustomPartitionedProducerTest.TestSource.class,
			"--spring.jmx.enabled=false", "--spring.main.web-application-type=none",
			"--spring.cloud.stream.bindings.output.producer.partitionKeyExtractorName=customPartitionKeyExtractor",
			"--spring.cloud.stream.bindings.output.producer.partitionSelectorName=customPartitionSelector",
			"--spring.cloud.stream.default-binder=mock");
	Source testSource = context.getBean(Source.class);
	DirectChannel messageChannel = (DirectChannel) testSource.output();
	for (ChannelInterceptor channelInterceptor : messageChannel
			.getInterceptors()) {
		if (channelInterceptor instanceof MessageConverterConfigurer.PartitioningInterceptor) {
			Field partitionHandlerField = ReflectionUtils.findField(
					MessageConverterConfigurer.PartitioningInterceptor.class,
					"partitionHandler");
			ReflectionUtils.makeAccessible(partitionHandlerField);
			PartitionHandler partitionHandler = (PartitionHandler) ReflectionUtils
					.getField(partitionHandlerField, channelInterceptor);
			Field partitonKeyExtractorField = ReflectionUtils.findField(
					PartitionHandler.class, "partitionKeyExtractorStrategy");
			ReflectionUtils.makeAccessible(partitonKeyExtractorField);
			Field partitonSelectorField = ReflectionUtils
					.findField(PartitionHandler.class, "partitionSelectorStrategy");
			ReflectionUtils.makeAccessible(partitonSelectorField);
			assertThat(((PartitionKeyExtractorStrategy) ReflectionUtils
					.getField(partitonKeyExtractorField, partitionHandler)).getClass()
							.equals(CustomPartitionKeyExtractorClass.class)).isTrue();
			assertThat(((PartitionSelectorStrategy) ReflectionUtils
					.getField(partitonSelectorField, partitionHandler)).getClass()
							.equals(CustomPartitionSelectorClass.class)).isTrue();
		}
	}
}
 
Example #20
Source File: CustomPartitionedProducerTest.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomPartitionedProducerAsSingletons() {
	ApplicationContext context = SpringApplication.run(
			CustomPartitionedProducerTest.TestSource.class,
			"--spring.jmx.enabled=false", "--spring.main.web-application-type=none",
			"--spring.cloud.stream.default-binder=mock");
	Source testSource = context.getBean(Source.class);
	DirectChannel messageChannel = (DirectChannel) testSource.output();
	for (ChannelInterceptor channelInterceptor : messageChannel
			.getInterceptors()) {
		if (channelInterceptor instanceof MessageConverterConfigurer.PartitioningInterceptor) {
			Field partitionHandlerField = ReflectionUtils.findField(
					MessageConverterConfigurer.PartitioningInterceptor.class,
					"partitionHandler");
			ReflectionUtils.makeAccessible(partitionHandlerField);
			PartitionHandler partitionHandler = (PartitionHandler) ReflectionUtils
					.getField(partitionHandlerField, channelInterceptor);
			Field partitonKeyExtractorField = ReflectionUtils.findField(
					PartitionHandler.class, "partitionKeyExtractorStrategy");
			ReflectionUtils.makeAccessible(partitonKeyExtractorField);
			Field partitonSelectorField = ReflectionUtils
					.findField(PartitionHandler.class, "partitionSelectorStrategy");
			ReflectionUtils.makeAccessible(partitonSelectorField);
			assertThat(((PartitionKeyExtractorStrategy) ReflectionUtils
					.getField(partitonKeyExtractorField, partitionHandler)).getClass()
							.equals(CustomPartitionKeyExtractorClass.class)).isTrue();
			assertThat(((PartitionSelectorStrategy) ReflectionUtils
					.getField(partitonSelectorField, partitionHandler)).getClass()
							.equals(CustomPartitionSelectorClass.class)).isTrue();
		}
	}
}
 
Example #21
Source File: CustomPartitionedProducerTest.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
public void testCustomPartitionedProducerMultipleInstances() {
	ApplicationContext context = SpringApplication.run(
			CustomPartitionedProducerTest.TestSourceMultipleStrategies.class,
			"--spring.jmx.enabled=false", "--spring.main.web-application-type=none",
			"--spring.cloud.stream.bindings.output.producer.partitionKeyExtractorName=customPartitionKeyExtractorOne",
			"--spring.cloud.stream.bindings.output.producer.partitionSelectorName=customPartitionSelectorTwo",
			"--spring.cloud.stream.default-binder=mock");
	Source testSource = context.getBean(Source.class);
	DirectChannel messageChannel = (DirectChannel) testSource.output();
	for (ChannelInterceptor channelInterceptor : messageChannel
			.getInterceptors()) {
		if (channelInterceptor instanceof MessageConverterConfigurer.PartitioningInterceptor) {
			Field partitionHandlerField = ReflectionUtils.findField(
					MessageConverterConfigurer.PartitioningInterceptor.class,
					"partitionHandler");
			ReflectionUtils.makeAccessible(partitionHandlerField);
			PartitionHandler partitionHandler = (PartitionHandler) ReflectionUtils
					.getField(partitionHandlerField, channelInterceptor);
			Field partitonKeyExtractorField = ReflectionUtils.findField(
					PartitionHandler.class, "partitionKeyExtractorStrategy");
			ReflectionUtils.makeAccessible(partitonKeyExtractorField);
			Field partitonSelectorField = ReflectionUtils
					.findField(PartitionHandler.class, "partitionSelectorStrategy");
			ReflectionUtils.makeAccessible(partitonSelectorField);
			assertThat(((PartitionKeyExtractorStrategy) ReflectionUtils
					.getField(partitonKeyExtractorField, partitionHandler)).getClass()
							.equals(CustomPartitionKeyExtractorClass.class)).isTrue();
			assertThat(((PartitionSelectorStrategy) ReflectionUtils
					.getField(partitonSelectorField, partitionHandler)).getClass()
							.equals(CustomPartitionSelectorClass.class)).isTrue();
		}
	}
}
 
Example #22
Source File: PollableConsumerTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testSimple() {
	TestChannelBinder binder = createBinder();
	MessageConverterConfigurer configurer = this.context
			.getBean(MessageConverterConfigurer.class);

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

		@Override
		public Message<?> preSend(Message<?> message, MessageChannel channel) {
			return MessageBuilder
					.withPayload(((String) message.getPayload()).toUpperCase())
					.copyHeaders(message.getHeaders()).build();
		}

	});
	ExtendedConsumerProperties<Object> properties = new ExtendedConsumerProperties<>(
			null);
	properties.setMaxAttempts(2);
	properties.setBackOffInitialInterval(0);
	binder.bindPollableConsumer("foo", "bar", pollableSource, properties);
	final AtomicInteger count = new AtomicInteger();
	assertThat(pollableSource.poll(received -> {
		assertThat(received.getPayload()).isEqualTo("POLLED DATA");
		assertThat(received.getHeaders().get(MessageHeaders.CONTENT_TYPE))
				.isEqualTo(MimeType.valueOf("text/plain"));
		if (count.incrementAndGet() == 1) {
			throw new RuntimeException("test retry");
		}
	})).isTrue();
	assertThat(count.get()).isEqualTo(2);
}
 
Example #23
Source File: WebSocketMessageBrokerConfigurationSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void clientOutboundChannel() {
	ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class);
	TestChannel channel = config.getBean("clientOutboundChannel", TestChannel.class);
	Set<MessageHandler> handlers = channel.getSubscribers();

	List<ChannelInterceptor> interceptors = channel.getInterceptors();
	assertEquals(ImmutableMessageChannelInterceptor.class, interceptors.get(interceptors.size()-1).getClass());

	assertEquals(1, handlers.size());
	assertTrue(handlers.contains(config.getBean(SubProtocolWebSocketHandler.class)));
}
 
Example #24
Source File: BusAutoConfigurationTests.java    From spring-cloud-bus with Apache License 2.0 5 votes vote down vote up
private ChannelInterceptor interceptor() {
	return new ChannelInterceptorAdapter() {
		@Override
		public void postSend(Message<?> message, MessageChannel channel,
				boolean sent) {
			OutboundMessageHandlerConfiguration.this.message = message;
			OutboundMessageHandlerConfiguration.this.latch.countDown();
		}
	};
}
 
Example #25
Source File: SpringIntegrationConfig.java    From bearchoke with Apache License 2.0 5 votes vote down vote up
/**
     * SubscribableChannel for Axon CQRS to use
     * @return
     */
    @Bean(name = "defaultInputChannel")
    public PublishSubscribeChannel defaultInputChannel() {
        PublishSubscribeChannel channel = new PublishSubscribeChannel();
        List<ChannelInterceptor> list = new ArrayList<>(1);
        list.add(messageSelectingInterceptor());
        channel.setInterceptors(list);

//        channel.setDatatypes(Object.class); // we've defined it using the PayloadTypeSelector instead and injected it as an interceptor above
        return channel;
    }
 
Example #26
Source File: SpringIntegrationConfig.java    From bearchoke with Apache License 2.0 5 votes vote down vote up
/**
 * This channel can be used to monitor messages from our main channel without interrupting it.
 * @return
 */
@Bean(name = "monitoringChannel")
public PublishSubscribeChannel monitoringChannel() {
    PublishSubscribeChannel channel = new PublishSubscribeChannel();
    List<ChannelInterceptor> list = new ArrayList<>(1);
    list.add(wireTap());
    channel.setInterceptors(list);

    return channel;
}
 
Example #27
Source File: MessageBrokerBeanDefinitionParserTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
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: WebSocketMessageBrokerConfigurationSupportTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void brokerChannel() {
	ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class);
	TestChannel channel = config.getBean("brokerChannel", TestChannel.class);
	Set<MessageHandler> handlers = channel.getSubscribers();

	List<ChannelInterceptor> interceptors = channel.getInterceptors();
	assertEquals(ImmutableMessageChannelInterceptor.class, interceptors.get(interceptors.size()-1).getClass());

	assertEquals(2, handlers.size());
	assertTrue(handlers.contains(config.getBean(SimpleBrokerMessageHandler.class)));
	assertTrue(handlers.contains(config.getBean(UserDestinationMessageHandler.class)));
}
 
Example #29
Source File: WebSocketMessageBrokerConfigurationSupportTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void clientOutboundChannel() {
	ApplicationContext config = createConfig(TestChannelConfig.class, TestConfigurer.class);
	TestChannel channel = config.getBean("clientOutboundChannel", TestChannel.class);
	Set<MessageHandler> handlers = channel.getSubscribers();

	List<ChannelInterceptor> interceptors = channel.getInterceptors();
	assertEquals(ImmutableMessageChannelInterceptor.class, interceptors.get(interceptors.size()-1).getClass());

	assertEquals(1, handlers.size());
	assertTrue(handlers.contains(config.getBean(SubProtocolWebSocketHandler.class)));
}
 
Example #30
Source File: SpringIntegrationConfig.java    From bearchoke with Apache License 2.0 5 votes vote down vote up
/**
 * Wraps our payload type selector as a channel interceptor
 * @return
 */
@Bean(name = "messageSelectingInterceptor")
public ChannelInterceptor messageSelectingInterceptor() {
    MessageSelectingInterceptor interceptor = new MessageSelectingInterceptor(payloadTypeSelector());

    return interceptor;
}