org.springframework.messaging.support.MessageHeaderAccessor Java Examples

The following examples show how to use org.springframework.messaging.support.MessageHeaderAccessor. 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: WebSocketInterceptor.java    From xechat with MIT License 7 votes vote down vote up
/**
 * 绑定用户信息
 *
 * @param message
 * @param channel
 * @return
 */
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
    log.debug("进入拦截器 -> preSend");
    StompHeaderAccessor stompHeaderAccessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);

    if (StompCommand.CONNECT.equals(stompHeaderAccessor.getCommand())) {
        User user = new User();
        user.setUserId(UUIDUtils.create());
        user.setUsername(SensitiveWordUtils.loveChina(stompHeaderAccessor.getFirstNativeHeader("username")));
        user.setAvatar(stompHeaderAccessor.getFirstNativeHeader("avatar"));
        user.setAddress(stompHeaderAccessor.getFirstNativeHeader("address"));
        user.setStatus(UserStatusConstant.ONLINE);

        stompHeaderAccessor.setUser(user);
        log.debug("绑定用户信息 -> {}", user);
    }

    return message;
}
 
Example #2
Source File: SimpMessagingTemplateTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void convertAndSendWithCustomDestinationPrefix() {
	this.messagingTemplate.setUserDestinationPrefix("/prefix");
	this.messagingTemplate.convertAndSendToUser("joe", "/queue/foo", "data");
	List<Message<byte[]>> messages = this.messageChannel.getMessages();

	assertEquals(1, messages.size());

	Message<byte[]> message = messages.get(0);
	SimpMessageHeaderAccessor headerAccessor =
			MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class);

	assertNotNull(headerAccessor);
	assertEquals(SimpMessageType.MESSAGE, headerAccessor.getMessageType());
	assertEquals("/prefix/joe/queue/foo", headerAccessor.getDestination());
}
 
Example #3
Source File: StompSubProtocolHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * The simple broker produces {@code SimpMessageType.CONNECT_ACK} that's not STOMP
 * specific and needs to be turned into a STOMP CONNECTED frame.
 */
private StompHeaderAccessor convertConnectAcktoStompConnected(StompHeaderAccessor connectAckHeaders) {
	String name = StompHeaderAccessor.CONNECT_MESSAGE_HEADER;
	Message<?> message = (Message<?>) connectAckHeaders.getHeader(name);
	Assert.notNull(message, "Original STOMP CONNECT not found in " + connectAckHeaders);
	StompHeaderAccessor connectHeaders = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	StompHeaderAccessor connectedHeaders = StompHeaderAccessor.create(StompCommand.CONNECTED);
	Set<String> acceptVersions = connectHeaders.getAcceptVersion();
	if (acceptVersions.contains("1.2")) {
		connectedHeaders.setVersion("1.2");
	}
	else if (acceptVersions.contains("1.1")) {
		connectedHeaders.setVersion("1.1");
	}
	else if (!acceptVersions.isEmpty()) {
		throw new IllegalArgumentException("Unsupported STOMP version '" + acceptVersions + "'");
	}
	long[] heartbeat = (long[]) connectAckHeaders.getHeader(SimpMessageHeaderAccessor.HEART_BEAT_HEADER);
	if (heartbeat != null) {
		connectedHeaders.setHeartbeat(heartbeat[0], heartbeat[1]);
	}
	else {
		connectedHeaders.setHeartbeat(0, 0);
	}
	return connectedHeaders;
}
 
Example #4
Source File: MessageMappingMessageHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected Mono<Void> handleMatch(CompositeMessageCondition mapping, HandlerMethod handlerMethod, Message<?> message) {
	Set<String> patterns = mapping.getCondition(DestinationPatternsMessageCondition.class).getPatterns();
	if (!CollectionUtils.isEmpty(patterns)) {
		String pattern = patterns.iterator().next();
		String destination = getDestination(message);
		Assert.state(destination != null, "Missing destination header");
		Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(pattern, destination);
		if (!CollectionUtils.isEmpty(vars)) {
			MessageHeaderAccessor mha = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
			Assert.state(mha != null && mha.isMutable(), "Mutable MessageHeaderAccessor required");
			mha.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars);
		}
	}
	return super.handleMatch(mapping, handlerMethod, message);
}
 
