org.springframework.integration.support.MessageBuilder Java Examples

The following examples show how to use org.springframework.integration.support.MessageBuilder. 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: JsonMessageMarshaller.java    From spring-integration-aws with MIT License 7 votes vote down vote up
private void copyHeaders(MessageBuilder<Object> builder, JSONObject headers)
		throws JSONException, ClassNotFoundException, IOException {

	Map<String, Object> map = new HashMap<String, Object>();
	String[] fieldNames = JSONObject.getNames(headers);
	if (fieldNames == null) {
		return;
	}
	for (String fieldName : fieldNames) {
		JSONObject headerObject = new JSONObject(
				headers.getString(fieldName));
		Class<?> clazz = Class.forName(headerObject
				.getString(HEADER_CLAZZ_KEY));
		if (String.class.equals(clazz)) {
			map.put(fieldName, headerObject.getString(HEADER_VALUE_KEY));
		} else if (Number.class.isAssignableFrom(clazz)) {
			map.put(fieldName, headerObject.get(HEADER_VALUE_KEY));
		} else {
			String source = headerObject.getString(HEADER_VALUE_KEY);
			map.put(fieldName, getObjectMapper().readValue(source, clazz));
		}
	}
	builder.copyHeaders(map);
}
 
Example #2
Source File: RoutingFunctionTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testExplicitRoutingFunctionBindingWithCompositionAndRoutingEnabledImplicitlyAndMoreComposition() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					RoutingFunctionConfiguration.class))
							.web(WebApplicationType.NONE)
							.run("--spring.jmx.enabled=false",
									"--spring.cloud.stream.function.definition=enrich|" + RoutingFunction.FUNCTION_NAME + "|reverse")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context
				.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder
				.withPayload("Hello".getBytes()).build();
		inputDestination.send(inputMessage);

		Message<byte[]> outputMessage = outputDestination.receive();
		assertThat(outputMessage.getPayload()).isEqualTo("OLLEH".getBytes());
	}
}
 
Example #3
Source File: BookingMessageEventHandler.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 6 votes vote down vote up
/**
 *
 * @param booking
 * @throws Exception
 */
public void produceBookingOrderEvent(Booking booking) throws Exception {
  final BookingOrder.Builder boBuilder = BookingOrder.newBuilder();
  boBuilder.setId(booking.getId());
  boBuilder.setName(booking.getName());
  boBuilder.setRestaurantId(booking.getRestaurantId());
  boBuilder.setTableId(booking.getTableId());
  boBuilder.setUserId(booking.getUserId());
  boBuilder.setDate(booking.getDate().toString());
  boBuilder.setTime(booking.getTime().toString());
  BookingOrder bo = boBuilder.build();
  final Message<BookingOrder> message = MessageBuilder.withPayload(bo)
      .setHeader("contentType", "application/*+avro").build();
  boolean isSent = bookingMessageChannels.send(message);
  if(isSent) LOG.info("new bookingOrder is published.");
}
 
Example #4
Source File: DefaultOutputMessageBuilder.java    From tensorflow with Apache License 2.0 6 votes vote down vote up
@Override
public MessageBuilder<?> createOutputMessageBuilder(Message<?> inputMessage, Object computedScore) {
	switch (this.outputMode) {

	case header:
		MessageBuilder<?> builder = MessageBuilder
				.withPayload(inputMessage.getPayload())
				.setHeader(this.outputName, computedScore);
		if (inputMessage.getHeaders().get(MessageHeaders.CONTENT_TYPE) != null) {
			builder.setHeader(MessageHeaders.CONTENT_TYPE, inputMessage.getHeaders().get(MessageHeaders.CONTENT_TYPE));
		}
		return builder;

	default: // payload mode
		return MessageBuilder
				.withPayload(computedScore)
				.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON_VALUE);
	}

}
 
