org.springframework.messaging.MessageHeaders Java Examples

The following examples show how to use org.springframework.messaging.MessageHeaders. 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: SendToMethodReturnValueHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testHeadersToSend() throws Exception {
	Message<?> message = createMessage("sess1", "sub1", "/app", "/dest", null);

	SimpMessageSendingOperations messagingTemplate = Mockito.mock(SimpMessageSendingOperations.class);
	SendToMethodReturnValueHandler handler = new SendToMethodReturnValueHandler(messagingTemplate, false);

	handler.handleReturnValue(PAYLOAD, this.noAnnotationsReturnType, message);

	ArgumentCaptor<MessageHeaders> captor = ArgumentCaptor.forClass(MessageHeaders.class);
	verify(messagingTemplate).convertAndSend(eq("/topic/dest"), eq(PAYLOAD), captor.capture());

	MessageHeaders headers = captor.getValue();
	SimpMessageHeaderAccessor accessor =
			MessageHeaderAccessor.getAccessor(headers, SimpMessageHeaderAccessor.class);
	assertNotNull(accessor);
	assertTrue(accessor.isMutable());
	assertEquals("sess1", accessor.getSessionId());
	assertNull("Subscription id should not be copied", accessor.getSubscriptionId());
	assertEquals(this.noAnnotationsReturnType,
			accessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER));
}
 
Example #2
Source File: DefaultUserDestinationResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Nullable
private ParseResult parseSubscriptionMessage(Message<?> message, String sourceDestination) {
	MessageHeaders headers = message.getHeaders();
	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	if (sessionId == null) {
		logger.error("No session id. Ignoring " + message);
		return null;
	}
	int prefixEnd = this.prefix.length() - 1;
	String actualDestination = sourceDestination.substring(prefixEnd);
	if (isRemoveLeadingSlash()) {
		actualDestination = actualDestination.substring(1);
	}
	Principal principal = SimpMessageHeaderAccessor.getUser(headers);
	String user = (principal != null ? principal.getName() : null);
	Set<String> sessionIds = Collections.singleton(sessionId);
	return new ParseResult(sourceDestination, actualDestination, sourceDestination, sessionIds, user);
}
 
Example #3
Source File: SimpMessagingTemplateTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void convertAndSendWithMutableSimpMessageHeaders() {
	SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create();
	accessor.setHeader("key", "value");
	accessor.setNativeHeader("fooNative", "barNative");
	accessor.setLeaveMutable(true);
	MessageHeaders headers = accessor.getMessageHeaders();

	this.messagingTemplate.convertAndSend("/foo", "data", headers);

	List<Message<byte[]>> messages = this.messageChannel.getMessages();
	Message<byte[]> message = messages.get(0);

	assertSame(headers, message.getHeaders());
	assertFalse(accessor.isMutable());
}
 
Example #4
Source File: BeanFactoryAwareFunctionRegistryTests.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
@Test
public void testImperativeFunction() {
	FunctionCatalog catalog = this.configureCatalog();

	Function<String, String> asIs = catalog.lookup("uppercase");
	assertThat(asIs.apply("uppercase")).isEqualTo("UPPERCASE");

	Function<Flux<String>, Flux<String>> asFlux = catalog.lookup("uppercase");
	List<String> result = asFlux.apply(Flux.just("uppercaseFlux", "uppercaseFlux2")).collectList().block();
	assertThat(result.get(0)).isEqualTo("UPPERCASEFLUX");
	assertThat(result.get(1)).isEqualTo("UPPERCASEFLUX2");

	Function<Flux<Message<byte[]>>, Flux<Message<byte[]>>> messageFlux = catalog.lookup("uppercase", "application/json");
	Message<byte[]> message1 = MessageBuilder.withPayload("\"uppercaseFlux\"".getBytes()).setHeader(MessageHeaders.CONTENT_TYPE, "application/json").build();
	Message<byte[]> message2 = MessageBuilder.withPayload("\"uppercaseFlux2\"".getBytes()).setHeader(MessageHeaders.CONTENT_TYPE, "application/json").build();
	List<Message<byte[]>> messageResult = messageFlux.apply(Flux.just(message1, message2)).collectList().block();
	assertThat(messageResult.get(0).getPayload()).isEqualTo("\"UPPERCASEFLUX\"".getBytes(StandardCharsets.UTF_8));
	assertThat(messageResult.get(1).getPayload()).isEqualTo("\"UPPERCASEFLUX2\"".getBytes(StandardCharsets.UTF_8));
}
 
