org.springframework.cloud.stream.config.BindingProperties Java Examples

The following examples show how to use org.springframework.cloud.stream.config.BindingProperties. 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: GlobalKTableBoundElementFactory.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 8 votes vote down vote up
@Override
public GlobalKTable createInput(String name) {
	BindingProperties bindingProperties = this.bindingServiceProperties.getBindingProperties(name);
	ConsumerProperties consumerProperties = bindingProperties.getConsumer();
	if (consumerProperties == null) {
		consumerProperties = this.bindingServiceProperties.getConsumerProperties(name);
		consumerProperties.setUseNativeDecoding(true);
	}
	else {
		if (!encodingDecodingBindAdviceHandler.isDecodingSettingProvided()) {
			consumerProperties.setUseNativeDecoding(true);
		}
	}
	// Always set multiplex to true in the kafka streams binder
	consumerProperties.setMultiplex(true);

	// @checkstyle:off
	GlobalKTableBoundElementFactory.GlobalKTableWrapperHandler wrapper = new GlobalKTableBoundElementFactory.GlobalKTableWrapperHandler();
	// @checkstyle:on
	ProxyFactory proxyFactory = new ProxyFactory(
			GlobalKTableBoundElementFactory.GlobalKTableWrapper.class,
			GlobalKTable.class);
	proxyFactory.addAdvice(wrapper);

	return (GlobalKTable) proxyFactory.getProxy();
}
 
Example #2
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnonWithBuiltInExchange() throws Exception {
	RabbitTestBinder binder = getBinder();
	ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties();
	properties.getExtension().setDeclareExchange(false);
	properties.getExtension().setQueueNameGroupOnly(true);

	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("anonymous.");
	assertThat(container.isRunning()).isTrue();
	consumerBinding.unbind();
	assertThat(container.isRunning()).isFalse();
}
 
Example #3
Source File: KafkaStreamsStreamListenerSetupMethodOrchestrator.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
private KStream<?, ?> getkStream(String inboundName,
								KafkaStreamsStateStoreProperties storeSpec,
								BindingProperties bindingProperties,
								KafkaStreamsConsumerProperties kafkaStreamsConsumerProperties, StreamsBuilder streamsBuilder,
								Serde<?> keySerde, Serde<?> valueSerde,
								Topology.AutoOffsetReset autoOffsetReset, boolean firstBuild) {
	if (storeSpec != null) {
		StoreBuilder storeBuilder = buildStateStore(storeSpec);
		streamsBuilder.addStateStore(storeBuilder);
		if (LOG.isInfoEnabled()) {
			LOG.info("state store " + storeBuilder.name() + " added to topology");
		}
	}
	return getKStream(inboundName, bindingProperties, kafkaStreamsConsumerProperties, streamsBuilder,
			keySerde, valueSerde, autoOffsetReset, firstBuild);
}
 
Example #4
Source File: AbstractKafkaStreamsBinderProcessor.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
private KStream<?, ?> getkStream(BindingProperties bindingProperties, KStream<?, ?> stream, boolean nativeDecoding) {
	if (!nativeDecoding) {
		stream = stream.mapValues((value) -> {
			Object returnValue;
			String contentType = bindingProperties.getContentType();
			if (value != null && !StringUtils.isEmpty(contentType)) {
				returnValue = MessageBuilder.withPayload(value)
						.setHeader(MessageHeaders.CONTENT_TYPE, contentType).build();
			}
			else {
				returnValue = value;
			}
			return returnValue;
		});
	}
	return stream;
}
 
Example #5
Source File: BindingServiceTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testConsumerPropertiesValidation() {
	BindingServiceProperties serviceProperties = new BindingServiceProperties();
	Map<String, BindingProperties> bindingProperties = new HashMap<>();
	BindingProperties props = new BindingProperties();
	ConsumerProperties consumerProperties = new ConsumerProperties();
	consumerProperties.setConcurrency(0);
	props.setDestination("foo");
	props.setConsumer(consumerProperties);
	final String inputChannelName = "input";
	bindingProperties.put(inputChannelName, props);
	serviceProperties.setBindings(bindingProperties);
	DefaultBinderFactory binderFactory = createMockBinderFactory();
	BindingService service = new BindingService(serviceProperties, binderFactory);
	MessageChannel inputChannel = new DirectChannel();
	try {
		service.bindConsumer(inputChannel, inputChannelName);
		fail("Consumer properties should be validated.");
	}
	catch (IllegalStateException e) {
		assertThat(e)
				.hasMessageContaining("Concurrency should be greater than zero.");
	}
}
 