Example #5
Source File: StreamListenerMessageArgumentTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: RoutingFunctionTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultRoutingFunctionBindingFlux() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					RoutingFunctionConfiguration.class))
							.web(WebApplicationType.NONE)
							.run("--spring.jmx.enabled=false",
									"--spring.cloud.stream.function.routing.enabled=true")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder
				.withPayload("Hello".getBytes())
				.setHeader("spring.cloud.function.definition", "echoFlux")
				.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN)
				.build();
		inputDestination.send(inputMessage);

		TestChannelBinder binder = context.getBean(TestChannelBinder.class);
		Throwable ex = ((Exception) binder.getLastError().getPayload()).getCause();
		assertThat(ex).isInstanceOf(IllegalStateException.class);
		assertThat(ex.getMessage()).isEqualTo("Routing to functions that return Publisher is not supported in the context of Spring Cloud Stream.");
	}
}
 
Example #7
Source File: StreamListenerHandlerMethodTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: SnsMessageHandlerParserTests.java    From spring-integration-aws with MIT License 6 votes vote down vote up
@Test
public void testPolledFlow() throws Exception {
	context = new ClassPathXmlApplicationContext(
			"SnsMessageHandlerParserTests.xml", getClass());

	MessageChannel inputChannel = (MessageChannel) context
			.getBean("pollableTarget");
	@SuppressWarnings("unchecked")
	BlockingQueue<String> dummyQueue = (BlockingQueue<String>) context
			.getBean("dummyQueue");

	String payload = "Hello, World";
	inputChannel.send(MessageBuilder.withPayload(payload).build());
	String messageJSON = dummyQueue.poll(1000, TimeUnit.MILLISECONDS);
	assertNotNull(messageJSON);

	assertEquals(payload, messageMarshaller.deserialize(messageJSON)
			.getPayload());
}
 
Example #9
Source File: StreamListenerMethodReturnWithConversionTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: RoutingFunctionTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testExplicitRoutingFunctionBindingWithCompositionAndRoutingEnabledExplicitly() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					RoutingFunctionConfiguration.class))
							.web(WebApplicationType.NONE)
							.run("--spring.jmx.enabled=false",
									"--spring.cloud.stream.function.definition=enrich|" + RoutingFunction.FUNCTION_NAME,
									"--spring.cloud.stream.function.routing.enabled=true")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context
				.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder
				.withPayload("Hello".getBytes()).build();
		inputDestination.send(inputMessage);

		Message<byte[]> outputMessage = outputDestination.receive();
		assertThat(outputMessage.getPayload()).isEqualTo("HELLO".getBytes());
	}
}
 
Example #11
Source File: ImplicitFunctionBindingTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testHeaderRetentionWithComposition() {

	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(NoEnableBindingConfiguration.class))
					.web(WebApplicationType.NONE)
					.run("--spring.jmx.enabled=false", "--spring.cloud.function.definition=func|addHeaders")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder.withPayload("Hello".getBytes()).build();
		inputDestination.send(inputMessage);

		Message<byte[]> outputMessage = outputDestination.receive();
		assertThat(outputMessage.getPayload()).isEqualTo("Hello".getBytes());

	}
}
 
Example #12
Source File: StreamListenerAnnotatedMethodArgumentsTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidAnnotationAtMethodParameterWithPojoThatPassesValidation() {
	ConfigurableApplicationContext context = SpringApplication.run(
			TestPojoWithValidAnnotationThatPassesValidation.class, "--server.port=0");

	TestPojoWithValidAnnotationThatPassesValidation testPojoWithValidAnnotationThatPassesValidation = context
			.getBean(TestPojoWithValidAnnotationThatPassesValidation.class);
	Sink sink = context.getBean(Sink.class);
	String id = UUID.randomUUID().toString();
	sink.input().send(MessageBuilder.withPayload("{\"foo\":\"" + id + "\"}")
			.setHeader("contentType", MimeType.valueOf("application/json")).build());
	assertThat(
			testPojoWithValidAnnotationThatPassesValidation.receivedArguments.get(0))
					.hasFieldOrPropertyWithValue("foo", id);
	context.close();
}
 