Example #5
Source File: AbstractMessageChannelMessagingSendingTemplateTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void send_WithDestinationNameAndMessage_shouldResolveTheDestinationAndSendTheMessage()
		throws Exception {
	// Arrange
	MessageSendingTemplateTest messageSendingTemplate = new MessageSendingTemplateTest(
			this.destinationResolver);
	when(this.destinationResolver.resolveDestination("destination"))
			.thenReturn("resolvedDestination");

	Map<String, Object> headers = Collections.singletonMap("headerKey",
			"headerValue");
	String payload = "payload";

	// Act
	messageSendingTemplate.send("destination",
			MessageBuilder.createMessage(payload, new MessageHeaders(headers)));

	// Assert
	verify(this.destinationResolver).resolveDestination("destination");
	assertThat(
			messageSendingTemplate.getMessageChannel().getSentMessage().getPayload())
					.isEqualTo(payload);
	assertThat(messageSendingTemplate.getMessageChannel().getSentMessage()
			.getHeaders().get("headerKey")).isEqualTo(headers.get("headerKey"));
}
 
Example #6
Source File: QueueMessageHandlerTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void receiveMessage_methodWithMessageAsParameter_parameterIsConverted() {
	new ApplicationContextRunner()
			.withConfiguration(UserConfigurations
					.of(QueueMessageHandlerWithJacksonMappingConfiguration.class))
			.withBean(IncomingMessageHandlerWithMessageParameter.class)
			.run((context) -> {
				DummyKeyValueHolder messagePayload = new DummyKeyValueHolder("myKey",
						"A value");
				MappingJackson2MessageConverter jsonMapper = context
						.getBean(MappingJackson2MessageConverter.class);
				Message<?> message = jsonMapper.toMessage(messagePayload,
						new MessageHeaders(Collections.singletonMap(
								QueueMessageHandler.LOGICAL_RESOURCE_ID,
								"testQueue")));

				MessageHandler messageHandler = context.getBean(MessageHandler.class);
				messageHandler.handleMessage(message);

				IncomingMessageHandlerWithMessageParameter messageListener = context
						.getBean(IncomingMessageHandlerWithMessageParameter.class);
				assertThat(messageListener.getLastReceivedMessage()).isNotNull();
				assertThat(messageListener.getLastReceivedMessage().getPayload())
						.isEqualTo(messagePayload);
			});
}
 
Example #7
Source File: SimpAnnotationMethodMessageHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void monoFailure() {
	Message emptyMessage = MessageBuilder.withPayload(new byte[0]).build();
	given(this.channel.send(any(Message.class))).willReturn(true);
	given(this.converter.toMessage(any(), any(MessageHeaders.class))).willReturn(emptyMessage);

	ReactiveController controller = new ReactiveController();
	this.messageHandler.registerHandler(controller);
	this.messageHandler.setDestinationPrefixes(Arrays.asList("/app1", "/app2/"));

	Message<?> message = createMessage("/app1/mono");
	this.messageHandler.handleMessage(message);

	controller.mono.onError(new IllegalStateException());
	assertTrue(controller.exceptionCaught);
}
 
Example #8
Source File: SimpAnnotationMethodMessageHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void monoSuccess() {
	Message emptyMessage = MessageBuilder.withPayload(new byte[0]).build();
	given(this.channel.send(any(Message.class))).willReturn(true);
	given(this.converter.toMessage(any(), any(MessageHeaders.class))).willReturn(emptyMessage);

	ReactiveController controller = new ReactiveController();
	this.messageHandler.registerHandler(controller);
	this.messageHandler.setDestinationPrefixes(Arrays.asList("/app1", "/app2/"));

	Message<?> message = createMessage("/app1/mono");
	this.messageHandler.handleMessage(message);

	assertNotNull(controller.mono);
	controller.mono.onNext("foo");
	verify(this.converter).toMessage(this.payloadCaptor.capture(), any(MessageHeaders.class));
	assertEquals("foo", this.payloadCaptor.getValue());
}
 