Example #6
Source File: FunctionConfiguration.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
private void adjustFunctionForNativeEncodingIfNecessary(String outputDestinationName, FunctionInvocationWrapper function, int index) {
	if (function.isConsumer()) {
		return;
	}
	BindingProperties properties = this.serviceProperties.getBindingProperties(outputDestinationName);
	if (properties.getProducer() != null && properties.getProducer().isUseNativeEncoding()) {
		Field acceptedOutputMimeTypesField = ReflectionUtils
				.findField(FunctionInvocationWrapper.class, "acceptedOutputMimeTypes", String[].class);
		acceptedOutputMimeTypesField.setAccessible(true);
		try {
			String[] acceptedOutputMimeTypes = (String[]) acceptedOutputMimeTypesField.get(function);
			acceptedOutputMimeTypes[index] = "";
		}
		catch (Exception e) {
			// ignore
		}
	}
}
 
Example #7
Source File: BindingServiceTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testProducerPropertiesValidation() {
	BindingServiceProperties serviceProperties = new BindingServiceProperties();
	Map<String, BindingProperties> bindingProperties = new HashMap<>();
	BindingProperties props = new BindingProperties();
	ProducerProperties producerProperties = new ProducerProperties();
	producerProperties.setPartitionCount(0);
	props.setDestination("foo");
	props.setProducer(producerProperties);
	final String outputChannelName = "output";
	bindingProperties.put(outputChannelName, props);
	serviceProperties.setBindings(bindingProperties);
	DefaultBinderFactory binderFactory = createMockBinderFactory();
	BindingService service = new BindingService(serviceProperties, binderFactory);
	MessageChannel outputChannel = new DirectChannel();
	try {
		service.bindProducer(outputChannel, outputChannelName);
		fail("Producer properties should be validated.");
	}
	catch (IllegalStateException e) {
		assertThat(e)
				.hasMessageContaining("Partition count should be greater than zero.");
	}
}
 
Example #8
Source File: BusAutoConfigurationTests.java    From spring-cloud-bus with Apache License 2.0 6 votes vote down vote up
@Test
public void initDoesNotOverrideCustomDestination() {
	HashMap<String, BindingProperties> properties = new HashMap<>();
	BindingProperties input = new BindingProperties();
	input.setDestination("mydestination");
	properties.put(SpringCloudBusClient.INPUT, input);
	BindingProperties output = new BindingProperties();
	output.setDestination("mydestination");
	properties.put(SpringCloudBusClient.OUTPUT, output);

	setupBusAutoConfig(properties);

	BindingProperties inputProps = properties.get(SpringCloudBusClient.INPUT);
	assertThat(inputProps.getDestination()).isEqualTo("mydestination");

	BindingProperties outputProps = properties.get(SpringCloudBusClient.OUTPUT);
	assertThat(outputProps.getDestination()).isEqualTo("mydestination");
}
 
Example #9
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnonWithBuiltInExchangeCustomPrefix() throws Exception {
	RabbitTestBinder binder = getBinder();
	ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties();
	properties.getExtension().setDeclareExchange(false);
	properties.getExtension().setQueueNameGroupOnly(true);
	properties.getExtension().setAnonymousGroupPrefix("customPrefix.");

	Binding<MessageChannel> consumerBinding = binder.bindConsumer("amq.topic", null,
			createBindableChannel("input", new BindingProperties()), properties);
	Lifecycle endpoint = extractEndpoint(consumerBinding);
	SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint,
			"messageListenerContainer", SimpleMessageListenerContainer.class);
	String queueName = container.getQueueNames()[0];
	assertThat(queueName).startsWith("customPrefix.");
	assertThat(container.isRunning()).isTrue();
	consumerBinding.unbind();
	assertThat(container.isRunning()).isFalse();
}
 