Example #5
Source File: SimpMessagingTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void convertAndSendWithCustomDestinationPrefix() {
	this.messagingTemplate.setUserDestinationPrefix("/prefix");
	this.messagingTemplate.convertAndSendToUser("joe", "/queue/foo", "data");
	List<Message<byte[]>> messages = this.messageChannel.getMessages();

	assertEquals(1, messages.size());

	Message<byte[]> message = messages.get(0);
	SimpMessageHeaderAccessor headerAccessor =
			MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class);

	assertNotNull(headerAccessor);
	assertEquals(SimpMessageType.MESSAGE, headerAccessor.getMessageType());
	assertEquals("/prefix/joe/queue/foo", headerAccessor.getDestination());
}
 
Example #6
Source File: SimpAnnotationMethodMessageHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected void handleMatch(SimpMessageMappingInfo mapping, HandlerMethod handlerMethod,
		String lookupDestination, Message<?> message) {

	Set<String> patterns = mapping.getDestinationConditions().getPatterns();
	if (!CollectionUtils.isEmpty(patterns)) {
		String pattern = patterns.iterator().next();
		Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(pattern, lookupDestination);
		if (!CollectionUtils.isEmpty(vars)) {
			MessageHeaderAccessor mha = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
			Assert.state(mha != null && mha.isMutable(), "Mutable MessageHeaderAccessor required");
			mha.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars);
		}
	}

	try {
		SimpAttributesContextHolder.setAttributesFromMessage(message);
		super.handleMatch(mapping, handlerMethod, lookupDestination, message);
	}
	finally {
		SimpAttributesContextHolder.resetAttributes();
	}
}
 
Example #7
Source File: StompBrokerRelayMessageHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void handleMessage(Message<byte[]> message) {
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	Assert.state(accessor != null, "No StompHeaderAccessor");
	accessor.setSessionId(this.sessionId);
	Principal user = this.connectHeaders.getUser();
	if (user != null) {
		accessor.setUser(user);
	}

	StompCommand command = accessor.getCommand();
	if (StompCommand.CONNECTED.equals(command)) {
		if (logger.isDebugEnabled()) {
			logger.debug("Received " + accessor.getShortLogMessage(EMPTY_PAYLOAD));
		}
		afterStompConnected(accessor);
	}
	else if (logger.isErrorEnabled() && StompCommand.ERROR.equals(command)) {
		logger.error("Received " + accessor.getShortLogMessage(message.getPayload()));
	}
	else if (logger.isTraceEnabled()) {
		logger.trace("Received " + accessor.getDetailedLogMessage(message.getPayload()));
	}

	handleInboundMessage(message);
}
 
Example #8
Source File: GenericMessagingTemplate.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected final void doSend(MessageChannel channel, Message<?> message, long timeout) {
	Assert.notNull(channel, "MessageChannel is required");

	Message<?> messageToSend = message;
	MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
	if (accessor != null && accessor.isMutable()) {
		accessor.removeHeader(this.sendTimeoutHeader);
		accessor.removeHeader(this.receiveTimeoutHeader);
		accessor.setImmutable();
	}
	else if (message.getHeaders().containsKey(this.sendTimeoutHeader)
			|| message.getHeaders().containsKey(this.receiveTimeoutHeader)) {
		messageToSend = MessageBuilder.fromMessage(message)
				.setHeader(this.sendTimeoutHeader, null)
				.setHeader(this.receiveTimeoutHeader, null)
				.build();
	}

	boolean sent = (timeout >= 0 ? channel.send(messageToSend, timeout) : channel.send(messageToSend));

	if (!sent) {
		throw new MessageDeliveryException(message,
				"Failed to send message to channel '" + channel + "' within timeout: " + timeout);
	}
}
 
Example #9
Source File: StompSubProtocolHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private void handleError(WebSocketSession session, Throwable ex, Message<byte[]> clientMessage) {
	if (getErrorHandler() == null) {
		sendErrorMessage(session, ex);
		return;
	}

	Message<byte[]> message = getErrorHandler().handleClientMessageProcessingError(clientMessage, ex);
	if (message == null) {
		return;
	}

	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	Assert.notNull(accessor, "Expected STOMP headers");
	sendToClient(session, accessor, message.getPayload());
}
 
Example #10
Source File: SendToMethodReturnValueHandlerTests.java    From java-technology-stack 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 #11
Source File: StompBrokerRelayMessageHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void handleMessage(Message<byte[]> message) {
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	Assert.state(accessor != null, "No StompHeaderAccessor");
	accessor.setSessionId(this.sessionId);
	Principal user = this.connectHeaders.getUser();
	if (user != null) {
		accessor.setUser(user);
	}

	StompCommand command = accessor.getCommand();
	if (StompCommand.CONNECTED.equals(command)) {
		if (logger.isDebugEnabled()) {
			logger.debug("Received " + accessor.getShortLogMessage(EMPTY_PAYLOAD));
		}
		afterStompConnected(accessor);
	}
	else if (logger.isErrorEnabled() && StompCommand.ERROR.equals(command)) {
		logger.error("Received " + accessor.getShortLogMessage(message.getPayload()));
	}
	else if (logger.isTraceEnabled()) {
		logger.trace("Received " + accessor.getDetailedLogMessage(message.getPayload()));
	}

	handleInboundMessage(message);
}
 