Example #13
Source File: ImplicitFunctionBindingTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test
public void testFunctionWithUseNativeEncoding() {

	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(NoEnableBindingConfiguration.class))
					.web(WebApplicationType.NONE).run("--spring.jmx.enabled=false",
							"--spring.cloud.function.definition=func",
							"--spring.cloud.stream.bindings.func-out-0.producer.useNativeEncoding=true")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder.withPayload("Hello".getBytes()).build();
		inputDestination.send(inputMessage);
		Message outputMessage = outputDestination.receive();
		assertThat(outputMessage.getPayload()).isEqualTo("Hello");
	}
}
 
Example #14
Source File: RoutingFunctionTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testExplicitRoutingFunctionBindingWithCompositionAndRoutingEnabledExplicitlyAndMoreComposition() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					RoutingFunctionConfiguration.class))
							.web(WebApplicationType.NONE)
							.run("--spring.jmx.enabled=false",
									"--spring.cloud.stream.function.definition=enrich|" + RoutingFunction.FUNCTION_NAME + "|reverse",
									"--spring.cloud.stream.function.routing.enabled=true")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context
				.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder
				.withPayload("Hello".getBytes()).build();
		inputDestination.send(inputMessage);

		Message<byte[]> outputMessage = outputDestination.receive();
		assertThat(outputMessage.getPayload()).isEqualTo("OLLEH".getBytes());
	}
}
 
Example #15
Source File: ContentTypeTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendBynaryData() throws Exception {
	try (ConfigurableApplicationContext context = SpringApplication.run(
			SourceApplication.class, "--server.port=0",
			"--spring.jmx.enabled=false")) {

		MessageCollector collector = context.getBean(MessageCollector.class);
		Source source = context.getBean(Source.class);
		byte[] data = new byte[] { 0, 1, 2, 3 };
		source.output()
				.send(MessageBuilder.withPayload(data)
						.setHeader(MessageHeaders.CONTENT_TYPE,
								MimeTypeUtils.APPLICATION_OCTET_STREAM)
						.build());
		Message<byte[]> message = (Message<byte[]>) collector
				.forChannel(source.output()).poll(1, TimeUnit.SECONDS);
		assertThat(
				message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
						.includes(MimeTypeUtils.APPLICATION_OCTET_STREAM));
		assertThat(message.getPayload()).isEqualTo(data);
	}
}
 
Example #16
Source File: LabelImageTensorflowProcessorIntegrationTests.java    From tensorflow-spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@Test
public void testEvaluationPositive() throws IOException {
	try(InputStream is = new ClassPathResource("/images/panda.jpeg").getInputStream()) {

		byte[] image = IOUtils.toByteArray(is);

		channels.input().send(MessageBuilder.withPayload(image).build());

		Message<String> received = (Message<String>) messageCollector.forChannel(channels.output()).poll();

		Assert.assertTrue(received.getPayload().getClass().isAssignableFrom(String.class));

		Assert.assertThat(received.getPayload().toString(),
				equalTo("{\"alternatives\":[" +
						"{\"giant panda\":0.98649305}," +
						"{\"badger\":0.010562794}," +
						"{\"ice bear\":0.001130851}]," +
						"\"label\":\"giant panda\"}"));
	}
}
 
Example #17
Source File: MultipleInputOutputFunctionTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleFunctionsWithComposition() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					ReactiveFunctionConfiguration.class))
							.web(WebApplicationType.NONE)
							.run("--spring.jmx.enabled=false",
								"--spring.cloud.function.definition=uppercase|reverse;reverse|uppercase")) {
		context.getBean(InputDestination.class);

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder.withPayload("Hello".getBytes()).build();
		inputDestination.send(inputMessage, "uppercasereverse-in-0");
		inputDestination.send(inputMessage, "reverseuppercase-in-0");

		Message<byte[]> outputMessage = outputDestination.receive(0, "uppercasereverse-out-0");
		System.out.println(new String(outputMessage.getPayload()));
		assertThat(outputMessage.getPayload()).isEqualTo("OLLEH".getBytes());

		outputMessage = outputDestination.receive(0, "reverseuppercase-out-0");
		assertThat(outputMessage.getPayload()).isEqualTo("OLLEH".getBytes());
	}
}
 