Example #10
Source File: KTableBoundElementFactory.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
@Override
public KTable createInput(String name) {
	BindingProperties bindingProperties = this.bindingServiceProperties.getBindingProperties(name);
	ConsumerProperties consumerProperties = bindingProperties.getConsumer();
	if (consumerProperties == null) {
		consumerProperties = this.bindingServiceProperties.getConsumerProperties(name);
		consumerProperties.setUseNativeDecoding(true);
	}
	else {
		if (!encodingDecodingBindAdviceHandler.isDecodingSettingProvided()) {
			consumerProperties.setUseNativeDecoding(true);
		}
	}
	// Always set multiplex to true in the kafka streams binder
	consumerProperties.setMultiplex(true);

	KTableBoundElementFactory.KTableWrapperHandler wrapper = new KTableBoundElementFactory.KTableWrapperHandler();
	ProxyFactory proxyFactory = new ProxyFactory(
			KTableBoundElementFactory.KTableWrapper.class, KTable.class);
	proxyFactory.addAdvice(wrapper);

	return (KTable) proxyFactory.getProxy();
}
 
Example #11
Source File: KStreamBoundElementFactory.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public KStream createOutput(final String name) {

	BindingProperties bindingProperties = this.bindingServiceProperties.getBindingProperties(name);
	ProducerProperties producerProperties = bindingProperties.getProducer();
	if (producerProperties == null) {
		producerProperties = this.bindingServiceProperties.getProducerProperties(name);
		producerProperties.setUseNativeEncoding(true);
	}
	else {
		if (!encodingDecodingBindAdviceHandler.isEncodingSettingProvided()) {
			producerProperties.setUseNativeEncoding(true);
		}
	}
	return createProxyForKStream(name);
}
 
Example #12
Source File: KStreamBoundElementFactory.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
@Override
public KStream createInput(String name) {
	BindingProperties bindingProperties = this.bindingServiceProperties.getBindingProperties(name);
	ConsumerProperties consumerProperties = bindingProperties.getConsumer();
	if (consumerProperties == null) {
		consumerProperties = this.bindingServiceProperties.getConsumerProperties(name);
		consumerProperties.setUseNativeDecoding(true);
	}
	else {
		if (!encodingDecodingBindAdviceHandler.isDecodingSettingProvided()) {
			consumerProperties.setUseNativeDecoding(true);
		}
	}
	// Always set multiplex to true in the kafka streams binder
	consumerProperties.setMultiplex(true);
	return createProxyForKStream(name);
}
 
Example #13
Source File: KinesisBinderTests.java    From spring-cloud-stream-binder-aws-kinesis with Apache License 2.0 6 votes vote down vote up
private DirectChannel createBindableChannelInternal(String channelName,
		BindingProperties bindingProperties, boolean inputChannel) {

	MessageConverterConfigurer messageConverterConfigurer = getBinder()
			.getApplicationContext().getBean(MessageConverterConfigurer.class);

	DirectChannel channel = new DirectChannel();
	channel.setBeanName(channelName);
	if (inputChannel) {
		messageConverterConfigurer.configureInputChannel(channel, channelName);
	}
	else {
		messageConverterConfigurer.configureOutputChannel(channel, channelName);
	}
	return channel;
}
 
Example #14
Source File: MessageConverterConfigurerTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
public void testConfigureOutputChannelWithBadContentType() {
	BindingServiceProperties props = new BindingServiceProperties();
	BindingProperties bindingProps = new BindingProperties();
	bindingProps.setContentType("application/json");
	props.setBindings(Collections.singletonMap("foo", bindingProps));
	CompositeMessageConverterFactory converterFactory = new CompositeMessageConverterFactory(
			Collections.<MessageConverter>emptyList(), null);
	MessageConverterConfigurer configurer = new MessageConverterConfigurer(props,
			converterFactory.getMessageConverterForAllRegistered());
	QueueChannel out = new QueueChannel();
	configurer.configureOutputChannel(out, "foo");
	out.send(new GenericMessage<Foo>(new Foo(), Collections
			.<String, Object>singletonMap(MessageHeaders.CONTENT_TYPE, "bad/ct")));
	Message<?> received = out.receive(0);
	assertThat(received).isNotNull();
	assertThat(received.getPayload()).isInstanceOf(Foo.class);
}
 