Example #12
Source File: SimpAnnotationMethodMessageHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void handleMatch(SimpMessageMappingInfo mapping, HandlerMethod handlerMethod,
		String lookupDestination, Message<?> message) {

	Set<String> patterns = mapping.getDestinationConditions().getPatterns();
	if (!CollectionUtils.isEmpty(patterns)) {
		String pattern = patterns.iterator().next();
		Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(pattern, lookupDestination);
		if (!CollectionUtils.isEmpty(vars)) {
			MessageHeaderAccessor mha = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
			Assert.state(mha != null && mha.isMutable(), "Mutable MessageHeaderAccessor required");
			mha.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars);
		}
	}

	try {
		SimpAttributesContextHolder.setAttributesFromMessage(message);
		super.handleMatch(mapping, handlerMethod, lookupDestination, message);
	}
	finally {
		SimpAttributesContextHolder.resetAttributes();
	}
}
 
Example #13
Source File: TracingChannelInterceptor.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
private Message<?> outputMessage(Message<?> originalMessage,
		Message<?> retrievedMessage, MessageHeaderAccessor additionalHeaders) {
	MessageHeaderAccessor headers = MessageHeaderAccessor
			.getMutableAccessor(originalMessage);
	if (originalMessage instanceof ErrorMessage) {
		ErrorMessage errorMessage = (ErrorMessage) originalMessage;
		headers.copyHeaders(MessageHeaderPropagation.propagationHeaders(
				additionalHeaders.getMessageHeaders(),
				this.tracing.propagation().keys()));
		return new ErrorMessage(errorMessage.getPayload(),
				isWebSockets(headers) ? headers.getMessageHeaders()
						: new MessageHeaders(headers.getMessageHeaders()),
				errorMessage.getOriginalMessage());
	}
	headers.copyHeaders(additionalHeaders.getMessageHeaders());
	return new GenericMessage<>(retrievedMessage.getPayload(),
			isWebSockets(headers) ? headers.getMessageHeaders()
					: new MessageHeaders(headers.getMessageHeaders()));
}
 
Example #14
Source File: DefaultSubscriptionRegistry.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
	MessageHeaders headers = (MessageHeaders) target;
	SimpMessageHeaderAccessor accessor =
			MessageHeaderAccessor.getAccessor(headers, SimpMessageHeaderAccessor.class);
	Object value;
	if ("destination".equalsIgnoreCase(name)) {
		value = accessor.getDestination();
	}
	else {
		value = accessor.getFirstNativeHeader(name);
		if (value == null) {
			value = headers.get(name);
		}
	}
	return new TypedValue(value);
}
 
Example #15
Source File: DefaultStompSessionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void unsubscribe() throws Exception {

	this.session.afterConnected(this.connection);
	assertTrue(this.session.isConnected());

	String destination = "/topic/foo";
	StompFrameHandler frameHandler = mock(StompFrameHandler.class);
	Subscription subscription = this.session.subscribe(destination, frameHandler);
	subscription.unsubscribe();

	Message<byte[]> message = this.messageCaptor.getValue();
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertEquals(StompCommand.UNSUBSCRIBE, accessor.getCommand());

	StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
	assertEquals(stompHeaders.toString(), 1, stompHeaders.size());
	assertEquals(subscription.getSubscriptionId(), stompHeaders.getId());
}
 
Example #16
Source File: WebSocketStompClientTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
public void handleWebSocketMessage() throws Exception {
	String text = "SEND\na:alpha\n\nMessage payload\0";
	connect().handleMessage(this.webSocketSession, new TextMessage(text));

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	verify(this.stompSession).handleMessage(captor.capture());
	Message<byte[]> message = captor.getValue();
	assertNotNull(message);

	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap());
	assertEquals(StompCommand.SEND, accessor.getCommand());
	assertEquals("alpha", headers.getFirst("a"));
	assertEquals("Message payload", new String(message.getPayload(), StandardCharsets.UTF_8));
}
 