Example #9
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 #10
Source File: SimpAnnotationMethodMessageHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void completableFutureSuccess() {
	Message emptyMessage = MessageBuilder.withPayload(new byte[0]).build();
	given(this.channel.send(any(Message.class))).willReturn(true);
	given(this.converter.toMessage(any(), any(MessageHeaders.class))).willReturn(emptyMessage);

	CompletableFutureController controller = new CompletableFutureController();
	this.messageHandler.registerHandler(controller);
	this.messageHandler.setDestinationPrefixes(Arrays.asList("/app1", "/app2/"));

	Message<?> message = createMessage("/app1/completable-future");
	this.messageHandler.handleMessage(message);

	assertNotNull(controller.future);
	controller.future.complete("foo");
	verify(this.converter).toMessage(this.payloadCaptor.capture(), any(MessageHeaders.class));
	assertEquals("foo", this.payloadCaptor.getValue());
}
 
Example #11
Source File: BeanFactoryAwareFunctionRegistryMultiInOutTests.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiOutputAsTuplePojoInInputByteArrayInputTypePojoMessage() {
	FunctionCatalog catalog = this.configureCatalog();
	Function<Flux<Message<byte[]>>, Tuple3<Flux<Person>, Flux<String>, Flux<Integer>>> multiOutputFunction =
								catalog.lookup("multiOutputAsTupleMessageIn");

	Message<byte[]> uncleSam = MessageBuilder.withPayload("{\"name\":\"Uncle Sam\",\"id\":1}".getBytes(StandardCharsets.UTF_8))
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
			.build();
	Message<byte[]> unclePierre = MessageBuilder.withPayload("{\"name\":\"Oncle Pierre\",\"id\":2}".getBytes(StandardCharsets.UTF_8))
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
			.build();
	Flux<Message<byte[]>> personStream = Flux.just(uncleSam, unclePierre);

	Tuple3<Flux<Person>, Flux<String>, Flux<Integer>> result = multiOutputFunction.apply(personStream);
	result.getT1().subscribe(v -> System.out.println("=> 1: " + v));
	result.getT2().subscribe(v -> System.out.println("=> 2: " + v));
	result.getT3().subscribe(v -> System.out.println("=> 3: " + v));
}
 
Example #12
Source File: StompBrokerRelayMessageHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void systemSubscription() throws Exception {

	MessageHandler handler = mock(MessageHandler.class);
	this.brokerRelay.setSystemSubscriptions(Collections.singletonMap("/topic/foo", handler));
	this.brokerRelay.start();

	StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECTED);
	accessor.setLeaveMutable(true);
	MessageHeaders headers = accessor.getMessageHeaders();
	this.tcpClient.handleMessage(MessageBuilder.createMessage(new byte[0], headers));

	assertEquals(2, this.tcpClient.getSentMessages().size());
	assertEquals(StompCommand.CONNECT, this.tcpClient.getSentHeaders(0).getCommand());
	assertEquals(StompCommand.SUBSCRIBE, this.tcpClient.getSentHeaders(1).getCommand());
	assertEquals("/topic/foo", this.tcpClient.getSentHeaders(1).getDestination());

	Message<byte[]> message = message(StompCommand.MESSAGE, null, null, "/topic/foo");
	this.tcpClient.handleMessage(message);

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	verify(handler).handleMessage(captor.capture());
	assertSame(message, captor.getValue());
}
 
Example #13
Source File: AzureSpringBootHttpRequestHandler.java    From spring-cloud-function with Apache License 2.0 6 votes vote down vote up
private MessageHeaders getHeaders(HttpRequestMessage<I> event) {
	Map<String, Object> headers = new HashMap<String, Object>();

	if (event.getHeaders() != null) {
		headers.putAll(event.getHeaders());
	}
	if (event.getQueryParameters() != null) {
		headers.putAll(event.getQueryParameters());
	}
	if (event.getUri() != null) {
		headers.put("path", event.getUri().getPath());
	}

	if (event.getHttpMethod() != null) {
		headers.put("httpMethod", event.getHttpMethod().toString());
	}

	headers.put("request", event.getBody());
	return new MessageHeaders(headers);
}
 
Example #14
Source File: MessageHeaderAccessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void leaveMutableDefaultBehavior() {
	MessageHeaderAccessor accessor = new MessageHeaderAccessor();
	accessor.setHeader("foo", "bar");
	MessageHeaders headers = accessor.getMessageHeaders();
	Message<?> message = MessageBuilder.createMessage("payload", headers);

	this.thrown.expect(IllegalStateException.class);
	this.thrown.expectMessage("Already immutable");
	accessor.setLeaveMutable(true);

	this.thrown.expect(IllegalStateException.class);
	this.thrown.expectMessage("Already immutable");
	accessor.setHeader("foo", "baz");

	assertEquals("bar", headers.get("foo"));
	assertSame(accessor, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class));
}
 
