Java Code Examples for org.springframework.cloud.stream.messaging.Processor

The following examples show how to use org.springframework.cloud.stream.messaging.Processor. 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
@Test
@SuppressWarnings("unchecked")
public void testReturnNoConversion() throws Exception {
	ConfigurableApplicationContext context = SpringApplication.run(
			this.configClass, "--server.port=0", "--spring.jmx.enabled=false");
	MessageCollector collector = context.getBean(MessageCollector.class);
	Processor processor = context.getBean(Processor.class);
	String id = UUID.randomUUID().toString();
	processor.input()
			.send(MessageBuilder.withPayload("{\"foo\":\"barbar" + id + "\"}")
					.setHeader("contentType", "application/json").build());
	TestPojoWithMimeType testPojoWithMimeType = context
			.getBean(TestPojoWithMimeType.class);
	Assertions.assertThat(testPojoWithMimeType.receivedPojos).hasSize(1);
	Assertions.assertThat(testPojoWithMimeType.receivedPojos.get(0))
			.hasFieldOrPropertyWithValue("foo", "barbar" + id);
	Message<String> message = (Message<String>) collector
			.forChannel(processor.output()).poll(1, TimeUnit.SECONDS);
	assertThat(message).isNotNull();
	StreamListenerTestUtils.BarPojo barPojo = this.mapper.readValue(
			message.getPayload(), StreamListenerTestUtils.BarPojo.class);
	assertThat(barPojo.getBar()).isEqualTo("barbar" + id);
	assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE,
			MimeType.class) != null);
	context.close();
}
 
Example 2
@SuppressWarnings("unchecked")
@Test
public void testMethodHeadersNotPropagatged() throws Exception {
	ConfigurableApplicationContext context = SpringApplication.run(
			TestMethodHeadersNotPropagated.class, "--server.port=0",
			"--spring.jmx.enabled=false",
			"--spring.cloud.stream.bindings.input.contentType=text/plain",
			"--spring.cloud.stream.bindings.output.contentType=text/plain");
	Processor processor = context.getBean(Processor.class);
	final String testMessage = "testing";
	processor.input().send(
			MessageBuilder.withPayload(testMessage).setHeader("foo", "bar").build());
	MessageCollector messageCollector = context.getBean(MessageCollector.class);
	Message<String> result = (Message<String>) messageCollector
			.forChannel(processor.output()).poll(1000, TimeUnit.MILLISECONDS);
	assertThat(result).isNotNull();
	assertThat(result.getPayload()).isEqualTo(testMessage.toUpperCase());
	assertThat(result.getHeaders().get("foo")).isNull();
	context.close();
}
 
Example 3
@SuppressWarnings("unchecked")
@Test
public void testMethodWithObjectAsMethodArgument() throws Exception {
	ConfigurableApplicationContext context = SpringApplication.run(
			TestMethodWithObjectAsMethodArgument.class, "--server.port=0",
			"--spring.jmx.enabled=false",
			"--spring.cloud.stream.bindings.input.contentType=text/plain",
			"--spring.cloud.stream.bindings.output.contentType=text/plain");
	Processor processor = context.getBean(Processor.class);
	final String testMessage = "testing";
	processor.input().send(MessageBuilder.withPayload(testMessage).build());
	MessageCollector messageCollector = context.getBean(MessageCollector.class);
	Message<String> result = (Message<String>) messageCollector
			.forChannel(processor.output()).poll(1000, TimeUnit.MILLISECONDS);
	assertThat(result).isNotNull();
	assertThat(result.getPayload()).isEqualTo(testMessage.toUpperCase());
	context.close();
}
 
Example 4
@Bean
@Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public MessageProcessor<?> transformer() {
	String language = this.properties.getLanguage();
	String script = this.properties.getScript();
	logger.info(String.format("Input script is '%s', language is '%s'", script, language));
	Resource scriptResource = new ByteArrayResource(decodeScript(script).getBytes()) {

		// TODO until INT-3976
		@Override
		public String getFilename() {
			// Only the groovy script processor enforces this requirement for a name
			return "StaticScript";
		}

	};
	return Scripts.script(scriptResource)
			.lang(language)
			.variableGenerator(this.scriptVariableGenerator)
			.get();
}
 
