org.springframework.messaging.support.GenericMessage Java Examples

The following examples show how to use org.springframework.messaging.support.GenericMessage. 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: BusAutoConfigurationTests.java    From spring-cloud-bus with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: ContentTypeTckTests.java    From spring-cloud-stream with 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 #3
Source File: AzureSpringBootHttpRequestHandler.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: FtpSinkIntegrationTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: MainController.java    From heroku-metrics-spring with 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 #6
Source File: Main.java    From java-course-ee with 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 #7
Source File: MessageConverterTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testBadDecode() throws Exception {
	byte[] bytes = new byte[] { (byte) 0xff, 99 };
	Message<byte[]> message = new GenericMessage<>(bytes);
	try {
		EmbeddedHeaderUtils.extractHeaders(message, false);
		fail("Exception expected");
	}
	catch (Exception e) {
		String s = EmbeddedHeaderUtils.decodeExceptionMessage(message);
		assertThat(e).isInstanceOf(BufferUnderflowException.class);
	}
}
 
Example #8
Source File: SpringCloudTaskSinkApplicationIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testTaskLaunch() throws IOException {

    TaskLauncher taskLauncher =
        context.getBean(TaskLauncher.class);

    Map<String, String> prop = new HashMap<String, String>();
    prop.put("server.port", "0");
    TaskLaunchRequest request = new TaskLaunchRequest(
        "maven://org.springframework.cloud.task.app:"
            + "timestamp-task:jar:1.0.1.RELEASE", null,
        prop,
        null, null);
    GenericMessage<TaskLaunchRequest> message = new GenericMessage<TaskLaunchRequest>(
        request);
    this.sink.input().send(message);

    ArgumentCaptor<AppDeploymentRequest> deploymentRequest = ArgumentCaptor
        .forClass(AppDeploymentRequest.class);

    verify(taskLauncher).launch(
        deploymentRequest.capture());

    AppDeploymentRequest actualRequest = deploymentRequest
        .getValue();

    // Verifying the co-ordinate of launched Task here.
    assertTrue(actualRequest.getCommandlineArguments()
        .isEmpty());
    assertEquals("0", actualRequest.getDefinition()
        .getProperties().get("server.port"));
    assertTrue(actualRequest
        .getResource()
        .toString()
        .contains(
            "org.springframework.cloud.task.app:timestamp-task:jar:1.0.1.RELEASE"));
}
 
Example #9
Source File: ContentTypeTckTests.java    From spring-cloud-stream with 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 #10
Source File: ContentTypeTckTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithMapInputParameter() {
	ApplicationContext context = new SpringApplicationBuilder(
			MapInputConfiguration.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(), StandardCharsets.UTF_8))
			.isEqualTo(jsonPayload);
}
 
Example #11
Source File: TaskLauncherSinkTests.java    From spring-cloud-task with 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 #12
Source File: LoadGeneratorSourceConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@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 #13
Source File: MessageRequestReplyTemplateTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #14
Source File: MessageRequestReplyTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void convertAndSendWithPostProcessor() {
	Message<?> responseMessage = new GenericMessage<Object>("response");
	this.template.setDefaultDestination("home");
	this.template.setReceiveMessage(responseMessage);
	String response = this.template.convertSendAndReceive("request", String.class, this.postProcessor);

	assertEquals("home", this.template.destination);
	assertSame("request", this.template.requestMessage.getPayload());
	assertSame("response", response);
	assertSame(this.postProcessor.getMessage(), this.template.requestMessage);
}
 
Example #15
Source File: MongodbProcessorApplicationTests.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@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 #16
Source File: Main.java    From java-course-ee with 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("publishChannel", MessageChannel.class);

    transformationChannel.send(new GenericMessage<String>("hello"));
    transformationChannel.send(new GenericMessage<String>("wonderful"));
    transformationChannel.send(new GenericMessage<String>("world"));
}
 