Example #15
Source File: StompBrokerRelayMessageHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private void sendSystemSubscriptions() {
	int i = 0;
	for (String destination : getSystemSubscriptions().keySet()) {
		StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
		accessor.setSubscriptionId(String.valueOf(i++));
		accessor.setDestination(destination);
		if (logger.isDebugEnabled()) {
			logger.debug("Subscribing to " + destination + " on \"system\" connection.");
		}
		TcpConnection<byte[]> conn = getTcpConnection();
		if (conn != null) {
			MessageHeaders headers = accessor.getMessageHeaders();
			conn.send(MessageBuilder.createMessage(EMPTY_PAYLOAD, headers)).addCallback(
					new ListenableFutureCallback<Void>() {
						public void onSuccess(Void result) {
						}
						public void onFailure(Throwable ex) {
							String error = "Failed to subscribe in \"system\" session.";
							handleTcpConnectionFailure(error, ex);
						}
					});
		}
	}
}
 
Example #16
Source File: SubscriptionMethodReturnValueHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testHeadersPassedToMessagingTemplate() throws Exception {
	String sessionId = "sess1";
	String subscriptionId = "subs1";
	String destination = "/dest";
	Message<?> inputMessage = createInputMessage(sessionId, subscriptionId, destination, null);

	MessageSendingOperations messagingTemplate = Mockito.mock(MessageSendingOperations.class);
	SubscriptionMethodReturnValueHandler handler = new SubscriptionMethodReturnValueHandler(messagingTemplate);

	handler.handleReturnValue(PAYLOAD, this.subscribeEventReturnType, inputMessage);

	ArgumentCaptor<MessageHeaders> captor = ArgumentCaptor.forClass(MessageHeaders.class);
	verify(messagingTemplate).convertAndSend(eq("/dest"), eq(PAYLOAD), captor.capture());

	SimpMessageHeaderAccessor headerAccessor =
			MessageHeaderAccessor.getAccessor(captor.getValue(), SimpMessageHeaderAccessor.class);

	assertNotNull(headerAccessor);
	assertTrue(headerAccessor.isMutable());
	assertEquals(sessionId, headerAccessor.getSessionId());
	assertEquals(subscriptionId, headerAccessor.getSubscriptionId());
	assertEquals(this.subscribeEventReturnType, headerAccessor.getHeader(SimpMessagingTemplate.CONVERSION_HINT_HEADER));
}
 
Example #17
Source File: DefaultContentTypeResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public MimeType resolve(MessageHeaders headers) {
	if (headers == null || headers.get(MessageHeaders.CONTENT_TYPE) == null) {
		return this.defaultMimeType;
	}
	Object value = headers.get(MessageHeaders.CONTENT_TYPE);
	if (value instanceof MimeType) {
		return (MimeType) value;
	}
	else if (value instanceof String) {
		return MimeType.valueOf((String) value);
	}
	else {
		throw new IllegalArgumentException(
				"Unknown type for contentType header value: " + value.getClass());
	}
}
 