Example 5
@StreamListener
public void receive(@Input(Processor.INPUT) SubscribableChannel input,
		@Output(Processor.OUTPUT) final MessageChannel output1,
		@Output(StreamListenerTestUtils.FooOutboundChannel1.OUTPUT) final MessageChannel output2) {
	input.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			if (message.getHeaders().get("output").equals("output1")) {
				output1.send(org.springframework.messaging.support.MessageBuilder
						.withPayload(
								message.getPayload().toString().toUpperCase())
						.build());
			}
			else if (message.getHeaders().get("output").equals("output2")) {
				output2.send(org.springframework.messaging.support.MessageBuilder
						.withPayload(
								message.getPayload().toString().toLowerCase())
						.build());
			}
		}
	});
}
 
Example 6
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testInputOutputBindingOrder() {
	ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(
			TestSource.class).web(WebApplicationType.NONE).run(
					"--spring.cloud.stream.defaultBinder=mock",
					"--spring.jmx.enabled=false");
	Binder binder = applicationContext.getBean(BinderFactory.class).getBinder(null,
			MessageChannel.class);
	Processor processor = applicationContext.getBean(Processor.class);
	// input is bound after the context has been started
	verify(binder).bindConsumer(eq("input"), isNull(), eq(processor.input()),
			Mockito.any());
	SomeLifecycle someLifecycle = applicationContext.getBean(SomeLifecycle.class);
	assertThat(someLifecycle.isRunning());
	applicationContext.close();
	assertThat(someLifecycle.isRunning()).isFalse();
	applicationContext.close();
}
 
Example 7
@SuppressWarnings("unchecked")
@Test
/**
 * @since 2.0 : This test is an example of the new behavior of 2.0 when it comes to
 * contentType handling. The default contentType being JSON in order to be able to
 * check a message without quotes the user needs to set the input/output contentType
 * accordingly Also, received messages are always of Message<byte[]> now.
 */
public void testMethodHeadersPropagatged() throws Exception {
	ConfigurableApplicationContext context = SpringApplication.run(
			TestMethodHeadersPropagated.class, "--server.port=0",
			"--spring.jmx.enabled=false",
			"--spring.cloud.stream.bindings.input.contentType=text/plain",
			"--spring.cloud.stream.bindings.output.contentType=text/plain");
	Processor processor = context.getBean(Processor.class);
	final String testMessage = "testing";
	processor.input().send(
			MessageBuilder.withPayload(testMessage).setHeader("foo", "bar").build());
	MessageCollector messageCollector = context.getBean(MessageCollector.class);
	Message<String> result = (Message<String>) messageCollector
			.forChannel(processor.output()).poll(1000, TimeUnit.MILLISECONDS);
	assertThat(result).isNotNull();
	assertThat(result.getPayload()).isEqualTo(testMessage.toUpperCase());
	assertThat(result.getHeaders().get("foo")).isEqualTo("bar");
	context.close();
}
 
Example 8
@Test
@SuppressWarnings("unchecked")
public void testMessageArgument() throws Exception {
	ConfigurableApplicationContext context = SpringApplication.run(this.configClass,
			"--server.port=0",
			"--spring.cloud.stream.bindings.output.contentType=text/plain",
			"--spring.jmx.enabled=false");
	MessageCollector collector = context.getBean(MessageCollector.class);
	Processor processor = context.getBean(Processor.class);
	String id = UUID.randomUUID().toString();
	processor.input().send(MessageBuilder.withPayload("barbar" + id)
			.setHeader("contentType", "text/plain").build());
	TestPojoWithMessageArgument testPojoWithMessageArgument = context
			.getBean(TestPojoWithMessageArgument.class);
	assertThat(testPojoWithMessageArgument.receivedMessages).hasSize(1);
	assertThat(testPojoWithMessageArgument.receivedMessages.get(0).getPayload())
			.isEqualTo("barbar" + id);
	Message<String> message = (Message<String>) collector
			.forChannel(processor.output()).poll(1, TimeUnit.SECONDS);
	assertThat(message).isNotNull();
	assertThat(message.getPayload()).contains("barbar" + id);
	context.close();
}
 
Example 9
@Test
@SuppressWarnings("unchecked")
public void testReturn() throws Exception {
	ConfigurableApplicationContext context = SpringApplication.run(this.configClass,
			"--server.port=0", "--spring.jmx.enabled=false");
	MessageCollector collector = context.getBean(MessageCollector.class);
	Processor processor = context.getBean(Processor.class);
	String id = UUID.randomUUID().toString();
	processor.input()
			.send(MessageBuilder.withPayload("{\"foo\":\"barbar" + id + "\"}")
					.setHeader("contentType", "application/json").build());
	Message<String> message = (Message<String>) collector
			.forChannel(processor.output()).poll(1, TimeUnit.SECONDS);
	TestStringProcessor testStringProcessor = context
			.getBean(TestStringProcessor.class);
	Assertions.assertThat(testStringProcessor.receivedPojos).hasSize(1);
	Assertions.assertThat(testStringProcessor.receivedPojos.get(0))
			.hasFieldOrPropertyWithValue("foo", "barbar" + id);
	assertThat(message).isNotNull();
	assertThat(message.getPayload()).contains("barbar" + id);
	context.close();
}
 
