Java Code Examples for org.springframework.messaging.support.GenericMessage

The following examples show how to use org.springframework.messaging.support.GenericMessage. 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
@SuppressWarnings("rawtypes")
@Override
protected Object convertEvent(HttpRequestMessage<I> event) {

	if (event.getBody() != null) {
		if (functionAcceptsMessage()) {
			return new GenericMessage<I>(event.getBody(), getHeaders(event));
		}
		else {
			return event.getBody();
		}
	}
	else {
		if (functionAcceptsMessage()) {
			return new GenericMessage<Optional>(Optional.empty(), getHeaders(event));
		}
		else {
			return Optional.empty();
		}
	}
}
 
Example 2
@Test
public void inboundNotFromSelfWithTrace() throws Exception {
	this.context = SpringApplication.run(
			new Class[] { InboundMessageHandlerConfiguration.class,
					OutboundMessageHandlerConfiguration.class,
					SentMessageConfiguration.class },
			new String[] { "--spring.cloud.bus.trace.enabled=true",
					"--spring.cloud.bus.id=bar", "--server.port=0" });
	this.context.getBean(SpringCloudBusClient.INPUT, MessageChannel.class)
			.send(new GenericMessage<>(
					new RefreshRemoteApplicationEvent(this, "foo", null)));
	RefreshRemoteApplicationEvent refresh = this.context
			.getBean(InboundMessageHandlerConfiguration.class).refresh;
	assertThat(refresh).isNotNull();
	SentMessageConfiguration sent = this.context
			.getBean(SentMessageConfiguration.class);
	assertThat(sent.event).isNotNull();
	assertThat(sent.count).isEqualTo(1);
}
 
Example 3
Source Project: heroku-metrics-spring   Source File: MainController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(value = "/logs", method = RequestMethod.POST)
@ResponseBody
public String logs(@RequestBody String body) throws IOException {

  // "application/logplex-1" does not conform to RFC5424.
  // It leaves out STRUCTURED-DATA but does not replace it with
  // a NILVALUE. To workaround this, we inject empty STRUCTURED-DATA.
  String[] parts = body.split("router - ");
  String log = parts[0] + "router - [] " + (parts.length > 1 ? parts[1] : "");

  RFC6587SyslogDeserializer parser = new RFC6587SyslogDeserializer();
  InputStream is = new ByteArrayInputStream(log.getBytes());
  Map<String, ?> messages = parser.deserialize(is);
  ObjectMapper mapper = new ObjectMapper();

  MessageChannel toKafka = context.getBean("toKafka", MessageChannel.class);
  String json = mapper.writeValueAsString(messages);
  toKafka.send(new GenericMessage<>(json));

  return "ok";
}
 
Example 4
Source Project: spring-cloud-stream   Source File: ContentTypeTckTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void typelessToPojoInboundContentTypeBindingJson() {
	ApplicationContext context = new SpringApplicationBuilder(
			TypelessToPojoStreamListener.class).web(WebApplicationType.NONE).run(
					"--spring.cloud.stream.bindings.input.contentType=application/json",
					"--spring.jmx.enabled=false");
	InputDestination source = context.getBean(InputDestination.class);
	OutputDestination target = context.getBean(OutputDestination.class);
	String jsonPayload = "{\"name\":\"oleg\"}";
	source.send(new GenericMessage<>(jsonPayload.getBytes()));
	Message<byte[]> outputMessage = target.receive();
	assertThat(outputMessage.getHeaders().get(MessageHeaders.CONTENT_TYPE))
			.isEqualTo(MimeTypeUtils.APPLICATION_JSON);
	assertThat(new String(outputMessage.getPayload(), StandardCharsets.UTF_8))
			.isEqualTo(jsonPayload);
}
 