Example #17
Source File: DefaultStompSessionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void send() {
	this.session.afterConnected(this.connection);
	assertTrue(this.session.isConnected());

	String destination = "/topic/foo";
	String payload = "sample payload";
	this.session.send(destination, payload);

	Message<byte[]> message = this.messageCaptor.getValue();
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertEquals(StompCommand.SEND, accessor.getCommand());

	StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
	assertEquals(stompHeaders.toString(), 2, stompHeaders.size());

	assertEquals(destination, stompHeaders.getDestination());
	assertEquals(new MimeType("text", "plain", StandardCharsets.UTF_8), stompHeaders.getContentType());
	assertEquals(-1, stompHeaders.getContentLength());  // StompEncoder isn't involved
	assertEquals(payload, new String(message.getPayload(), StandardCharsets.UTF_8));
}
 
Example #18
Source File: DefaultStompSessionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void sendWithReceipt() {
	this.session.afterConnected(this.connection);
	assertTrue(this.session.isConnected());

	this.session.setTaskScheduler(mock(TaskScheduler.class));
	this.session.setAutoReceipt(true);
	this.session.send("/topic/foo", "sample payload");

	Message<byte[]> message = this.messageCaptor.getValue();
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertNotNull(accessor.getReceipt());

	StompHeaders stompHeaders = new StompHeaders();
	stompHeaders.setDestination("/topic/foo");
	stompHeaders.setReceipt("my-receipt");
	this.session.send(stompHeaders, "sample payload");

	message = this.messageCaptor.getValue();
	accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertEquals("my-receipt", accessor.getReceipt());
}
 
Example #19
Source File: SimpMessagingTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void convertAndSendWithCustomHeaderNonNative() {
	Map<String, Object> headers = new HashMap<>();
	headers.put("key", "value");
	headers.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, new LinkedMultiValueMap<String, String>());
	this.messagingTemplate.convertAndSend("/foo", "data", headers);

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

	SimpMessageHeaderAccessor headerAccessor =
			MessageHeaderAccessor.getAccessor(messages.get(0), SimpMessageHeaderAccessor.class);

	assertNotNull(headerAccessor);
	assertEquals("value", headerAccessor.toMap().get("key"));
	assertNull(headerAccessor.getNativeHeader("key"));
}
 
Example #20
Source File: DefaultStompSessionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void subscribe() throws Exception {

	this.session.afterConnected(this.connection);
	assertTrue(this.session.isConnected());

	String destination = "/topic/foo";
	StompFrameHandler frameHandler = mock(StompFrameHandler.class);
	Subscription subscription = this.session.subscribe(destination, frameHandler);

	Message<byte[]> message = this.messageCaptor.getValue();
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertEquals(StompCommand.SUBSCRIBE, accessor.getCommand());

	StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
	assertEquals(stompHeaders.toString(), 2, stompHeaders.size());
	assertEquals(destination, stompHeaders.getDestination());
	assertEquals(subscription.getSubscriptionId(), stompHeaders.getId());
}
 
Example #21
Source File: DefaultStompSessionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void nack() {
	this.session.afterConnected(this.connection);
	assertTrue(this.session.isConnected());

	String messageId = "123";
	this.session.acknowledge(messageId, false);

	Message<byte[]> message = this.messageCaptor.getValue();
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertEquals(StompCommand.NACK, accessor.getCommand());

	StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
	assertEquals(stompHeaders.toString(), 1, stompHeaders.size());
	assertEquals(messageId, stompHeaders.getId());
}
 
Example #22
Source File: AbstractMethodMessageHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(Message<?> message) throws MessagingException {
	String destination = getDestination(message);
	if (destination == null) {
		return;
	}
	String lookupDestination = getLookupDestination(destination);
	if (lookupDestination == null) {
		return;
	}
	MessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getMutableAccessor(message);
	headerAccessor.setHeader(DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER, lookupDestination);
	headerAccessor.setLeaveMutable(true);
	message = MessageBuilder.createMessage(message.getPayload(), headerAccessor.getMessageHeaders());

	if (logger.isDebugEnabled()) {
		logger.debug("Searching methods to handle " + headerAccessor.getShortLogMessage(message.getPayload()));
	}

	handleMessageInternal(message, lookupDestination);
	headerAccessor.setImmutable();
}
 
Example #23
Source File: DefaultStompSessionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void subscribe() {
	this.session.afterConnected(this.connection);
	assertTrue(this.session.isConnected());

	String destination = "/topic/foo";
	StompFrameHandler frameHandler = mock(StompFrameHandler.class);
	Subscription subscription = this.session.subscribe(destination, frameHandler);

	Message<byte[]> message = this.messageCaptor.getValue();
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertEquals(StompCommand.SUBSCRIBE, accessor.getCommand());

	StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
	assertEquals(stompHeaders.toString(), 2, stompHeaders.size());
	assertEquals(destination, stompHeaders.getDestination());
	assertEquals(subscription.getSubscriptionId(), stompHeaders.getId());
}
 