Example #18
Source File: StreamListenerHandlerMethodTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void testStreamListenerMethodWithTargetBeanFromOutside() throws Exception {
	ConfigurableApplicationContext context = SpringApplication.run(
			TestStreamListenerMethodWithTargetBeanFromOutside.class,
			"--server.port=0", "--spring.jmx.enabled=false",
			"--spring.cloud.stream.bindings.input.contentType=text/plain",
			"--spring.cloud.stream.bindings.output.contentType=text/plain");
	Sink sink = context.getBean(Sink.class);
	final String testMessageToSend = "testing";
	sink.input().send(MessageBuilder.withPayload(testMessageToSend).build());
	DirectChannel directChannel = (DirectChannel) context
			.getBean(testMessageToSend.toUpperCase(), MessageChannel.class);
	MessageCollector messageCollector = context.getBean(MessageCollector.class);
	Message<String> result = (Message<String>) messageCollector
			.forChannel(directChannel).poll(1000, TimeUnit.MILLISECONDS);
	sink.input().send(MessageBuilder.withPayload(testMessageToSend).build());
	assertThat(result).isNotNull();
	assertThat(result.getPayload()).isEqualTo(testMessageToSend.toUpperCase());
	context.close();
}
 
Example #19
Source File: RocketMQInboundChannelAdapter.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Override
protected void doStart() {
	if (consumerProperties == null
			|| !consumerProperties.getExtension().getEnabled()) {
		return;
	}
	try {
		rocketMQListenerContainer.start();
		instrumentationManager
				.getHealthInstrumentation(rocketMQListenerContainer.getTopic()
						+ rocketMQListenerContainer.getConsumerGroup())
				.markStartedSuccessfully();
	}
	catch (Exception e) {
		instrumentationManager
				.getHealthInstrumentation(rocketMQListenerContainer.getTopic()
						+ rocketMQListenerContainer.getConsumerGroup())
				.markStartFailed(e);
		log.error("RocketMQTemplate startup failed, Caused by " + e.getMessage());
		throw new MessagingException(MessageBuilder.withPayload(
				"RocketMQTemplate startup failed, Caused by " + e.getMessage())
				.build(), e);
	}
}
 
Example #20
Source File: ImplicitFunctionBindingTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void partitionOnOutputPayloadTestReactive() {
	System.clearProperty("spring.cloud.function.definition");
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(TestChannelBinderConfiguration
			.getCompleteConfiguration(PojoFunctionConfiguration.class))
					.web(WebApplicationType.NONE).run("--spring.cloud.function.definition=funcReactive",
							"--spring.cloud.stream.bindings.funcReactive-out-0.producer.partitionKeyExpression=payload.id",
							"--spring.cloud.stream.bindings.funcReactive-out-0.producer.partitionCount=5",
							"--spring.jmx.enabled=false")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder.withPayload("Jim Lahey".getBytes()).build();

		inputDestination.send(inputMessage, "funcReactive-in-0");

		assertThat(outputDestination.receive(100, "funcReactive-out-0").getHeaders().get("scst_partition")).isEqualTo(3);

		assertThat(outputDestination.receive(100)).isNull();
	}
}
 