Example 5
@Test
public void sendFiles() {
	for (int i = 1; i <= 2; i++) {
		String pathname = "/localSource" + i + ".txt";
		String upperPathname = pathname.toUpperCase();
		new File(getTargetRemoteDirectory() + upperPathname).delete();
		assertFalse(new File(getTargetRemoteDirectory() + upperPathname).exists());
		this.ftpSink.input().send(new GenericMessage<>(new File(getSourceLocalDirectory() + pathname)));
		File expected = new File(getTargetRemoteDirectory() + upperPathname);
		assertTrue(expected.getAbsolutePath() + " does not exist", expected.exists());
		// verify the upcase on a case-insensitive file system
		File[] files = getTargetRemoteDirectory().listFiles();
		for (File file : files) {
			assertThat(file.getName(), startsWith("LOCALSOURCE"));
		}
	}
}
 
Example 6
Source Project: spring-cloud-stream   Source File: ContentTypeTckTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testWithListInputParameter() {
	ApplicationContext context = new SpringApplicationBuilder(
			ListInputConfiguration.class).web(WebApplicationType.NONE)
					.run("--spring.jmx.enabled=false");
	InputDestination source = context.getBean(InputDestination.class);
	OutputDestination target = context.getBean(OutputDestination.class);
	String jsonPayload = "[\"foo\",\"bar\"]";
	source.send(new GenericMessage<>(jsonPayload.getBytes()));
	Message<byte[]> outputMessage = target.receive();
	assertThat(new String(outputMessage.getPayload(), StandardCharsets.UTF_8))
			.isEqualTo(jsonPayload);
}
 
Example 7
Source Project: spring-cloud-aws   Source File: QueueMessageUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Message<String> createMessage(
		com.amazonaws.services.sqs.model.Message message,
		Map<String, Object> additionalHeaders) {
	HashMap<String, Object> messageHeaders = new HashMap<>();
	messageHeaders.put(MESSAGE_ID_MESSAGE_ATTRIBUTE_NAME, message.getMessageId());
	messageHeaders.put(RECEIPT_HANDLE_MESSAGE_ATTRIBUTE_NAME,
			message.getReceiptHandle());

	messageHeaders.putAll(additionalHeaders);
	messageHeaders.putAll(getAttributesAsMessageHeaders(message));
	messageHeaders.putAll(getMessageAttributesAsMessageHeaders(message));

	return new GenericMessage<>(message.getBody(),
			new SqsMessageHeaders(messageHeaders));
}
 
Example 8
Source Project: spring-cloud-stream   Source File: ContentTypeTckTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void stringToMapMessageStreamListener() {
	ApplicationContext context = new SpringApplicationBuilder(
			StringToMapMessageStreamListener.class).web(WebApplicationType.NONE)
					.run("--spring.jmx.enabled=false");
	InputDestination source = context.getBean(InputDestination.class);
	OutputDestination target = context.getBean(OutputDestination.class);
	String jsonPayload = "{\"name\":\"oleg\"}";
	source.send(new GenericMessage<>(jsonPayload.getBytes()));
	Message<byte[]> outputMessage = target.receive();
	assertThat(new String(outputMessage.getPayload())).isEqualTo("oleg");
}
 
Example 9
Source Project: spring-cloud-task   Source File: TaskLauncherSinkTests.java    License: Apache License 2.0 5 votes vote down vote up
private TaskConfiguration.TestTaskLauncher launchTaskByteArray(String artifactURL,
		List<String> commandLineArgs, String applicationName) throws Exception {
	TaskConfiguration.TestTaskLauncher testTaskLauncher = this.context
			.getBean(TaskConfiguration.TestTaskLauncher.class);
	String stringRequest = getStringTaskLaunchRequest(artifactURL, commandLineArgs,
			applicationName);
	GenericMessage<byte[]> message = new GenericMessage<>(stringRequest.getBytes());

	this.sink.input().send(message);
	return testTaskLauncher;
}
 