Example #24
Source File: WebSocketStompClientTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void handleWebSocketMessage() throws Exception {
	String text = "SEND\na:alpha\n\nMessage payload\0";
	connect().handleMessage(this.webSocketSession, new TextMessage(text));

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	verify(this.stompSession).handleMessage(captor.capture());
	Message<byte[]> message = captor.getValue();
	assertNotNull(message);

	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap());
	assertEquals(StompCommand.SEND, accessor.getCommand());
	assertEquals("alpha", headers.getFirst("a"));
	assertEquals("Message payload", new String(message.getPayload(), UTF_8));
}
 
Example #25
Source File: SimpMessagingTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void convertAndSendWithCustomHeaderNonNative() {
	Map<String, Object> headers = new HashMap<>();
	headers.put("key", "value");
	headers.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, new LinkedMultiValueMap<String, String>());
	this.messagingTemplate.convertAndSend("/foo", "data", headers);

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

	SimpMessageHeaderAccessor headerAccessor =
			MessageHeaderAccessor.getAccessor(messages.get(0), SimpMessageHeaderAccessor.class);

	assertNotNull(headerAccessor);
	assertEquals("value", headerAccessor.toMap().get("key"));
	assertNull(headerAccessor.getNativeHeader("key"));
}
 
Example #26
Source File: TracingChannelInterceptor.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
TracingChannelInterceptor(Tracing tracing,
		Propagation.Setter<MessageHeaderAccessor, String> setter,
		Propagation.Getter<MessageHeaderAccessor, String> getter) {
	this.tracing = tracing;
	this.tracer = tracing.tracer();
	this.threadLocalSpan = ThreadLocalSpan.create(this.tracer);
	this.injector = tracing.propagation().injector(setter);
	this.extractor = tracing.propagation().extractor(getter);
	this.integrationObjectSupportPresent = ClassUtils.isPresent(
			"org.springframework.integration.context.IntegrationObjectSupport", null);
	this.hasDirectChannelClass = ClassUtils
			.isPresent("org.springframework.integration.channel.DirectChannel", null);
	this.directWithAttributesChannelClass = ClassUtils
			.isPresent(STREAM_DIRECT_CHANNEL, null)
					? ClassUtils.resolveClassName(STREAM_DIRECT_CHANNEL, null) : null;
}
 
Example #27
Source File: DefaultStompSessionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void send() {
	this.session.afterConnected(this.connection);
	assertTrue(this.session.isConnected());

	String destination = "/topic/foo";
	String payload = "sample payload";
	this.session.send(destination, payload);

	Message<byte[]> message = this.messageCaptor.getValue();
	StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
	assertEquals(StompCommand.SEND, accessor.getCommand());

	StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
	assertEquals(stompHeaders.toString(), 2, stompHeaders.size());

	assertEquals(destination, stompHeaders.getDestination());
	assertEquals(new MimeType("text", "plain", StandardCharsets.UTF_8), stompHeaders.getContentType());
	assertEquals(-1, stompHeaders.getContentLength());  // StompEncoder isn't involved
	assertEquals(payload, new String(message.getPayload(), StandardCharsets.UTF_8));
}
 
Example #28
Source File: GenericMessagingTemplate.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected final void doSend(MessageChannel channel, Message<?> message) {
	Assert.notNull(channel, "'channel' is required");

	MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
	if (accessor != null && accessor.isMutable()) {
		accessor.setImmutable();
	}

	long timeout = this.sendTimeout;
	boolean sent = (timeout >= 0 ? channel.send(message, timeout) : channel.send(message));

	if (!sent) {
		throw new MessageDeliveryException(message,
				"failed to send message to channel '" + channel + "' within timeout: " + timeout);
	}
}
 
Example #29
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 #30
Source File: GenericMessagingTemplateTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void convertAndSendWithSimpMessageHeaders() {
	MessageHeaderAccessor accessor = new MessageHeaderAccessor();
	accessor.setHeader("key", "value");
	accessor.setLeaveMutable(true);
	MessageHeaders headers = accessor.getMessageHeaders();

	this.template.convertAndSend("channel", "data", headers);
	List<Message<byte[]>> messages = this.messageChannel.getMessages();
	Message<byte[]> message = messages.get(0);

	assertSame(headers, message.getHeaders());
	assertFalse(accessor.isMutable());
}