Java Code Examples for org.springframework.messaging.Message#getHeaders()

The following examples show how to use org.springframework.messaging.Message#getHeaders() . 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: UserDestinationMessageHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public void handleUnresolved(Message<?> message) {
	MessageHeaders headers = message.getHeaders();
	if (SimpMessageHeaderAccessor.getFirstNativeHeader(
			SimpMessageHeaderAccessor.ORIGINAL_DESTINATION, headers) != null) {
		// Re-broadcast
		return;
	}
	SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.wrap(message);
	String destination = accessor.getDestination();
	accessor.setNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION, destination);
	accessor.setLeaveMutable(true);
	message = MessageBuilder.createMessage(message.getPayload(), accessor.getMessageHeaders());
	if (logger.isTraceEnabled()) {
		logger.trace("Translated " + destination + " -> " + getBroadcastDestination());
	}
	this.messagingTemplate.send(getBroadcastDestination(), message);
}
 
Example 2
Source File: DefaultUserDestinationResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Nullable
private ParseResult parse(Message<?> message) {
	MessageHeaders headers = message.getHeaders();
	String sourceDestination = SimpMessageHeaderAccessor.getDestination(headers);
	if (sourceDestination == null || !checkDestination(sourceDestination, this.prefix)) {
		return null;
	}
	SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
	if (messageType != null) {
		switch (messageType) {
			case SUBSCRIBE:
			case UNSUBSCRIBE:
				return parseSubscriptionMessage(message, sourceDestination);
			case MESSAGE:
				return parseMessage(headers, sourceDestination);
		}
	}
	return null;
}
 
Example 3
Source File: DefaultUserDestinationResolver.java    From spring-analysis-note 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 4
Source File: DefaultUserDestinationResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Nullable
private ParseResult parse(Message<?> message) {
	MessageHeaders headers = message.getHeaders();
	String sourceDestination = SimpMessageHeaderAccessor.getDestination(headers);
	if (sourceDestination == null || !checkDestination(sourceDestination, this.prefix)) {
		return null;
	}
	SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
	if (messageType != null) {
		switch (messageType) {
			case SUBSCRIBE:
			case UNSUBSCRIBE:
				return parseSubscriptionMessage(message, sourceDestination);
			case MESSAGE:
				return parseMessage(headers, sourceDestination);
		}
	}
	return null;
}
 
Example 5
Source File: UserDestinationMessageHandler.java    From java-technology-stack with MIT License 6 votes vote down vote up
public void handleUnresolved(Message<?> message) {
	MessageHeaders headers = message.getHeaders();
	if (SimpMessageHeaderAccessor.getFirstNativeHeader(
			SimpMessageHeaderAccessor.ORIGINAL_DESTINATION, headers) != null) {
		// Re-broadcast
		return;
	}
	SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.wrap(message);
	String destination = accessor.getDestination();
	accessor.setNativeHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION, destination);
	accessor.setLeaveMutable(true);
	message = MessageBuilder.createMessage(message.getPayload(), accessor.getMessageHeaders());
	if (logger.isTraceEnabled()) {
		logger.trace("Translated " + destination + " -> " + getBroadcastDestination());
	}
	this.messagingTemplate.send(getBroadcastDestination(), message);
}
 
Example 6
Source File: LocalTransactionRocketMQListener.java    From fw-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 执行本地事务
 * @param message 消息
 * @param o 额外参数
 * @return RocketMQ事务状态
 */
@Override
public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
    MessageHeaders headers = message.getHeaders();
    String transicationId = (String) headers.get(RocketMQHeaders.TRANSACTION_ID);

    try {
        FwTradeLog tradeLog = (FwTradeLog) o;
        orderService.payOrder(tradeLog,transicationId); // 对应图中第3步,执行本地事务
        log.info("本地事务=>{} 执行成功,往RocketMQ发送COMMIT",transicationId);
        return RocketMQLocalTransactionState.COMMIT; // 对应图中第4步,COMMIT,半消息经过COMMIT后,消息消费端就可以消费这条消息了
    } catch (Exception e){
        log.info("本地事务=>{} 回滚,往RocketMQ发送ROLLBACK",transicationId ,e);
        return RocketMQLocalTransactionState.ROLLBACK; // 对应途中第4步,ROLLBACK
    }
}
 
Example 7
Source File: AbstractSubscriptionRegistry.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public final MultiValueMap<String, String> findSubscriptions(Message<?> message) {
	MessageHeaders headers = message.getHeaders();

	SimpMessageType type = SimpMessageHeaderAccessor.getMessageType(headers);
	if (!SimpMessageType.MESSAGE.equals(type)) {
		throw new IllegalArgumentException("Unexpected message type: " + type);
	}

	String destination = SimpMessageHeaderAccessor.getDestination(headers);
	if (destination == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No destination in " + message);
		}
		return EMPTY_MAP;
	}

	return findSubscriptionsInternal(destination, message);
}
 