Example 10
Source Project: spring-cloud-stream   Source File: PollableConsumerTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testConvertMap() {
	TestChannelBinder binder = createBinder();
	MessageConverterConfigurer configurer = this.context
			.getBean(MessageConverterConfigurer.class);

	binder.setMessageSourceDelegate(
			() -> new GenericMessage<>("{\"qux\":{\"foo\":\"bar\"}}".getBytes()));
	DefaultPollableMessageSource pollableSource = new DefaultPollableMessageSource(
			this.messageConverter);
	configurer.configurePolledMessageSource(pollableSource, "foo");

	ExtendedConsumerProperties<Object> properties = new ExtendedConsumerProperties<>(
			null);
	properties.setMaxAttempts(1);
	properties.setBackOffInitialInterval(0);
	binder.bindPollableConsumer("foo", "bar", pollableSource, properties);
	final AtomicReference<Object> payload = new AtomicReference<>();
	assertThat(pollableSource.poll(received -> {
		payload.set(received.getPayload());
	}, new ParameterizedTypeReference<Map<String, Foo>>() {
	})).isTrue();
	@SuppressWarnings("unchecked")
	Map<String, Foo> map = (Map<String, Foo>) payload.get();
	assertThat(map.size()).isEqualTo(1);
	assertThat(map.get("qux").getFoo()).isEqualTo("bar");
}
 
Example 11
@Test
public void testSinkFromConsumer() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration
					.getCompleteConfiguration(SinkFromConsumer.class))
							.web(WebApplicationType.NONE)
							.run("--spring.cloud.function.definition=sink",
									"--spring.jmx.enabled=false")) {

		InputDestination source = context.getBean(InputDestination.class);
		PollableChannel result = context.getBean("result", PollableChannel.class);
		source.send(new GenericMessage<byte[]>("John Doe".getBytes()));
		assertThat(result.receive(10000).getPayload()).isEqualTo("John Doe");
	}
}
 
Example 12
@Test
public void testCountWithTimestampInMessageAndCustomFormat() {
	this.sink.input().send(new GenericMessage<Object>(Collections.singletonMap("ts", "14/10/1978")));
	DateTime endDate = new DateTime(1980, 1, 1, 0, 0);
	AggregateCounter counts = this.aggregateCounterRepository.getCounts(AGGREGATE_COUNTER_NAME, 5, endDate,
			AggregateCounterResolution.year);
	assertThat(counts.getCounts(), equalTo(new long[] {0, 0, 1, 0, 0}));
}
 
Example 13
@Test
public void receiveAndConvert() {
	Message<?> expected = new GenericMessage<Object>("payload");
	this.template.setReceiveMessage(expected);
	String payload = this.template.receiveAndConvert("myChannel", String.class);

	assertEquals("payload", payload);
	assertSame(this.myChannel, this.template.messageChannel);
}
 
Example 14
Source Project: spring-cloud-stream   Source File: ContentTypeTckTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void pojoToPojo() {
	ApplicationContext context = new SpringApplicationBuilder(
			PojoToPojoStreamListener.class).web(WebApplicationType.NONE)
					.run("--spring.jmx.enabled=false");
	InputDestination source = context.getBean(InputDestination.class);
	OutputDestination target = context.getBean(OutputDestination.class);
	String jsonPayload = "{\"name\":\"oleg\"}";
	source.send(new GenericMessage<>(jsonPayload.getBytes()));
	Message<byte[]> outputMessage = target.receive();
	assertThat(outputMessage.getHeaders().get(MessageHeaders.CONTENT_TYPE))
			.isEqualTo(MimeTypeUtils.APPLICATION_JSON);
	assertThat(new String(outputMessage.getPayload(), StandardCharsets.UTF_8))
			.isEqualTo(jsonPayload);
}
 
Example 15
@Test
public void test() throws InterruptedException {
	channels.input().send(new GenericMessage<Object>("hello"));
	channels.input().send(new GenericMessage<Object>("hello world"));
	channels.input().send(new GenericMessage<Object>("hi!"));
	assertThat(collector.forChannel(channels.output()), receivesPayloadThat(is("hello world")));
	assertThat(collector.forChannel(channels.output()).poll(10, MILLISECONDS), is(nullValue(Message.class)));
}
 