Example #18
Source File: MessageHeaderAccessor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * A variation of {@link #getAccessor(org.springframework.messaging.Message, Class)}
 * with a {@code MessageHeaders} instance instead of a {@code Message}.
 * <p>This is for cases when a full message may not have been created yet.
 * @return an accessor instance of the specified type, or {@code null} if none
 * @since 4.1
 */
@SuppressWarnings("unchecked")
public static <T extends MessageHeaderAccessor> T getAccessor(
		MessageHeaders messageHeaders, Class<T> requiredType) {

	if (messageHeaders instanceof MutableMessageHeaders) {
		MutableMessageHeaders mutableHeaders = (MutableMessageHeaders) messageHeaders;
		MessageHeaderAccessor headerAccessor = mutableHeaders.getMessageHeaderAccessor();
		if (requiredType.isAssignableFrom(headerAccessor.getClass()))  {
			return (T) headerAccessor;
		}
	}
	return null;
}
 
Example #19
Source File: AbstractMessageConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected boolean supportsMimeType(@Nullable MessageHeaders headers) {
	if (getSupportedMimeTypes().isEmpty()) {
		return true;
	}
	MimeType mimeType = getMimeType(headers);
	if (mimeType == null) {
		return !isStrictContentTypeMatch();
	}
	for (MimeType current : getSupportedMimeTypes()) {
		if (current.getType().equals(mimeType.getType()) && current.getSubtype().equals(mimeType.getSubtype())) {
			return true;
		}
	}
	return false;
}
 
Example #20
Source File: HeadersMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
private void handleMessage(
		@Headers Map<String, Object> param1,
		@Headers String param2,
		MessageHeaders param3,
		MessageHeaderAccessor param4,
		TestMessageHeaderAccessor param5) {
}
 
Example #21
Source File: MessageHeaderAccessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
public Long getTimestamp() {
	Object value = getHeader(MessageHeaders.TIMESTAMP);
	if (value == null) {
		return null;
	}
	return (value instanceof Long ? (Long) value : Long.parseLong(value.toString()));
}
 
Example #22
Source File: NegotiatingMessageConverterWrapperTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerializationWithFallbackContentTypeHeader() {
	MimeType fallbackContentType = MimeType.valueOf("text/csv");

	Message<?> result = NegotiatingMessageConverterWrapper.wrap(new NaiveCsvTupleMessageConverter())
		.toMessage(somePayload, new MessageHeaders(newHashMap(CONTENT_TYPE, fallbackContentType)));

	assertMessageContent(result, "text/csv", expectedSerializedPayload);
}
 
Example #23
Source File: MessageConverterDelegateSerde.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] serialize(String topic, V data) {
	Message<?> message = MessageBuilder.withPayload(data).build();
	Map<String, Object> headers = new HashMap<>(message.getHeaders());
	headers.put(MessageHeaders.CONTENT_TYPE, this.mimeType.toString());
	MessageHeaders messageHeaders = new MessageHeaders(headers);
	final Object payload = this.messageConverter
			.toMessage(message.getPayload(), messageHeaders).getPayload();
	return (byte[]) payload;
}
 
Example #24
Source File: EmbeddedHeaderUtils.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
private static MessageValues extractHeaders(byte[] payload,
		boolean copyRequestHeaders, MessageHeaders requestHeaders) throws Exception {
	ByteBuffer byteBuffer = ByteBuffer.wrap(payload);
	int headerCount = byteBuffer.get() & 0xff;
	if (headerCount == 0xff) {
		headerCount = byteBuffer.get() & 0xff;
		Map<String, Object> headers = new HashMap<String, Object>();
		for (int i = 0; i < headerCount; i++) {
			int len = byteBuffer.get() & 0xff;
			String headerName = new String(payload, byteBuffer.position(), len,
					"UTF-8");
			byteBuffer.position(byteBuffer.position() + len);
			len = byteBuffer.getInt();
			String headerValue = new String(payload, byteBuffer.position(), len,
					"UTF-8");
			Object headerContent = objectMapper.fromJson(headerValue, Object.class);
			headers.put(headerName, headerContent);
			byteBuffer.position(byteBuffer.position() + len);
		}
		byte[] newPayload = new byte[byteBuffer.remaining()];
		byteBuffer.get(newPayload);
		return buildMessageValues(newPayload, headers, copyRequestHeaders,
				requestHeaders);
	}
	else {
		return buildMessageValues(payload, new HashMap<>(), copyRequestHeaders,
				requestHeaders);
	}
}
 
Example #25
Source File: BeanFactoryAwareFunctionRegistryTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void byteArrayNoSpecialHandling() throws Exception {
	FunctionCatalog catalog = this.configureCatalog(ByteArrayFunction.class);
	FunctionInvocationWrapper function = catalog.lookup("beanFactoryAwareFunctionRegistryTests.ByteArrayFunction", "application/json");
	assertThat(function).isNotNull();
	Message<byte[]> result = (Message<byte[]>) function.apply(MessageBuilder.withPayload("hello".getBytes()).setHeader(MessageHeaders.CONTENT_TYPE, "application/octet-stream").build());
	assertThat(result.getPayload()).isEqualTo("\"b2xsZWg=\"".getBytes());
}
 