Example 10
@Test
@SuppressWarnings("unchecked")
public void testReturnMessage() throws Exception {
	ConfigurableApplicationContext context = SpringApplication.run(this.configClass,
			"--server.port=0", "--spring.jmx.enabled=false");
	MessageCollector collector = context.getBean(MessageCollector.class);
	Processor processor = context.getBean(Processor.class);
	String id = UUID.randomUUID().toString();
	processor.input()
			.send(MessageBuilder.withPayload("{\"foo\":\"barbar" + id + "\"}")
					.setHeader("contentType", "application/json").build());
	TestPojoWithMessageReturn testPojoWithMessageReturn = context
			.getBean(TestPojoWithMessageReturn.class);
	Assertions.assertThat(testPojoWithMessageReturn.receivedPojos).hasSize(1);
	Assertions.assertThat(testPojoWithMessageReturn.receivedPojos.get(0))
			.hasFieldOrPropertyWithValue("foo", "barbar" + id);
	Message<String> message = (Message<String>) collector
			.forChannel(processor.output()).poll(1, TimeUnit.SECONDS);
	assertThat(message).isNotNull();
	assertThat(message.getPayload()).contains("barbar" + id);
	context.close();
}
 
Example 11
@StreamListener
@Output(StreamListenerTestUtils.FooOutboundChannel1.OUTPUT)
public void receive(@Input(Processor.INPUT) SubscribableChannel input,
		@Output(Processor.OUTPUT) final MessageChannel output1) {
	input.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			output1.send(org.springframework.messaging.support.MessageBuilder
					.withPayload(message.getPayload().toString().toUpperCase())
					.build());
		}
	});
}
 
Example 12
@StreamListener(Processor.INPUT)
@SendTo(Processor.OUTPUT)
public StreamListenerTestUtils.BarPojo receive(
		StreamListenerTestUtils.FooPojo fooPojo) {
	this.receivedPojos.add(fooPojo);
	StreamListenerTestUtils.BarPojo barPojo = new StreamListenerTestUtils.BarPojo();
	barPojo.setBar(fooPojo.getFoo());
	return barPojo;
}
 
Example 13
@StreamListener
@Output(Processor.OUTPUT)
public Flux<Comment> save(@Input(Processor.INPUT) Flux<Comment> newComment) {
	return repository
		.saveAll(newComment)
		.map(comment -> {
			meterRegistry
				.counter("comments.consumed", "imageId", comment.getImageId())
				.increment();
			return comment;
		});
}
 
Example 14
@StreamListener
public void receive(@Output(Processor.OUTPUT) final MessageChannel output,
		@Input("input") SubscribableChannel input) {
	input.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			output.send(MessageBuilder
					.withPayload(message.getPayload().toString().toUpperCase())
					.build());
		}
	});
}
 
Example 15
@StreamListener
@Output(Processor.OUTPUT)
public Flux<Comment> save(@Input(Processor.INPUT) Flux<Comment> newComment) {
	return repository
		.saveAll(newComment)
		.map(comment -> {
			meterRegistry
				.counter("comments.consumed", "imageId", comment.getImageId())
				.increment();
			return comment;
		});
}
 
Example 16
@StreamListener
@Output(Processor.OUTPUT)
public Flux<Comment> save(@Input(Processor.INPUT) Flux<Comment> newComment) {
	return repository
		.saveAll(newComment)
		.map(comment -> {
			meterRegistry
				.counter("comments.consumed", "imageId", comment.getImageId())
				.increment();
			return comment;
		});
}
 
Example 17
@StreamListener
@Output(Processor.OUTPUT)
public Flux<Void> save(@Input(Processor.INPUT) Flux<Comment> newComment) {
	return repository
		.saveAll(newComment)
		.flatMap(comment -> {
			meterRegistry
				.counter("comments.consumed", "imageId", comment.getImageId())
				.increment();
			return Mono.empty();
		});
}
 
