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

The following examples show how to use org.springframework.cloud.stream.config.BindingProperties. 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
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 2
@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 3
@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 4
@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 5
@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 6
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 7
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 8
@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
@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 10
@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 11
Source Project: spring-cloud-stream   Source File: FunctionConfiguration.java    License: 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 12
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 13
Source Project: spring-cloud-stream   Source File: BindingServiceTests.java    License: 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 14
Source Project: spring-cloud-stream   Source File: BindingServiceTests.java    License: 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 15
@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 16
private KStream createProxyForKStream(String name) {
	KStreamWrapperHandler wrapper = new KStreamWrapperHandler();
	ProxyFactory proxyFactory = new ProxyFactory(KStreamWrapper.class, KStream.class);
	proxyFactory.addAdvice(wrapper);

	KStream proxy = (KStream) proxyFactory.getProxy();

	// Add the binding properties to the catalogue for later retrieval during further
	// binding steps downstream.
	BindingProperties bindingProperties = this.bindingServiceProperties
			.getBindingProperties(name);
	this.kafkaStreamsBindingInformationCatalogue.registerBindingProperties(proxy,
			bindingProperties);
	return proxy;
}
 
Example 17
/**
 * Is native decoding is enabled on this {@link KStream}.
 * @param bindingTarget binding target for KStream
 * @return true if native decoding is enabled, fasle otherwise.
 */
boolean isUseNativeDecoding(KStream<?, ?> bindingTarget) {
	BindingProperties bindingProperties = this.bindingProperties.get(bindingTarget);
	if (bindingProperties.getConsumer() == null) {
		bindingProperties.setConsumer(new ConsumerProperties());
	}
	return bindingProperties.getConsumer().isUseNativeDecoding();
}
 
Example 18
protected Serde<?> getValueSerde(String inboundName, KafkaStreamsConsumerProperties kafkaStreamsConsumerProperties, ResolvableType resolvableType) {
	if (bindingServiceProperties.getConsumerProperties(inboundName).isUseNativeDecoding()) {
		BindingProperties bindingProperties = this.bindingServiceProperties
				.getBindingProperties(inboundName);
		return this.keyValueSerdeResolver.getInboundValueSerde(
				bindingProperties.getConsumer(), kafkaStreamsConsumerProperties, resolvableType);
	}
	else {
		return Serdes.ByteArray();
	}
}
 
Example 19
protected KStream<?, ?> getKStream(String inboundName, BindingProperties bindingProperties, KafkaStreamsConsumerProperties kafkaStreamsConsumerProperties,
		StreamsBuilder streamsBuilder, Serde<?> keySerde, Serde<?> valueSerde, Topology.AutoOffsetReset autoOffsetReset, boolean firstBuild) {
	if (firstBuild) {
		addStateStoreBeans(streamsBuilder);
	}

	KStream<?, ?> stream;
	if (this.kafkaStreamsExtendedBindingProperties
			.getExtendedConsumerProperties(inboundName).isDestinationIsPattern()) {
		final Pattern pattern = Pattern.compile(this.bindingServiceProperties.getBindingDestination(inboundName));
		stream = streamsBuilder.stream(pattern);
	}
	else {
		String[] bindingTargets = StringUtils.commaDelimitedListToStringArray(
				this.bindingServiceProperties.getBindingDestination(inboundName));
		final Consumed<?, ?> consumed = getConsumed(kafkaStreamsConsumerProperties, keySerde, valueSerde, autoOffsetReset);
		stream = streamsBuilder.stream(Arrays.asList(bindingTargets),
				consumed);
	}
	final boolean nativeDecoding = this.bindingServiceProperties
			.getConsumerProperties(inboundName).isUseNativeDecoding();
	if (nativeDecoding) {
		LOG.info("Native decoding is enabled for " + inboundName
				+ ". Inbound deserialization done at the broker.");
	}
	else {
		LOG.info("Native decoding is disabled for " + inboundName
				+ ". Inbound message conversion done by Spring Cloud Stream.");
	}

	return getkStream(bindingProperties, stream, nativeDecoding);
}
 
Example 20
private BusProperties setupBusAutoConfig(
		HashMap<String, BindingProperties> properties) {
	BindingServiceProperties serviceProperties = mock(BindingServiceProperties.class);
	when(serviceProperties.getBindings()).thenReturn(properties);

	BusProperties bus = new BusProperties();
	BusAutoConfiguration configuration = new BusAutoConfiguration(
			mock(ServiceMatcher.class), serviceProperties, bus);
	configuration.init();
	return bus;
}
 
Example 21
Source Project: spring-cloud-bus   Source File: BusAutoConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
	BindingProperties inputBinding = this.bindings.getBindings()
			.get(SpringCloudBusClient.INPUT);
	if (inputBinding == null) {
		this.bindings.getBindings().put(SpringCloudBusClient.INPUT,
				new BindingProperties());
	}
	BindingProperties input = this.bindings.getBindings()
			.get(SpringCloudBusClient.INPUT);
	if (input.getDestination() == null
			|| input.getDestination().equals(SpringCloudBusClient.INPUT)) {
		input.setDestination(this.bus.getDestination());
	}
	BindingProperties outputBinding = this.bindings.getBindings()
			.get(SpringCloudBusClient.OUTPUT);
	if (outputBinding == null) {
		this.bindings.getBindings().put(SpringCloudBusClient.OUTPUT,
				new BindingProperties());
	}
	BindingProperties output = this.bindings.getBindings()
			.get(SpringCloudBusClient.OUTPUT);
	if (output.getDestination() == null
			|| output.getDestination().equals(SpringCloudBusClient.OUTPUT)) {
		output.setDestination(this.bus.getDestination());
	}
}
 
Example 22
@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
@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:[email protected]:15672/api/");
	List<?> bindings = client.getBindingsBySource("/", exchange.getName());
	assertThat(bindings.size()).isEqualTo(1);
}
 
Example 24
@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 25
@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 26
/**
 * @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
@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 28
/**
 * 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 29
PartitioningInterceptor(BindingProperties bindingProperties) {
	this.bindingProperties = bindingProperties;
	this.partitionHandler = new PartitionHandler(
			ExpressionUtils.createStandardEvaluationContext(
					MessageConverterConfigurer.this.beanFactory),
			this.bindingProperties.getProducer(), MessageConverterConfigurer.this.beanFactory);
}
 
Example 30
@Test
public void initSetsBindingDestinationIfNullDefault() {
	HashMap<String, BindingProperties> properties = new HashMap<>();
	properties.put(SpringCloudBusClient.INPUT, new BindingProperties());
	properties.put(SpringCloudBusClient.OUTPUT, new BindingProperties());

	testDestinations(properties);
}