Example #17
Source File: BeanFactoryAwareFunctionRegistryTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void testConsumerFunction() { // function that returns Void, effectively a Consumer
	FunctionCatalog catalog = this.configureCatalog();

	Function<String, Void> consumerFunction = catalog.lookup("consumerFunction");
	assertThat(consumerFunction.apply("hello")).isNull();

	Function<Message<byte[]>, Void> consumerFunctionAsMessageA = catalog.lookup("consumerFunction");
	assertThat(consumerFunctionAsMessageA.apply(new GenericMessage<byte[]>("\"hello\"".getBytes()))).isNull();

	Function<Message<byte[]>, Void> consumerFunctionAsMessageB = catalog.lookup("consumerFunction", "application/json");
	assertThat(consumerFunctionAsMessageB.apply(new GenericMessage<byte[]>("\"hello\"".getBytes()))).isNull();
}
 
Example #18
Source File: BusAutoConfigurationTests.java    From spring-cloud-bus with Apache License 2.0 5 votes vote down vote up
@Test
public void inboundFromSelf() {
	this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class,
			"--spring.cloud.bus.id=foo", "--server.port=0");
	this.context.getBean(SpringCloudBusClient.INPUT, MessageChannel.class)
			.send(new GenericMessage<>(
					new RefreshRemoteApplicationEvent(this, "foo", null)));
	assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh)
			.isNull();
}
 
Example #19
Source File: MessageReceivingTemplateTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 #20
Source File: GreenfieldFunctionEnableBindingTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessorFromFunction() {
	try (ConfigurableApplicationContext context = new SpringApplicationBuilder(
			TestChannelBinderConfiguration.getCompleteConfiguration(
					ProcessorFromFunction.class)).web(WebApplicationType.NONE).run(
							"--spring.cloud.function.definition=toUpperCase",
							"--spring.jmx.enabled=false")) {

		InputDestination source = context.getBean(InputDestination.class);
		source.send(new GenericMessage<byte[]>("John Doe".getBytes()));
		OutputDestination target = context.getBean(OutputDestination.class);
		assertThat(target.receive(10000).getPayload())
				.isEqualTo("JOHN DOE".getBytes(StandardCharsets.UTF_8));
	}
}
 
Example #21
Source File: MessageQueueMatcherTest.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void testTimeout() {
	Message<?> msg = new GenericMessage<>("hello");
	MessageQueueMatcher<?> matcher = MessageQueueMatcher.receivesMessageThat(is(msg))
			.within(2, TimeUnit.MILLISECONDS);

	boolean result = matcher.matches(this.queue);
	assertThat(result).isFalse();
	matcher.describeMismatch(this.queue, this.description);
	assertThat(this.description.toString())
			.isEqualTo("timed out after 2 milliseconds");
}
 
Example #22
Source File: ErrorHandlingTests.java    From spring-cloud-stream with 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 #23
Source File: DestinationResolvingMessagingTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void convertSendAndReceiveWithHeadersAndPostProcessor() {
	Message<?> responseMessage = new GenericMessage<Object>("response");
	this.template.setReceiveMessage(responseMessage);
	String actual = this.template.convertSendAndReceive("myChannel", "request", this.headers,
			String.class, this.postProcessor);

	assertEquals("value", this.template.message.getHeaders().get("key"));
	assertEquals("request", this.template.message.getPayload());
	assertSame("request", this.postProcessor.getMessage().getPayload());
	assertSame("response", actual);
	assertSame(this.myChannel, this.template.messageChannel);
}
 
Example #24
Source File: TestSpringIntegrationSecurityIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@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 #25
Source File: AzureSpringBootHttpRequestHandlerTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@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 #26
Source File: DestinationResolvingMessagingTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #27
Source File: MessageRequestReplyTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #28
Source File: DestinationResolvingMessagingTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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);
}
 
Example #29
Source File: ContentTypeTckTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Test
public void withInternalPipeline() {
	ApplicationContext context = new SpringApplicationBuilder(InternalPipeLine.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 #30
Source File: DestinationResolvingMessagingTemplateTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void sendAndReceive() {
	Message<?> requestMessage = new GenericMessage<Object>("request");
	Message<?> responseMessage = new GenericMessage<Object>("response");
	this.template.setReceiveMessage(responseMessage);
	Message<?> actual = this.template.sendAndReceive("myChannel", requestMessage);

	assertEquals(requestMessage, this.template.message);
	assertSame(responseMessage, actual);
	assertSame(this.myChannel, this.template.messageChannel);
}