Example #21
Source File: SnsChannelParserTests.java    From spring-integration-aws with MIT License 6 votes vote down vote up
@Test
public void testMessageFlow() throws Exception {

	setUp("SnsChannelParserTests.xml", getClass(), "snsChannel");

	recvPayload = null;
	PublishSubscribeSnsChannel snsChannel = (PublishSubscribeSnsChannel) context
			.getBean("snsChannel");
	snsChannel.subscribe(new MessageHandler() {

		@Override
		public void handleMessage(Message<?> message)
				throws MessagingException {
			recvPayload = message.getPayload();
		}
	});

	String payload = "Hello, World";
	snsChannel.send(MessageBuilder.withPayload(payload).build());
	Thread.sleep(1000);

	assertNotNull(recvPayload);
	assertEquals(payload, recvPayload);
}
 
Example #22
Source File: BookingServiceImpl.java    From Mastering-Microservices-with-Java-9-Second-Edition with MIT License 6 votes vote down vote up
/**
 *
 * @param booking
 * @throws Exception
 */
@Override
public void produceBookingOrderEvent(Booking booking) throws Exception {
    final BookingOrder.Builder boBuilder = BookingOrder.newBuilder();
    boBuilder.setId(booking.getId());
    boBuilder.setName(booking.getName());
    boBuilder.setRestaurantId(booking.getRestaurantId());
    boBuilder.setTableId(booking.getTableId());
    boBuilder.setUserId(booking.getUserId());
    boBuilder.setDate(booking.getDate().toString());
    boBuilder.setTime(booking.getTime().toString());
    BookingOrder bo = boBuilder.build();
    final Message<BookingOrder> message = MessageBuilder.withPayload(bo).build();
    bookingMessageChannels.bookingOrderOutput().send(message);
    LOG.info("sending bookingOrder: {}", booking);
}
 
Example #23
Source File: ImplicitFunctionBindingTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithContextTypeApplicationProperty() {
	System.clearProperty("spring.cloud.function.definition");
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(SingleFunctionConfiguration.class))
					.web(WebApplicationType.NONE).run("--spring.jmx.enabled=false",
							"--spring.cloud.stream.bindings.input.content-type=text/plain", "--debug")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context.getBean(OutputDestination.class);

		Message<byte[]> inputMessageOne = MessageBuilder.withPayload("Hello".getBytes()).build();
		Message<byte[]> inputMessageTwo = MessageBuilder.withPayload("Hello Again".getBytes()).build();
		inputDestination.send(inputMessageOne);
		inputDestination.send(inputMessageTwo);

		Message<byte[]> outputMessage = outputDestination.receive();
		assertThat(outputMessage.getPayload()).isEqualTo("Hello".getBytes());
		outputMessage = outputDestination.receive();
		assertThat(outputMessage.getPayload()).isEqualTo("Hello Again".getBytes());
	}
}
 
Example #24
Source File: ImplicitFunctionBindingTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void partitionOnOutputPayloadTest() {
	System.clearProperty("spring.cloud.function.definition");
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(TestChannelBinderConfiguration
			.getCompleteConfiguration(PojoFunctionConfiguration.class))
					.web(WebApplicationType.NONE).run("--spring.cloud.function.definition=func",
							"--spring.cloud.stream.bindings.func-out-0.producer.partitionKeyExpression=payload.id",
							"--spring.cloud.stream.bindings.func-out-0.producer.partitionCount=5",
							"--spring.jmx.enabled=false")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder.withPayload("Jim Lahey".getBytes()).build();

		inputDestination.send(inputMessage, "func-in-0");

		assertThat(outputDestination.receive(100, "func-out-0").getHeaders().get("scst_partition")).isEqualTo(3);

		assertThat(outputDestination.receive(100)).isNull();
	}
}
 