Example 8
Source File: MessagingMessageListenerAdapterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void headerConversionLazilyInvoked() throws JMSException {
	javax.jms.Message jmsMessage = mock(javax.jms.Message.class);
	when(jmsMessage.getPropertyNames()).thenThrow(new IllegalArgumentException("Header failure"));
	MessagingMessageListenerAdapter listener = getSimpleInstance("simple", Message.class);
	Message<?> message = listener.toMessagingMessage(jmsMessage);

	this.thrown.expect(IllegalArgumentException.class);
	this.thrown.expectMessage("Header failure");
	message.getHeaders(); // Triggers headers resolution
}
 
Example 9
Source File: SubscriptionMethodReturnValueHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, Message<?> message)
		throws Exception {

	if (returnValue == null) {
		return;
	}

	MessageHeaders headers = message.getHeaders();
	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
	String destination = SimpMessageHeaderAccessor.getDestination(headers);

	if (subscriptionId == null) {
		throw new IllegalStateException("No simpSubscriptionId in " + message +
				" returned by: " + returnType.getMethod());
	}
	if (destination == null) {
		throw new IllegalStateException("No simpDestination in " + message +
				" returned by: " + returnType.getMethod());
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Reply to @SubscribeMapping: " + returnValue);
	}
	MessageHeaders headersToSend = createHeaders(sessionId, subscriptionId, returnType);
	this.messagingTemplate.convertAndSend(destination, returnValue, headersToSend);
}
 
Example 10
Source File: MessagingMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public javax.jms.Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
	if (!(object instanceof Message)) {
		throw new IllegalArgumentException("Could not convert [" + object + "] - only [" +
				Message.class.getName() + "] is handled by this converter");
	}
	Message<?> input = (Message<?>) object;
	MessageHeaders headers = input.getHeaders();
	Object conversionHint = headers.get(AbstractMessagingTemplate.CONVERSION_HINT_HEADER);
	javax.jms.Message reply = createMessageForPayload(input.getPayload(), session, conversionHint);
	this.headerMapper.fromHeaders(headers, reply);
	return reply;
}
 
Example 11
Source File: UserRegistryMessageHandlerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void broadcastRegistry() throws Exception {

	TestSimpUser simpUser1 = new TestSimpUser("joe");
	TestSimpUser simpUser2 = new TestSimpUser("jane");

	simpUser1.addSessions(new TestSimpSession("123"));
	simpUser1.addSessions(new TestSimpSession("456"));

	HashSet<SimpUser> simpUsers = new HashSet<>(Arrays.asList(simpUser1, simpUser2));
	given(this.localRegistry.getUsers()).willReturn(simpUsers);

	getUserRegistryTask().run();

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	verify(this.brokerChannel).send(captor.capture());

	Message<?> message = captor.getValue();
	assertNotNull(message);
	MessageHeaders headers = message.getHeaders();
	assertEquals("/topic/simp-user-registry", SimpMessageHeaderAccessor.getDestination(headers));

	MultiServerUserRegistry remoteRegistry = new MultiServerUserRegistry(mock(SimpUserRegistry.class));
	remoteRegistry.addRemoteRegistryDto(message, this.converter, 20000);
	assertEquals(2, remoteRegistry.getUserCount());
	assertNotNull(remoteRegistry.getUser("joe"));
	assertNotNull(remoteRegistry.getUser("jane"));
}
 
Example 12
Source File: AbstractSubscriptionRegistry.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public final void unregisterSubscription(Message<?> message) {
	MessageHeaders headers = message.getHeaders();

	SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
	if (!SimpMessageType.UNSUBSCRIBE.equals(messageType)) {
		throw new IllegalArgumentException("Expected UNSUBSCRIBE: " + message);
	}

	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	if (sessionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No sessionId in " + message);
		}
		return;
	}

	String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
	if (subscriptionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No subscriptionId " + message);
		}
		return;
	}

	removeSubscriptionInternal(sessionId, subscriptionId, message);
}
 
Example 13
Source File: DestinationVariableMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
@SuppressWarnings("unchecked")
protected Object resolveArgumentInternal(MethodParameter parameter, Message<?> message, String name) {
	MessageHeaders headers = message.getHeaders();
	Map<String, String> vars = (Map<String, String>) headers.get(DESTINATION_TEMPLATE_VARIABLES_HEADER);
	return vars != null ? vars.get(name) : null;
}
 