Example #15
Source File: AbstractBinderTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
protected DirectChannel createBindableChannel(String channelName,
		BindingProperties bindingProperties, boolean inputChannel) throws Exception {
	MessageConverterConfigurer messageConverterConfigurer = createConverterConfigurer(
			channelName, bindingProperties);
	DirectChannel channel = new DirectChannel();
	channel.setBeanName(channelName);
	if (inputChannel) {
		messageConverterConfigurer.configureInputChannel(channel, channelName);
	}
	else {
		messageConverterConfigurer.configureOutputChannel(channel, channelName);
	}
	return channel;
}
 
Example #16
Source File: BusAutoConfigurationTests.java    From spring-cloud-bus with Apache License 2.0 5 votes vote down vote up
@Test
public void initSetsBindingDestinationIfNotNullDefault() {
	HashMap<String, BindingProperties> properties = new HashMap<>();
	BindingProperties input = new BindingProperties();
	input.setDestination(SpringCloudBusClient.INPUT);
	properties.put(SpringCloudBusClient.INPUT, input);
	BindingProperties output = new BindingProperties();
	output.setDestination(SpringCloudBusClient.OUTPUT);
	properties.put(SpringCloudBusClient.OUTPUT, output);

	testDestinations(properties);
}
 
Example #17
Source File: SourceBindingWithGlobalPropertiesTest.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testGlobalPropertiesSet() {
	BindingProperties bindingProperties = this.serviceProperties
			.getBindingProperties(Source.OUTPUT);
	Assertions.assertThat(bindingProperties.getContentType())
			.isEqualTo("application/json");
	Assertions.assertThat(bindingProperties.getDestination()).isEqualTo("ticktock");
	Assertions.assertThat(bindingProperties.getProducer().getRequiredGroups())
			.containsExactly("someGroup"); // default propagates to producer
	Assertions.assertThat(bindingProperties.getProducer().getPartitionCount())
			.isEqualTo(4); // validates binding property takes precedence over default
	Assertions.assertThat(bindingProperties.getProducer().getHeaderMode())
			.isEqualTo(HeaderMode.none);
}
 
Example #18
Source File: AbstractBinderTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
protected DefaultPollableMessageSource createBindableMessageSource(String bindingName,
		BindingProperties bindingProperties) throws Exception {
	DefaultPollableMessageSource source = new DefaultPollableMessageSource(
			new CompositeMessageConverterFactory()
					.getMessageConverterForAllRegistered());
	createConverterConfigurer(bindingName, bindingProperties)
			.configurePolledMessageSource(source, bindingName);
	return source;
}
 
Example #19
Source File: BindingServiceTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testExplicitGroup() throws Exception {
	BindingServiceProperties properties = new BindingServiceProperties();
	Map<String, BindingProperties> bindingProperties = new HashMap<>();
	BindingProperties props = new BindingProperties();
	props.setDestination("foo");
	props.setGroup("fooGroup");
	final String inputChannelName = "input";
	bindingProperties.put(inputChannelName, props);
	properties.setBindings(bindingProperties);
	DefaultBinderFactory binderFactory = createMockBinderFactory();
	Binder binder = binderFactory.getBinder("mock", MessageChannel.class);
	BindingService service = new BindingService(properties, binderFactory);
	MessageChannel inputChannel = new DirectChannel();
	Binding<MessageChannel> mockBinding = Mockito.mock(Binding.class);
	when(binder.bindConsumer(eq("foo"), eq("fooGroup"), same(inputChannel),
			any(ConsumerProperties.class))).thenReturn(mockBinding);
	Collection<Binding<MessageChannel>> bindings = service.bindConsumer(inputChannel,
			inputChannelName);
	assertThat(bindings).hasSize(1);
	Binding<MessageChannel> binding = bindings.iterator().next();
	assertThat(binding).isSameAs(mockBinding);

	service.unbindConsumers(inputChannelName);
	verify(binder).bindConsumer(eq("foo"), eq(props.getGroup()), same(inputChannel),
			any(ConsumerProperties.class));
	verify(binding).unbind();
	binderFactory.destroy();
}
 