Example 18
@SuppressWarnings("unchecked")
private void sendMessageAndValidate(ConfigurableApplicationContext context)
		throws InterruptedException {
	Processor processor = context.getBean(Processor.class);
	processor.input().send(MessageBuilder.withPayload("hello")
			.setHeader("contentType", "text/plain").build());
	MessageCollector messageCollector = context.getBean(MessageCollector.class);
	Message<String> result = (Message<String>) messageCollector
			.forChannel(processor.output()).poll(1000, TimeUnit.MILLISECONDS);
	assertThat(result).isNotNull();
	assertThat(result.getPayload()).isEqualTo("HELLO");
	context.close();
}
 
Example 19
@StreamListener
@Output(Processor.OUTPUT)
public Flux<Void> save(@Input(Processor.INPUT) Flux<Comment> newComment) {
	return repository
		.saveAll(newComment)
		.flatMap(comment -> {
			meterRegistry
				.counter("comments.consumed", "imageId", comment.getImageId())
				.increment();
			return Mono.empty();
		});
}
 
Example 20
@ServiceActivator(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public Message<?> evaluate(Message<?> input) {

	Map<String, Object> processorContext = new ConcurrentHashMap<>();

	Map<String, Object> inputData = tensorflowInputConverter.convert(input, processorContext);

	Tensor outputTensor = tensorFlowService.evaluate(
			inputData, properties.getOutputName(), properties.getOutputIndex());

	Object outputData = tensorflowOutputConverter.convert(outputTensor, processorContext);

	if (properties.isSaveOutputInHeader()) {
		// Add the result to the message header
		return MessageBuilder
				.withPayload(input.getPayload())
				.copyHeadersIfAbsent(input.getHeaders())
				.setHeaderIfAbsent(TF_OUTPUT_HEADER, outputData)
				.build();
	}

	// Add the outputData as part of the message payload
	Message<?> outputMessage = MessageBuilder
			.withPayload(outputData)
			.copyHeadersIfAbsent(input.getHeaders())
			.build();

	return outputMessage;
}
 
Example 21
@Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public String transform(Message<String> message) {
	String payload = message.getPayload();
	if (!"junk".equals(payload)) {
		return payload.toUpperCase();
	}
	else {
		throw new IllegalStateException("Invalid payload: " + payload);
	}
}
 
Example 22
@StreamListener(Processor.INPUT)
@Output(Processor.OUTPUT)
public StreamListenerTestUtils.BarPojo receive(
		StreamListenerTestUtils.FooPojo fooMessage) {
	this.receivedPojos.add(fooMessage);
	StreamListenerTestUtils.BarPojo barPojo = new StreamListenerTestUtils.BarPojo();
	barPojo.setBar(fooMessage.getFoo());
	return barPojo;
}
 
Example 23
@Bean
public MessageProducer kinesisMessageDriverChannelAdapter() {
	KinesisMessageDrivenChannelAdapter kinesisMessageDrivenChannelAdapter =
			new KinesisMessageDrivenChannelAdapter(amazonKinesis(), Processor.OUTPUT);
	kinesisMessageDrivenChannelAdapter.setOutputChannel(fromProcessorChannel());
	kinesisMessageDrivenChannelAdapter.setConverter(null);
	kinesisMessageDrivenChannelAdapter.setBindSourceRecord(true);

	DirectFieldAccessor dfa = new DirectFieldAccessor(kinesisMessageDrivenChannelAdapter);
	dfa.setPropertyValue("describeStreamBackoff", 10);
	dfa.setPropertyValue("consumerBackoff", 10);
	dfa.setPropertyValue("idleBetweenPolls", 1);

	return kinesisMessageDrivenChannelAdapter;
}
 
Example 24
Source Project: spring-cloud-task   Source File: TaskProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public Object setupRequest(String message) {
	Map<String, String> properties = new HashMap<>();
	if (StringUtils.hasText(this.processorProperties.getDataSourceUrl())) {
		properties
			.put("spring_datasource_url", this.processorProperties
				.getDataSourceUrl());
	}
	if (StringUtils
		.hasText(this.processorProperties.getDataSourceDriverClassName())) {
		properties.put("spring_datasource_driverClassName", this.processorProperties
			.getDataSourceDriverClassName());
	}
	if (StringUtils.hasText(this.processorProperties.getDataSourceUserName())) {
		properties.put("spring_datasource_username", this.processorProperties
			.getDataSourceUserName());
	}
	if (StringUtils.hasText(this.processorProperties.getDataSourcePassword())) {
		properties.put("spring_datasource_password", this.processorProperties
			.getDataSourcePassword());
	}
	properties.put("payload", message);

	TaskLaunchRequest request = new TaskLaunchRequest(
		this.processorProperties.getUri(), null, properties, null,
		this.processorProperties.getApplicationName());

	return new GenericMessage<>(request);
}
 
Example 25
@StreamListener
public void receive(@Input(Processor.INPUT) SubscribableChannel input,
		@Output(Processor.OUTPUT) final MessageChannel output, String someArg) {
	input.subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			output.send(MessageBuilder
					.withPayload(message.getPayload().toString().toUpperCase())
					.build());
		}
	});
}
 