Example #26
Source File: GenericMessagingTemplate.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
protected final Message<?> doSendAndReceive(MessageChannel channel, Message<?> requestMessage) {
	Assert.notNull(channel, "'channel' is required");
	Object originalReplyChannelHeader = requestMessage.getHeaders().getReplyChannel();
	Object originalErrorChannelHeader = requestMessage.getHeaders().getErrorChannel();

	long sendTimeout = sendTimeout(requestMessage);
	long receiveTimeout = receiveTimeout(requestMessage);

	TemporaryReplyChannel tempReplyChannel = new TemporaryReplyChannel(this.throwExceptionOnLateReply);
	requestMessage = MessageBuilder.fromMessage(requestMessage).setReplyChannel(tempReplyChannel)
			.setHeader(this.sendTimeoutHeader, null)
			.setHeader(this.receiveTimeoutHeader, null)
			.setErrorChannel(tempReplyChannel).build();

	try {
		doSend(channel, requestMessage, sendTimeout);
	}
	catch (RuntimeException ex) {
		tempReplyChannel.setSendFailed(true);
		throw ex;
	}

	Message<?> replyMessage = this.doReceive(tempReplyChannel, receiveTimeout);
	if (replyMessage != null) {
		replyMessage = MessageBuilder.fromMessage(replyMessage)
				.setHeader(MessageHeaders.REPLY_CHANNEL, originalReplyChannelHeader)
				.setHeader(MessageHeaders.ERROR_CHANNEL, originalErrorChannelHeader)
				.build();
	}

	return replyMessage;
}
 
Example #27
Source File: MessageConverterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void canConvertFromStrictContentTypeMatch() {
	this.converter = new TestMessageConverter(Arrays.asList(MimeTypeUtils.TEXT_PLAIN));
	this.converter.setStrictContentTypeMatch(true);

	Message<String> message = MessageBuilder.withPayload("ABC").build();
	assertFalse(this.converter.canConvertFrom(message, String.class));

	message = MessageBuilder.withPayload("ABC")
			.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.TEXT_PLAIN).build();
	assertTrue(this.converter.canConvertFrom(message, String.class));

}
 
Example #28
Source File: MessageBuilder.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * A shortcut factory method for creating a message with the given payload
 * and {@code MessageHeaders}.
 * <p><strong>Note:</strong> the given {@code MessageHeaders} instance is used
 * directly in the new message, i.e. it is not copied.
 * @param payload the payload to use (never {@code null})
 * @param messageHeaders the headers to use (never {@code null})
 * @return the created message
 * @since 4.1
 */
@SuppressWarnings("unchecked")
public static <T> Message<T> createMessage(T payload, MessageHeaders messageHeaders) {
	Assert.notNull(payload, "Payload must not be null");
	Assert.notNull(messageHeaders, "MessageHeaders must not be null");
	if (payload instanceof Throwable) {
		return (Message<T>) new ErrorMessage((Throwable) payload, messageHeaders);
	}
	else {
		return new GenericMessage<T>(payload, messageHeaders);
	}
}
 
Example #29
Source File: StompHeaderAccessorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void messageIdAndTimestampDefaultBehavior() {
	StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.SEND);
	MessageHeaders headers = headerAccessor.getMessageHeaders();

	assertNull(headers.getId());
	assertNull(headers.getTimestamp());
}
 
Example #30
Source File: BigQueryFileMessageHandlerIntegrationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadFile() throws InterruptedException, ExecutionException {
	HashMap<String, Object> messageHeaders = new HashMap<>();
	this.messageHandler.setTableName(TABLE_NAME);
	this.messageHandler.setFormatOptions(FormatOptions.csv());

	Message<File> message = MessageBuilder.createMessage(
			new File("src/test/resources/data.csv"),
			new MessageHeaders(messageHeaders));

	ListenableFuture<Job> jobFuture =
			(ListenableFuture<Job>) this.messageHandler.handleRequestMessage(message);

	// Assert that a BigQuery polling task is scheduled successfully.
	await().atMost(Duration.FIVE_SECONDS)
			.untilAsserted(
					() -> assertThat(
							this.taskScheduler.getScheduledThreadPoolExecutor().getQueue()).hasSize(1));
	jobFuture.get();

	QueryJobConfiguration queryJobConfiguration = QueryJobConfiguration
			.newBuilder("SELECT * FROM test_dataset.test_table").build();
	TableResult result = this.bigquery.query(queryJobConfiguration);

	assertThat(result.getTotalRows()).isEqualTo(1);
	assertThat(
			result.getValues().iterator().next().get("State").getStringValue()).isEqualTo("Alabama");

	// This asserts that the BigQuery job polling task is no longer in the scheduler.
	assertThat(this.taskScheduler.getScheduledThreadPoolExecutor().getQueue()).hasSize(0);
}