Example 16
@Test
public void convertAndSendToDestinationWithHeadersAndPostProcessor() {
	Message<?> responseMessage = new GenericMessage<Object>("response");
	this.template.setReceiveMessage(responseMessage);
	String response = this.template.convertSendAndReceive("somewhere", "request", this.headers,
			String.class, this.postProcessor);

	assertEquals("somewhere", this.template.destination);
	assertEquals("value", this.template.requestMessage.getHeaders().get("key"));
	assertSame("request", this.template.requestMessage.getPayload());
	assertSame("response", response);
	assertSame(this.postProcessor.getMessage(), this.template.requestMessage);
}
 
Example 17
@Test
@WithMockUser(username = "user", roles = { "LOGGER", "VIEWER" })
public void givenRoleUserAndLogger_whenSendMessageToPSChannel_then2GetMessages() throws IllegalStateException, InterruptedException {
    startPSChannel.send(new GenericMessage<String>(DIRECT_CHANNEL_MESSAGE));

    executor.getThreadPoolExecutor().awaitTermination(2, TimeUnit.SECONDS);

    assertEquals(2, messageConsumer.getMessagePSContent().size());
    assertTrue(messageConsumer.getMessagePSContent().values().contains("user"));
    assertTrue(messageConsumer.getMessagePSContent().values().contains("ROLE_LOGGER,ROLE_VIEWER"));
}
 
Example 18
@Test
public void test() {
	Map<String, String> data1 = Collections.singletonMap("foo", "bar");

	Map<String, String> data2 = new HashMap<>();
	data2.put("firstName", "Foo");
	data2.put("lastName", "Bar");

	this.channel.input().send(new GenericMessage<>(data1));
	this.channel.input().send(new GenericMessage<>(data2));
	this.channel.input().send(new GenericMessage<>("{\"my_data\": \"THE DATA\"}"));

	assertThat(collector.forChannel(channel.output()), receivesPayloadThat(is("{\"foo\":\"bar\"}")));
	assertThat(collector.forChannel(channel.output()), receivesPayloadThat(is("{\"firstName\":\"Foo\",\"lastName\":\"Bar\"}")));
	assertThat(collector.forChannel(channel.output()), receivesPayloadThat(is("{\"my_data\": \"THE DATA\"}")));

	List<Document> result =
			this.mongoTemplate.findAll(Document.class, mongoDbSinkProperties.getCollection());

	assertEquals(3, result.size());

	Document dbObject = result.get(0);
	assertNotNull(dbObject.get("_id"));
	assertEquals(dbObject.get("foo"), "bar");
	assertNotNull(dbObject.get("_class"));

	dbObject = result.get(1);
	assertEquals(dbObject.get("firstName"), "Foo");
	assertEquals(dbObject.get("lastName"), "Bar");

	dbObject = result.get(2);
	assertNull(dbObject.get("_class"));
	assertEquals(dbObject.get("my_data"), "THE DATA");
}
 
Example 19
@Test
public void convertAndSendToDestination() {
	Message<?> responseMessage = new GenericMessage<Object>("response");
	this.template.setReceiveMessage(responseMessage);
	String response = this.template.convertSendAndReceive("somewhere", "request", String.class);

	assertEquals("somewhere", this.template.destination);
	assertSame("request", this.template.requestMessage.getPayload());
	assertSame("response", response);
}
 
Example 20
@Override
public void run() {
	logger.info(String.format("Producer %d sending %d messages", this.producerId, this.messageCount));
	Message<byte[]> message = new GenericMessage<>(new byte[this.messageSize]);
	for (int i = 0; i < this.messageCount; i++) {
		channel.output().send(message);
	}
	logger.info("All Messages Dispatched");
}
 
Example 21
Source Project: spring-cloud-task   Source File: TaskLauncherSinkTests.java    License: Apache License 2.0 5 votes vote down vote up
private TaskConfiguration.TestTaskLauncher launchTaskTaskLaunchRequest(
		String artifactURL, List<String> commandLineArgs, String applicationName)
		throws Exception {
	TaskConfiguration.TestTaskLauncher testTaskLauncher = this.context
			.getBean(TaskConfiguration.TestTaskLauncher.class);
	TaskLaunchRequest request = new TaskLaunchRequest(artifactURL, commandLineArgs,
			this.properties, null, applicationName);
	GenericMessage<TaskLaunchRequest> message = new GenericMessage<>(request);

	this.sink.input().send(message);
	return testTaskLauncher;
}
 