Example 26
@StreamListener(Processor.INPUT)
public void listenIn(String in) {
	this.output.send(new GenericMessage<>(in.toUpperCase()));
	if (in.equals("two")) {
		throw new RuntimeException("fail");
	}
}
 
Example 27
@StreamListener(Processor.INPUT)
@SendTo(Processor.OUTPUT)
public Bar receive(Bar bar) {
	logger.info("******************\nAt the transformer\n******************");
	logger.info("Received value "+ bar.getValue() + " of type " + bar.getClass());
	logger.info("Transforming the value to " + TRANSFORMATION_VALUE + " and with the type " + bar.getClass());
	bar.setValue(TRANSFORMATION_VALUE);
	return bar;
}
 
Example 28
@Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public Object setupRequest(String message) {
	Map<String, String> properties = new HashMap<String, String>();
	Map<String, String> deploymentProperties = null;
	List<String> commandLineArgs = null;

	if (StringUtils.hasText(processorProperties.getDataSourceUrl())) {
		properties.put("spring_datasource_url", processorProperties.getDataSourceUrl());
	}
	if (StringUtils.hasText(processorProperties.getDataSourceDriverClassName())) {
		properties.put("spring_datasource_driverClassName", processorProperties.getDataSourceDriverClassName());
	}
	if (StringUtils.hasText(processorProperties.getDataSourceUserName())) {
		properties.put("spring_datasource_username", processorProperties.getDataSourceUserName());
	}
	if (StringUtils.hasText(processorProperties.getDataSourcePassword())) {
		properties.put("spring_datasource_password", processorProperties.getDataSourcePassword());
	}
	if (StringUtils.hasLength(processorProperties.getDeploymentProperties())) {
		deploymentProperties = parse(processorProperties.getDeploymentProperties());
	}
	if (StringUtils.hasLength(processorProperties.getCommandLineArguments())) {
		commandLineArgs = parseParams(processorProperties.getCommandLineArguments());
	}

	TaskLaunchRequest request = new TaskLaunchRequest(
			processorProperties.getUri(), commandLineArgs, properties,
			deploymentProperties);

	return request;
}
 
Example 29
@StreamListener(Processor.INPUT)
@SendTo(Processor.OUTPUT)
public StreamListenerTestUtils.BarPojo receive(
		StreamListenerTestUtils.FooPojo fooMessage) {
	this.receivedPojos.add(fooMessage);
	StreamListenerTestUtils.BarPojo barPojo = new StreamListenerTestUtils.BarPojo();
	barPojo.setBar(fooMessage.getFoo());
	return barPojo;
}
 
Example 30
@Test
public void testMethodWithMultipleInputParameters() throws Exception {
	ConfigurableApplicationContext context = SpringApplication.run(
			TestMethodWithMultipleInputParameters.class, "--server.port=0",
			"--spring.jmx.enabled=false");
	Processor processor = context.getBean(Processor.class);
	StreamListenerTestUtils.FooInboundChannel1 inboundChannel2 = context
			.getBean(StreamListenerTestUtils.FooInboundChannel1.class);
	final CountDownLatch latch = new CountDownLatch(2);
	((SubscribableChannel) processor.output()).subscribe(new MessageHandler() {
		@Override
		public void handleMessage(Message<?> message) throws MessagingException {
			Assert.isTrue(
					message.getPayload().equals("footesting")
							|| message.getPayload().equals("BARTESTING"),
					"Assert failed");
			latch.countDown();
		}
	});
	processor.input().send(MessageBuilder.withPayload("{\"foo\":\"fooTESTing\"}")
			.setHeader("contentType", "application/json").build());
	inboundChannel2.input()
			.send(MessageBuilder.withPayload("{\"bar\":\"bartestING\"}")
					.setHeader("contentType", "application/json").build());
	assertThat(latch.await(1, TimeUnit.SECONDS));
	context.close();
}