Example #25
Source File: JsonMessageMarshaller.java    From spring-integration-aws with MIT License 6 votes vote down vote up
private void setProperties(MessageBuilder<Object> builder,
		JSONObject properties) throws JSONException {

	if (properties.has(HeaderKeys.CORRELATION_ID)) {
		builder.setCorrelationId(properties
				.getString(HeaderKeys.CORRELATION_ID));
	}
	if (properties.has(HeaderKeys.EXPIRATION_DATE)) {
		builder.setExpirationDate(Long.valueOf(properties
				.getString(HeaderKeys.EXPIRATION_DATE)));
	}
	if (properties.has(HeaderKeys.PRIORITY)) {
		builder.setPriority(Integer.valueOf(properties
				.getString(HeaderKeys.PRIORITY)));
	}
	if (properties.has(HeaderKeys.SEQUENCE_NUMBER)) {
		builder.setSequenceNumber(Integer.valueOf(properties
				.getString(HeaderKeys.SEQUENCE_NUMBER)));
	}
	if (properties.has(HeaderKeys.SEQUENCE_SIZE)) {
		builder.setSequenceSize(Integer.valueOf(properties
				.getString(HeaderKeys.SEQUENCE_SIZE)));
	}
}
 
Example #26
Source File: ContentTypeTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendJsonAsString() throws Exception {
	try (ConfigurableApplicationContext context = SpringApplication.run(
			SourceApplication.class, "--server.port=0",
			"--spring.jmx.enabled=false")) {
		MessageCollector collector = context.getBean(MessageCollector.class);
		Source source = context.getBean(Source.class);
		User user = new User("Alice");
		String json = this.mapper.writeValueAsString(user);
		source.output().send(MessageBuilder.withPayload(user).build());
		Message<String> message = (Message<String>) collector
				.forChannel(source.output()).poll(1, TimeUnit.SECONDS);
		assertThat(
				message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
						.includes(MimeTypeUtils.APPLICATION_JSON));
		assertThat(json).isEqualTo(message.getPayload());
	}
}
 
Example #27
Source File: StreamListenerHandlerMethodTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@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 #28
Source File: ImageRecognitionTensorflowProcessorIntegrationTests.java    From tensorflow with Apache License 2.0 6 votes vote down vote up
@Test
public void testEvaluationPositive() throws IOException {
	try (InputStream is = new ClassPathResource("/images/panda.jpeg").getInputStream()) {

		byte[] image = StreamUtils.copyToByteArray(is);

		channels.input().send(MessageBuilder.withPayload(image).build());

		Message<byte[]> received = (Message<byte[]>) messageCollector.forChannel(channels.output()).poll();

		Assert.assertThat(received.getPayload(),
				equalTo("{\"labels\":[" +
						"{\"giant panda\":0.9864928}, " +
						"{\"badger\":0.0105627915}, " +
						"{\"ice bear\":0.0011308496}]}"));
	}
}
 
Example #29
Source File: StreamListenerHandlerBeanTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testHandlerBean() throws Exception {
	ConfigurableApplicationContext context = SpringApplication.run(this.configClass,
			"--spring.cloud.stream.bindings.output.contentType=application/json",
			"--server.port=0");
	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());
	HandlerBean handlerBean = context.getBean(HandlerBean.class);
	Assertions.assertThat(handlerBean.receivedPojos).hasSize(1);
	Assertions.assertThat(handlerBean.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()).isEqualTo("{\"bar\":\"barbar" + id + "\"}");
	assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)
			.includes(MimeTypeUtils.APPLICATION_JSON));
	context.close();
}
 
Example #30
Source File: RoutingFunctionTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testRoutingViaExplicitEnablingAndRoutingExpressionHeader() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					RoutingFunctionConfiguration.class))
							.web(WebApplicationType.NONE)
							.run("--spring.jmx.enabled=false",
								"--spring.cloud.stream.function.routing.enabled=true")) {

		InputDestination inputDestination = context.getBean(InputDestination.class);
		OutputDestination outputDestination = context
				.getBean(OutputDestination.class);

		Message<byte[]> inputMessage = MessageBuilder
				.withPayload("Hello".getBytes())
				.setHeader("spring.cloud.function.routing-expression", "'echo'")
				.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN)
				.build();
		inputDestination.send(inputMessage);

		Message<byte[]> outputMessage = outputDestination.receive();
		assertThat(outputMessage.getPayload()).isEqualTo("Hello".getBytes());
	}
}