Example #20
Source File: AbstractBinderTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
protected DirectChannel createBindableChannel(String channelName,
		BindingProperties bindingProperties) throws Exception {
	// The 'channelName.contains("input")' is strictly for convenience to avoid
	// modifications in multiple tests
	return this.createBindableChannel(channelName, bindingProperties,
			channelName.contains("input"));
}
 
Example #21
Source File: BinderAwareChannelResolverTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@Test
public void testProducerAckChannel() throws Exception {
	RabbitTestBinder binder = getBinder();
	CachingConnectionFactory ccf = this.rabbitAvailableRule.getResource();
	ccf.setPublisherReturns(true);
	ccf.setPublisherConfirms(true);
	ccf.resetConnection();
	DirectChannel moduleOutputChannel = createBindableChannel("output",
			new BindingProperties());
	ExtendedProducerProperties<RabbitProducerProperties> producerProps = createProducerProperties();
	producerProps.setErrorChannelEnabled(true);
	producerProps.getExtension().setConfirmAckChannel("acksChannel");
	Binding<MessageChannel> producerBinding = binder.bindProducer("acks.0",
			moduleOutputChannel, producerProps);
	final Message<?> message = MessageBuilder.withPayload("acksMessage".getBytes())
			.build();
	final AtomicReference<Message<?>> confirm = new AtomicReference<>();
	final CountDownLatch confirmLatch = new CountDownLatch(1);
	binder.getApplicationContext().getBean("acksChannel", DirectChannel.class)
			.subscribe(m -> {
				confirm.set(m);
				confirmLatch.countDown();
			});
	moduleOutputChannel.send(message);
	assertThat(confirmLatch.await(10, TimeUnit.SECONDS)).isTrue();
	assertThat(confirm.get().getPayload()).isEqualTo("acksMessage".getBytes());
	producerBinding.unbind();
}
 
Example #23
Source File: MessageConverterConfigurer.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
PartitioningInterceptor(BindingProperties bindingProperties) {
	this.bindingProperties = bindingProperties;
	this.partitionHandler = new PartitionHandler(
			ExpressionUtils.createStandardEvaluationContext(
					MessageConverterConfigurer.this.beanFactory),
			this.bindingProperties.getProducer(), MessageConverterConfigurer.this.beanFactory);
}
 
Example #24
Source File: MessageConverterConfigurer.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
/**
 * Setup data-type and message converters for the given message channel.
 * @param channel message channel to set the data-type and message converters
 * @param channelName the channel name
 * @param inbound inbound (i.e., "input") or outbound channel
 */
private void configureMessageChannel(MessageChannel channel, String channelName,
		boolean inbound) {
	Assert.isAssignable(AbstractMessageChannel.class, channel.getClass());
	AbstractMessageChannel messageChannel = (AbstractMessageChannel) channel;
	BindingProperties bindingProperties = this.bindingServiceProperties
			.getBindingProperties(channelName);
	String contentType = bindingProperties.getContentType();
	ProducerProperties producerProperties = bindingProperties.getProducer();
	boolean partitioned = !inbound && producerProperties != null && producerProperties.isPartitioned();
	boolean functional = streamFunctionProperties != null
			&& (StringUtils.hasText(streamFunctionProperties.getDefinition()) || StringUtils.hasText(bindingServiceProperties.getSource()));

	if (partitioned) {
		if (inbound || !functional) {
			messageChannel.addInterceptor(new PartitioningInterceptor(bindingProperties));
		}
	}

	ConsumerProperties consumerProperties = bindingProperties.getConsumer();
	if (this.isNativeEncodingNotSet(producerProperties, consumerProperties, inbound)) {
		if (inbound) {
			messageChannel.addInterceptor(
					new InboundContentTypeEnhancingInterceptor(contentType));
		}
		else {
			messageChannel.addInterceptor(
					new OutboundContentTypeConvertingInterceptor(contentType,
							this.compositeMessageConverter));
		}
	}
}
 