Example 22
Source Project: spring-cloud-stream   Source File: ContentTypeTckTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void _jsonToPojoWrongDefaultContentTypeProperty() {
	ApplicationContext context = new SpringApplicationBuilder(
			PojoToPojoStreamListener.class).web(WebApplicationType.NONE).run(
					"--spring.cloud.stream.default.contentType=text/plain",
					"--spring.jmx.enabled=false");
	InputDestination source = context.getBean(InputDestination.class);
	TestChannelBinder binder = context.getBean(TestChannelBinder.class);
	String jsonPayload = "{\"name\":\"oleg\"}";
	source.send(new GenericMessage<>(jsonPayload.getBytes()));
	assertThat(binder.getLastError().getPayload() instanceof MessagingException)
			.isTrue();
}
 
Example 23
Source Project: java-course-ee   Source File: Main.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
    MessageChannel transformationChannel = context.getBean("transformationChannel", MessageChannel.class);

    transformationChannel.send(new GenericMessage<String>("hello"));
    transformationChannel.send(new GenericMessage<String>("world"));
}
 
Example 24
@Test
public void receiveAndConvert() {
	Message<?> expected = new GenericMessage<>("payload");
	this.template.setDefaultDestination("home");
	this.template.setReceiveMessage(expected);
	String payload = this.template.receiveAndConvert(String.class);

	assertEquals("home", this.template.destination);
	assertSame("payload", payload);
}
 
Example 25
Source Project: spring-cloud-stream   Source File: ErrorHandlingTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGlobalErrorWithThrowable() {
	ApplicationContext context = new SpringApplicationBuilder(
			GlobalErrorHandlerWithThrowableConfig.class).web(WebApplicationType.NONE)
					.run("--spring.jmx.enabled=false");
	InputDestination source = context.getBean(InputDestination.class);
	source.send(new GenericMessage<>("foo".getBytes()));
	GlobalErrorHandlerWithThrowableConfig config = context
			.getBean(GlobalErrorHandlerWithThrowableConfig.class);
	assertThat(config.globalErroInvoked).isTrue();
}
 
Example 26
@Test
@WithMockUser(username = "jane")
public void givenJane_whenSendMessageToDirectChannel_thenAccessDenied() {
    expectedException.expectCause(IsInstanceOf.<Throwable> instanceOf(AccessDeniedException.class));

    startDirectChannel.send(new GenericMessage<String>(DIRECT_CHANNEL_MESSAGE));
}
 
Example 27
@Bean
public Function<Message<Void>, Message<Bar>> function() {
	return (message -> {
		Map<String, Object> headers = new HashMap<>();
		headers.put("path", message.getHeaders().get("path"));
		headers.put("query", message.getHeaders().get("query"));
		headers.put("test-header", message.getHeaders().get("test-header"));
		headers.put("httpMethod", message.getHeaders().get("httpMethod"));
		return new GenericMessage<>(new Bar("body"), headers);
	});
}
 
Example 28
@Test
public void send() {
	Message<?> message = new GenericMessage<Object>("payload");
	this.template.send("myChannel", message);

	assertSame(this.myChannel, this.template.messageChannel);
	assertSame(message, this.template.message);
}
 
Example 29
@Test
public void convertAndSendToDestination() {
	Message<?> responseMessage = new GenericMessage<Object>("response");
	this.template.setReceiveMessage(responseMessage);
	String response = this.template.convertSendAndReceive("somewhere", "request", String.class);

	assertEquals("somewhere", this.template.destination);
	assertSame("request", this.template.requestMessage.getPayload());
	assertSame("response", response);
}
 
Example 30
@Test
public void receive() {
	Message<?> expected = new GenericMessage<Object>("payload");
	this.template.setReceiveMessage(expected);
	Message<?> actual = this.template.receive("myChannel");

	assertSame(expected, actual);
	assertSame(this.myChannel, this.template.messageChannel);
}