Example 14
Source File: UserRegistryMessageHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void broadcastRegistry() throws Exception {

	TestSimpUser simpUser1 = new TestSimpUser("joe");
	TestSimpUser simpUser2 = new TestSimpUser("jane");

	simpUser1.addSessions(new TestSimpSession("123"));
	simpUser1.addSessions(new TestSimpSession("456"));

	HashSet<SimpUser> simpUsers = new HashSet<>(Arrays.asList(simpUser1, simpUser2));
	when(this.localRegistry.getUsers()).thenReturn(simpUsers);

	getUserRegistryTask().run();

	ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
	verify(this.brokerChannel).send(captor.capture());

	Message<?> message = captor.getValue();
	assertNotNull(message);
	MessageHeaders headers = message.getHeaders();
	assertEquals("/topic/simp-user-registry", SimpMessageHeaderAccessor.getDestination(headers));

	MultiServerUserRegistry remoteRegistry = new MultiServerUserRegistry(mock(SimpUserRegistry.class));
	remoteRegistry.addRemoteRegistryDto(message, this.converter, 20000);
	assertEquals(2, remoteRegistry.getUserCount());
	assertNotNull(remoteRegistry.getUser("joe"));
	assertNotNull(remoteRegistry.getUser("jane"));
}
 
Example 15
Source File: AbstractSubscriptionRegistry.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public final void unregisterSubscription(Message<?> message) {
	MessageHeaders headers = message.getHeaders();

	SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
	if (!SimpMessageType.UNSUBSCRIBE.equals(messageType)) {
		throw new IllegalArgumentException("Expected UNSUBSCRIBE: " + message);
	}

	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	if (sessionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No sessionId in " + message);
		}
		return;
	}

	String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
	if (subscriptionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No subscriptionId " + message);
		}
		return;
	}

	removeSubscriptionInternal(sessionId, subscriptionId, message);
}
 
Example 16
Source File: AbstractSubscriptionRegistry.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public final void registerSubscription(Message<?> message) {
	MessageHeaders headers = message.getHeaders();

	SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
	if (!SimpMessageType.SUBSCRIBE.equals(messageType)) {
		throw new IllegalArgumentException("Expected SUBSCRIBE: " + message);
	}

	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	if (sessionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No sessionId in  " + message);
		}
		return;
	}

	String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
	if (subscriptionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No subscriptionId in " + message);
		}
		return;
	}

	String destination = SimpMessageHeaderAccessor.getDestination(headers);
	if (destination == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No destination in " + message);
		}
		return;
	}

	addSubscriptionInternal(sessionId, subscriptionId, destination, message);
}
 
Example 17
Source File: AbstractSubscriptionRegistry.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public final void registerSubscription(Message<?> message) {
	MessageHeaders headers = message.getHeaders();

	SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
	if (!SimpMessageType.SUBSCRIBE.equals(messageType)) {
		throw new IllegalArgumentException("Expected SUBSCRIBE: " + message);
	}

	String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
	if (sessionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No sessionId in  " + message);
		}
		return;
	}

	String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
	if (subscriptionId == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No subscriptionId in " + message);
		}
		return;
	}

	String destination = SimpMessageHeaderAccessor.getDestination(headers);
	if (destination == null) {
		if (logger.isErrorEnabled()) {
			logger.error("No destination in " + message);
		}
		return;
	}

	addSubscriptionInternal(sessionId, subscriptionId, destination, message);
}
 
Example 18
Source File: MessageHeaderAccessor.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Return a mutable {@code MessageHeaderAccessor} for the given message attempting
 * to match the type of accessor used to create the message headers, or otherwise
 * wrapping the message with a {@code MessageHeaderAccessor} instance.
 * <p>This is for cases where a header needs to be updated in generic code
 * while preserving the accessor type for downstream processing.
 * @return an accessor of the required type (never {@code null})
 * @since 4.1
 */
public static MessageHeaderAccessor getMutableAccessor(Message<?> message) {
	if (message.getHeaders() instanceof MutableMessageHeaders) {
		MutableMessageHeaders mutableHeaders = (MutableMessageHeaders) message.getHeaders();
		MessageHeaderAccessor accessor = mutableHeaders.getAccessor();
		return (accessor.isMutable() ? accessor : accessor.createAccessor(message));
	}
	return new MessageHeaderAccessor(message);
}
 
Example 19
Source File: MessageHeaderAccessor.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Return a mutable {@code MessageHeaderAccessor} for the given message attempting
 * to match the type of accessor used to create the message headers, or otherwise
 * wrapping the message with a {@code MessageHeaderAccessor} instance.
 * <p>This is for cases where a header needs to be updated in generic code
 * while preserving the accessor type for downstream processing.
 * @return an accessor of the required type (never {@code null})
 * @since 4.1
 */
public static MessageHeaderAccessor getMutableAccessor(Message<?> message) {
	if (message.getHeaders() instanceof MutableMessageHeaders) {
		MutableMessageHeaders mutableHeaders = (MutableMessageHeaders) message.getHeaders();
		MessageHeaderAccessor accessor = mutableHeaders.getAccessor();
		return (accessor.isMutable() ? accessor : accessor.createAccessor(message));
	}
	return new MessageHeaderAccessor(message);
}
 
Example 20
Source File: MessageHeaderAccessor.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * A constructor accepting the headers of an existing message to copy.
 * @param message a message to copy the headers from, or {@code null} if none
 */
public MessageHeaderAccessor(@Nullable Message<?> message) {
	this.headers = new MutableMessageHeaders(message != null ? message.getHeaders() : null);
}