Example #25
Source File: MessageConverterConfigurer.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Override
public void configurePolledMessageSource(PollableMessageSource binding, String name) {
	BindingProperties bindingProperties = this.bindingServiceProperties
			.getBindingProperties(name);
	String contentType = bindingProperties.getContentType();
	ConsumerProperties consumerProperties = bindingProperties.getConsumer();
	if ((consumerProperties == null || !consumerProperties.isUseNativeDecoding())
			&& binding instanceof DefaultPollableMessageSource) {
		((DefaultPollableMessageSource) binding).addInterceptor(
				new InboundContentTypeEnhancingInterceptor(contentType));
	}
}
 
Example #26
Source File: CompositeMessageConverterFactory.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
/**
 * @param customConverters a list of {@link AbstractMessageConverter}
 * @param objectMapper object mapper for for serialization / deserialization
 */
public CompositeMessageConverterFactory(
		List<? extends MessageConverter> customConverters,
		ObjectMapper objectMapper) {
	this.objectMapper = objectMapper;
	if (!CollectionUtils.isEmpty(customConverters)) {
		this.converters = new ArrayList<>(customConverters);
	}
	else {
		this.converters = new ArrayList<>();
	}
	initDefaultConverters();

	Field headersField = ReflectionUtils.findField(MessageHeaders.class, "headers");
	headersField.setAccessible(true);
	DefaultContentTypeResolver resolver = new DefaultContentTypeResolver() {
		@Override
		@SuppressWarnings("unchecked")
		public MimeType resolve(@Nullable MessageHeaders headers) {
			Object contentType = headers.get(MessageHeaders.CONTENT_TYPE);
			if (contentType instanceof byte[]) {
				contentType = new String((byte[]) contentType, StandardCharsets.UTF_8);
				contentType = ((String) contentType).replace("\"", "");
				Map<String, Object> headersMap = (Map<String, Object>) ReflectionUtils.getField(headersField, headers);
				headersMap.put(MessageHeaders.CONTENT_TYPE, contentType);
			}
			return super.resolve(headers);
		}
	};
	resolver.setDefaultMimeType(BindingProperties.DEFAULT_CONTENT_TYPE);
	this.converters.stream().filter(mc -> mc instanceof AbstractMessageConverter)
			.forEach(mc -> ((AbstractMessageConverter) mc)
					.setContentTypeResolver(resolver));
}
 
Example #27
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadUserDeclarationsFatal() throws Exception {
	RabbitTestBinder binder = getBinder();
	ConfigurableApplicationContext context = binder.getApplicationContext();
	ConfigurableListableBeanFactory bf = context.getBeanFactory();
	bf.registerSingleton("testBadUserDeclarationsFatal",
			new Queue("testBadUserDeclarationsFatal", false));
	bf.registerSingleton("binder", binder);
	RabbitExchangeQueueProvisioner provisioner = TestUtils.getPropertyValue(binder,
			"binder.provisioningProvider", RabbitExchangeQueueProvisioner.class);
	bf.initializeBean(provisioner, "provisioner");
	bf.registerSingleton("provisioner", provisioner);
	context.addApplicationListener(provisioner);
	RabbitAdmin admin = new RabbitAdmin(rabbitAvailableRule.getResource());
	admin.declareQueue(new Queue("testBadUserDeclarationsFatal"));
	// reset the connection and configure the "user" admin to auto declare queues...
	rabbitAvailableRule.getResource().resetConnection();
	bf.initializeBean(admin, "rabbitAdmin");
	bf.registerSingleton("rabbitAdmin", admin);
	admin.afterPropertiesSet();
	// the mis-configured queue should be fatal
	Binding<?> binding = null;
	try {
		binding = binder.bindConsumer("input", "baddecls",
				this.createBindableChannel("input", new BindingProperties()),
				createConsumerProperties());
		fail("Expected exception");
	}
	catch (BinderException e) {
		assertThat(e.getCause()).isInstanceOf(AmqpIOException.class);
	}
	finally {
		admin.deleteQueue("testBadUserDeclarationsFatal");
		if (binding != null) {
			binding.unbind();
		}
	}
}
 
Example #28
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonDurablePubSubWithAutoBindDLQ() throws Exception {
	RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());

	RabbitTestBinder binder = getBinder();
	ExtendedConsumerProperties<RabbitConsumerProperties> consumerProperties = createConsumerProperties();
	consumerProperties.getExtension().setPrefix(TEST_PREFIX);
	consumerProperties.getExtension().setAutoBindDlq(true);
	consumerProperties.getExtension().setDurableSubscription(false);
	consumerProperties.setMaxAttempts(1); // disable retry
	BindingProperties bindingProperties = createConsumerBindingProperties(
			consumerProperties);
	DirectChannel moduleInputChannel = createBindableChannel("input",
			bindingProperties);
	moduleInputChannel.setBeanName("nondurabletest");
	moduleInputChannel.subscribe(new MessageHandler() {

		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			throw new RuntimeException("foo");
		}

	});
	Binding<MessageChannel> consumerBinding = binder.bindConsumer("nondurabletest.0",
			"tgroup", moduleInputChannel, consumerProperties);

	consumerBinding.unbind();
	assertThat(admin.getQueueProperties(TEST_PREFIX + "nondurabletest.0.dlq"))
			.isNull();
}
 
Example #29
Source File: RabbitBinderTests.java    From spring-cloud-stream-binder-rabbit with Apache License 2.0 5 votes vote down vote up
@Test
public void testConsumerPropertiesWithUserInfrastructureNoBind() throws Exception {
	RabbitAdmin admin = new RabbitAdmin(this.rabbitAvailableRule.getResource());
	Queue queue = new Queue("propsUser1.infra");
	admin.declareQueue(queue);
	DirectExchange exchange = new DirectExchange("propsUser1");
	admin.declareExchange(exchange);
	admin.declareBinding(BindingBuilder.bind(queue).to(exchange).with("foo"));

	RabbitTestBinder binder = getBinder();
	ExtendedConsumerProperties<RabbitConsumerProperties> properties = createConsumerProperties();
	properties.getExtension().setDeclareExchange(false);
	properties.getExtension().setBindQueue(false);

	Binding<MessageChannel> consumerBinding = binder.bindConsumer("propsUser1",
			"infra", createBindableChannel("input", new BindingProperties()),
			properties);
	Lifecycle endpoint = extractEndpoint(consumerBinding);
	SimpleMessageListenerContainer container = TestUtils.getPropertyValue(endpoint,
			"messageListenerContainer", SimpleMessageListenerContainer.class);
	assertThat(TestUtils.getPropertyValue(container, "missingQueuesFatal",
			Boolean.class)).isFalse();
	assertThat(container.isRunning()).isTrue();
	consumerBinding.unbind();
	assertThat(container.isRunning()).isFalse();
	Client client = new Client("http://guest:guest@localhost:15672/api/");
	List<?> bindings = client.getBindingsBySource("/", exchange.getName());
	assertThat(bindings.size()).isEqualTo(1);
}
 
Example #30
Source File: AbstractBinderTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
private MessageConverterConfigurer createConverterConfigurer(String channelName,
		BindingProperties bindingProperties) throws Exception {
	BindingServiceProperties bindingServiceProperties = new BindingServiceProperties();
	bindingServiceProperties.getBindings().put(channelName, bindingProperties);
	bindingServiceProperties.setApplicationContext(applicationContext);
	bindingServiceProperties.setConversionService(new DefaultConversionService());
	bindingServiceProperties.afterPropertiesSet();
	MessageConverterConfigurer messageConverterConfigurer = new MessageConverterConfigurer(
			bindingServiceProperties,
			new CompositeMessageConverterFactory(null, null).getMessageConverterForAllRegistered());
	messageConverterConfigurer.setBeanFactory(applicationContext.getBeanFactory());
	return messageConverterConfigurer;
}