Merge pull request #512 from rstoyanchev/message-headers

Enhance MessageHeaderAccessor support and optimize message creation
This commit is contained in:
Rossen Stoyanchev
2014-04-13 18:52:05 -04:00
59 changed files with 2755 additions and 912 deletions

View File

@@ -24,7 +24,6 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -34,7 +33,6 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.AlternativeJdkIdGenerator;
import org.springframework.util.Assert;
import org.springframework.util.IdGenerator;
/**
@@ -70,10 +68,12 @@ import org.springframework.util.IdGenerator;
*/
public class MessageHeaders implements Map<String, Object>, Serializable {
private static final long serialVersionUID = -4615750558355702881L;
private static final long serialVersionUID = 7035068984263400920L;
private static final Log logger = LogFactory.getLog(MessageHeaders.class);
public static final UUID ID_VALUE_NONE = new UUID(0,0);
private static volatile IdGenerator idGenerator = null;
private static final IdGenerator defaultIdGenerator = new AlternativeJdkIdGenerator();
@@ -99,29 +99,43 @@ public class MessageHeaders implements Map<String, Object>, Serializable {
/**
* Consructs a {@link MessageHeaders} from the headers map; adding (or
* overwriting) the {@link #ID} and {@link #TIMESTAMP} headers.
* Construct a {@link MessageHeaders} with the given headers. An {@link #ID} and
* {@link #TIMESTAMP} headers will also be added, overriding any existing values.
*
* @param headers a map with headers to add
*/
public MessageHeaders(Map<String, Object> headers) {
this(headers, ((idGenerator != null) ? idGenerator : defaultIdGenerator).generateId(),
System.currentTimeMillis());
this(headers, null, null);
}
/**
* Constructor allowing a sub-class to access the (mutable) header map as well
* to provide the ID and TIMESTAMP header values.
* Constructor providing control over the ID and TIMESTAMP header values.
*
* @param headers a map with headers to add
* @param id the value for the {@link #ID} header, never {@code null}
* @param timestamp the value for the {@link #TIMESTAMP} header,
* or {@code null} meaning no timestamp header
* @param id the {@link #ID} header value
* @param timestamp the {@link #TIMESTAMP} header value
*/
protected MessageHeaders(Map<String, Object> headers, UUID id, Long timestamp) {
Assert.notNull(id, "'id' is required");
this.headers = (headers != null) ? new HashMap<String, Object>(headers) : new HashMap<String, Object>();
this.headers.put(ID, id);
if (timestamp != null) {
if (id == null) {
this.headers.put(ID, getIdGenerator().generateId());
}
else if (id == ID_VALUE_NONE) {
this.headers.remove(ID);
}
else {
this.headers.put(ID, id);
}
if (timestamp == null) {
this.headers.put(TIMESTAMP, System.currentTimeMillis());
}
else if (timestamp < 0) {
this.headers.remove(TIMESTAMP);
}
else {
this.headers.put(TIMESTAMP, timestamp);
}
}
@@ -131,6 +145,10 @@ public class MessageHeaders implements Map<String, Object>, Serializable {
return this.headers;
}
protected static IdGenerator getIdGenerator() {
return ((idGenerator != null) ? idGenerator : defaultIdGenerator);
}
public UUID getId() {
return this.get(ID, UUID.class);
}
@@ -179,10 +197,7 @@ public class MessageHeaders implements Map<String, Object>, Serializable {
@Override
public String toString() {
Map<String, Object> map = new LinkedHashMap<String, Object>(this.headers);
map.put(ID, map.remove(ID)); // remove and add again at the end
map.put(TIMESTAMP, map.remove(TIMESTAMP));
return map.toString();
return this.headers.toString();
}
/*

View File

@@ -27,6 +27,7 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.Assert;
import org.springframework.util.MimeType;
@@ -194,18 +195,27 @@ public abstract class AbstractMessageConverter implements MessageConverter {
@Override
public final Message<?> toMessage(Object payload, MessageHeaders headers) {
if (!canConvertTo(payload, headers)) {
return null;
}
payload = convertToInternal(payload, headers);
MimeType mimeType = getDefaultContentType(payload);
if (headers != null) {
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(headers, MessageHeaderAccessor.class);
if (accessor != null && accessor.isMutable()) {
accessor.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType);
return MessageBuilder.createMessage(payload, accessor.getMessageHeaders());
}
}
MessageBuilder<?> builder = MessageBuilder.withPayload(payload);
if (headers != null) {
builder.copyHeaders(headers);
}
MimeType mimeType = getDefaultContentType(payload);
if (mimeType != null) {
builder.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType);
}
builder.setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, mimeType);
return builder.build();
}

View File

@@ -19,6 +19,7 @@ package org.springframework.messaging.converter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.ClassUtils;
/**
@@ -44,7 +45,16 @@ public class SimpleMessageConverter implements MessageConverter {
@Override
public Message<?> toMessage(Object payload, MessageHeaders headers) {
return (payload != null ? MessageBuilder.withPayload(payload).copyHeaders(headers).build() : null);
if (payload == null) {
return null;
}
if (headers != null) {
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(headers, MessageHeaderAccessor.class);
if (accessor != null && accessor.isMutable()) {
return MessageBuilder.createMessage(payload, accessor.getMessageHeaders());
}
}
return MessageBuilder.withPayload(payload).copyHeaders(headers).build();
}
}

View File

@@ -108,8 +108,7 @@ public abstract class AbstractMessageSendingTemplate<D> implements MessageSendin
@Override
public void convertAndSend(D destination, Object payload, Map<String, Object> headers) throws MessagingException {
MessagePostProcessor postProcessor = null;
this.convertAndSend(destination, payload, headers, postProcessor);
this.convertAndSend(destination, payload, headers, null);
}
@Override
@@ -121,38 +120,49 @@ public abstract class AbstractMessageSendingTemplate<D> implements MessageSendin
public void convertAndSend(D destination, Object payload, MessagePostProcessor postProcessor)
throws MessagingException {
Map<String, Object> headers = null;
this.convertAndSend(destination, payload, headers, postProcessor);
this.convertAndSend(destination, payload, null, postProcessor);
}
@Override
public void convertAndSend(D destination, Object payload, Map<String, Object> headers,
MessagePostProcessor postProcessor) throws MessagingException {
MessageHeaders messageHeaders = null;
headers = processHeadersToSend(headers);
MessageHeaders messageHeaders = (headers != null) ? new MessageHeaders(headers) : null;
if (headers != null) {
if (headers instanceof MessageHeaders) {
messageHeaders = (MessageHeaders) headers;
}
else {
messageHeaders = new MessageHeaders(headers);
}
}
Message<?> message = this.converter.toMessage(payload, messageHeaders);
if (message == null) {
String payloadType = (payload != null) ? payload.getClass().getName() : null;
Object contentType = (messageHeaders != null) ? messageHeaders.get(MessageHeaders.CONTENT_TYPE) : null;
throw new MessageConversionException("Unable to convert payload type '"
+ payloadType + "', Content-Type=" + messageHeaders.get(MessageHeaders.CONTENT_TYPE)
+ ", converter=" + this.converter, null);
+ payloadType + "', Content-Type=" + contentType + ", converter=" + this.converter, null);
}
if (postProcessor != null) {
message = postProcessor.postProcessMessage(message);
}
this.send(destination, message);
}
/**
* Provides access to the map of headers before a send operation.
* Implementations can modify the headers by returning a different map.
* This implementation returns the map that was passed in (i.e. without any changes).
* Provides access to the map of input headers before a send operation. Sub-classes
* can modify the headers and then return the same or a different map.
*
* @param headers the headers to send, possibly {@code null}
* @return the actual headers to send
* <p>This default implementation in this class returns the input map.
*
* @param headers the headers to send or {@code null}.
* @return the actual headers to send or {@code null}.
*/
protected Map<String, Object> processHeadersToSend(Map<String, Object> headers) {
return headers;

View File

@@ -31,6 +31,7 @@ import org.springframework.messaging.MessageDeliveryException;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.Assert;
/**
@@ -110,6 +111,11 @@ public class GenericMessagingTemplate extends AbstractDestinationResolvingMessag
Assert.notNull(channel, "channel must not be null");
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);

View File

@@ -26,7 +26,7 @@ import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolver;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.ClassUtils;
import org.springframework.util.Assert;
import org.springframework.util.ReflectionUtils;
/**
@@ -42,7 +42,6 @@ import org.springframework.util.ReflectionUtils;
*/
public class HeadersMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
Class<?> paramType = parameter.getParameterType();
@@ -60,15 +59,23 @@ public class HeadersMethodArgumentResolver implements HandlerMethodArgumentResol
return message.getHeaders();
}
else if (MessageHeaderAccessor.class.equals(paramType)) {
return new MessageHeaderAccessor(message);
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
return (accessor != null ? accessor : new MessageHeaderAccessor(message));
}
else if (MessageHeaderAccessor.class.isAssignableFrom(paramType)) {
Method factoryMethod = ClassUtils.getMethod(paramType, "wrap", Message.class);
return ReflectionUtils.invokeMethod(factoryMethod, null, message);
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
if (accessor != null && paramType.isAssignableFrom(accessor.getClass())) {
return accessor;
}
else {
Method method = ReflectionUtils.findMethod(paramType, "wrap", Message.class);
Assert.notNull(method, "Cannot create accessor of type " + paramType + " for message " + message);
return ReflectionUtils.invokeMethod(method, null, message);
}
}
else {
throw new IllegalStateException("Unexpected method parameter type "
+ paramType + "in method " + parameter.getMethod() + ". "
throw new IllegalStateException(
"Unexpected method parameter type " + paramType + "in method " + parameter.getMethod() + ". "
+ "@Headers method arguments must be assignable to java.util.Map.");
}
}

View File

@@ -42,6 +42,7 @@ import org.springframework.messaging.handler.DestinationPatternsMessageCondition
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.messaging.handler.HandlerMethodSelector;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
@@ -321,6 +322,7 @@ public abstract class AbstractMethodMessageHandler<T>
@Override
public void handleMessage(Message<?> message) throws MessagingException {
String destination = getDestination(message);
if (destination == null) {
logger.trace("Ignoring message, no destination");
@@ -339,10 +341,13 @@ public abstract class AbstractMethodMessageHandler<T>
logger.debug("Handling message, lookupDestination=" + lookupDestination);
}
message = MessageBuilder.fromMessage(message).setHeader(
DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER, lookupDestination).build();
MessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getMutableAccessor(message);
headerAccessor.setHeader(DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER, lookupDestination);
headerAccessor.setLeaveMutable(true);
message = MessageBuilder.createMessage(message.getPayload(), headerAccessor.getMessageHeaders());
handleMessageInternal(message, lookupDestination);
headerAccessor.setImmutable();
}
protected abstract String getDestination(Message<?> message);

View File

@@ -0,0 +1,70 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.simp;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageHeaderAccessorFactorySupport;
import org.springframework.util.IdGenerator;
import java.util.UUID;
/**
* A default implementation of
* {@link org.springframework.messaging.simp.SimpMessageHeaderAccessorFactory}.
*
* @author Rossen Stoyanchev
* @since 4.1
*/
public class DefaultSimpMessageHeaderAccessorFactory extends MessageHeaderAccessorFactorySupport
implements SimpMessageHeaderAccessorFactory {
public DefaultSimpMessageHeaderAccessorFactory() {
super.setIdGenerator(ID_VALUE_NONE_GENERATOR);
}
@Override
public SimpMessageHeaderAccessor create() {
SimpMessageHeaderAccessor accessor = new SimpMessageHeaderAccessor(SimpMessageType.MESSAGE, null);
updateMessageHeaderAccessor(accessor);
return accessor;
}
@Override
public SimpMessageHeaderAccessor create(SimpMessageType messageType) {
SimpMessageHeaderAccessor accessor = new SimpMessageHeaderAccessor(messageType, null);
updateMessageHeaderAccessor(accessor);
return accessor;
}
@Override
public SimpMessageHeaderAccessor wrap(Message<?> message) {
SimpMessageHeaderAccessor accessor = new SimpMessageHeaderAccessor(message);
updateMessageHeaderAccessor(accessor);
return accessor;
}
private static final IdGenerator ID_VALUE_NONE_GENERATOR = new IdGenerator() {
@Override
public UUID generateId() {
return MessageHeaders.ID_VALUE_NONE;
}
};
}

View File

@@ -21,6 +21,8 @@ import java.util.List;
import java.util.Map;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.messaging.support.NativeMessageHeaderAccessor;
import org.springframework.util.Assert;
@@ -38,6 +40,10 @@ import org.springframework.util.Assert;
*/
public class SimpMessageHeaderAccessor extends NativeMessageHeaderAccessor {
private static final SimpMessageHeaderAccessorFactory factory = new DefaultSimpMessageHeaderAccessorFactory();
// SiMP header names
public static final String CONNECT_MESSAGE_HEADER = "simpConnectMessage";
public static final String DESTINATION_HEADER = "simpDestination";
@@ -83,25 +89,32 @@ public class SimpMessageHeaderAccessor extends NativeMessageHeaderAccessor {
/**
* Create {@link SimpMessageHeaderAccessor} for a new {@link Message} with
* {@link SimpMessageType#MESSAGE}.
* Create an instance with
* {@link org.springframework.messaging.simp.SimpMessageType} {@code MESSAGE}.
*/
public static SimpMessageHeaderAccessor create() {
return new SimpMessageHeaderAccessor(SimpMessageType.MESSAGE, null);
return factory.create();
}
/**
* Create {@link SimpMessageHeaderAccessor} for a new {@link Message} of a specific type.
* Create an instance with the given
* {@link org.springframework.messaging.simp.SimpMessageType}.
*/
public static SimpMessageHeaderAccessor create(SimpMessageType messageType) {
return new SimpMessageHeaderAccessor(messageType, null);
return factory.create(messageType);
}
/**
* Create {@link SimpMessageHeaderAccessor} from the headers of an existing message.
* Create an instance from the payload and headers of the given Message.
*/
public static SimpMessageHeaderAccessor wrap(Message<?> message) {
return new SimpMessageHeaderAccessor(message);
return factory.wrap(message);
}
@Override
protected MessageHeaderAccessor createAccessor(Message<?> message) {
return factory.wrap(message);
}
public void setMessageTypeIfNotSet(SimpMessageType messageType) {
@@ -117,6 +130,13 @@ public class SimpMessageHeaderAccessor extends NativeMessageHeaderAccessor {
return (SimpMessageType) getHeader(MESSAGE_TYPE_HEADER);
}
/**
* A static alternative for access to the message type.
*/
public static SimpMessageType getMessageType(Map<String, Object> headers) {
return (SimpMessageType) headers.get(MESSAGE_TYPE_HEADER);
}
public void setDestination(String destination) {
Assert.notNull(destination, "Destination must not be null");
setHeader(DESTINATION_HEADER, destination);
@@ -129,6 +149,17 @@ public class SimpMessageHeaderAccessor extends NativeMessageHeaderAccessor {
return (String) getHeader(DESTINATION_HEADER);
}
/**
* A static alternative for access to the destination header.
*/
public static String getDestination(Map<String, Object> headers) {
return (String) headers.get(DESTINATION_HEADER);
}
public void setSubscriptionId(String subscriptionId) {
setHeader(SUBSCRIPTION_ID_HEADER, subscriptionId);
}
/**
* @return the subscription id (if any) of the message
*/
@@ -136,8 +167,15 @@ public class SimpMessageHeaderAccessor extends NativeMessageHeaderAccessor {
return (String) getHeader(SUBSCRIPTION_ID_HEADER);
}
public void setSubscriptionId(String subscriptionId) {
setHeader(SUBSCRIPTION_ID_HEADER, subscriptionId);
/**
* A static alternative for access to the subscription id header.
*/
public static String getSubscriptionId(Map<String, Object> headers) {
return (String) headers.get(SUBSCRIPTION_ID_HEADER);
}
public void setSessionId(String sessionId) {
setHeader(SESSION_ID_HEADER, sessionId);
}
/**
@@ -147,8 +185,18 @@ public class SimpMessageHeaderAccessor extends NativeMessageHeaderAccessor {
return (String) getHeader(SESSION_ID_HEADER);
}
public void setSessionId(String sessionId) {
setHeader(SESSION_ID_HEADER, sessionId);
/**
* A static alternative for access to the session id header.
*/
public static String getSessionId(Map<String, Object> headers) {
return (String) headers.get(SESSION_ID_HEADER);
}
/**
* A static alternative for access to the session attributes header.
*/
public void setSessionAttributes(Map<String, Object> attributes) {
setHeader(SESSION_ATTRIBUTES, attributes);
}
/**
@@ -159,8 +207,16 @@ public class SimpMessageHeaderAccessor extends NativeMessageHeaderAccessor {
return (Map<String, Object>) getHeader(SESSION_ATTRIBUTES);
}
public void setSessionAttributes(Map<String, Object> attributes) {
setHeader(SESSION_ATTRIBUTES, attributes);
/**
* A static alternative for access to the session attributes header.
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> getSessionAttributes(Map<String, Object> headers) {
return (Map<String, Object>) headers.get(SESSION_ATTRIBUTES);
}
public void setUser(Principal principal) {
setHeader(USER_HEADER, principal);
}
/**
@@ -170,8 +226,11 @@ public class SimpMessageHeaderAccessor extends NativeMessageHeaderAccessor {
return (Principal) getHeader(USER_HEADER);
}
public void setUser(Principal principal) {
setHeader(USER_HEADER, principal);
/**
* A static alternative for access to the user header.
*/
public static Principal getUser(Map<String, Object> headers) {
return (Principal) headers.get(USER_HEADER);
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.simp;
import org.springframework.messaging.Message;
/**
* A factory for creating pre-configured instances of type
* {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor}.
*
* @author Rossen Stoyanchev
* @since 4.1
*/
public interface SimpMessageHeaderAccessorFactory {
/**
* Create an instance with
* {@link org.springframework.messaging.simp.SimpMessageType} {@code MESSAGE}.
*/
SimpMessageHeaderAccessor create();
/**
* Create an instance with the given
* {@link org.springframework.messaging.simp.SimpMessageType}.
*/
SimpMessageHeaderAccessor create(SimpMessageType messageType);
/**
* Create an instance from the payload and headers of the given Message.
*/
SimpMessageHeaderAccessor wrap(Message<?> message);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,7 +24,10 @@ import org.springframework.messaging.core.MessageSendingOperations;
/**
* A specialization of {@link MessageSendingOperations} with methods for use with
* the Spring Framework support for simple messaging protocols (like STOMP).
* the Spring Framework support for Simple Messaging Protocols (like STOMP).
*
* <p>For more on user destinations see
* {@link org.springframework.messaging.simp.user.UserDestinationResolver}.
*
* @author Rossen Stoyanchev
* @since 4.0
@@ -32,7 +35,8 @@ import org.springframework.messaging.core.MessageSendingOperations;
public interface SimpMessageSendingOperations extends MessageSendingOperations<String> {
/**
* Send a message to a specific user.
* Send a message to the given user.
*
* @param user the user that should receive the message.
* @param destination the destination to send the message to.
* @param payload the payload to send
@@ -40,27 +44,62 @@ public interface SimpMessageSendingOperations extends MessageSendingOperations<S
void convertAndSendToUser(String user, String destination, Object payload) throws MessagingException;
/**
* Send a message to a specific user.
* @param user the user that should receive the message.
* @param destination the destination to send the message to.
* @param payload the payload to send
* @param headers the message headers
* Send a message to the given user.
*
* <p>By default headers are interpreted as native headers (e.g. STOMP) and
* are saved under a special key in the resulting Spring
* {@link org.springframework.messaging.Message Message}. In effect when the
* message leaves the application, the provided headers are included with it
* and delivered to the destination (e.g. the STOMP client or broker).
*
* <p>If the map already contains the key
* {@link org.springframework.messaging.support.NativeMessageHeaderAccessor#NATIVE_HEADERS "nativeHeaders"}
* or was prepared with
* {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor SimpMessageHeaderAccessor}
* then the headers are used directly. A common expected case is providing a
* content type (to influence the message conversion) and native headers.
* This may be done as follows:
*
* <pre class="code">
* SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create();
* accessor.setContentType(MimeTypeUtils.TEXT_PLAIN);
* accessor.setNativeHeader("foo", "bar");
* accessor.setLeaveMutable(true);
* MessageHeaders headers = accessor.getMessageHeaders();
*
* messagingTemplate.convertAndSendToUser(user, destination, payload, headers);
* </pre>
*
* <p><strong>Note:</strong> if the {@code MessageHeaders} are mutable as in
* the above example, implementations of this interface should take notice and
* update the headers in the same instance (rather than copy or re-create it)
* and then set it immutable before sending the final message.
*
* @param user the user that should receive the message, must not be {@code null}
* @param destination the destination to send the message to, must not be {@code null}
* @param payload the payload to send, may be {@code null}
* @param headers the message headers, may be {@code null}
*/
void convertAndSendToUser(String user, String destination, Object payload, Map<String, Object> headers)
throws MessagingException;
/**
* Send a message to a specific user.
* @param user the user that should receive the message.
* @param destination the destination to send the message to.
* @param payload the payload to send
* Send a message to the given user.
*
* @param user the user that should receive the message, must not be {@code null}
* @param destination the destination to send the message to, must not be {@code null}
* @param payload the payload to send, may be {@code null}
* @param postProcessor a postProcessor to post-process or modify the created message
*/
void convertAndSendToUser(String user, String destination, Object payload,
MessagePostProcessor postProcessor) throws MessagingException;
/**
* Send a message to a specific user.
* Send a message to the given user.
*
* <p>See {@link #convertAndSend(Object, Object, java.util.Map)} for important
* notes regarding the input headers.
*
* @param user the user that should receive the message.
* @param destination the destination to send the message to.
* @param payload the payload to send

View File

@@ -73,7 +73,7 @@ public class SimpMessageTypeMessageCondition extends AbstractMessageCondition<Si
@Override
public SimpMessageTypeMessageCondition getMatchingCondition(Message<?> message) {
Object actualMessageType = message.getHeaders().get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER);
Object actualMessageType = SimpMessageHeaderAccessor.getMessageType(message.getHeaders());
if (actualMessageType == null) {
return null;
}
@@ -83,7 +83,7 @@ public class SimpMessageTypeMessageCondition extends AbstractMessageCondition<Si
@Override
public int compareTo(SimpMessageTypeMessageCondition other, Message<?> message) {
Object actualMessageType = message.getHeaders().get(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER);
Object actualMessageType = SimpMessageHeaderAccessor.getMessageType(message.getHeaders());
if (actualMessageType != null) {
if (actualMessageType.equals(this.getMessageType()) && actualMessageType.equals(other.getMessageType())) {
return 0;

View File

@@ -16,29 +16,25 @@
package org.springframework.messaging.simp;
import java.util.HashMap;
import java.util.Map;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageDeliveryException;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.core.AbstractMessageSendingTemplate;
import org.springframework.messaging.core.MessagePostProcessor;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.messaging.support.NativeMessageHeaderAccessor;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
/**
* A specialization of {@link AbstractMessageSendingTemplate} that interprets a
* String-based destination as the
* {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor#DESTINATION_HEADER DESTINATION_HEADER}
* to be added to the headers of sent messages.
* <p>
* Also provides methods for sending messages to a user. See
* An implementation of {@link org.springframework.messaging.simp.SimpMessageSendingOperations}.
*
* <p>Also provides methods for sending messages to a user. See
* {@link org.springframework.messaging.simp.user.UserDestinationResolver UserDestinationResolver}
* for more on user destinations.
*
@@ -106,22 +102,66 @@ public class SimpMessagingTemplate extends AbstractMessageSendingTemplate<String
}
/**
* If the headers of the given message already contain a
* {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor#DESTINATION_HEADER
* SimpMessageHeaderAccessor#DESTINATION_HEADER} then the message is sent without
* further changes.
*
* <p>If a destination header is not already present ,the message is sent
* to the configured {@link #setDefaultDestination(Object) defaultDestination}
* or an exception an {@code IllegalStateException} is raised if that isn't
* configured.
*
* @param message the message to send, never {@code null}
*/
@Override
public void send(Message<?> message) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
String destination = headers.getDestination();
destination = (destination != null) ? destination : getRequiredDefaultDestination();
doSend(destination, message);
Assert.notNull(message, "'message' is required");
String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders());
if (destination != null) {
sendInternal(message);
return;
}
doSend(getRequiredDefaultDestination(), message);
}
@SuppressWarnings("unchecked")
@Override
protected void doSend(String destination, Message<?> message) {
Assert.notNull(destination, "Destination must not be null");
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
headers.setDestination(destination);
headers.setMessageTypeIfNotSet(SimpMessageType.MESSAGE);
message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
SimpMessageHeaderAccessor simpAccessor =
MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class);
if (simpAccessor != null) {
if (simpAccessor.isMutable()) {
simpAccessor.setDestination(destination);
simpAccessor.setMessageTypeIfNotSet(SimpMessageType.MESSAGE);
simpAccessor.setImmutable();
sendInternal(message);
return;
}
else {
// Try and keep the original accessor type
simpAccessor = (SimpMessageHeaderAccessor) MessageHeaderAccessor.getMutableAccessor(message);
}
}
else {
simpAccessor = SimpMessageHeaderAccessor.wrap(message);
}
simpAccessor.setDestination(destination);
simpAccessor.setMessageTypeIfNotSet(SimpMessageType.MESSAGE);
message = MessageBuilder.createMessage(message.getPayload(), simpAccessor.getMessageHeaders());
sendInternal(message);
}
private void sendInternal(Message<?> message) {
String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders());
Assert.notNull(destination);
long timeout = this.sendTimeout;
boolean sent = (timeout >= 0)
@@ -130,12 +170,11 @@ public class SimpMessagingTemplate extends AbstractMessageSendingTemplate<String
if (!sent) {
throw new MessageDeliveryException(message,
"failed to send message to destination '" + destination + "' within timeout: " + timeout);
"Failed to send message to destination '" + destination + "' within timeout: " + timeout);
}
}
@Override
public void convertAndSendToUser(String user, String destination, Object payload) throws MessagingException {
this.convertAndSendToUser(user, destination, payload, (MessagePostProcessor) null);
@@ -166,34 +205,45 @@ public class SimpMessagingTemplate extends AbstractMessageSendingTemplate<String
/**
* Creates a new map and puts the given headers under the key
* {@link org.springframework.messaging.support.NativeMessageHeaderAccessor#NATIVE_HEADERS NATIVE_HEADERS}.
* Effectively this treats all given headers as headers to be sent out to the
* external source.
* <p>
* If the given headers already contain the key
* {@link org.springframework.messaging.support.NativeMessageHeaderAccessor#NATIVE_HEADERS NATIVE_HEADERS}
* then the same header map is returned (i.e. without any changes).
* {@link org.springframework.messaging.support.NativeMessageHeaderAccessor#NATIVE_HEADERS NATIVE_HEADERS NATIVE_HEADERS NATIVE_HEADERS}.
* effectively treats the input header map as headers to be sent out to the
* destination.
*
* <p>However if the given headers already contain the key
* {@code NATIVE_HEADERS NATIVE_HEADERS} then the same headers instance is
* returned without changes.
*
* <p>Also if the given headers were prepared and obtained with
* {@link SimpMessageHeaderAccessor#getMessageHeaders()} then the same headers
* instance is also returned without changes.
*/
@Override
protected Map<String, Object> processHeadersToSend(Map<String, Object> headers) {
if (headers == null) {
return null;
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headerAccessor.setLeaveMutable(true);
return headerAccessor.getMessageHeaders();
}
else if (headers.containsKey(NativeMessageHeaderAccessor.NATIVE_HEADERS)) {
return headers;
}
else {
MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<String, String>(headers.size());
for (String key : headers.keySet()) {
Object value = headers.get(key);
nativeHeaders.set(key, (value != null ? value.toString() : null));
}
headers = new HashMap<String, Object>(1);
headers.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, nativeHeaders);
if (headers.containsKey(NativeMessageHeaderAccessor.NATIVE_HEADERS)) {
return headers;
}
if (headers instanceof MessageHeaders) {
SimpMessageHeaderAccessor accessor =
MessageHeaderAccessor.getAccessor((MessageHeaders) headers, SimpMessageHeaderAccessor.class);
if (accessor != null) {
return headers;
}
}
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
for (String key : headers.keySet()) {
Object value = headers.get(key);
headerAccessor.setNativeHeader(key, (value != null ? value.toString() : null));
}
return headerAccessor.getMessageHeaders();
}
}

View File

@@ -37,8 +37,7 @@ public class PrincipalMethodArgumentResolver implements HandlerMethodArgumentRes
@Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
Principal user = headers.getUser();
Principal user = SimpMessageHeaderAccessor.getUser(message.getHeaders());
if (user == null) {
throw new MissingSessionUserException(message);
}

View File

@@ -23,15 +23,15 @@ import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.core.MessagePostProcessor;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.DestinationPatternsMessageCondition;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.handler.invocation.HandlerMethodReturnValueHandler;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.messaging.simp.user.DestinationUserNameProvider;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
@@ -113,73 +113,65 @@ public class SendToMethodReturnValueHandler implements HandlerMethodReturnValueH
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, Message<?> inputMessage)
public void handleReturnValue(Object returnValue, MethodParameter returnType, Message<?> message)
throws Exception {
if (returnValue == null) {
return;
}
SimpMessageHeaderAccessor inputHeaders = SimpMessageHeaderAccessor.wrap(inputMessage);
String sessionId = inputHeaders.getSessionId();
MessagePostProcessor postProcessor = new SessionHeaderPostProcessor(sessionId);
MessageHeaders headers = message.getHeaders();
String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
SendToUser sendToUser = returnType.getMethodAnnotation(SendToUser.class);
if (sendToUser != null) {
Principal principal = inputHeaders.getUser();
if (principal == null) {
throw new MissingSessionUserException(inputMessage);
}
String userName = principal.getName();
if (principal instanceof DestinationUserNameProvider) {
userName = ((DestinationUserNameProvider) principal).getDestinationUserName();
}
String[] destinations = getTargetDestinations(sendToUser, inputHeaders, this.defaultUserDestinationPrefix);
String user = getUserName(message, headers);
String[] destinations = getTargetDestinations(sendToUser, message, this.defaultUserDestinationPrefix);
for (String destination : destinations) {
this.messagingTemplate.convertAndSendToUser(userName, destination, returnValue, postProcessor);
this.messagingTemplate.convertAndSendToUser(user, destination, returnValue, createHeaders(sessionId));
}
return;
}
else {
SendTo sendTo = returnType.getMethodAnnotation(SendTo.class);
String[] destinations = getTargetDestinations(sendTo, inputHeaders, this.defaultDestinationPrefix);
String[] destinations = getTargetDestinations(sendTo, message, this.defaultDestinationPrefix);
for (String destination : destinations) {
this.messagingTemplate.convertAndSend(destination, returnValue, postProcessor);
this.messagingTemplate.convertAndSend(destination, returnValue, createHeaders(sessionId));
}
}
}
protected String[] getTargetDestinations(Annotation annot, SimpMessageHeaderAccessor inputHeaders,
String defaultPrefix) {
protected String getUserName(Message<?> message, MessageHeaders headers) {
Principal principal = SimpMessageHeaderAccessor.getUser(headers);
if (principal == null) {
throw new MissingSessionUserException(message);
}
if (principal instanceof DestinationUserNameProvider) {
return ((DestinationUserNameProvider) principal).getDestinationUserName();
}
return principal.getName();
}
if (annot != null) {
String[] value = (String[]) AnnotationUtils.getValue(annot);
protected String[] getTargetDestinations(Annotation annotation, Message<?> message, String defaultPrefix) {
if (annotation != null) {
String[] value = (String[]) AnnotationUtils.getValue(annotation);
if (!ObjectUtils.isEmpty(value)) {
return value;
}
}
return new String[] { defaultPrefix +
inputHeaders.getHeader(DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER) };
String name = DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER;
return new String[] { defaultPrefix + message.getHeaders().get(name) };
}
private final class SessionHeaderPostProcessor implements MessagePostProcessor {
private final String sessionId;
public SessionHeaderPostProcessor(String sessionId) {
this.sessionId = sessionId;
}
@Override
public Message<?> postProcessMessage(Message<?> message) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
headers.setSessionId(this.sessionId);
return MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
}
private MessageHeaders createHeaders(String sessionId) {
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headerAccessor.setSessionId(sessionId);
headerAccessor.setLeaveMutable(true);
return headerAccessor.getMessageHeaders();
}
@Override
public String toString() {
return "SendToMethodReturnValueHandler [annotationRequired=" + annotationRequired + "]";

View File

@@ -58,11 +58,12 @@ import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessageTypeMessageCondition;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
@@ -329,7 +330,7 @@ public class SimpAnnotationMethodMessageHandler extends AbstractMethodMessageHan
@Override
protected String getDestination(Message<?> message) {
return (String) message.getHeaders().get(SimpMessageHeaderAccessor.DESTINATION_HEADER);
return SimpMessageHeaderAccessor.getDestination(message.getHeaders());
}
@Override
@@ -352,13 +353,14 @@ public class SimpAnnotationMethodMessageHandler extends AbstractMethodMessageHan
protected void handleMatch(SimpMessageMappingInfo mapping, HandlerMethod handlerMethod,
String lookupDestination, Message<?> message) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
String matchedPattern = mapping.getDestinationConditions().getPatterns().iterator().next();
Map<String, String> vars = getPathMatcher().extractUriTemplateVariables(matchedPattern, lookupDestination);
headers.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars);
message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
if (!CollectionUtils.isEmpty(vars)) {
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
Assert.state(accessor != null && accessor.isMutable());
accessor.setHeader(DestinationVariableMethodArgumentResolver.DESTINATION_TEMPLATE_VARIABLES_HEADER, vars);
}
super.handleMatch(mapping, handlerMethod, lookupDestination, message);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,7 @@ package org.springframework.messaging.simp.annotation.support;
import org.springframework.core.MethodParameter;
import org.springframework.messaging.Message;
import org.springframework.messaging.core.MessagePostProcessor;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.core.MessageSendingOperations;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.handler.invocation.HandlerMethodReturnValueHandler;
@@ -26,17 +26,18 @@ import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.Assert;
/**
* A {@link HandlerMethodReturnValueHandler} for replying directly to a subscription. It
* supports methods annotated with {@link org.springframework.messaging.simp.annotation.SubscribeMapping} unless they're also annotated
* with {@link SendTo} or {@link SendToUser}.
* A {@link HandlerMethodReturnValueHandler} for replying directly to a subscription.
* It is supported on methods annotated with
* {@link org.springframework.messaging.simp.annotation.SubscribeMapping}
* unless they're also annotated with {@link SendTo} or {@link SendToUser} in
* which case a message is sent to the broker instead.
*
* <p>The value returned from the method is converted, and turned to a {@link Message} and
* then enriched with the sessionId, subscriptionId, and destination of the input message.
* The message is then sent directly back to the connected client.
* <p>The value returned from the method is converted, and turned to a {@link Message}
* and then enriched with the sessionId, subscriptionId, and destination of the
* input message. The message is then sent directly back to the connected client.
*
* @author Rossen Stoyanchev
* @since 4.0
@@ -47,8 +48,10 @@ public class SubscriptionMethodReturnValueHandler implements HandlerMethodReturn
/**
* @param messagingTemplate a messaging template for sending messages directly
* to clients, e.g. in response to a subscription
* Class constructor.
*
* @param messagingTemplate a messaging template to send messages to, most
* likely the "clientOutboundChannel", must not be {@link null}.
*/
public SubscriptionMethodReturnValueHandler(MessageSendingOperations<String> messagingTemplate) {
Assert.notNull(messagingTemplate, "messagingTemplate must not be null");
@@ -71,38 +74,23 @@ public class SubscriptionMethodReturnValueHandler implements HandlerMethodReturn
return;
}
SimpMessageHeaderAccessor inputHeaders = SimpMessageHeaderAccessor.wrap(message);
String sessionId = inputHeaders.getSessionId();
String subscriptionId = inputHeaders.getSubscriptionId();
String destination = inputHeaders.getDestination();
MessageHeaders headers = message.getHeaders();
String destination = SimpMessageHeaderAccessor.getDestination(headers);
String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
Assert.state(inputHeaders.getSubscriptionId() != null,
"No subsriptiondId in input message to method " + returnType.getMethod());
Assert.state(subscriptionId != null,
"No subscriptionId in message=" + message + ", method=" + returnType.getMethod());
MessagePostProcessor postProcessor = new SubscriptionHeaderPostProcessor(sessionId, subscriptionId);
this.messagingTemplate.convertAndSend(destination, returnValue, postProcessor);
this.messagingTemplate.convertAndSend(destination, returnValue, createHeaders(sessionId, subscriptionId));
}
private final class SubscriptionHeaderPostProcessor implements MessagePostProcessor {
private final String sessionId;
private final String subscriptionId;
public SubscriptionHeaderPostProcessor(String sessionId, String subscriptionId) {
this.sessionId = sessionId;
this.subscriptionId = subscriptionId;
}
@Override
public Message<?> postProcessMessage(Message<?> message) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
headers.setSessionId(this.sessionId);
headers.setSubscriptionId(this.subscriptionId);
headers.setMessageTypeIfNotSet(SimpMessageType.MESSAGE);
return MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
}
private MessageHeaders createHeaders(String sessionId, String subscriptionId) {
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headerAccessor.setSessionId(sessionId);
headerAccessor.setSubscriptionId(subscriptionId);
headerAccessor.setLeaveMutable(true);
return headerAccessor.getMessageHeaders();
}
}

View File

@@ -164,7 +164,7 @@ public abstract class AbstractBrokerMessageHandler
public final void handleMessage(Message<?> message) {
if (!this.running) {
if (logger.isTraceEnabled()) {
logger.trace("Message broker is not running. Ignoring message id=" + message.getHeaders().getId());
logger.trace("Message broker is not running. Ignoring message=" + message);
}
return;
}

View File

@@ -19,8 +19,10 @@ package org.springframework.messaging.simp.broker;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.MultiValueMap;
/**
@@ -38,29 +40,31 @@ public abstract class AbstractSubscriptionRegistry implements SubscriptionRegist
@Override
public final void registerSubscription(Message<?> message) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
if (!SimpMessageType.SUBSCRIBE.equals(headers.getMessageType())) {
MessageHeaders headers = message.getHeaders();
SimpMessageType type = SimpMessageHeaderAccessor.getMessageType(headers);
if (!SimpMessageType.SUBSCRIBE.equals(type)) {
logger.error("Expected SUBSCRIBE message: " + message);
return;
}
String sessionId = headers.getSessionId();
String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
if (sessionId == null) {
logger.error("Ignoring subscription. No sessionId in message: " + message);
return;
}
String subscriptionId = headers.getSubscriptionId();
String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
if (subscriptionId == null) {
logger.error("Ignoring subscription. No subscriptionId in message: " + message);
return;
}
String destination = headers.getDestination();
String destination = SimpMessageHeaderAccessor.getDestination(headers);
if (destination == null) {
logger.error("Ignoring destination. No destination in message: " + message);
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Adding subscription id=" + headers.getSubscriptionId()
+ ", destination=" + headers.getDestination());
logger.debug("Adding subscription id=" + subscriptionId + ", destination=" + destination);
}
addSubscriptionInternal(sessionId, subscriptionId, destination, message);
}
@@ -70,17 +74,20 @@ public abstract class AbstractSubscriptionRegistry implements SubscriptionRegist
@Override
public final void unregisterSubscription(Message<?> message) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
if (!SimpMessageType.UNSUBSCRIBE.equals(headers.getMessageType())) {
MessageHeaders headers = message.getHeaders();
SimpMessageType type = SimpMessageHeaderAccessor.getMessageType(headers);
if (!SimpMessageType.UNSUBSCRIBE.equals(type)) {
logger.error("Expected UNSUBSCRIBE message: " + message);
return;
}
String sessionId = headers.getSessionId();
String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
if (sessionId == null) {
logger.error("Ignoring subscription. No sessionId in message: " + message);
return;
}
String subscriptionId = headers.getSubscriptionId();
String subscriptionId = SimpMessageHeaderAccessor.getSubscriptionId(headers);
if (subscriptionId == null) {
logger.error("Ignoring subscription. No subscriptionId in message: " + message);
return;
@@ -98,19 +105,22 @@ public abstract class AbstractSubscriptionRegistry implements SubscriptionRegist
@Override
public final MultiValueMap<String, String> findSubscriptions(Message<?> message) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
if (!SimpMessageType.MESSAGE.equals(headers.getMessageType())) {
logger.trace("Ignoring message type " + headers.getMessageType());
MessageHeaders headers = message.getHeaders();
SimpMessageType type = SimpMessageHeaderAccessor.getMessageType(headers);
if (!SimpMessageType.MESSAGE.equals(type)) {
logger.trace("Ignoring message type " + type);
return null;
}
String destination = headers.getDestination();
String destination = SimpMessageHeaderAccessor.getDestination(headers);
if (destination == null) {
logger.trace("Ignoring message, no destination");
return null;
}
MultiValueMap<String, String> result = findSubscriptionsInternal(destination, message);
if (logger.isTraceEnabled()) {
logger.trace("Found " + result.size() + " subscriptions for destination=" + headers.getDestination());
logger.trace("Found " + result.size() + " subscriptions for destination=" + destination);
}
return result;
}

View File

@@ -20,6 +20,7 @@ import java.util.Collection;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
@@ -111,9 +112,10 @@ public class SimpleBrokerMessageHandler extends AbstractBrokerMessageHandler {
@Override
protected void handleMessageInternal(Message<?> message) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
SimpMessageType messageType = headers.getMessageType();
String destination = headers.getDestination();
MessageHeaders headers = message.getHeaders();
SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
String destination = SimpMessageHeaderAccessor.getDestination(headers);
String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
if (!checkDestinationPrefix(destination)) {
if (logger.isTraceEnabled()) {
@@ -122,27 +124,30 @@ public class SimpleBrokerMessageHandler extends AbstractBrokerMessageHandler {
return;
}
if (SimpMessageType.SUBSCRIBE.equals(messageType)) {
if (SimpMessageType.MESSAGE.equals(messageType)) {
sendMessageToSubscribers(destination, message);
}
else if (SimpMessageType.SUBSCRIBE.equals(messageType)) {
this.subscriptionRegistry.registerSubscription(message);
}
else if (SimpMessageType.UNSUBSCRIBE.equals(messageType)) {
this.subscriptionRegistry.unregisterSubscription(message);
}
else if (SimpMessageType.MESSAGE.equals(messageType)) {
sendMessageToSubscribers(headers.getDestination(), message);
}
else if (SimpMessageType.DISCONNECT.equals(messageType)) {
String sessionId = headers.getSessionId();
this.subscriptionRegistry.unregisterAllSubscriptions(sessionId);
this.subscriptionRegistry.unregisterAllSubscriptions(sessionId);
}
else if (SimpMessageType.CONNECT.equals(messageType)) {
SimpMessageHeaderAccessor replyHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
replyHeaders.setSessionId(headers.getSessionId());
replyHeaders.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, message);
Message<byte[]> connectAck = MessageBuilder.withPayload(EMPTY_PAYLOAD).setHeaders(replyHeaders).build();
SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
accessor.setSessionId(sessionId);
accessor.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, message);
Message<byte[]> connectAck = MessageBuilder.createMessage(EMPTY_PAYLOAD, accessor.getMessageHeaders());
this.clientOutboundChannel.send(connectAck);
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Message type not supported. Ignoring: " + message);
}
}
}
protected void sendMessageToSubscribers(String destination, Message<?> message) {
@@ -153,17 +158,17 @@ public class SimpleBrokerMessageHandler extends AbstractBrokerMessageHandler {
}
for (String sessionId : subscriptions.keySet()) {
for (String subscriptionId : subscriptions.get(sessionId)) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
headers.setSessionId(sessionId);
headers.setSubscriptionId(subscriptionId);
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headerAccessor.setSessionId(sessionId);
headerAccessor.setSubscriptionId(subscriptionId);
headerAccessor.copyHeadersIfAbsent(message.getHeaders());
Object payload = message.getPayload();
Message<?> clientMessage = MessageBuilder.withPayload(payload).setHeaders(headers).build();
Message<?> reply = MessageBuilder.createMessage(payload, headerAccessor.getMessageHeaders());
try {
this.clientOutboundChannel.send(clientMessage);
this.clientOutboundChannel.send(reply);
}
catch (Throwable ex) {
logger.error("Failed to send message to destination=" + destination +
", sessionId=" + sessionId + ", subscriptionId=" + subscriptionId, ex);
logger.error("Failed to send message=" + message, ex);
}
}
}

View File

@@ -123,7 +123,7 @@ public class BufferingStompDecoder extends StompDecoder {
if (bufferToDecode.hasRemaining()) {
this.chunks.add(bufferToDecode);
this.expectedContentLength = getContentLength(headers);
this.expectedContentLength = StompHeaderAccessor.getContentLength(headers);
}
return messages;

View File

@@ -0,0 +1,78 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.simp.stomp;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageHeaderAccessorFactorySupport;
import org.springframework.util.IdGenerator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* A default implementation of
* {@link org.springframework.messaging.simp.stomp.StompHeaderAccessorFactory}.
*
* @author Rossen Stoyanchev
* @since 4.1
*/
public class DefaultStompHeaderAccessorFactory extends MessageHeaderAccessorFactorySupport
implements StompHeaderAccessorFactory {
public DefaultStompHeaderAccessorFactory() {
super.setIdGenerator(ID_VALUE_NONE_GENERATOR);
}
@Override
public StompHeaderAccessor create(StompCommand command) {
StompHeaderAccessor accessor = new StompHeaderAccessor(command, null);
updateMessageHeaderAccessor(accessor);
return accessor;
}
@Override
public StompHeaderAccessor create(StompCommand command, Map<String, List<String>> headers) {
StompHeaderAccessor accessor = new StompHeaderAccessor(command, headers);
updateMessageHeaderAccessor(accessor);
return accessor;
}
@Override
public StompHeaderAccessor createForHeartbeat() {
StompHeaderAccessor accessor = new StompHeaderAccessor();
updateMessageHeaderAccessor(accessor);
return accessor;
}
@Override
public StompHeaderAccessor wrap(Message<?> message) {
StompHeaderAccessor accessor = new StompHeaderAccessor(message);
updateMessageHeaderAccessor(accessor);
return accessor;
}
private static final IdGenerator ID_VALUE_NONE_GENERATOR = new IdGenerator() {
@Override
public UUID generateId() {
return MessageHeaders.ID_VALUE_NONE;
}
};
}

View File

@@ -20,7 +20,6 @@ import java.util.Collection;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
@@ -30,6 +29,7 @@ import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.broker.AbstractBrokerMessageHandler;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.messaging.tcp.FixedIntervalReconnectStrategy;
import org.springframework.messaging.tcp.TcpConnection;
import org.springframework.messaging.tcp.TcpConnectionHandler;
@@ -79,9 +79,9 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
private static final Message<byte[]> HEARTBEAT_MESSAGE;
static {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.HEARTBEAT);
HEARTBEAT_MESSAGE = MessageBuilder.withPayload(new byte[] {'\n'}).setHeaders(headers).build();
EMPTY_TASK.run();
StompHeaderAccessor accessor = StompHeaderAccessor.createForHeartbeat();
HEARTBEAT_MESSAGE = MessageBuilder.createMessage(StompDecoder.HEARTBEAT_PAYLOAD, accessor.getMessageHeaders());
}
@@ -370,37 +370,53 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
@Override
protected void handleMessageInternal(Message<?> message) {
StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
String sessionId = headers.getSessionId();
String sessionId = SimpMessageHeaderAccessor.getSessionId(message.getHeaders());
if (!isBrokerAvailable()) {
if (sessionId == null || sessionId == SystemStompConnectionHandler.SESSION_ID) {
if (sessionId == null || SystemStompConnectionHandler.SESSION_ID.equals(sessionId)) {
throw new MessageDeliveryException("Message broker is not active.");
}
if (logger.isTraceEnabled()) {
logger.trace("Message broker is not active. Ignoring message id=" + message.getHeaders().getId());
logger.trace("Message broker is not active. Ignoring: " + message);
}
return;
}
String destination = headers.getDestination();
StompCommand command = headers.getCommand();
SimpMessageType messageType = headers.getMessageType();
StompHeaderAccessor stompAccessor;
StompCommand command;
if (SimpMessageType.MESSAGE.equals(messageType)) {
sessionId = (sessionId == null) ? SystemStompConnectionHandler.SESSION_ID : sessionId;
headers.setSessionId(sessionId);
command = headers.updateStompCommandAsClientMessage();
message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
if (accessor == null) {
logger.error("No header accessor, please use SimpMessagingTemplate. Ignoring: " + message);
return;
}
else if (accessor instanceof StompHeaderAccessor) {
stompAccessor = (StompHeaderAccessor) accessor;
command = stompAccessor.getCommand();
}
else if (accessor instanceof SimpMessageHeaderAccessor) {
stompAccessor = StompHeaderAccessor.wrap(message);
command = stompAccessor.getCommand();
if (command == null) {
command = stompAccessor.updateStompCommandAsClientMessage();
}
}
else {
// Should not happen
logger.error("Unexpected header accessor type: " + accessor + ". Ignoring: " + message);
return;
}
if (sessionId == null) {
if (logger.isWarnEnabled()) {
logger.warn("No sessionId, ignoring message: " + message);
if (!SimpMessageType.MESSAGE.equals(stompAccessor.getMessageType())) {
logger.error("Only STOMP SEND frames supported on \"system\" connection. Ignoring: " + message);
return;
}
return;
sessionId = SystemStompConnectionHandler.SESSION_ID;
stompAccessor.setSessionId(sessionId);
}
String destination = stompAccessor.getDestination();
if ((command != null) && command.requiresDestination() && !checkDestinationPrefix(destination)) {
if (logger.isTraceEnabled()) {
logger.trace("Ignoring message to destination=" + destination);
@@ -412,20 +428,21 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
logger.trace("Processing message=" + message);
}
if (SimpMessageType.CONNECT.equals(messageType)) {
if (StompCommand.CONNECT.equals(command)) {
if (logger.isDebugEnabled()) {
logger.debug("Processing CONNECT (total connected=" + this.connectionHandlers.size() + ")");
}
headers.setLogin(this.clientLogin);
headers.setPasscode(this.clientPasscode);
stompAccessor = (stompAccessor.isMutable() ? stompAccessor : StompHeaderAccessor.wrap(message));
stompAccessor.setLogin(this.clientLogin);
stompAccessor.setPasscode(this.clientPasscode);
if (getVirtualHost() != null) {
headers.setHost(getVirtualHost());
stompAccessor.setHost(getVirtualHost());
}
StompConnectionHandler handler = new StompConnectionHandler(sessionId, headers);
StompConnectionHandler handler = new StompConnectionHandler(sessionId, stompAccessor);
this.connectionHandlers.put(sessionId, handler);
this.tcpClient.connect(handler);
}
else if (SimpMessageType.DISCONNECT.equals(messageType)) {
else if (StompCommand.DISCONNECT.equals(command)) {
StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
if (handler == null) {
if (logger.isTraceEnabled()) {
@@ -433,7 +450,7 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
}
return;
}
handler.forward(message);
handler.forward(message, stompAccessor);
}
else {
StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
@@ -443,7 +460,7 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
}
return;
}
handler.forward(message);
handler.forward(message, stompAccessor);
}
}
@@ -486,7 +503,7 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
logger.debug("Established TCP connection to broker in session '" + this.sessionId + "'");
}
this.tcpConnection = connection;
connection.send(MessageBuilder.withPayload(EMPTY_PAYLOAD).setHeaders(this.connectHeaders).build());
connection.send(MessageBuilder.createMessage(EMPTY_PAYLOAD, this.connectHeaders.getMessageHeaders()));
}
@Override
@@ -522,7 +539,7 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.ERROR);
headers.setSessionId(this.sessionId);
headers.setMessage(errorText);
Message<?> errorMessage = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<?> errorMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
sendMessageToClient(errorMessage);
}
}
@@ -536,20 +553,23 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
@Override
public void handleMessage(Message<byte[]> message) {
StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
if (SimpMessageType.HEARTBEAT.equals(headers.getMessageType())) {
StompHeaderAccessor headerAccessor =
MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (headerAccessor.isHeartbeat()) {
logger.trace("Received broker heartbeat");
}
else if (logger.isDebugEnabled()) {
logger.debug("Received message from broker in session '" + this.sessionId + "'");
}
if (StompCommand.CONNECTED == headers.getCommand()) {
afterStompConnected(headers);
if (StompCommand.CONNECTED == headerAccessor.getCommand()) {
afterStompConnected(headerAccessor);
}
headers.setSessionId(this.sessionId);
message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
headerAccessor.setSessionId(this.sessionId);
headerAccessor.setImmutable();
sendMessageToClient(message);
}
@@ -630,9 +650,7 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
clearConnection();
}
catch (Throwable t) {
if (logger.isErrorEnabled()) {
// Ignore
}
// Ignore
}
}
}
@@ -661,7 +679,7 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
* @return a future to wait for the result
*/
@SuppressWarnings("unchecked")
public ListenableFuture<Void> forward(final Message<?> message) {
public ListenableFuture<Void> forward(Message<?> message, final StompHeaderAccessor headerAccessor) {
TcpConnection<byte[]> conn = this.tcpConnection;
@@ -682,8 +700,7 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
}
if (logger.isDebugEnabled()) {
StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
if (SimpMessageType.HEARTBEAT.equals(headers.getMessageType())) {
if (headerAccessor.isHeartbeat()) {
logger.trace("Forwarding heartbeat to broker");
}
else {
@@ -691,13 +708,16 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
}
}
if (headerAccessor.isMutable() && headerAccessor.isModified()) {
message = MessageBuilder.createMessage(message.getPayload(), headerAccessor.getMessageHeaders());
}
ListenableFuture<Void> future = conn.send((Message<byte[]>) message);
future.addCallback(new ListenableFutureCallback<Void>() {
@Override
public void onSuccess(Void result) {
StompCommand command = StompHeaderAccessor.wrap(message).getCommand();
if (command == StompCommand.DISCONNECT) {
if (headerAccessor.getCommand() == StompCommand.DISCONNECT) {
clearConnection();
}
}
@@ -707,7 +727,7 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
// already reset
}
else {
handleTcpConnectionFailure("Failed to send message " + message, t);
handleTcpConnectionFailure("Failed to send message " + headerAccessor, t);
}
}
});
@@ -777,9 +797,9 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
}
@Override
public ListenableFuture<Void> forward(Message<?> message) {
public ListenableFuture<Void> forward(Message<?> message, StompHeaderAccessor headerAccessor) {
try {
ListenableFuture<Void> future = super.forward(message);
ListenableFuture<Void> future = super.forward(message, headerAccessor);
future.get();
return future;
}

View File

@@ -26,10 +26,9 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.messaging.support.NativeMessageHeaderAccessor;
import org.springframework.util.InvalidMimeTypeException;
import org.springframework.util.MultiValueMap;
/**
@@ -47,9 +46,9 @@ import org.springframework.util.MultiValueMap;
*/
public class StompDecoder {
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
private static final byte[] HEARTBEAT_PAYLOAD = new byte[] {'\n'};
static final byte[] HEARTBEAT_PAYLOAD = new byte[] {'\n'};
private final Log logger = LogFactory.getLog(StompDecoder.class);
@@ -65,7 +64,7 @@ public class StompDecoder {
* @return the decoded messages or an empty list
*/
public List<Message<byte[]>> decode(ByteBuffer buffer) {
return decode(buffer, new LinkedMultiValueMap<String, String>());
return decode(buffer, null);
}
/**
@@ -79,27 +78,25 @@ public class StompDecoder {
* <p>If the buffer contains one ore more STOMP frames, those are returned and
* the buffer reset to point to the beginning of the unused partial content.
*
* <p>The input headers map is used to store successfully parsed headers and
* is cleared after ever successfully read message. So when partial content is
* read the caller can check if a "content-length" header was read, which helps
* to determine how much more content is needed before the next STOMP frame
* can be decoded.
* <p>The output partialMessageHeaders map is used to store successfully parsed
* headers in case of partial content. The caller can then check if a
* "content-length" header was read, which helps to determine how much more
* content is needed before the next attempt to decode.
*
* @param buffer The buffer to decode the STOMP frame from
* @param headers an empty map that will contain successfully parsed headers
* @param partialMessageHeaders an empty output map that will store the last
* successfully parsed partialMessageHeaders in case of partial message content
* in cases where the partial buffer ended with a partial STOMP frame
*
* @return decoded messages or an empty list
* @throws StompConversionException raised in case of decoding issues
*/
public List<Message<byte[]>> decode(ByteBuffer buffer, MultiValueMap<String, String> headers) {
Assert.notNull(headers, "headers is required");
public List<Message<byte[]>> decode(ByteBuffer buffer, MultiValueMap<String, String> partialMessageHeaders) {
List<Message<byte[]>> messages = new ArrayList<Message<byte[]>>();
while (buffer.hasRemaining()) {
Message<byte[]> m = decodeMessage(buffer, headers);
Message<byte[]> m = decodeMessage(buffer, partialMessageHeaders);
if (m != null) {
messages.add(m);
headers.clear();
}
else {
break;
@@ -120,17 +117,25 @@ public class StompDecoder {
String command = readCommand(buffer);
if (command.length() > 0) {
readHeaders(buffer, headers);
byte[] payload = readPayload(buffer, headers);
StompHeaderAccessor headerAccessor = null;
byte[] payload = null;
if (buffer.remaining() > 0) {
StompCommand stompCommand = StompCommand.valueOf(command);
headerAccessor = StompHeaderAccessor.create(stompCommand);
readHeaders(buffer, headerAccessor);
payload = readPayload(buffer, headerAccessor);
}
if (payload != null) {
StompCommand stompCommand = StompCommand.valueOf(command);
if ((payload.length > 0) && (!stompCommand.isBodyAllowed())) {
throw new StompConversionException(stompCommand + " shouldn't have but " +
"has a payload with length=" + payload.length + ", headers=" + headers);
if ((payload.length > 0) && (!headerAccessor.getCommand().isBodyAllowed())) {
throw new StompConversionException(headerAccessor.getCommand() +
" shouldn't have a payload: length=" + payload.length + ", headers=" + headers);
}
decodedMessage = MessageBuilder.withPayload(payload)
.setHeaders(StompHeaderAccessor.create(stompCommand, headers)).build();
headerAccessor.updateSimpMessageHeadersFromStompHeaders();
headerAccessor.setLeaveMutable(true);
decodedMessage = MessageBuilder.createMessage(payload, headerAccessor.getMessageHeaders());
if (logger.isDebugEnabled()) {
logger.debug("Decoded " + decodedMessage);
}
@@ -139,6 +144,14 @@ public class StompDecoder {
if (logger.isTraceEnabled()) {
logger.trace("Received incomplete frame. Resetting buffer.");
}
if (headers != null && headerAccessor != null) {
String name = NativeMessageHeaderAccessor.NATIVE_HEADERS;
@SuppressWarnings("unchecked")
MultiValueMap<String, String> map = (MultiValueMap<String, String>) headerAccessor.getHeader(name);
if (map != null) {
headers.putAll(map);
}
}
buffer.reset();
}
}
@@ -146,8 +159,9 @@ public class StompDecoder {
if (logger.isTraceEnabled()) {
logger.trace("Decoded heartbeat");
}
decodedMessage = MessageBuilder.withPayload(HEARTBEAT_PAYLOAD).setHeaders(
StompHeaderAccessor.create(SimpMessageType.HEARTBEAT)).build();
StompHeaderAccessor headerAccessor = StompHeaderAccessor.createForHeartbeat();
headerAccessor.setLeaveMutable(true);
decodedMessage = MessageBuilder.createMessage(HEARTBEAT_PAYLOAD, headerAccessor.getMessageHeaders());
}
return decodedMessage;
}
@@ -173,7 +187,7 @@ public class StompDecoder {
return new String(command.toByteArray(), UTF8_CHARSET);
}
private void readHeaders(ByteBuffer buffer, MultiValueMap<String, String> headers) {
private void readHeaders(ByteBuffer buffer, StompHeaderAccessor headerAccessor) {
while (true) {
ByteArrayOutputStream headerStream = new ByteArrayOutputStream(256);
while (buffer.remaining() > 0 && !tryConsumeEndOfLine(buffer)) {
@@ -191,7 +205,14 @@ public class StompDecoder {
else {
String headerName = unescape(header.substring(0, colonIndex));
String headerValue = unescape(header.substring(colonIndex + 1));
headers.add(headerName, headerValue);
try {
headerAccessor.addNativeHeader(headerName, headerValue);
}
catch (InvalidMimeTypeException ex) {
if (buffer.remaining() > 0) {
throw ex;
}
}
}
}
else {
@@ -237,8 +258,17 @@ public class StompDecoder {
return sb.toString();
}
private byte[] readPayload(ByteBuffer buffer, MultiValueMap<String, String> headers) {
Integer contentLength = getContentLength(headers);
private byte[] readPayload(ByteBuffer buffer, StompHeaderAccessor headerAccessor) {
Integer contentLength;
try {
contentLength = headerAccessor.getContentLength();
}
catch (NumberFormatException ex) {
logger.warn("Ignoring invalid content-length: '" + headerAccessor);
contentLength = null;
}
if (contentLength != null && contentLength >= 0) {
if (buffer.remaining() > contentLength) {
byte[] payload = new byte[contentLength];
@@ -267,19 +297,6 @@ public class StompDecoder {
return null;
}
protected Integer getContentLength(MultiValueMap<String, String> headers) {
if (headers.containsKey(StompHeaderAccessor.STOMP_CONTENT_LENGTH_HEADER)) {
String rawContentLength = headers.getFirst(StompHeaderAccessor.STOMP_CONTENT_LENGTH_HEADER);
try {
return Integer.valueOf(rawContentLength);
}
catch (NumberFormatException ex) {
logger.warn("Ignoring invalid content-length header value: '" + rawContentLength + "'");
}
}
return null;
}
/**
* Try to read an EOL incrementing the buffer position if successful.
*

View File

@@ -19,7 +19,7 @@ package org.springframework.messaging.simp.stomp;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@@ -28,7 +28,10 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.NativeMessageHeaderAccessor;
import org.springframework.util.Assert;
/**
* An encoder for STOMP frames.
@@ -43,32 +46,45 @@ public final class StompEncoder {
private static final byte COLON = ':';
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
private final Log logger = LogFactory.getLog(StompEncoder.class);
/**
* Encodes the given STOMP {@code message} into a {@code byte[]}
*
* @param message the message to encode
* @return the encoded message
*/
public byte[] encode(Message<byte[]> message) {
return encode(message.getHeaders(), message.getPayload());
}
/**
* Encodes the given payload and headers into a {@code byte[]}.
*
* @param headers the headers
* @param payload the payload
* @return the encoded message
*/
public byte[] encode(Map<String, Object> headers, byte[] payload) {
Assert.notNull(headers, "'headers' is required");
Assert.notNull(payload, "'payload' is required");
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(128 + message.getPayload().length);
ByteArrayOutputStream baos = new ByteArrayOutputStream(128 + payload.length);
DataOutputStream output = new DataOutputStream(baos);
StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
if (SimpMessageType.HEARTBEAT == headers.getMessageType()) {
if (SimpMessageType.HEARTBEAT.equals(SimpMessageHeaderAccessor.getMessageType(headers))) {
logger.trace("Encoded heartbeat");
output.write(message.getPayload());
output.write(StompDecoder.HEARTBEAT_PAYLOAD);
}
else {
output.write(headers.getCommand().toString().getBytes(UTF8_CHARSET));
StompCommand command = StompHeaderAccessor.getCommand(headers);
Assert.notNull(command, "Missing STOMP command: " + headers);
output.write(command.toString().getBytes(StompDecoder.UTF8_CHARSET));
output.write(LF);
writeHeaders(headers, message, output);
writeHeaders(command, headers, payload, output);
output.write(LF);
writeBody(message, output);
writeBody(payload, output);
output.write((byte) 0);
}
@@ -79,20 +95,30 @@ public final class StompEncoder {
}
}
private void writeHeaders(StompHeaderAccessor headers, Message<byte[]> message, DataOutputStream output)
private void writeHeaders(StompCommand command, Map<String, Object> headers, byte[] payload, DataOutputStream output)
throws IOException {
StompCommand command = headers.getCommand();
Map<String,List<String>> stompHeaders = headers.toStompHeaderMap();
boolean shouldEscape = (command != StompCommand.CONNECT && command != StompCommand.CONNECTED);
@SuppressWarnings("unchecked")
Map<String,List<String>> nativeHeaders =
(Map<String, List<String>>) headers.get(NativeMessageHeaderAccessor.NATIVE_HEADERS);
if (logger.isDebugEnabled()) {
logger.debug("Encoded STOMP " + command + ", headers=" + stompHeaders);
logger.debug("Encoding STOMP " + command + ", headers=" + nativeHeaders);
}
for (Entry<String, List<String>> entry : stompHeaders.entrySet()) {
if (nativeHeaders == null) {
return;
}
boolean shouldEscape = (command != StompCommand.CONNECT && command != StompCommand.CONNECTED);
for (Entry<String, List<String>> entry : nativeHeaders.entrySet()) {
byte[] key = encodeHeaderString(entry.getKey(), shouldEscape);
for (String value : entry.getValue()) {
List<String> values = entry.getValue();
if (StompHeaderAccessor.STOMP_PASSCODE_HEADER.equals(entry.getKey())) {
values = Arrays.asList(StompHeaderAccessor.getPasscode(headers));
}
for (String value : values) {
output.write(key);
output.write(COLON);
output.write(encodeHeaderString(value, shouldEscape));
@@ -100,16 +126,16 @@ public final class StompEncoder {
}
}
if (command.requiresContentLength()) {
int contentLength = message.getPayload().length;
output.write("content-length:".getBytes(UTF8_CHARSET));
output.write(Integer.toString(contentLength).getBytes(UTF8_CHARSET));
int contentLength = payload.length;
output.write("content-length:".getBytes(StompDecoder.UTF8_CHARSET));
output.write(Integer.toString(contentLength).getBytes(StompDecoder.UTF8_CHARSET));
output.write(LF);
}
}
private byte[] encodeHeaderString(String input, boolean escape) {
input = escape ? escape(input) : input;
return input.getBytes(UTF8_CHARSET);
return input.getBytes(StompDecoder.UTF8_CHARSET);
}
/**
@@ -139,8 +165,8 @@ public final class StompEncoder {
return sb.toString();
}
private void writeBody(Message<byte[]> message, DataOutputStream output) throws IOException {
output.write(message.getPayload());
private void writeBody(byte[] payload, DataOutputStream output) throws IOException {
output.write(payload);
}
}

View File

@@ -26,27 +26,45 @@ import java.util.concurrent.atomic.AtomicLong;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
/**
* Can be used to prepare headers for a new STOMP message, or to access and/or modify
* STOMP-specific headers of an existing message.
* A {@code MessageHeaderAccessor} to use when creating a {@code Message} from a
* decoded STOMP frame, or when encoding a {@code Message} to a STOMP frame.
*
* <p>Use one of the static factory method in this class, then call getters and setters,
* and at the end if necessary call {@link #toMap()} to obtain the updated headers
* or call {@link #toNativeHeaderMap()} to obtain only the STOMP-specific headers.
* <p>When created from STOMP frame content, the actual STOMP headers are stored
* in the native header sub-map managed by the parent class
* {@link org.springframework.messaging.support.NativeMessageHeaderAccessor}
* while the parent class
* {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor} manages
* common processing headers some of which are based on STOMP headers (e.g.
* destination, content-type, etc).
*
* <p>An instance of this class can also be created by wrapping an existing
* {@code Message}. That message may have been created with the more generic
* {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor} in
* which case STOMP headers are created from common processing headers.
* In this case it is also necessary to invoke either
* {@link #updateStompCommandAsClientMessage()} or
* {@link #updateStompCommandAsServerMessage()} if sending a message and
* depending on whether a message is sent to a client or the message broker.
*
* @author Rossen Stoyanchev
* @since 4.0
*/
public class StompHeaderAccessor extends SimpMessageHeaderAccessor {
private static final StompHeaderAccessorFactory factory = new DefaultStompHeaderAccessorFactory();
private static final AtomicLong messageIdCounter = new AtomicLong();
private static final long[] DEFAULT_HEARTBEAT = new long[] {0, 0};
// STOMP header names
public static final String STOMP_ID_HEADER = "id";
@@ -83,9 +101,6 @@ public class StompHeaderAccessor extends SimpMessageHeaderAccessor {
public static final String STOMP_HEARTBEAT_HEADER = "heart-beat";
private static final long[] DEFAULT_HEARTBEAT = new long[] {0, 0};
// Other header names
private static final String COMMAND_HEADER = "stompCommand";
@@ -94,135 +109,113 @@ public class StompHeaderAccessor extends SimpMessageHeaderAccessor {
/**
* A constructor for creating new STOMP message headers.
* A constructor for creating message headers from a parsed STOMP frame.
*/
private StompHeaderAccessor(StompCommand command, Map<String, List<String>> externalSourceHeaders) {
StompHeaderAccessor(StompCommand command, Map<String, List<String>> externalSourceHeaders) {
super(command.getMessageType(), externalSourceHeaders);
Assert.notNull(command, "Command must not be null");
setHeader(COMMAND_HEADER, command);
if (externalSourceHeaders != null) {
setSimpMessageHeaders(command, externalSourceHeaders);
}
}
private void setSimpMessageHeaders(StompCommand command, Map<String, List<String>> extHeaders) {
List<String> values = extHeaders.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER);
if (!CollectionUtils.isEmpty(values)) {
super.setDestination(values.get(0));
}
values = extHeaders.get(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER);
if (!CollectionUtils.isEmpty(values)) {
super.setContentType(MimeTypeUtils.parseMimeType(values.get(0)));
}
if (StompCommand.SUBSCRIBE.equals(command) || StompCommand.UNSUBSCRIBE.equals(command)) {
values = extHeaders.get(StompHeaderAccessor.STOMP_ID_HEADER);
if (!CollectionUtils.isEmpty(values)) {
super.setSubscriptionId(values.get(0));
}
}
else if (StompCommand.MESSAGE.equals(command)) {
values = extHeaders.get(StompHeaderAccessor.STOMP_SUBSCRIPTION_HEADER);
if (!CollectionUtils.isEmpty(values)) {
super.setSubscriptionId(values.get(0));
}
}
else if (StompCommand.CONNECT.equals(command)) {
if (!StringUtils.isEmpty(getPasscode())) {
setHeader(CREDENTIALS_HEADER, new StompPasscode(getPasscode()));
setPasscode("PROTECTED");
}
}
updateSimpMessageHeadersFromStompHeaders();
}
/**
* A constructor for accessing and modifying existing message headers.
* Note that the message headers may not have been created from a STOMP frame
* but may have rather originated from using the more generic
* {@link org.springframework.messaging.simp.SimpMessageHeaderAccessor}.
*/
private StompHeaderAccessor(Message<?> message) {
StompHeaderAccessor(Message<?> message) {
super(message);
updateStompHeadersFromSimpMessageHeaders();
}
StompHeaderAccessor() {
super(SimpMessageType.HEARTBEAT, null);
}
void updateSimpMessageHeadersFromStompHeaders() {
if (getNativeHeaders() == null) {
return;
}
String value = getFirstNativeHeader(STOMP_DESTINATION_HEADER);
if (value != null) {
super.setDestination(value);
}
value = getFirstNativeHeader(STOMP_CONTENT_TYPE_HEADER);
if (value != null) {
super.setContentType(MimeTypeUtils.parseMimeType(value));
}
StompCommand command = getCommand();
if (StompCommand.MESSAGE.equals(command)) {
value = getFirstNativeHeader(STOMP_SUBSCRIPTION_HEADER);
if (value != null) {
super.setSubscriptionId(value);
}
}
else if (StompCommand.SUBSCRIBE.equals(command) || StompCommand.UNSUBSCRIBE.equals(command)) {
value = getFirstNativeHeader(STOMP_ID_HEADER);
if (value != null) {
super.setSubscriptionId(value);
}
}
else if (StompCommand.CONNECT.equals(command)) {
protectPasscode();
}
}
private void updateStompHeadersFromSimpMessageHeaders() {
if (getDestination() != null) {
setNativeHeader(STOMP_DESTINATION_HEADER, getDestination());
}
if (getContentType() != null) {
setNativeHeader(STOMP_CONTENT_TYPE_HEADER, getContentType().toString());
}
trySetStompHeaderForSubscriptionId();
}
/**
* Create {@link StompHeaderAccessor} for a new {@link Message}.
* Create an instance for the given STOMP command.
*/
public static StompHeaderAccessor create(StompCommand command) {
return new StompHeaderAccessor(command, null);
return factory.create(command);
}
/**
* Create {@link StompHeaderAccessor} from parsed STOP frame content.
* Create an instance for the given STOMP command and headers.
*/
public static StompHeaderAccessor create(StompCommand command, Map<String, List<String>> headers) {
return new StompHeaderAccessor(command, headers);
return factory.create(command, headers);
}
/**
* Create {@link StompHeaderAccessor} from the headers of an existing {@link Message}.
* Create headers for a heartbeat. While a STOMP heartbeat frame does not
* have headers, a session id is needed for processing purposes at a minimum.
*/
public static StompHeaderAccessor createForHeartbeat() {
return factory.createForHeartbeat();
}
/**
* Create an instance from the payload and headers of the given Message.
*/
public static StompHeaderAccessor wrap(Message<?> message) {
return new StompHeaderAccessor(message);
return factory.wrap(message);
}
/**
* Return STOMP headers including original, wrapped STOMP headers (if any) plus
* additional header updates made through accessor methods.
*/
@Override
public Map<String, List<String>> toNativeHeaderMap() {
Map<String, List<String>> result = super.toNativeHeaderMap();
String destination = super.getDestination();
if (destination != null) {
result.put(STOMP_DESTINATION_HEADER, Arrays.asList(destination));
}
MimeType contentType = super.getContentType();
if (contentType != null) {
result.put(STOMP_CONTENT_TYPE_HEADER, Arrays.asList(contentType.toString()));
}
if (getCommand() != null && getCommand().requiresSubscriptionId()) {
String subscriptionId = getSubscriptionId();
if (subscriptionId != null) {
String name = StompCommand.MESSAGE.equals(getCommand()) ? STOMP_SUBSCRIPTION_HEADER : STOMP_ID_HEADER;
result.put(name, Arrays.asList(subscriptionId));
}
else {
logger.warn(getCommand() + " frame does not have a subscription identifier" + this.toString());
}
}
if (StompCommand.MESSAGE.equals(getCommand()) && ((getMessageId() == null))) {
String messageId = getSessionId() + "-" + messageIdCounter.getAndIncrement();
result.put(STOMP_MESSAGE_ID_HEADER, Arrays.asList(messageId));
}
return result;
protected MessageHeaderAccessor createAccessor(Message<?> message) {
return factory.wrap(message);
}
public Map<String, List<String>> toStompHeaderMap() {
if (StompCommand.CONNECT.equals(getCommand())) {
StompPasscode credentials = (StompPasscode) getHeader(CREDENTIALS_HEADER);
if (credentials != null) {
Map<String, List<String>> headers = toNativeHeaderMap();
headers.put(STOMP_PASSCODE_HEADER, Arrays.asList(credentials.passcode));
return headers;
}
}
return toNativeHeaderMap();
Map<String, List<String>> getNativeHeaders() {
@SuppressWarnings("unchecked")
Map<String, List<String>> map = (Map<String, List<String>>) getHeader(NATIVE_HEADERS);
return (map != null ? map : Collections.<String, List<String>>emptyMap());
}
public StompCommand updateStompCommandAsClientMessage() {
Assert.state(SimpMessageType.MESSAGE.equals(getMessageType()),
"Unexpected message type " + getMessage());
Assert.state(SimpMessageType.MESSAGE.equals(getMessageType()), "Unexpected message type " + getMessage());
if (getCommand() == null) {
setHeader(COMMAND_HEADER, StompCommand.SEND);
@@ -236,26 +229,47 @@ public class StompHeaderAccessor extends SimpMessageHeaderAccessor {
public void updateStompCommandAsServerMessage() {
Assert.state(SimpMessageType.MESSAGE.equals(getMessageType()),
"Unexpected message type " + getMessage());
Assert.state(SimpMessageType.MESSAGE.equals(getMessageType()), "Unexpected message type " + getMessage());
if ((getCommand() == null) || getCommand().equals(StompCommand.SEND)) {
StompCommand command = getCommand();
if ((command == null) || StompCommand.SEND.equals(command)) {
setHeader(COMMAND_HEADER, StompCommand.MESSAGE);
}
else if (!getCommand().equals(StompCommand.MESSAGE)) {
throw new IllegalStateException("Unexpected STOMP command " + getCommand());
else if (!StompCommand.MESSAGE.equals(command)) {
throw new IllegalStateException("Unexpected STOMP command " + command);
}
trySetStompHeaderForSubscriptionId();
if (getMessageId() == null) {
String messageId = getSessionId() + "-" + messageIdCounter.getAndIncrement();
setNativeHeader(STOMP_MESSAGE_ID_HEADER, messageId);
}
}
/**
* @return the STOMP command, or {@code null} if not yet set.
*/
public StompCommand getCommand() {
return (StompCommand) getHeader(COMMAND_HEADER);
}
/**
* A static alternative for access to the STOMP command.
*/
public static StompCommand getCommand(Map<String, Object> headers) {
return (StompCommand) headers.get(COMMAND_HEADER);
}
public Set<String> getAcceptVersion() {
String rawValue = getFirstNativeHeader(STOMP_ACCEPT_VERSION_HEADER);
return (rawValue != null) ? StringUtils.commaDelimitedListToSet(rawValue) : Collections.<String>emptySet();
}
public boolean isHeartbeat() {
return (SimpMessageType.HEARTBEAT == getMessageType());
}
public void setAcceptVersion(String acceptVersion) {
setNativeHeader(STOMP_ACCEPT_VERSION_HEADER, acceptVersion);
}
@@ -288,9 +302,41 @@ public class StompHeaderAccessor extends SimpMessageHeaderAccessor {
setNativeHeader(STOMP_CONTENT_TYPE_HEADER, contentType.toString());
}
@Override
public void setSubscriptionId(String subscriptionId) {
super.setSubscriptionId(subscriptionId);
trySetStompHeaderForSubscriptionId();
}
private void trySetStompHeaderForSubscriptionId() {
String subscriptionId = getSubscriptionId();
if (subscriptionId != null) {
if (getCommand() != null && StompCommand.MESSAGE.equals(getCommand())) {
setNativeHeader(STOMP_SUBSCRIPTION_HEADER, subscriptionId);
}
else {
SimpMessageType messageType = getMessageType();
if (SimpMessageType.SUBSCRIBE.equals(messageType) || SimpMessageType.UNSUBSCRIBE.equals(messageType)) {
setNativeHeader(STOMP_ID_HEADER, subscriptionId);
}
}
}
}
public Integer getContentLength() {
String contentLength = getFirstNativeHeader(STOMP_CONTENT_LENGTH_HEADER);
return StringUtils.hasText(contentLength) ? new Integer(contentLength) : null;
if (containsNativeHeader(STOMP_CONTENT_LENGTH_HEADER)) {
return Integer.valueOf(getFirstNativeHeader(STOMP_CONTENT_LENGTH_HEADER));
}
return null;
}
public static Integer getContentLength(Map<String, List<String>> nativeHeaders) {
if (nativeHeaders.containsKey(STOMP_CONTENT_LENGTH_HEADER)) {
List<String> values = nativeHeaders.get(STOMP_CONTENT_LENGTH_HEADER);
String value = (values != null ? values.get(0) : null);
return Integer.valueOf(value);
}
return null;
}
public void setContentLength(int contentLength) {
@@ -298,7 +344,7 @@ public class StompHeaderAccessor extends SimpMessageHeaderAccessor {
}
public void setHeartbeat(long cx, long cy) {
setNativeHeader(STOMP_HEARTBEAT_HEADER, StringUtils.arrayToCommaDelimitedString(new Object[] {cx, cy}));
setNativeHeader(STOMP_HEARTBEAT_HEADER, StringUtils.arrayToCommaDelimitedString(new Object[]{cx, cy}));
}
public void setAck(String ack) {
@@ -328,10 +374,31 @@ public class StompHeaderAccessor extends SimpMessageHeaderAccessor {
public void setPasscode(String passcode) {
setNativeHeader(STOMP_PASSCODE_HEADER, passcode);
protectPasscode();
}
private void protectPasscode() {
String value = getFirstNativeHeader(STOMP_PASSCODE_HEADER);
if (value != null && !"PROTECTED".equals(value)) {
setHeader(CREDENTIALS_HEADER, new StompPasscode(value));
setNativeHeader(STOMP_PASSCODE_HEADER, "PROTECTED");
}
}
/**
* @return the passcode header value or {@code null}.
*/
public String getPasscode() {
return getFirstNativeHeader(STOMP_PASSCODE_HEADER);
StompPasscode credentials = (StompPasscode) getHeader(CREDENTIALS_HEADER);
return (credentials != null ? credentials.passcode : null);
}
/**
* A static alternative for access to the passcode header.
*/
public static String getPasscode(Map<String, Object> headers) {
StompPasscode credentials = (StompPasscode) headers.get(CREDENTIALS_HEADER);
return (credentials != null ? credentials.passcode : null);
}
public void setReceiptId(String receiptId) {

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.simp.stomp;
import org.springframework.messaging.Message;
import java.util.List;
import java.util.Map;
/**
* A factory for creating pre-configured instances of type
* {@link org.springframework.messaging.simp.stomp.StompHeaderAccessor}.
*
* @author Rossen Stoyanchev
* @since 4.1
*/
public interface StompHeaderAccessorFactory {
/**
* Create an instance for the given STOMP command.
*/
StompHeaderAccessor create(StompCommand command);
/**
* Create an instance for the given STOMP command and headers.
*/
StompHeaderAccessor create(StompCommand command, Map<String, List<String>> headers);
/**
* Create headers for a heartbeat. While a STOMP heartbeat frame does not
* have headers, a session id is needed for processing purposes at a minimum.
*/
StompHeaderAccessor createForHeartbeat();
/**
* Create an instance from the payload and headers of the given Message.
*/
StompHeaderAccessor wrap(Message<?> message);
}

View File

@@ -19,6 +19,7 @@ package org.springframework.messaging.simp.user;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.util.Assert;
@@ -100,34 +101,34 @@ public class DefaultUserDestinationResolver implements UserDestinationResolver {
@Override
public UserDestinationResult resolveDestination(Message<?> message) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
DestinationInfo info = parseUserDestination(headers);
String destination = SimpMessageHeaderAccessor.getDestination(message.getHeaders());
DestinationInfo info = parseUserDestination(message);
if (info == null) {
return null;
}
Set<String> targetDestinations = new HashSet<String>();
for (String sessionId : info.getSessionIds()) {
targetDestinations.add(getTargetDestination(
headers.getDestination(), info.getDestinationWithoutPrefix(), sessionId, info.getUser()));
targetDestinations.add(getTargetDestination(destination,
info.getDestinationWithoutPrefix(), sessionId, info.getUser()));
}
return new UserDestinationResult(headers.getDestination(),
return new UserDestinationResult(destination,
targetDestinations, info.getSubscribeDestination(), info.getUser());
}
private DestinationInfo parseUserDestination(SimpMessageHeaderAccessor headers) {
private DestinationInfo parseUserDestination(Message<?> message) {
String destination = headers.getDestination();
MessageHeaders headers = message.getHeaders();
SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
String destination = SimpMessageHeaderAccessor.getDestination(headers);
Principal principal = SimpMessageHeaderAccessor.getUser(headers);
String destinationWithoutPrefix;
String subscribeDestination;
String user;
Set<String> sessionIds;
Principal principal = headers.getUser();
SimpMessageType messageType = headers.getMessageType();
if (SimpMessageType.SUBSCRIBE.equals(messageType) || SimpMessageType.UNSUBSCRIBE.equals(messageType)) {
if (!checkDestination(destination, this.destinationPrefix)) {
return null;
@@ -136,14 +137,15 @@ public class DefaultUserDestinationResolver implements UserDestinationResolver {
logger.error("Ignoring message, no principal info available");
return null;
}
if (headers.getSessionId() == null) {
String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
if (sessionId == null) {
logger.error("Ignoring message, no session id available");
return null;
}
destinationWithoutPrefix = destination.substring(this.destinationPrefix.length()-1);
subscribeDestination = destination;
user = principal.getName();
sessionIds = Collections.singleton(headers.getSessionId());
sessionIds = Collections.singleton(sessionId);
}
else if (SimpMessageType.MESSAGE.equals(messageType)) {
if (!checkDestination(destination, this.destinationPrefix)) {

View File

@@ -152,16 +152,16 @@ public class UserDestinationMessageHandler implements MessageHandler, SmartLifec
if (destinations.isEmpty()) {
return;
}
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.wrap(message);
if (SimpMessageType.MESSAGE.equals(headerAccessor.getMessageType())) {
if (SimpMessageType.MESSAGE.equals(SimpMessageHeaderAccessor.getMessageType(message.getHeaders()))) {
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.wrap(message);
headerAccessor.setHeader(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION, result.getSubscribeDestination());
message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headerAccessor).build();
message = MessageBuilder.createMessage(message.getPayload(), headerAccessor.getMessageHeaders());
}
for (String targetDestination : destinations) {
for (String destination : destinations) {
if (logger.isDebugEnabled()) {
logger.debug("Sending message to resolved destination=" + targetDestination);
logger.debug("Sending message to resolved destination=" + destination);
}
this.brokerMessagingTemplate.send(targetDestination, message);
this.brokerMessagingTemplate.send(destination, message);
}
}

View File

@@ -104,7 +104,7 @@ public abstract class AbstractMessageChannel implements MessageChannel, BeanName
Assert.notNull(message, "Message must not be null");
if (logger.isTraceEnabled()) {
logger.trace("[" + this.beanName + "] sending message id=" + message.getHeaders().getId());
logger.trace("[" + this.beanName + "] sending message=" + message);
}
message = this.interceptorChain.preSend(message, this);

View File

@@ -57,7 +57,7 @@ class ChannelInterceptorChain {
public Message<?> preSend(Message<?> message, MessageChannel channel) {
UUID originalId = message.getHeaders().getId();
Message<?> originalMessage = message;
for (ChannelInterceptor interceptor : this.interceptors) {
message = interceptor.preSend(message, channel);
if (message == null) {
@@ -68,8 +68,8 @@ class ChannelInterceptorChain {
}
}
if (logger.isDebugEnabled()) {
if (!message.getHeaders().getId().equals(originalId)) {
logger.debug("preSend returned modified message, new message id=" + message.getHeaders().getId());
if (message != originalMessage) {
logger.debug("preSend returned modified message, new message=" + message);
}
}
return message;
@@ -77,7 +77,7 @@ class ChannelInterceptorChain {
public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
if (logger.isTraceEnabled()) {
logger.trace("postSend (sent=" + sent + ") message id " + message.getHeaders().getId());
logger.trace("postSend (sent=" + sent + ")");
}
for (ChannelInterceptor interceptor : this.interceptors) {
interceptor.postSend(message, channel, sent);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.messaging.support;
import org.springframework.messaging.MessageHeaders;
import java.util.Map;
/**
@@ -43,12 +45,26 @@ public class ErrorMessage extends GenericMessage<Throwable> {
/**
* Create a new message with the given payload and headers.
* The content of the given header map is copied.
*
* @param payload the message payload, never {@code null}
* @param headers message headers
* @param headers message headers to use for initialization
*/
public ErrorMessage(Throwable payload, Map<String, Object> headers) {
super(payload, headers);
}
/**
* A constructor with the {@link MessageHeaders} instance to use.
*
* <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 message payload, never {@code null}
* @param headers message headers
*/
public ErrorMessage(Throwable payload, MessageHeaders headers) {
super(payload, headers);
}
}

View File

@@ -49,18 +49,33 @@ public class GenericMessage<T> implements Message<T>, Serializable {
* @param payload the message payload, never {@code null}
*/
public GenericMessage(T payload) {
this(payload, null);
this(payload, new MessageHeaders(null));
}
/**
* Create a new message with the given payload and headers.
* The content of the given header map is copied.
*
* @param payload the message payload, never {@code null}
* @param headers message headers to use for initialization
*/
public GenericMessage(T payload, Map<String, Object> headers) {
this(payload, new MessageHeaders(headers));
}
/**
* A constructor with the {@link MessageHeaders} instance to use.
*
* <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 message payload, never {@code null}
* @param headers message headers
*/
public GenericMessage(T payload, Map<String, Object> headers) {
public GenericMessage(T payload, MessageHeaders headers) {
Assert.notNull(headers, "'headers' must not be null");
Assert.notNull(payload, "payload must not be null");
this.headers = new MessageHeaders(headers);
this.headers = headers;
this.payload = payload;
}
@@ -96,7 +111,7 @@ public class GenericMessage<T> implements Message<T>, Serializable {
}
if (obj != null && obj instanceof GenericMessage<?>) {
GenericMessage<?> other = (GenericMessage<?>) obj;
return (this.headers.getId().equals(other.headers.getId()) &&
return (ObjectUtils.nullSafeEquals(this.headers.getId(), other.headers.getId()) &&
this.headers.equals(other.headers) && this.payload.equals(other.payload));
}
return false;

View File

@@ -20,6 +20,7 @@ import java.util.Map;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.util.Assert;
/**
@@ -36,23 +37,27 @@ import org.springframework.util.Assert;
*/
public final class MessageBuilder<T> {
private final Message<T> originalMessage;
private final T payload;
private MessageHeaderAccessor headerAccessor;
private final Message<T> originalMessage;
/**
* Private constructor to be invoked from the static factory methods only.
*/
private MessageBuilder(T payload, Message<T> originalMessage) {
Assert.notNull(payload, "payload must not be null");
this.payload = payload;
this.originalMessage = originalMessage;
private MessageBuilder(Message<T> originalMessage) {
Assert.notNull(originalMessage, "'originalMessage' must not be null");
this.payload = originalMessage.getPayload();
this.headerAccessor = new MessageHeaderAccessor(originalMessage);
this.originalMessage = originalMessage;
}
private MessageBuilder(T payload, MessageHeaderAccessor accessor) {
Assert.notNull(payload, "'payload' must not be null");
Assert.notNull(accessor, "'messageHeaderAccessor' must not be null");
this.payload = payload;
this.headerAccessor = accessor;
this.originalMessage = null;
}
/**
* Create a builder for a new {@link Message} instance pre-populated with all of the
@@ -62,26 +67,49 @@ public final class MessageBuilder<T> {
* @param message the Message from which the payload and all headers will be copied
*/
public static <T> MessageBuilder<T> fromMessage(Message<T> message) {
Assert.notNull(message, "message must not be null");
return new MessageBuilder<T>(message.getPayload(), message);
return new MessageBuilder<T>(message);
}
/**
* Create a builder for a new {@link Message} instance with the provided payload.
* @param payload the payload for the new message
* Create a new builder for a message with the given payload.
* @param payload the payload
*/
public static <T> MessageBuilder<T> withPayload(T payload) {
return new MessageBuilder<T>(payload, null);
return new MessageBuilder<T>(payload, new MessageHeaderAccessor());
}
/**
* 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);
}
}
/**
* Set the message headers.
* @param headerAccessor the headers for the message
* Set the message headers to use by providing a {@code MessageHeaderAccessor}.
*
* @param accessor the headers to use
*/
public MessageBuilder<T> setHeaders(MessageHeaderAccessor headerAccessor) {
Assert.notNull(headerAccessor, "HeaderAccessor must not be null");
this.headerAccessor = headerAccessor;
public MessageBuilder<T> setHeaders(MessageHeaderAccessor accessor) {
Assert.notNull(accessor, "HeaderAccessor must not be null");
this.headerAccessor = accessor;
return this;
}
@@ -161,13 +189,17 @@ public final class MessageBuilder<T> {
@SuppressWarnings("unchecked")
public Message<T> build() {
if ((this.originalMessage != null) && !this.headerAccessor.isModified()) {
if (this.originalMessage != null && !this.headerAccessor.isModified()) {
return this.originalMessage;
}
if (this.payload instanceof Throwable) {
return (Message<T>) new ErrorMessage((Throwable) this.payload, this.headerAccessor.toMap());
}
return new GenericMessage<T>(this.payload, this.headerAccessor.toMap());
else {
return new GenericMessage<T>(this.payload, this.headerAccessor.toMap());
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,19 +29,74 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.util.Assert;
import org.springframework.util.IdGenerator;
import org.springframework.util.MimeType;
import org.springframework.util.ObjectUtils;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;
/**
* A base class for read/write access to {@link MessageHeaders}. Supports creation of new
* headers or modification of existing message headers.
* A base for classes providing strongly typed getters and setters as well as
* behavior around specific categories of headers (e.g. STOMP headers).
* Supports creating new headers (default constructor), modifying existing headers
* (when still mutable), or copying and modifying existing headers.
*
* <p>Sub-classes can provide additional typed getters and setters for convenient access
* to specific headers. Getters and setters should delegate to {@link #getHeader(String)}
* or {@link #setHeader(String, Object)} respectively. At the end {@link #toMap()} can be
* used to obtain the resulting headers.
* <p>The {@link #getMessageHeaders()} method provides access to the underlying,
* fully-prepared {@code MessageHeaders} instance that can then be used as-is
* to create a single message as follows:
*
* <pre class="code">
* MessageHeaderAccessor headerAccessor = new MessageHeaderAccessor();
* headerAccessor.set("foo", "bar");
* Message message = MessageBuilder.createMessage("payload", headerAccessor.getMessageHeaders());
* </pre>
*
* <p>After the above is executed, by default the {@code MessageHeaderAccessor}
* is immutable. It is also possible to leave it mutable, for example for further
* initialization of the message in the same thread:
*
* <pre class="code">
* MessageHeaderAccessor headerAccessor = new MessageHeaderAccessor();
* headerAccessor.set("foo", "bar");
* headerAccessor.setLeaveMutable(true);
* Message message = MessageBuilder.createMessage("payload", headerAccessor.getMessageHeaders());
*
* // later on in the same thread...
*
* MessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(message);
* headerAccessor.set("bar", "baz");
* headerAccessor.setImmutable();
* </pre>
*
* <p>To re-obtain the {@code MessageHeaderAccessor} for a {@code MessageHeaders}
* instance, use the following:
*
* <pre class="code">
* MessageHeaderAccessor headerAccessor = new MessageHeaderAccessor();
* headerAccessor.set("foo", "bar");
* Message message = MessageBuilder.createMessage("payload", headerAccessor.getMessageHeaders());
*
* // later on (any thread)...
* MessageHeaderAccessor headerAccessor = MessageHeaderAccessor.getAccessor(message);
* headerAccessor.get("foo");
* </pre>
*
* <p>To prepare multiple messages with the same {@code MessageHeaderAccessor}
* instance, use the code below. However note that this usage style does not allow
* re-obtaining a header accessor later on:
* <pre class="code">
* MessageHeaderAccessor headerAccessor = new MessageHeaderAccessor();
* MessageBuilder builder = MessageBuilder.withPayload("payload").setHeaders(headerAccessor);
*
* headerAccessor.setHeader("foo", "bar1");
* Message message1 = builder.build();
*
* headerAccessor.setHeader("foo", "bar2");
* Message message2 = builder.build();
*
* headerAccessor.setHeader("foo", "bar3");
* Message message3 = builder.build();
* </pre>
*
* @author Rossen Stoyanchev
* @since 4.0
@@ -50,62 +105,209 @@ public class MessageHeaderAccessor {
protected Log logger = LogFactory.getLog(getClass());
private final MutableMessageHeaders headers;
// wrapped read-only message headers
private final MessageHeaders originalHeaders;
private boolean modified;
// header updates
private final Map<String, Object> headers = new HashMap<String, Object>(4);
private boolean leaveMutable;
private IdGenerator idGenerator;
private boolean enableTimestamp = false;
/**
* A constructor for creating new message headers.
* A constructor to create new headers.
*/
public MessageHeaderAccessor() {
this.originalHeaders = null;
this.headers = new MutableMessageHeaders();
}
/**
* A constructor for accessing and modifying existing message headers.
* A constructor accepting the headers of an existing message to copy.
*/
public MessageHeaderAccessor(Message<?> message) {
this.originalHeaders = (message != null) ? message.getHeaders() : null;
if (message != null) {
this.headers = new MutableMessageHeaders(message.getHeaders());
MessageHeaderAccessor accessor = getAccessor(message, MessageHeaderAccessor.class);
if (accessor != null) {
this.idGenerator = accessor.idGenerator;
this.enableTimestamp = accessor.enableTimestamp;
}
}
else {
this.headers = new MutableMessageHeaders();
}
}
/**
* Return the original {@code MessageHeaderAccessor} used to create the headers
* of the given {@code Message}, or {@code null} if that's not available or if
* its type does not match the required type.
*
* <p>This is for cases where the existence of an accessor is strongly expected
* (to be followed up with an assertion) or will created if not provided.
*
* @return an accessor instance of the specified type or {@code null}.
* @since 4.1
*/
@SuppressWarnings("unchecked")
public static <T extends MessageHeaderAccessor> T getAccessor(Message<?> message, Class<T> requiredType) {
return getAccessor(message.getHeaders(), requiredType);
}
/**
* Return a header map including original, wrapped headers (if any) plus additional
* header updates made through accessor methods.
* 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}.
* @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;
}
/**
* 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.getMessageHeaderAccessor();
if (accessor != null) {
return (accessor.isMutable() ? accessor : accessor.createAccessor(message));
}
}
return new MessageHeaderAccessor(message);
}
protected MessageHeaderAccessor createAccessor(Message<?> message) {
return new MessageHeaderAccessor(message);
}
/**
* Return the underlying {@code MessageHeaders} instance.
*
* <p>Unless {@link #setLeaveMutable(boolean)} was set to {@code true}, after
* this call, the headers are immutable and this accessor can no longer
* modify them.
*
* <p>This method always returns the same {@code MessageHeaders} instance if
* invoked multiples times. To obtain a copy of the underlying headers instead
* use {@link #toMap()}.
*/
public MessageHeaders getMessageHeaders() {
this.headers.setIdAndTimestamp();
if (!this.leaveMutable) {
setImmutable();
}
return this.headers;
}
/**
* Return a copy of the underlying header values.
*
* <p>This method can be invoked many times, with modifications in between
* where each new call returns a fresh copy of the current header values.
*/
public Map<String, Object> toMap() {
Map<String, Object> result = new HashMap<String, Object>();
if (this.originalHeaders != null) {
result.putAll(this.originalHeaders);
}
for (String key : this.headers.keySet()) {
Object value = this.headers.get(key);
if (value == null) {
result.remove(key);
}
else {
result.put(key, value);
}
}
return result;
return new HashMap<String, Object>(this.headers);
}
/**
* By default when {@link #getMessageHeaders()} is called, {@code "this"}
* {@code MessageHeaderAccessor} instance can no longer be used to modify the
* underlying message headers and the returned {@code MessageHeaders} is immutable.
*
* <p>However when this is set to {@code true}, the returned (underlying)
* {@code MessageHeaders} instance remains mutable. To make further modifications
* continue to use the same accessor instance or re-obtain it via:<br>
* {@link org.springframework.messaging.support.MessageHeaderAccessor#getAccessor(org.springframework.messaging.Message, Class)
* MessageHeaderAccessor.getAccessor(Message, Class)}
*
* <p>When modifications are complete use {@link #setImmutable()} to prevent
* further changes. The intended use case for this mechanism is initialization
* of a Message within a single thread.
*
* <p>By default this is set to {@code false}.
* @since 4.1
*/
public void setLeaveMutable(boolean leaveMutable) {
Assert.state(this.headers.isMutable(), "Already immutable");
this.leaveMutable = leaveMutable;
}
/**
* By default when {@link #getMessageHeaders()} is called, {@code "this"}
* {@code MessageHeaderAccessor} instance can no longer be used to modify the
* underlying message headers. However if {@link #setLeaveMutable(boolean)}
* is used, this method is necessary to indicate explicitly when the
* {@code MessageHeaders} instance should no longer be modified.
* @since 4.1
*/
public void setImmutable() {
this.headers.setImmutable();
}
/**
* Whether the underlying headers can still be modified.
* @since 4.1
*/
public boolean isMutable() {
return this.headers.isMutable();
}
/**
* A private mechanism for providing an alternate IdGenerator strategy.
*
* <p>By default this property is not set in which case the default IdGenerator
* of {@link org.springframework.messaging.MessageHeaders} is used.
*
* @see org.springframework.messaging.support.MessageHeaderAccessorFactorySupport
*/
void setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
/**
* A private mechanism to enable having a timestamp added to every message.
*
* <p>By default this property is set to false.
*
* @see org.springframework.messaging.support.MessageHeaderAccessorFactorySupport
*/
void setEnableTimestamp(boolean enableTimestamp) {
this.enableTimestamp = enableTimestamp;
}
public boolean isModified() {
return (!this.headers.isEmpty());
return this.modified;
}
protected void setModified(boolean modified) {
this.modified = modified;
}
public Object getHeader(String headerName) {
if (this.headers.containsKey(headerName)) {
return this.headers.get(headerName);
}
else if (this.originalHeaders != null) {
return this.originalHeaders.get(headerName);
}
return null;
return this.headers.get(headerName);
}
/**
@@ -116,7 +318,22 @@ public class MessageHeaderAccessor {
Assert.isTrue(!isReadOnly(name), "The '" + name + "' header is read-only.");
verifyType(name, value);
if (!ObjectUtils.nullSafeEquals(value, getHeader(name))) {
this.headers.put(name, value);
this.modified = true;
if (value != null) {
this.headers.getRawHeaders().put(name, value);
}
else {
this.headers.getRawHeaders().remove(name);
}
}
}
protected void verifyType(String headerName, Object headerValue) {
if (headerName != null && headerValue != null) {
if (MessageHeaders.ERROR_CHANNEL.equals(headerName) || MessageHeaders.REPLY_CHANNEL.endsWith(headerName)) {
Assert.isTrue(headerValue instanceof MessageChannel || headerValue instanceof String, "The '"
+ headerName + "' header value must be a MessageChannel or String.");
}
}
}
@@ -144,7 +361,6 @@ public class MessageHeaderAccessor {
if (StringUtils.hasLength(pattern)){
if (pattern.contains("*")){
headersToRemove.addAll(getMatchingHeaderNames(pattern, this.headers));
headersToRemove.addAll(getMatchingHeaderNames(pattern, this.originalHeaders));
}
else {
headersToRemove.add(pattern);
@@ -251,17 +467,59 @@ public class MessageHeaderAccessor {
@Override
public String toString() {
return getClass().getSimpleName() + " [originalHeaders=" + this.originalHeaders
+ ", updated headers=" + this.headers + "]";
return getClass().getSimpleName() + " [headers=" + this.headers + "]";
}
@SuppressWarnings("serial")
private class MutableMessageHeaders extends MessageHeaders {
private boolean immutable;
public MutableMessageHeaders() {
this(null);
}
public MutableMessageHeaders(Map<String, Object> headers) {
super(headers, MessageHeaders.ID_VALUE_NONE, -1L);
}
public MessageHeaderAccessor getMessageHeaderAccessor() {
return MessageHeaderAccessor.this;
}
@Override
public Map<String, Object> getRawHeaders() {
Assert.state(!this.immutable, "Already immutable");
return super.getRawHeaders();
}
public void setImmutable() {
this.immutable = true;
}
public boolean isMutable() {
return !this.immutable;
}
public void setIdAndTimestamp() {
if (getId() == null) {
IdGenerator idGenerator = (MessageHeaderAccessor.this.idGenerator != null) ?
MessageHeaderAccessor.this.idGenerator :
MessageHeaders.getIdGenerator();
UUID id = idGenerator.generateId();
if (id != null && id != MessageHeaders.ID_VALUE_NONE) {
getRawHeaders().put(ID, id);
}
}
if (getTimestamp() == null) {
if (MessageHeaderAccessor.this.enableTimestamp) {
getRawHeaders().put(TIMESTAMP, System.currentTimeMillis());
}
}
}
}
protected void verifyType(String headerName, Object headerValue) {
if (headerName != null && headerValue != null) {
if (MessageHeaders.ERROR_CHANNEL.equals(headerName)
|| MessageHeaders.REPLY_CHANNEL.endsWith(headerName)) {
Assert.isTrue(headerValue instanceof MessageChannel || headerValue instanceof String, "The '"
+ headerName + "' header value must be a MessageChannel or String.");
}
}
}
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.support;
import org.springframework.util.IdGenerator;
/**
* A support class for factories creating pre-configured instances of type
* {@link org.springframework.messaging.support.MessageHeaderAccessor}.
*
* @author Rossen Stoyanchev
* @since 4.1
*/
public class MessageHeaderAccessorFactorySupport {
private IdGenerator idGenerator;
private Boolean enableTimestamp;
protected MessageHeaderAccessorFactorySupport() {
}
/**
*
* @param idGenerator
*/
public void setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
public IdGenerator getIdGenerator() {
return this.idGenerator;
}
public void setEnableTimestamp(boolean enableTimestamp) {
this.enableTimestamp = enableTimestamp;
}
public boolean isEnableTimestamp() {
return this.enableTimestamp;
}
protected void updateMessageHeaderAccessor(MessageHeaderAccessor headerAccessor) {
if (this.idGenerator != null) {
headerAccessor.setIdGenerator(this.idGenerator);
}
if (this.enableTimestamp != null) {
headerAccessor.setEnableTimestamp(this.enableTimestamp);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,25 +16,26 @@
package org.springframework.messaging.support;
import java.util.HashMap;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.springframework.messaging.Message;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
/**
* An extension of {@link MessageHeaderAccessor} that also stores and provides read/write
* access to message headers from an external source -- e.g. a Spring {@link Message}
* created to represent a STOMP message received from a STOMP client or message broker.
* Native message headers are kept in a {@link MultiValueMap} under the key
* Native message headers are kept in a {@code Map<String, List<String>>} under the key
* {@link #NATIVE_HEADERS}.
* <p>
* This class is not intended for direct use but is rather expected to be consumed
* through sub-classes such as
* This class is not intended for direct use but is rather expected to be used
* indirectly through protocol-specific sub-classes such as
* {@link org.springframework.messaging.simp.stomp.StompHeaderAccessor StompHeaderAccessor}.
* Such sub-classes may provide factory methods to translate message headers from
* an external messaging source (e.g. STOMP) to Spring {@link Message} headers and
@@ -49,107 +50,140 @@ public class NativeMessageHeaderAccessor extends MessageHeaderAccessor {
public static final String NATIVE_HEADERS = "nativeHeaders";
// wrapped native headers
private final Map<String, List<String>> originalNativeHeaders;
// native header updates
private final MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<String, String>(4);
/**
* A constructor for creating new headers, accepting an optional native header map.
* A protected constructor to create new headers.
*/
protected NativeMessageHeaderAccessor(Map<String, List<String>> nativeHeaders) {
this.originalNativeHeaders = nativeHeaders;
protected NativeMessageHeaderAccessor() {
this((Map<String, List<String>>) null);
}
/**
* A constructor for accessing and modifying existing message headers.
* A protected constructor to create new headers.
* @param nativeHeaders native headers to create the message with, may be {@code null}
*/
protected NativeMessageHeaderAccessor(Map<String, List<String>> nativeHeaders) {
if (!CollectionUtils.isEmpty(nativeHeaders)) {
setHeader(NATIVE_HEADERS, new LinkedMultiValueMap<String, String>(nativeHeaders));
}
}
/**
* A protected constructor accepting the headers of an existing message to copy.
*/
protected NativeMessageHeaderAccessor(Message<?> message) {
super(message);
this.originalNativeHeaders = initNativeHeaders(message);
}
private static Map<String, List<String>> initNativeHeaders(Message<?> message) {
if (message != null) {
@SuppressWarnings("unchecked")
Map<String, List<String>> headers = (Map<String, List<String>>) message.getHeaders().get(NATIVE_HEADERS);
if (headers != null) {
return headers;
Map<String, List<String>> map = (Map<String, List<String>>) getHeader(NATIVE_HEADERS);
if (map != null) {
// Force removal since setHeader checks for equality
removeHeader(NATIVE_HEADERS);
setHeader(NATIVE_HEADERS, new LinkedMultiValueMap<String, String>(map));
}
}
return null;
}
@Override
public Map<String, Object> toMap() {
Map<String, Object> result = super.toMap();
result.put(NATIVE_HEADERS, toNativeHeaderMap());
return result;
}
@Override
public boolean isModified() {
return (super.isModified() || (!this.nativeHeaders.isEmpty()));
@SuppressWarnings("unchecked")
private Map<String, List<String>> getNativeHeaders() {
return (Map<String, List<String>>) getHeader(NATIVE_HEADERS);
}
/**
* Return a map with native headers including original, wrapped headers (if any) plus
* additional header updates made through accessor methods.
* Return a copy of the native header values or an empty map.
*/
public Map<String, List<String>> toNativeHeaderMap() {
Map<String, List<String>> result = new HashMap<String, List<String>>();
if (this.originalNativeHeaders != null) {
result.putAll(this.originalNativeHeaders);
}
for (String key : this.nativeHeaders.keySet()) {
List<String> value = this.nativeHeaders.get(key);
if (value == null) {
result.remove(key);
}
else {
result.put(key, value);
Map<String, List<String>> map = getNativeHeaders();
return (map != null ? new LinkedMultiValueMap<String, String>(map) : Collections.<String, List<String>>emptyMap());
}
@Override
public void setImmutable() {
if (isMutable()) {
Map<String, List<String>> map = getNativeHeaders();
if (map != null) {
// Force removal since setHeader checks for equality
removeHeader(NATIVE_HEADERS);
setHeader(NATIVE_HEADERS, Collections.<String, List<String>>unmodifiableMap(map));
}
super.setImmutable();
}
return result;
}
/**
* Return all values for the specified native header or {@code null}.
* Whether the native header map contains the give header name.
*/
public boolean containsNativeHeader(String headerName) {
Map<String, List<String>> map = getNativeHeaders();
return (map != null ? map.containsKey(headerName) : false);
}
/**
* @return all values for the specified native header or {@code null}.
*/
public List<String> getNativeHeader(String headerName) {
if (this.nativeHeaders.containsKey(headerName)) {
return this.nativeHeaders.get(headerName);
}
else if (this.originalNativeHeaders != null) {
return this.originalNativeHeaders.get(headerName);
Map<String, List<String>> map = getNativeHeaders();
return (map != null ? map.get(headerName) : null);
}
/**
* @return the first value for the specified native header of {@code null}.
*/
public String getFirstNativeHeader(String headerName) {
Map<String, List<String>> map = getNativeHeaders();
if (map != null) {
List<String> values = map.get(headerName);
if (values != null) {
return values.get(0);
}
}
return null;
}
/**
* Return the first value for the specified native header of {@code null}.
*/
public String getFirstNativeHeader(String headerName) {
List<String> values = getNativeHeader(headerName);
return CollectionUtils.isEmpty(values) ? null : values.get(0);
}
/**
* Set the specified native header value.
* Set the specified native header value replacing existing values.
*/
public void setNativeHeader(String name, String value) {
if (!ObjectUtils.nullSafeEquals(value, getHeader(name))) {
this.nativeHeaders.set(name, value);
Assert.state(isMutable(), "Already immutable");
Map<String, List<String>> map = getNativeHeaders();
if (value == null) {
if (map != null && map.get(name) != null) {
setModified(true);
map.remove(name);
}
return;
}
if (map == null) {
map = new LinkedMultiValueMap<String, String>(4);
setHeader(NATIVE_HEADERS, map);
}
List<String> values = new LinkedList<String>();
values.add(value);
if (!ObjectUtils.nullSafeEquals(values, getHeader(name))) {
setModified(true);
map.put(name, values);
}
}
/**
* Add the specified native header value.
* Add the specified native header value to existing values.
*/
public void addNativeHeader(String name, String value) {
this.nativeHeaders.add(name, value);
Assert.state(isMutable(), "Already immutable");
if (value == null) {
return;
}
Map<String, List<String>> nativeHeaders = getNativeHeaders();
if (nativeHeaders == null) {
nativeHeaders = new LinkedMultiValueMap<String, String>(4);
setHeader(NATIVE_HEADERS, nativeHeaders);
}
List<String> values = nativeHeaders.get(name);
if (values == null) {
values = new LinkedList<String>();
nativeHeaders.put(name, values);
}
values.add(value);
setModified(true);
}
}

View File

@@ -20,6 +20,7 @@ import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@@ -53,6 +54,25 @@ public class MessageHeadersTests {
assertNotSame(headers1.getTimestamp(), headers2.getTimestamp());
}
@Test
public void testTimestampProvided() throws Exception {
MessageHeaders headers = new MessageHeaders(null, null, 10L);
assertEquals(10L, (long) headers.getTimestamp());
}
@Test
public void testTimestampProvidedNullValue() throws Exception {
Map<String, Object> input = Collections.<String, Object>singletonMap(MessageHeaders.TIMESTAMP, 1L);
MessageHeaders headers = new MessageHeaders(input, null, null);
assertNotNull(headers.getTimestamp());
}
@Test
public void testTimestampNone() throws Exception {
MessageHeaders headers = new MessageHeaders(null, null, -1L);
assertNull(headers.getTimestamp());
}
@Test
public void testIdOverwritten() throws Exception {
MessageHeaders headers1 = new MessageHeaders(null);
@@ -66,6 +86,26 @@ public class MessageHeadersTests {
assertNotNull(headers.getId());
}
@Test
public void testIdProvided() {
UUID id = new UUID(0L, 25L);
MessageHeaders headers = new MessageHeaders(null, id, null);
assertEquals(id, headers.getId());
}
@Test
public void testIdProvidedNullValue() {
Map<String, Object> input = Collections.<String, Object>singletonMap(MessageHeaders.ID, new UUID(0L, 25L));
MessageHeaders headers = new MessageHeaders(input, null, null);
assertNotNull(headers.getId());
}
@Test
public void testIdNone() {
MessageHeaders headers = new MessageHeaders(null, MessageHeaders.ID_VALUE_NONE, null);
assertNull(headers.getId());
}
@Test
public void testNonTypedAccessOfHeaderValue() {
Integer value = new Integer(123);
@@ -148,7 +188,7 @@ public class MessageHeadersTests {
class MyMH extends MessageHeaders {
public MyMH() {
super(null, new UUID(0, id.incrementAndGet()), null);
super(null, new UUID(0, id.incrementAndGet()), -1L);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,6 +26,8 @@ import org.junit.Before;
import org.junit.Test;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
@@ -34,7 +36,8 @@ import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
/**
* Test fixture for {@link org.springframework.messaging.converter.AbstractMessageConverter}.
* Unit tests for
* {@link org.springframework.messaging.converter.AbstractMessageConverter}.
*
* @author Rossen Stoyanchev
*/
@@ -109,15 +112,34 @@ public class MessageConverterTests {
}
@Test
public void toMessageHeadersCopied() {
public void toMessageWithHeaders() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("foo", "bar");
MessageHeaders headers = new MessageHeaders(map );
MessageHeaders headers = new MessageHeaders(map);
Message<?> message = this.converter.toMessage("ABC", headers);
assertNotNull(message.getHeaders().getId());
assertNotNull(message.getHeaders().getTimestamp());
assertEquals(MimeTypeUtils.TEXT_PLAIN, message.getHeaders().get(MessageHeaders.CONTENT_TYPE));
assertEquals("bar", message.getHeaders().get("foo"));
}
@Test
public void toMessageWithMutableMessageHeaders() {
SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
accessor.setHeader("foo", "bar");
accessor.setNativeHeader("fooNative", "barNative");
accessor.setLeaveMutable(true);
MessageHeaders headers = accessor.getMessageHeaders();
Message<?> message = this.converter.toMessage("ABC", headers);
assertSame(headers, message.getHeaders());
assertNull(message.getHeaders().getId());
assertNull(message.getHeaders().getTimestamp());
assertEquals(MimeTypeUtils.TEXT_PLAIN, message.getHeaders().get(MessageHeaders.CONTENT_TYPE));
}
@Test
public void toMessageContentTypeHeader() {
Message<?> message = this.converter.toMessage("ABC", null);

View File

@@ -0,0 +1,74 @@
/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.converter;
import org.junit.Before;
import org.junit.Test;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageHeaderAccessor;
import java.util.Collections;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
/**
* Unit tests for
* {@link org.springframework.messaging.converter.SimpleMessageConverter}.
*
* @author Rossen Stoyanchev
*/
public class SimpleMessageConverterTests {
private SimpleMessageConverter converter;
@Before
public void setup() {
this.converter = new SimpleMessageConverter();
}
@Test
public void toMessageWithNullPayload() {
assertNull(this.converter.toMessage(null, null));
}
@Test
public void toMessageWithPayloadAndHeaders() {
MessageHeaders headers = new MessageHeaders(Collections.<String, Object>singletonMap("foo", "bar"));
Message<?> message = this.converter.toMessage("payload", headers);
assertEquals("payload", message.getPayload());
assertEquals("bar", message.getHeaders().get("foo"));
}
@Test
public void toMessageWithPayloadAndMutableHeaders() {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setHeader("foo", "bar");
accessor.setLeaveMutable(true);
MessageHeaders headers = accessor.getMessageHeaders();
Message<?> message = this.converter.toMessage("payload", headers);
assertEquals("payload", message.getPayload());
assertSame(headers, message.getHeaders());
assertEquals("bar", message.getHeaders().get("foo"));
}
}

View File

@@ -16,6 +16,7 @@
package org.springframework.messaging.core;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@@ -27,10 +28,13 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageDeliveryException;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.StubMessageChannel;
import org.springframework.messaging.SubscribableChannel;
import org.springframework.messaging.support.ExecutorSubscribableChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import static org.junit.Assert.*;
@@ -44,12 +48,17 @@ public class GenericMessagingTemplateTests {
private GenericMessagingTemplate template;
private StubMessageChannel messageChannel;
private ThreadPoolTaskExecutor executor;
@Before
public void setup() {
this.messageChannel = new StubMessageChannel();
this.template = new GenericMessagingTemplate();
this.template.setDefaultDestination(this.messageChannel);
this.template.setDestinationResolver(new TestDestinationResolver());
this.executor = new ThreadPoolTaskExecutor();
this.executor.afterPropertiesSet();
}
@@ -114,4 +123,26 @@ public class GenericMessagingTemplateTests {
}
}
@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());
}
private class TestDestinationResolver implements DestinationResolver<MessageChannel> {
@Override
public MessageChannel resolveDestination(String name) throws DestinationResolutionException {
return messageChannel;
}
}
}

View File

@@ -16,6 +16,7 @@
package org.springframework.messaging.core;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@@ -27,6 +28,8 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.*;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import static org.junit.Assert.*;
@@ -122,6 +125,22 @@ public class MessageSendingTemplateTests {
assertEquals("payload", this.template.message.getPayload());
}
@Test
public void convertAndSendPayloadAndMutableHeadersToDestination() {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setHeader("foo", "bar");
accessor.setLeaveMutable(true);
MessageHeaders messageHeaders = accessor.getMessageHeaders();
this.template.setMessageConverter(new StringMessageConverter());
this.template.convertAndSend("somewhere", "payload", messageHeaders);
MessageHeaders actual = this.template.message.getHeaders();
assertSame(messageHeaders, actual);
assertEquals(new MimeType("text", "plain", Charset.forName("UTF-8")), actual.get(MessageHeaders.CONTENT_TYPE));
assertEquals("bar", actual.get("foo"));
}
@Test
public void convertAndSendPayloadWithPostProcessor() {
this.template.setDefaultDestination("home");

View File

@@ -17,6 +17,8 @@
package org.springframework.messaging.handler.annotation.support;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
@@ -149,7 +151,7 @@ public class HeaderMethodArgumentResolverTests {
public static class TestMessageHeaderAccessor extends NativeMessageHeaderAccessor {
protected TestMessageHeaderAccessor() {
super((Message<?>) null);
super((Map<String, List<String>>) null);
}
}

View File

@@ -16,16 +16,27 @@
package org.springframework.messaging.simp;
import org.apache.activemq.transport.stomp.Stomp;
import org.junit.Before;
import org.junit.Test;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.StubMessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.messaging.support.NativeMessageHeaderAccessor;
import org.springframework.util.LinkedMultiValueMap;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for {@link org.springframework.messaging.simp.SimpMessagingTemplate}.
@@ -42,7 +53,7 @@ public class SimpMessagingTemplateTests {
@Before
public void setup() {
this.messageChannel = new StubMessageChannel();
this.messagingTemplate = new SimpMessagingTemplate(messageChannel);
this.messagingTemplate = new SimpMessagingTemplate(this.messageChannel);
}
@@ -54,10 +65,12 @@ public class SimpMessagingTemplateTests {
assertEquals(1, messages.size());
Message<byte[]> message = messages.get(0);
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
SimpMessageHeaderAccessor headerAccessor =
MessageHeaderAccessor.getAccessor(message, SimpMessageHeaderAccessor.class);
assertEquals(SimpMessageType.MESSAGE, headers.getMessageType());
assertEquals("/user/joe/queue/foo", headers.getDestination());
assertNotNull(headerAccessor);
assertEquals(SimpMessageType.MESSAGE, headerAccessor.getMessageType());
assertEquals("/user/joe/queue/foo", headerAccessor.getDestination());
}
@Test
@@ -67,9 +80,11 @@ public class SimpMessagingTemplateTests {
assertEquals(1, messages.size());
Message<byte[]> message = messages.get(0);
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
assertEquals("/user/http:%2F%2Fjoe.openid.example.org%2F/queue/foo", headers.getDestination());
SimpMessageHeaderAccessor headerAccessor =
MessageHeaderAccessor.getAccessor(messages.get(0), SimpMessageHeaderAccessor.class);
assertNotNull(headerAccessor);
assertEquals("/user/http:%2F%2Fjoe.openid.example.org%2F/queue/foo", headerAccessor.getDestination());
}
@Test
@@ -78,26 +93,95 @@ public class SimpMessagingTemplateTests {
this.messagingTemplate.convertAndSend("/foo", "data", headers);
List<Message<byte[]>> messages = this.messageChannel.getMessages();
Message<byte[]> message = messages.get(0);
SimpMessageHeaderAccessor resultHeaders = SimpMessageHeaderAccessor.wrap(message);
assertNull(resultHeaders.toMap().get("key"));
assertEquals(Arrays.asList("value"), resultHeaders.getNativeHeader("key"));
SimpMessageHeaderAccessor headerAccessor =
MessageHeaderAccessor.getAccessor(messages.get(0), SimpMessageHeaderAccessor.class);
assertNotNull(headerAccessor);
assertNull(headerAccessor.toMap().get("key"));
assertEquals(Arrays.asList("value"), headerAccessor.getNativeHeader("key"));
}
@Test
public void convertAndSendWithCustomHeaderNonNative() {
Map<String, Object> headers = new HashMap<String, Object>();
Map<String, Object> headers = new HashMap<>();
headers.put("key", "value");
headers.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, Collections.emptyMap());
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"));
}
@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);
SimpMessageHeaderAccessor resultHeaders = SimpMessageHeaderAccessor.wrap(message);
assertEquals("value", resultHeaders.toMap().get("key"));
assertNull(resultHeaders.getNativeHeader("key"));
assertSame(headers, message.getHeaders());
assertFalse(accessor.isMutable());
}
}
@Test
public void processHeadersToSend() {
Map<String, Object> map = this.messagingTemplate.processHeadersToSend(null);
assertNotNull(map);
assertTrue("Actual: " + map.getClass().toString(), MessageHeaders.class.isAssignableFrom(map.getClass()));
SimpMessageHeaderAccessor headerAccessor =
MessageHeaderAccessor.getAccessor((MessageHeaders) map, SimpMessageHeaderAccessor.class);
assertTrue(headerAccessor.isMutable());
assertEquals(SimpMessageType.MESSAGE, headerAccessor.getMessageType());
}
@Test
public void doSendWithMutableHeaders() {
SimpMessageHeaderAccessor accessor = SimpMessageHeaderAccessor.create();
accessor.setHeader("key", "value");
accessor.setNativeHeader("fooNative", "barNative");
accessor.setLeaveMutable(true);
MessageHeaders headers = accessor.getMessageHeaders();
Message<?> message = MessageBuilder.createMessage("payload", headers);
this.messagingTemplate.doSend("/topic/foo", message);
List<Message<byte[]>> messages = this.messageChannel.getMessages();
Message<byte[]> sentMessage = messages.get(0);
assertSame(message, sentMessage);
assertFalse(accessor.isMutable());
}
@Test
public void doSendWithStompHeaders() {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
accessor.setDestination("/user/queue/foo");
Message<?> message = MessageBuilder.createMessage(new byte[0], accessor.getMessageHeaders());
this.messagingTemplate.doSend("/queue/foo-user123", message);
List<Message<byte[]>> messages = this.messageChannel.getMessages();
Message<byte[]> sentMessage = messages.get(0);
MessageHeaderAccessor sentAccessor = MessageHeaderAccessor.getAccessor(sentMessage, MessageHeaderAccessor.class);
assertEquals(StompHeaderAccessor.class, sentAccessor.getClass());
assertEquals("/queue/foo-user123", ((StompHeaderAccessor) sentAccessor).getDestination());
}
}

View File

@@ -17,6 +17,7 @@
package org.springframework.messaging.simp.annotation.support;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.security.Principal;
import javax.security.auth.Subject;
@@ -27,22 +28,29 @@ import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.core.MethodParameter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.core.MessageSendingOperations;
import org.springframework.messaging.handler.DestinationPatternsMessageCondition;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.messaging.simp.user.DestinationUserNameProvider;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.MimeType;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
/**
@@ -52,7 +60,9 @@ import static org.mockito.Mockito.*;
*/
public class SendToMethodReturnValueHandlerTests {
private static final String payloadContent = "payload";
public static final MimeType MIME_TYPE = new MimeType("text", "plain", Charset.forName("UTF-8"));
private static final String PAYLOAD = "payload";
private SendToMethodReturnValueHandler handler;
@@ -63,8 +73,6 @@ public class SendToMethodReturnValueHandlerTests {
@Captor ArgumentCaptor<Message<?>> messageCaptor;
@Mock private MessageConverter messageConverter;
private MethodParameter noAnnotationsReturnType;
private MethodParameter sendToReturnType;
private MethodParameter sendToDefaultDestReturnType;
@@ -78,11 +86,8 @@ public class SendToMethodReturnValueHandlerTests {
MockitoAnnotations.initMocks(this);
Message message = MessageBuilder.withPayload(payloadContent).build();
when(this.messageConverter.toMessage(payloadContent, null)).thenReturn(message);
SimpMessagingTemplate messagingTemplate = new SimpMessagingTemplate(this.messageChannel);
messagingTemplate.setMessageConverter(this.messageConverter);
messagingTemplate.setMessageConverter(new StringMessageConverter());
this.handler = new SendToMethodReturnValueHandler(messagingTemplate, true);
this.handlerAnnotationNotRequired = new SendToMethodReturnValueHandler(messagingTemplate, false);
@@ -118,15 +123,16 @@ public class SendToMethodReturnValueHandlerTests {
when(this.messageChannel.send(any(Message.class))).thenReturn(true);
Message<?> inputMessage = createInputMessage("sess1", "sub1", "/app", "/dest", null);
this.handler.handleReturnValue(payloadContent, this.noAnnotationsReturnType, inputMessage);
this.handler.handleReturnValue(PAYLOAD, this.noAnnotationsReturnType, inputMessage);
verify(this.messageChannel, times(1)).send(this.messageCaptor.capture());
Message<?> message = this.messageCaptor.getAllValues().get(0);
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
assertEquals("sess1", headers.getSessionId());
assertNull(headers.getSubscriptionId());
assertEquals("/topic/dest", headers.getDestination());
assertEquals(MIME_TYPE, headers.getContentType());
assertNull("Subscription id should not be copied", headers.getSubscriptionId());
}
@Test
@@ -136,21 +142,23 @@ public class SendToMethodReturnValueHandlerTests {
String sessionId = "sess1";
Message<?> inputMessage = createInputMessage(sessionId, "sub1", null, null, null);
this.handler.handleReturnValue(payloadContent, this.sendToReturnType, inputMessage);
this.handler.handleReturnValue(PAYLOAD, this.sendToReturnType, inputMessage);
verify(this.messageChannel, times(2)).send(this.messageCaptor.capture());
Message<?> message = this.messageCaptor.getAllValues().get(0);
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
assertEquals(sessionId, headers.getSessionId());
assertNull(headers.getSubscriptionId());
assertEquals("/dest1", headers.getDestination());
assertEquals(MIME_TYPE, headers.getContentType());
assertNull("Subscription id should not be copied", headers.getSubscriptionId());
message = this.messageCaptor.getAllValues().get(1);
headers = SimpMessageHeaderAccessor.wrap(message);
assertEquals(sessionId, headers.getSessionId());
assertNull(headers.getSubscriptionId());
assertEquals("/dest2", headers.getDestination());
assertEquals(MIME_TYPE, headers.getContentType());
assertNull("Subscription id should not be copied", headers.getSubscriptionId());
}
@Test
@@ -160,15 +168,38 @@ public class SendToMethodReturnValueHandlerTests {
String sessionId = "sess1";
Message<?> inputMessage = createInputMessage(sessionId, "sub1", "/app", "/dest", null);
this.handler.handleReturnValue(payloadContent, this.sendToDefaultDestReturnType, inputMessage);
this.handler.handleReturnValue(PAYLOAD, this.sendToDefaultDestReturnType, inputMessage);
verify(this.messageChannel, times(1)).send(this.messageCaptor.capture());
Message<?> message = this.messageCaptor.getAllValues().get(0);
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
assertEquals(sessionId, headers.getSessionId());
assertNull(headers.getSubscriptionId());
assertEquals("/topic/dest", headers.getDestination());
assertEquals(MIME_TYPE, headers.getContentType());
assertNull("Subscription id should not be copied", headers.getSubscriptionId());
}
@Test
public void testHeadersToSend() throws Exception {
Message<?> inputMessage = createInputMessage("sess1", "sub1", "/app", "/dest", null);
SimpMessageSendingOperations messagingTemplate = Mockito.mock(SimpMessageSendingOperations.class);
SendToMethodReturnValueHandler handler = new SendToMethodReturnValueHandler(messagingTemplate, false);
handler.handleReturnValue(PAYLOAD, this.noAnnotationsReturnType, inputMessage);
ArgumentCaptor<MessageHeaders> captor = ArgumentCaptor.forClass(MessageHeaders.class);
verify(messagingTemplate).convertAndSend(eq("/topic/dest"), eq(PAYLOAD), captor.capture());
SimpMessageHeaderAccessor headerAccessor =
MessageHeaderAccessor.getAccessor(captor.getValue(), SimpMessageHeaderAccessor.class);
assertNotNull(headerAccessor);
assertTrue(headerAccessor.isMutable());
assertEquals("sess1", headerAccessor.getSessionId());
assertNull("Subscription id should not be copied", headerAccessor.getSubscriptionId());
}
@Test
@@ -179,21 +210,23 @@ public class SendToMethodReturnValueHandlerTests {
String sessionId = "sess1";
TestUser user = new TestUser();
Message<?> inputMessage = createInputMessage(sessionId, "sub1", null, null, user);
this.handler.handleReturnValue(payloadContent, this.sendToUserReturnType, inputMessage);
this.handler.handleReturnValue(PAYLOAD, this.sendToUserReturnType, inputMessage);
verify(this.messageChannel, times(2)).send(this.messageCaptor.capture());
Message<?> message = this.messageCaptor.getAllValues().get(0);
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
assertEquals(sessionId, headers.getSessionId());
assertNull(headers.getSubscriptionId());
assertEquals(MIME_TYPE, headers.getContentType());
assertEquals("/user/" + user.getName() + "/dest1", headers.getDestination());
assertNull("Subscription id should not be copied", headers.getSubscriptionId());
message = this.messageCaptor.getAllValues().get(1);
headers = SimpMessageHeaderAccessor.wrap(message);
assertEquals(sessionId, headers.getSessionId());
assertNull(headers.getSubscriptionId());
assertEquals("/user/" + user.getName() + "/dest2", headers.getDestination());
assertEquals(MIME_TYPE, headers.getContentType());
assertNull("Subscription id should not be copied", headers.getSubscriptionId());
}
@Test
@@ -204,7 +237,7 @@ public class SendToMethodReturnValueHandlerTests {
String sessionId = "sess1";
TestUser user = new UniqueUser();
Message<?> inputMessage = createInputMessage(sessionId, "sub1", null, null, user);
this.handler.handleReturnValue(payloadContent, this.sendToUserReturnType, inputMessage);
this.handler.handleReturnValue(PAYLOAD, this.sendToUserReturnType, inputMessage);
verify(this.messageChannel, times(2)).send(this.messageCaptor.capture());
@@ -223,31 +256,56 @@ public class SendToMethodReturnValueHandlerTests {
String sessionId = "sess1";
TestUser user = new TestUser();
Message<?> inputMessage = createInputMessage(sessionId, "sub1", "/app", "/dest", user);
this.handler.handleReturnValue(payloadContent, this.sendToUserDefaultDestReturnType, inputMessage);
this.handler.handleReturnValue(PAYLOAD, this.sendToUserDefaultDestReturnType, inputMessage);
verify(this.messageChannel, times(1)).send(this.messageCaptor.capture());
Message<?> message = this.messageCaptor.getAllValues().get(0);
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
assertEquals(sessionId, headers.getSessionId());
assertNull(headers.getSubscriptionId());
assertEquals("/user/" + user.getName() + "/queue/dest", headers.getDestination());
assertEquals(MIME_TYPE, headers.getContentType());
assertNull("Subscription id should not be copied", headers.getSubscriptionId());
}
@Test
public void testHeadersToSendToUser() throws Exception {
TestUser user = new TestUser();
Message<?> inputMessage = createInputMessage("sess1", "sub1", "/app", "/dest", user);
SimpMessageSendingOperations messagingTemplate = Mockito.mock(SimpMessageSendingOperations.class);
SendToMethodReturnValueHandler handler = new SendToMethodReturnValueHandler(messagingTemplate, false);
handler.handleReturnValue(PAYLOAD, this.sendToUserDefaultDestReturnType, inputMessage);
ArgumentCaptor<MessageHeaders> captor = ArgumentCaptor.forClass(MessageHeaders.class);
verify(messagingTemplate).convertAndSendToUser(eq("joe"), eq("/queue/dest"), eq(PAYLOAD), captor.capture());
SimpMessageHeaderAccessor headerAccessor =
MessageHeaderAccessor.getAccessor(captor.getValue(), SimpMessageHeaderAccessor.class);
assertNotNull(headerAccessor);
assertTrue(headerAccessor.isMutable());
assertEquals("sess1", headerAccessor.getSessionId());
assertNull("Subscription id should not be copied", headerAccessor.getSubscriptionId());
}
private Message<?> createInputMessage(String sessId, String subsId, String destinationPrefix,
String destination, Principal principal) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create();
headers.setSessionId(sessId);
headers.setSubscriptionId(subsId);
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create();
headerAccessor.setSessionId(sessId);
headerAccessor.setSubscriptionId(subsId);
if (destination != null && destinationPrefix != null) {
headers.setDestination(destinationPrefix + destination);
headers.setHeader(DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER, destination);
headerAccessor.setDestination(destinationPrefix + destination);
headerAccessor.setHeader(DestinationPatternsMessageCondition.LOOKUP_DESTINATION_HEADER, destination);
}
if (principal != null) {
headers.setUser(principal);
headerAccessor.setUser(principal);
}
return MessageBuilder.withPayload(new byte[0]).copyHeaders(headers.toMap()).build();
return MessageBuilder.createMessage(new byte[0], headerAccessor.getMessageHeaders());
}
private static class TestUser implements Principal {
@@ -270,27 +328,27 @@ public class SendToMethodReturnValueHandlerTests {
}
public String handleNoAnnotations() {
return payloadContent;
return PAYLOAD;
}
@SendTo
public String handleAndSendToDefaultDestination() {
return payloadContent;
return PAYLOAD;
}
@SendTo({"/dest1", "/dest2"})
public String handleAndSendTo() {
return payloadContent;
return PAYLOAD;
}
@SendToUser
public String handleAndSendToUserDefaultDestination() {
return payloadContent;
return PAYLOAD;
}
@SendToUser({"/dest1", "/dest2"})
public String handleAndSendToUser() {
return payloadContent;
return PAYLOAD;
}
}

View File

@@ -17,6 +17,7 @@
package org.springframework.messaging.simp.annotation.support;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.security.Principal;
import org.junit.Before;
@@ -24,17 +25,22 @@ import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.core.MethodParameter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.StringMessageConverter;
import org.springframework.messaging.core.MessageSendingOperations;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.MimeType;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
@@ -47,7 +53,9 @@ import static org.mockito.Mockito.*;
*/
public class SubscriptionMethodReturnValueHandlerTests {
private static final String payloadContent = "payload";
public static final MimeType MIME_TYPE = new MimeType("text", "plain", Charset.forName("UTF-8"));
private static final String PAYLOAD = "payload";
private SubscriptionMethodReturnValueHandler handler;
@@ -56,8 +64,6 @@ public class SubscriptionMethodReturnValueHandlerTests {
@Captor ArgumentCaptor<Message<?>> messageCaptor;
@Mock private MessageConverter messageConverter;
private MethodParameter subscribeEventReturnType;
private MethodParameter subscribeEventSendToReturnType;
@@ -71,11 +77,8 @@ public class SubscriptionMethodReturnValueHandlerTests {
MockitoAnnotations.initMocks(this);
Message message = MessageBuilder.withPayload(payloadContent).build();
when(this.messageConverter.toMessage(payloadContent, null)).thenReturn(message);
SimpMessagingTemplate messagingTemplate = new SimpMessagingTemplate(this.messageChannel);
messagingTemplate.setMessageConverter(this.messageConverter);
messagingTemplate.setMessageConverter(new StringMessageConverter());
this.handler = new SubscriptionMethodReturnValueHandler(messagingTemplate);
@@ -98,7 +101,7 @@ public class SubscriptionMethodReturnValueHandlerTests {
}
@Test
public void subscribeEventMethod() throws Exception {
public void testMessageSentToChannel() throws Exception {
when(this.messageChannel.send(any(Message.class))).thenReturn(true);
@@ -107,17 +110,46 @@ public class SubscriptionMethodReturnValueHandlerTests {
String destination = "/dest";
Message<?> inputMessage = createInputMessage(sessionId, subscriptionId, destination, null);
this.handler.handleReturnValue(payloadContent, this.subscribeEventReturnType, inputMessage);
this.handler.handleReturnValue(PAYLOAD, this.subscribeEventReturnType, inputMessage);
verify(this.messageChannel).send(this.messageCaptor.capture());
assertNotNull(this.messageCaptor.getValue());
Message<?> message = this.messageCaptor.getValue();
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.wrap(message);
assertEquals("sessionId should always be copied", sessionId, headers.getSessionId());
assertEquals(subscriptionId, headers.getSubscriptionId());
assertEquals(destination, headers.getDestination());
assertNull("SimpMessageHeaderAccessor should have disabled id", headerAccessor.getId());
assertNull("SimpMessageHeaderAccessor should have disabled timestamp", headerAccessor.getTimestamp());
assertEquals(sessionId, headerAccessor.getSessionId());
assertEquals(subscriptionId, headerAccessor.getSubscriptionId());
assertEquals(destination, headerAccessor.getDestination());
assertEquals(MIME_TYPE, headerAccessor.getContentType());
}
@SuppressWarnings("unchecked")
@Test
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());
}
@@ -131,19 +163,22 @@ public class SubscriptionMethodReturnValueHandlerTests {
}
@SuppressWarnings("unused")
@SubscribeMapping("/data") // not needed for the tests but here for completeness
private String getData() {
return payloadContent;
return PAYLOAD;
}
@SuppressWarnings("unused")
@SubscribeMapping("/data") // not needed for the tests but here for completeness
@SendTo("/sendToDest")
private String getDataAndSendTo() {
return payloadContent;
return PAYLOAD;
}
@SuppressWarnings("unused")
@MessageMapping("/handle") // not needed for the tests but here for completeness
public String handle() {
return payloadContent;
return PAYLOAD;
}
}

View File

@@ -31,7 +31,6 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.converter.*;
import org.springframework.messaging.handler.annotation.MessageMapping;

View File

@@ -19,6 +19,7 @@ package org.springframework.messaging.simp.stomp;
import org.junit.Test;
import org.springframework.messaging.Message;
import org.springframework.messaging.converter.MessageConversionException;
import org.springframework.util.LinkedMultiValueMap;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
@@ -175,6 +176,17 @@ public class BufferingStompDecoderTests {
stompDecoder.decode(toByteBuffer(payload));
}
@Test
public void incompleteCommand() throws InterruptedException {
BufferingStompDecoder stompDecoder = new BufferingStompDecoder(128);
String chunk = "MESSAG";
LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
List<Message<byte[]>> messages = stompDecoder.decode(toByteBuffer(chunk), headers);
assertEquals(0, messages.size());
}
private ByteBuffer toByteBuffer(String chunk) {
return ByteBuffer.wrap(chunk.getBytes(Charset.forName("UTF-8")));

View File

@@ -38,6 +38,7 @@ import org.springframework.messaging.MessageDeliveryException;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.messaging.StubMessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.broker.BrokerAvailabilityEvent;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.ExecutorSubscribableChannel;
@@ -168,7 +169,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
public void messageDeliverExceptionIfSystemSessionForwardFails() throws Exception {
stopActiveMqBrokerAndAwait();
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND);
this.relay.handleMessage(MessageBuilder.withPayload("test".getBytes()).setHeaders(headers).build());
this.relay.handleMessage(MessageBuilder.createMessage("test".getBytes(), headers.getMessageHeaders()));
}
@Test
@@ -244,7 +245,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT);
headers.setSessionId("sess1");
this.relay.handleMessage(MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build());
this.relay.handleMessage(MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()));
Thread.sleep(2000);
@@ -394,7 +395,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
headers.setSessionId(sessionId);
headers.setAcceptVersion("1.1,1.2");
headers.setHeartbeat(0, 0);
Message<?> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());
MessageExchangeBuilder builder = new MessageExchangeBuilder(message);
builder.expected.add(new StompConnectedFrameMessageMatcher(sessionId));
@@ -405,7 +406,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
headers.setSessionId(sessionId);
headers.setAcceptVersion("1.1,1.2");
Message<?> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());
MessageExchangeBuilder builder = new MessageExchangeBuilder(message);
return builder.andExpectError();
}
@@ -418,7 +419,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
headers.setSubscriptionId(subscriptionId);
headers.setDestination(destination);
headers.setReceipt(receiptId);
Message<?> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<?> message = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());
MessageExchangeBuilder builder = new MessageExchangeBuilder(message);
builder.expected.add(new StompReceiptFrameMessageMatcher(sessionId, receiptId));
@@ -426,14 +427,14 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
}
public static MessageExchangeBuilder send(String destination, String payload) {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND);
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headers.setDestination(destination);
Message<?> message = MessageBuilder.withPayload(payload.getBytes(UTF_8)).setHeaders(headers).build();
Message<?> message = MessageBuilder.createMessage(payload.getBytes(UTF_8), headers.getMessageHeaders());
return new MessageExchangeBuilder(message);
}
public MessageExchangeBuilder andExpectMessage(String sessionId, String subscriptionId) {
Assert.isTrue(StompCommand.SEND.equals(headers.getCommand()), "MESSAGE can only be expected after SEND");
Assert.isTrue(SimpMessageType.MESSAGE.equals(headers.getMessageType()));
String destination = this.headers.getDestination();
Object payload = this.message.getPayload();
this.expected.add(new StompMessageFrameMessageMatcher(sessionId, subscriptionId, destination, payload));

View File

@@ -27,6 +27,7 @@ import org.springframework.messaging.StubMessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.messaging.tcp.ReconnectStrategy;
import org.springframework.messaging.tcp.TcpConnection;
import org.springframework.messaging.tcp.TcpConnectionHandler;
@@ -77,17 +78,21 @@ public class StompBrokerRelayMessageHandlerTests {
String sessionId = "sess1";
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
headers.setSessionId(sessionId);
this.brokerRelay.handleMessage(MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build());
this.brokerRelay.handleMessage(MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()));
List<Message<byte[]>> sent = this.tcpClient.connection.messages;
assertEquals(2, sent.size());
StompHeaderAccessor headers1 = StompHeaderAccessor.wrap(sent.get(0));
assertEquals(virtualHost, headers1.getHost());
assertNotNull("The prepared message does not have an accessor",
MessageHeaderAccessor.getAccessor(sent.get(0), MessageHeaderAccessor.class));
StompHeaderAccessor headers2 = StompHeaderAccessor.wrap(sent.get(1));
assertEquals(sessionId, headers2.getSessionId());
assertEquals(virtualHost, headers2.getHost());
assertNotNull("The prepared message does not have an accessor",
MessageHeaderAccessor.getAccessor(sent.get(1), MessageHeaderAccessor.class));
}
@Test
@@ -104,7 +109,7 @@ public class StompBrokerRelayMessageHandlerTests {
String sessionId = "sess1";
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
headers.setSessionId(sessionId);
this.brokerRelay.handleMessage(MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build());
this.brokerRelay.handleMessage(MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()));
List<Message<byte[]>> sent = this.tcpClient.connection.messages;
assertEquals(2, sent.size());
@@ -126,11 +131,13 @@ public class StompBrokerRelayMessageHandlerTests {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headers.setSessionId("sess1");
headers.setDestination("/user/daisy/foo");
this.brokerRelay.handleMessage(MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build());
this.brokerRelay.handleMessage(MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders()));
List<Message<byte[]>> sent = this.tcpClient.connection.messages;
assertEquals(1, sent.size());
assertEquals(StompCommand.CONNECT, StompHeaderAccessor.wrap(sent.get(0)).getCommand());
assertNotNull("The prepared message does not have an accessor",
MessageHeaderAccessor.getAccessor(sent.get(0), MessageHeaderAccessor.class));
}

View File

@@ -25,6 +25,7 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.InvalidMimeTypeException;
import reactor.function.Consumer;
import reactor.function.Function;
import reactor.io.Buffer;
@@ -48,7 +49,7 @@ public class StompCodecTests {
StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame);
assertEquals(StompCommand.DISCONNECT, headers.getCommand());
assertEquals(0, headers.toStompHeaderMap().size());
assertEquals(0, headers.toNativeHeaderMap().size());
assertEquals(0, frame.getPayload().length);
}
@@ -58,7 +59,7 @@ public class StompCodecTests {
StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame);
assertEquals(StompCommand.DISCONNECT, headers.getCommand());
assertEquals(0, headers.toStompHeaderMap().size());
assertEquals(0, headers.toNativeHeaderMap().size());
assertEquals(0, frame.getPayload().length);
}
@@ -72,7 +73,7 @@ public class StompCodecTests {
assertEquals(StompCommand.CONNECT, headers.getCommand());
assertEquals(2, headers.toStompHeaderMap().size());
assertEquals(2, headers.toNativeHeaderMap().size());
assertEquals("1.1", headers.getFirstNativeHeader("accept-version"));
assertEquals("github.org", headers.getHost());
@@ -86,7 +87,7 @@ public class StompCodecTests {
assertEquals(StompCommand.SEND, headers.getCommand());
assertEquals(1, headers.toStompHeaderMap().size());
assertEquals(headers.toNativeHeaderMap().toString(), 1, headers.toNativeHeaderMap().size());
assertEquals("test", headers.getDestination());
String bodyText = new String(frame.getPayload());
@@ -95,15 +96,15 @@ public class StompCodecTests {
@Test
public void decodeFrameWithContentLength() {
Message<byte[]> frame = decode("SEND\ncontent-length:23\n\nThe body of the message\0");
StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame);
Message<byte[]> message = decode("SEND\ncontent-length:23\n\nThe body of the message\0");
StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
assertEquals(StompCommand.SEND, headers.getCommand());
assertEquals(1, headers.toStompHeaderMap().size());
assertEquals(1, headers.toNativeHeaderMap().size());
assertEquals(Integer.valueOf(23), headers.getContentLength());
String bodyText = new String(frame.getPayload());
String bodyText = new String(message.getPayload());
assertEquals("The body of the message", bodyText);
}
@@ -111,15 +112,15 @@ public class StompCodecTests {
@Test
public void decodeFrameWithInvalidContentLength() {
Message<byte[]> frame = decode("SEND\ncontent-length:-1\n\nThe body of the message\0");
StompHeaderAccessor headers = StompHeaderAccessor.wrap(frame);
Message<byte[]> message = decode("SEND\ncontent-length:-1\n\nThe body of the message\0");
StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
assertEquals(StompCommand.SEND, headers.getCommand());
assertEquals(1, headers.toStompHeaderMap().size());
assertEquals(1, headers.toNativeHeaderMap().size());
assertEquals(Integer.valueOf(-1), headers.getContentLength());
String bodyText = new String(frame.getPayload());
String bodyText = new String(message.getPayload());
assertEquals("The body of the message", bodyText);
}
@@ -130,7 +131,7 @@ public class StompCodecTests {
assertEquals(StompCommand.SEND, headers.getCommand());
assertEquals(1, headers.toStompHeaderMap().size());
assertEquals(1, headers.toNativeHeaderMap().size());
assertEquals(Integer.valueOf(0), headers.getContentLength());
String bodyText = new String(frame.getPayload());
@@ -144,7 +145,7 @@ public class StompCodecTests {
assertEquals(StompCommand.SEND, headers.getCommand());
assertEquals(1, headers.toStompHeaderMap().size());
assertEquals(1, headers.toNativeHeaderMap().size());
assertEquals(Integer.valueOf(23), headers.getContentLength());
String bodyText = new String(frame.getPayload());
@@ -158,7 +159,7 @@ public class StompCodecTests {
assertEquals(StompCommand.DISCONNECT, headers.getCommand());
assertEquals(1, headers.toStompHeaderMap().size());
assertEquals(1, headers.toNativeHeaderMap().size());
assertEquals("alpha:bravo\r\n\\", headers.getFirstNativeHeader("a:\r\n\\b"));
}
@@ -187,6 +188,11 @@ public class StompCodecTests {
assertEquals(StompCommand.DISCONNECT, StompHeaderAccessor.wrap(messages.get(1)).getCommand());
}
@Test
public void decodeFrameWithIncompleteCommand() {
assertIncompleteDecode("MESSAG");
}
@Test
public void decodeFrameWithIncompleteHeader() {
assertIncompleteDecode("SEND\ndestination");
@@ -206,6 +212,16 @@ public class StompCodecTests {
assertIncompleteDecode("SEND\ncontent-length:23\n\nThe body of the mess");
}
@Test
public void decodeFrameWithIncompleteContentType() {
assertIncompleteDecode("SEND\ncontent-type:text/plain;charset=U");
}
@Test(expected = InvalidMimeTypeException.class)
public void decodeFrameWithInvalidContentType() {
assertIncompleteDecode("SEND\ncontent-type:text/plain;charset=U\n\nThe body\0");
}
@Test(expected=StompConversionException.class)
public void decodeFrameWithIncorrectTerminator() {
decode("SEND\ncontent-length:23\n\nThe body of the message*");
@@ -233,7 +249,7 @@ public class StompCodecTests {
public void encodeFrameWithNoHeadersAndNoBody() {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT);
Message<byte[]> frame = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<byte[]> frame = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());
assertEquals("DISCONNECT\n\n\0", new StompCodec().encoder().apply(frame).asString());
}
@@ -244,7 +260,7 @@ public class StompCodecTests {
headers.setAcceptVersion("1.2");
headers.setHost("github.org");
Message<byte[]> frame = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<byte[]> frame = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());
String frameString = new StompCodec().encoder().apply(frame).asString();
@@ -257,9 +273,10 @@ public class StompCodecTests {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT);
headers.addNativeHeader("a:\r\n\\b", "alpha:bravo\r\n\\");
Message<byte[]> frame = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<byte[]> frame = MessageBuilder.createMessage(new byte[0], headers.getMessageHeaders());
assertEquals("DISCONNECT\na\\c\\r\\n\\\\b:alpha\\cbravo\\r\\n\\\\\n\n\0", new StompCodec().encoder().apply(frame).asString());
assertEquals("DISCONNECT\na\\c\\r\\n\\\\b:alpha\\cbravo\\r\\n\\\\\n\n\0",
new StompCodec().encoder().apply(frame).asString());
}
@Test
@@ -267,9 +284,10 @@ public class StompCodecTests {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND);
headers.addNativeHeader("a", "alpha");
Message<byte[]> frame = MessageBuilder.withPayload("Message body".getBytes()).setHeaders(headers).build();
Message<byte[]> frame = MessageBuilder.createMessage("Message body".getBytes(), headers.getMessageHeaders());
assertEquals("SEND\na:alpha\ncontent-length:12\n\nMessage body\0", new StompCodec().encoder().apply(frame).asString());
assertEquals("SEND\na:alpha\ncontent-length:12\n\nMessage body\0",
new StompCodec().encoder().apply(frame).asString());
}
private void assertIncompleteDecode(String partialFrame) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,22 +16,28 @@
package org.springframework.messaging.simp.stomp;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.AlternativeJdkIdGenerator;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MimeTypeUtils;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
/**
* Test fixture for {@link StompHeaderAccessor}.
* Unit tests for {@link StompHeaderAccessor}.
*
* @author Rossen Stoyanchev
* @since 4.0
@@ -99,17 +105,18 @@ public class StompHeaderAccessorTests {
extHeaders.add(StompHeaderAccessor.STOMP_LOGIN_HEADER, "joe");
extHeaders.add(StompHeaderAccessor.STOMP_PASSCODE_HEADER, "joe123");
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT, extHeaders);
StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.CONNECT, extHeaders);
assertEquals(StompCommand.CONNECT, headers.getCommand());
assertEquals(SimpMessageType.CONNECT, headers.getMessageType());
assertNotNull(headers.getHeader("stompCredentials"));
assertEquals("joe", headers.getLogin());
assertEquals("PROTECTED", headers.getPasscode());
assertEquals(StompCommand.CONNECT, headerAccessor.getCommand());
assertEquals(SimpMessageType.CONNECT, headerAccessor.getMessageType());
assertNotNull(headerAccessor.getHeader("stompCredentials"));
assertEquals("joe", headerAccessor.getLogin());
assertEquals("joe123", headerAccessor.getPasscode());
assertThat(headerAccessor.toString(), CoreMatchers.containsString("passcode=[PROTECTED]"));
Map<String, List<String>> output = headers.toStompHeaderMap();
Map<String, List<String>> output = headerAccessor.toNativeHeaderMap();
assertEquals("joe", output.get(StompHeaderAccessor.STOMP_LOGIN_HEADER).get(0));
assertEquals("joe123", output.get(StompHeaderAccessor.STOMP_PASSCODE_HEADER).get(0));
assertEquals("PROTECTED", output.get(StompHeaderAccessor.STOMP_PASSCODE_HEADER).get(0));
}
@Test
@@ -145,10 +152,11 @@ public class StompHeaderAccessorTests {
headers.setSubscriptionId("s1");
headers.setDestination("/d");
headers.setContentType(MimeTypeUtils.APPLICATION_JSON);
headers.updateStompCommandAsServerMessage();
Map<String, List<String>> actual = headers.toNativeHeaderMap();
assertEquals(4, actual.size());
assertEquals(actual.toString(), 4, actual.size());
assertEquals("s1", actual.get(StompHeaderAccessor.STOMP_SUBSCRIPTION_HEADER).get(0));
assertEquals("/d", actual.get(StompHeaderAccessor.STOMP_DESTINATION_HEADER).get(0));
assertEquals("application/json", actual.get(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER).get(0));
@@ -158,15 +166,30 @@ public class StompHeaderAccessorTests {
@Test
public void toNativeHeadersContentType() {
Message<byte[]> message = MessageBuilder.withPayload(new byte[0])
.setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_ATOM_XML).build();
SimpMessageHeaderAccessor simpHeaderAccessor = SimpMessageHeaderAccessor.create();
simpHeaderAccessor.setContentType(MimeTypeUtils.APPLICATION_ATOM_XML);
Message<byte[]> message = MessageBuilder.createMessage(new byte[0], simpHeaderAccessor.getMessageHeaders());
StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
Map<String, List<String>> map = headers.toNativeHeaderMap();
StompHeaderAccessor stompHeaderAccessor = StompHeaderAccessor.wrap(message);
Map<String, List<String>> map = stompHeaderAccessor.toNativeHeaderMap();
assertEquals("application/atom+xml", map.get(StompHeaderAccessor.STOMP_CONTENT_TYPE_HEADER).get(0));
}
@Test
public void encodeConnectWithLoginAndPasscode() throws UnsupportedEncodingException {
MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>();
extHeaders.add(StompHeaderAccessor.STOMP_LOGIN_HEADER, "joe");
extHeaders.add(StompHeaderAccessor.STOMP_PASSCODE_HEADER, "joe123");
StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.CONNECT, extHeaders);
Message<byte[]> message = MessageBuilder.createMessage(new byte[0], headerAccessor.getMessageHeaders());
byte[] bytes = new StompEncoder().encode(message);
assertEquals("CONNECT\nlogin:joe\npasscode:joe123\n\n\0", new String(bytes, "UTF-8"));
}
@Test
public void modifyCustomNativeHeader() {
@@ -187,5 +210,34 @@ public class StompHeaderAccessorTests {
assertNotNull("abc123", actual.get("accountId").get(0));
}
@Test
public void messageIdAndTimestampDefaultBehavior() {
StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.SEND);
MessageHeaders headers = headerAccessor.getMessageHeaders();
assertNull(headers.getId());
assertNull(headers.getTimestamp());
}
@Test
public void messageIdAndTimestampEnabled() {
DefaultStompHeaderAccessorFactory factory = new DefaultStompHeaderAccessorFactory();
factory.setIdGenerator(new AlternativeJdkIdGenerator());
factory.setEnableTimestamp(true);
StompHeaderAccessor headerAccessor = factory.create(StompCommand.SEND);
MessageHeaders headers = headerAccessor.getMessageHeaders();
assertNotNull(headers.getId());
assertNotNull(headers.getTimestamp());
}
@Test
public void getAccessor() {
StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.CONNECT);
Message<byte[]> message = MessageBuilder.createMessage(new byte[0], headerAccessor.getMessageHeaders());
assertSame(headerAccessor, MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class));
}
}

View File

@@ -66,8 +66,7 @@ public class UserDestinationMessageHandlerTests {
ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
Mockito.verify(this.brokerChannel).send(captor.capture());
assertEquals("/queue/foo-user123",
captor.getValue().getHeaders().get(SimpMessageHeaderAccessor.DESTINATION_HEADER));
assertEquals("/queue/foo-user123", SimpMessageHeaderAccessor.getDestination(captor.getValue().getHeaders()));
}
@Test
@@ -79,8 +78,7 @@ public class UserDestinationMessageHandlerTests {
ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
Mockito.verify(this.brokerChannel).send(captor.capture());
assertEquals("/queue/foo-user123",
captor.getValue().getHeaders().get(SimpMessageHeaderAccessor.DESTINATION_HEADER));
assertEquals("/queue/foo-user123", SimpMessageHeaderAccessor.getDestination(captor.getValue().getHeaders()));
}
@Test
@@ -93,10 +91,8 @@ public class UserDestinationMessageHandlerTests {
ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
Mockito.verify(this.brokerChannel).send(captor.capture());
assertEquals("/queue/foo-user123",
captor.getValue().getHeaders().get(SimpMessageHeaderAccessor.DESTINATION_HEADER));
assertEquals("/user/queue/foo",
captor.getValue().getHeaders().get(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION));
assertEquals("/queue/foo-user123", SimpMessageHeaderAccessor.getDestination(captor.getValue().getHeaders()));
assertEquals("/user/queue/foo", captor.getValue().getHeaders().get(SimpMessageHeaderAccessor.ORIGINAL_DESTINATION));
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,17 +21,25 @@ import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.util.IdGenerator;
import static org.junit.Assert.*;
/**
* @author Mark Fisher
* @author Rossen Stoyanchev
*/
public class MessageBuilderTests {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void testSimpleMessageCreation() {
Message<String> message = MessageBuilder.withPayload("foo").build();
@@ -42,7 +50,7 @@ public class MessageBuilderTests {
public void testHeaderValues() {
Message<String> message = MessageBuilder.withPayload("test")
.setHeader("foo", "bar")
.setHeader("count", new Integer(123))
.setHeader("count", 123)
.build();
assertEquals("bar", message.getHeaders().get("foo", String.class));
assertEquals(new Integer(123), message.getHeaders().get("count", Integer.class));
@@ -153,11 +161,11 @@ public class MessageBuilderTests {
@Test
public void testCopySameHeaderValuesNotModifiedSameMessage() throws Exception {
Date current = new Date();
Map<String, Object> originalHeaders = new HashMap<String, Object>();
Map<String, Object> originalHeaders = new HashMap<>();
originalHeaders.put("b", "xyz");
originalHeaders.put("c", current);
Message<?> original = MessageBuilder.withPayload("foo").setHeader("a", 123).copyHeaders(originalHeaders).build();
Map<String, Object> newHeaders = new HashMap<String, Object>();
Map<String, Object> newHeaders = new HashMap<>();
newHeaders.put("a", 123);
newHeaders.put("b", "xyz");
newHeaders.put("c", current);
@@ -165,4 +173,61 @@ public class MessageBuilderTests {
assertEquals(original, result);
}
@Test
public void testBuildMessageWithMutableHeaders() {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setLeaveMutable(true);
MessageHeaders headers = accessor.getMessageHeaders();
Message<?> message = MessageBuilder.createMessage("payload", headers);
accessor.setHeader("foo", "bar");
assertEquals("bar", headers.get("foo"));
assertSame(accessor, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class));
}
@Test
public void testBuildMessageWithDefaultMutability() {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
MessageHeaders headers = accessor.getMessageHeaders();
Message<?> message = MessageBuilder.createMessage("foo", headers);
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Already immutable");
accessor.setHeader("foo", "bar");
assertSame(accessor, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class));
}
@Test
public void testBuildMessageWithoutIdAndTimestamp() {
MessageHeaderAccessor headerAccessor = new MessageHeaderAccessor();
headerAccessor.setIdGenerator(new IdGenerator() {
@Override
public UUID generateId() {
return MessageHeaders.ID_VALUE_NONE;
}
});
Message<?> message = MessageBuilder.createMessage("foo", headerAccessor.getMessageHeaders());
assertNull(message.getHeaders().getId());
assertNull(message.getHeaders().getTimestamp());
}
@Test
public void testBuildMultipleMessages() {
MessageHeaderAccessor headerAccessor = new MessageHeaderAccessor();
MessageBuilder messageBuilder = MessageBuilder.withPayload("payload").setHeaders(headerAccessor);
headerAccessor.setHeader("foo", "bar1");
Message<?> message1 = messageBuilder.build();
headerAccessor.setHeader("foo", "bar2");
Message<?> message2 = messageBuilder.build();
headerAccessor.setHeader("foo", "bar3");
Message<?> message3 = messageBuilder.build();
assertEquals("bar1", message1.getHeaders().get("foo"));
assertEquals("bar2", message2.getHeaders().get("foo"));
assertEquals("bar3", message3.getHeaders().get("foo"));
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,14 +16,21 @@
package org.springframework.messaging.support;
import java.util.Collections;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.UUID;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.util.IdGenerator;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
/**
* Test fixture for {@link MessageHeaderAccessor}.
@@ -32,55 +39,229 @@ import static org.junit.Assert.*;
*/
public class MessageHeaderAccessorTests {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void empty() {
MessageHeaderAccessor headers = new MessageHeaderAccessor();
assertEquals(Collections.emptyMap(), headers.toMap());
public void newEmptyHeaders() {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
assertEquals(0, accessor.toMap().size());
}
@Test
public void wrapMessage() {
Map<String, Object> original = new HashMap<>();
original.put("foo", "bar");
original.put("bar", "baz");
GenericMessage<String> message = new GenericMessage<>("payload", original);
public void existingHeaders() throws InterruptedException {
Map<String, Object> map = new HashMap<>();
map.put("foo", "bar");
map.put("bar", "baz");
GenericMessage<String> message = new GenericMessage<>("payload", map);
MessageHeaderAccessor headers = new MessageHeaderAccessor(message);
Map<String, Object> actual = headers.toMap();
MessageHeaderAccessor accessor = new MessageHeaderAccessor(message);
MessageHeaders actual = accessor.getMessageHeaders();
assertEquals(4, actual.size());
assertNotNull(actual.get(MessageHeaders.ID));
assertNotNull(actual.get(MessageHeaders.TIMESTAMP));
assertEquals(3, actual.size());
assertEquals("bar", actual.get("foo"));
assertEquals("baz", actual.get("bar"));
}
@Test
public void wrapMessageAndModifyHeaders() {
Map<String, Object> original = new HashMap<>();
original.put("foo", "bar");
original.put("bar", "baz");
GenericMessage<String> message = new GenericMessage<>("payload", original);
public void existingHeadersModification() throws InterruptedException {
Map<String, Object> map = new HashMap<>();
map.put("foo", "bar");
map.put("bar", "baz");
GenericMessage<String> message = new GenericMessage<>("payload", map);
MessageHeaderAccessor headers = new MessageHeaderAccessor(message);
headers.setHeader("foo", "BAR");
Map<String, Object> actual = headers.toMap();
Thread.sleep(50);
assertEquals(4, actual.size());
assertNotNull(actual.get(MessageHeaders.ID));
assertNotNull(actual.get(MessageHeaders.TIMESTAMP));
MessageHeaderAccessor accessor = new MessageHeaderAccessor(message);
accessor.setHeader("foo", "BAR");
MessageHeaders actual = accessor.getMessageHeaders();
assertEquals(3, actual.size());
assertNotEquals(message.getHeaders().getId(), actual.getId());
assertEquals("BAR", actual.get("foo"));
assertEquals("baz", actual.get("bar"));
}
@Test
public void copyHeadersNullMap() {
public void copyHeadersFromNullMap() {
MessageHeaderAccessor headers = new MessageHeaderAccessor();
headers.copyHeaders(null);
headers.copyHeadersIfAbsent(null);
assertEquals(0, headers.toMap().size());
assertEquals(1, headers.getMessageHeaders().size());
assertEquals(new HashSet<>(Arrays.asList("id")), headers.getMessageHeaders().keySet());
}
@Test
public void toMap() {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setHeader("foo", "bar1");
Map<String, Object> map1 = accessor.toMap();
accessor.setHeader("foo", "bar2");
Map<String, Object> map2 = accessor.toMap();
accessor.setHeader("foo", "bar3");
Map<String, Object> map3 = accessor.toMap();
assertEquals(1, map1.size());
assertEquals(1, map2.size());
assertEquals(1, map3.size());
assertEquals("bar1", map1.get("foo"));
assertEquals("bar2", map2.get("foo"));
assertEquals("bar3", map3.get("foo"));
}
@Test
public void leaveMutable() {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setHeader("foo", "bar");
accessor.setLeaveMutable(true);
MessageHeaders headers = accessor.getMessageHeaders();
Message<?> message = MessageBuilder.createMessage("payload", headers);
accessor.setHeader("foo", "baz");
assertEquals("baz", headers.get("foo"));
assertSame(accessor, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class));
}
@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));
}
@Test
public void getAccessor() {
MessageHeaderAccessor expected = new MessageHeaderAccessor();
Message<?> message = MessageBuilder.createMessage("payload", expected.getMessageHeaders());
assertSame(expected, MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class));
}
@Test
public void getMutableAccessorSameInstance() {
TestMessageHeaderAccessor expected = new TestMessageHeaderAccessor();
expected.setLeaveMutable(true);
Message<?> message = MessageBuilder.createMessage("payload", expected.getMessageHeaders());
MessageHeaderAccessor actual = MessageHeaderAccessor.getMutableAccessor(message);
assertNotNull(actual);
assertTrue(actual.isMutable());
assertSame(expected, actual);
}
@Test
public void getMutableAccessorNewInstance() {
Message<?> message = MessageBuilder.withPayload("payload").build();
MessageHeaderAccessor actual = MessageHeaderAccessor.getMutableAccessor(message);
assertNotNull(actual);
assertTrue(actual.isMutable());
}
@Test
public void getMutableAccessorNewInstanceMatchingType() {
TestMessageHeaderAccessor expected = new TestMessageHeaderAccessor();
Message<?> message = MessageBuilder.createMessage("payload", expected.getMessageHeaders());
MessageHeaderAccessor actual = MessageHeaderAccessor.getMutableAccessor(message);
assertNotNull(actual);
assertTrue(actual.isMutable());
assertEquals(TestMessageHeaderAccessor.class, actual.getClass());
}
@Test
public void timestampEnabled() {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setEnableTimestamp(true);
assertNotNull(accessor.getMessageHeaders().getTimestamp());
}
@Test
public void timestampDefaultBehavior() {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
assertNull(accessor.getMessageHeaders().getTimestamp());
}
@Test
public void timestampBehaviorCopyFromExistingMessage() {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setEnableTimestamp(true);
Message<?> message = MessageBuilder.createMessage("payload", accessor.getMessageHeaders());
MessageHeaderAccessor secondAccessor = new MessageHeaderAccessor(message);
assertNotNull(secondAccessor.getMessageHeaders().getTimestamp());
}
@Test
public void idGeneratorCustom() {
final UUID id = new UUID(0L, 23L);
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setIdGenerator(new IdGenerator() {
@Override
public UUID generateId() {
return id;
}
});
assertSame(id, accessor.getMessageHeaders().getId());
}
@Test
public void idGeneratorDefaultBehavior() {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
assertNotNull(accessor.getMessageHeaders().getId());
}
@Test
public void idGeneratorCopyFromExistingMessage() {
final UUID id = new UUID(0L, 23L);
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setIdGenerator(new IdGenerator() {
@Override
public UUID generateId() {
return id;
}
});
Message<?> message = MessageBuilder.createMessage("payload", accessor.getMessageHeaders());
MessageHeaderAccessor secondAccessor = new MessageHeaderAccessor(message);
assertSame(id, secondAccessor.getMessageHeaders().getId());
}
public static class TestMessageHeaderAccessor extends MessageHeaderAccessor {
private TestMessageHeaderAccessor() {
}
private TestMessageHeaderAccessor(Message<?> message) {
super(message);
}
public static TestMessageHeaderAccessor wrap(Message<?> message) {
return new TestMessageHeaderAccessor(message);
}
@Override
protected TestMessageHeaderAccessor createAccessor(Message<?> message) {
return wrap(message);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,16 +19,19 @@ package org.springframework.messaging.support;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
/**
* Test fixture for {@link NativeMessageHeaderAccessor}.
@@ -37,81 +40,78 @@ import static org.junit.Assert.*;
*/
public class NativeMessageHeaderAccessorTests {
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Test
public void originalNativeHeaders() {
MultiValueMap<String, String> original = new LinkedMultiValueMap<>();
original.add("foo", "bar");
original.add("bar", "baz");
public void createFromNativeHeaderMap() {
MultiValueMap<String, String> inputNativeHeaders = new LinkedMultiValueMap<>();
inputNativeHeaders.add("foo", "bar");
inputNativeHeaders.add("bar", "baz");
NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(original);
Map<String, Object> actual = headers.toMap();
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(inputNativeHeaders);
Map<String, Object> actual = headerAccessor.toMap();
assertEquals(1, actual.size());
assertEquals(actual.toString(), 1, actual.size());
assertNotNull(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
assertEquals(original, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
assertEquals(inputNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
assertNotSame(inputNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
}
@Test
public void wrapMessage() {
public void createFromMessage() {
MultiValueMap<String, String> inputNativeHeaders = new LinkedMultiValueMap<>();
inputNativeHeaders.add("foo", "bar");
inputNativeHeaders.add("bar", "baz");
MultiValueMap<String, String> originalNativeHeaders = new LinkedMultiValueMap<>();
originalNativeHeaders.add("foo", "bar");
originalNativeHeaders.add("bar", "baz");
Map<String, Object> inputHeaders = new HashMap<String, Object>();
inputHeaders.put("a", "b");
inputHeaders.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, inputNativeHeaders);
Map<String, Object> original = new HashMap<String, Object>();
original.put("a", "b");
original.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, originalNativeHeaders);
GenericMessage<String> message = new GenericMessage<>("p", inputHeaders);
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(message);
Map<String, Object> actual = headerAccessor.toMap();
GenericMessage<String> message = new GenericMessage<>("p", original);
NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(message);
Map<String, Object> actual = headers.toMap();
assertEquals(4, actual.size());
assertNotNull(actual.get(MessageHeaders.ID));
assertNotNull(actual.get(MessageHeaders.TIMESTAMP));
assertEquals(2, actual.size());
assertEquals("b", actual.get("a"));
assertNotNull(actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
assertEquals(originalNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
assertEquals(inputNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
assertNotSame(inputNativeHeaders, actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
}
@Test
public void wrapNullMessage() {
NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor((Message<?>) null);
Map<String, Object> actual = headers.toMap();
public void createFromMessageNull() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor((Message<?>) null);
assertEquals(1, actual.size());
Map<String, Object> actual = headerAccessor.toMap();
assertEquals(0, actual.size());
@SuppressWarnings("unchecked")
Map<String, List<String>> actualNativeHeaders =
(Map<String, List<String>>) actual.get(NativeMessageHeaderAccessor.NATIVE_HEADERS);
Map<String, List<String>> actualNativeHeaders = headerAccessor.toNativeHeaderMap();
assertEquals(Collections.emptyMap(), actualNativeHeaders);
}
@Test
public void wrapMessageAndModifyHeaders() {
public void createFromMessageAndModify() {
MultiValueMap<String, String> originalNativeHeaders = new LinkedMultiValueMap<>();
originalNativeHeaders.add("foo", "bar");
originalNativeHeaders.add("bar", "baz");
MultiValueMap<String, String> inputNativeHeaders = new LinkedMultiValueMap<>();
inputNativeHeaders.add("foo", "bar");
inputNativeHeaders.add("bar", "baz");
Map<String, Object> original = new HashMap<String, Object>();
original.put("a", "b");
original.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, originalNativeHeaders);
Map<String, Object> nativeHeaders = new HashMap<String, Object>();
nativeHeaders.put("a", "b");
nativeHeaders.put(NativeMessageHeaderAccessor.NATIVE_HEADERS, inputNativeHeaders);
GenericMessage<String> message = new GenericMessage<>("p", original);
GenericMessage<String> message = new GenericMessage<>("p", nativeHeaders);
NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(message);
headers.setHeader("a", "B");
headers.setNativeHeader("foo", "BAR");
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor(message);
headerAccessor.setHeader("a", "B");
headerAccessor.setNativeHeader("foo", "BAR");
Map<String, Object> actual = headers.toMap();
Map<String, Object> actual = headerAccessor.toMap();
assertEquals(4, actual.size());
assertNotNull(actual.get(MessageHeaders.ID));
assertNotNull(actual.get(MessageHeaders.TIMESTAMP));
assertEquals(2, actual.size());
assertEquals("B", actual.get("a"));
@SuppressWarnings("unchecked")
@@ -123,4 +123,112 @@ public class NativeMessageHeaderAccessorTests {
assertEquals(Arrays.asList("baz"), actualNativeHeaders.get("bar"));
}
}
@Test
public void setNativeHeader() {
MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<>();
nativeHeaders.add("foo", "bar");
NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders);
headers.setNativeHeader("foo", "baz");
assertEquals(Arrays.asList("baz"), headers.getNativeHeader("foo"));
}
@Test
public void setNativeHeaderNullValue() {
MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<>();
nativeHeaders.add("foo", "bar");
NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders);
headers.setNativeHeader("foo", null);
assertNull(headers.getNativeHeader("foo"));
}
@Test
public void setNativeHeaderLazyInit() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.setNativeHeader("foo", "baz");
assertEquals(Arrays.asList("baz"), headerAccessor.getNativeHeader("foo"));
}
@Test
public void setNativeHeaderLazyInitNullValue() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.setNativeHeader("foo", null);
assertNull(headerAccessor.getNativeHeader("foo"));
assertNull(headerAccessor.getMessageHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
}
@Test
public void setNativeHeaderImmutable() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.setNativeHeader("foo", "bar");
headerAccessor.setImmutable();
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Already immutable");
headerAccessor.setNativeHeader("foo", "baz");
}
@Test
public void addNativeHeader() {
MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<>();
nativeHeaders.add("foo", "bar");
NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders);
headers.addNativeHeader("foo", "baz");
assertEquals(Arrays.asList("bar", "baz"), headers.getNativeHeader("foo"));
}
@Test
public void addNativeHeaderNullValue() {
MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<>();
nativeHeaders.add("foo", "bar");
NativeMessageHeaderAccessor headers = new NativeMessageHeaderAccessor(nativeHeaders);
headers.addNativeHeader("foo", null);
assertEquals(Arrays.asList("bar"), headers.getNativeHeader("foo"));
}
@Test
public void addNativeHeaderLazyInit() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.addNativeHeader("foo", "bar");
assertEquals(Arrays.asList("bar"), headerAccessor.getNativeHeader("foo"));
}
@Test
public void addNativeHeaderLazyInitNullValue() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.addNativeHeader("foo", null);
assertNull(headerAccessor.getNativeHeader("foo"));
assertNull(headerAccessor.getMessageHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS));
}
@Test
public void addNativeHeaderImmutable() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.addNativeHeader("foo", "bar");
headerAccessor.setImmutable();
this.thrown.expect(IllegalStateException.class);
this.thrown.expectMessage("Already immutable");
headerAccessor.addNativeHeader("foo", "baz");
}
@Test
public void setImmutableIdempotent() {
NativeMessageHeaderAccessor headerAccessor = new NativeMessageHeaderAccessor();
headerAccessor.addNativeHeader("foo", "bar");
headerAccessor.setImmutable();
headerAccessor.setImmutable();
}
}

View File

@@ -41,9 +41,9 @@ import org.springframework.messaging.simp.stomp.StompConversionException;
import org.springframework.messaging.simp.stomp.StompEncoder;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.simp.user.DestinationUserNameProvider;
import org.springframework.messaging.simp.user.UserDestinationMessageHandler;
import org.springframework.messaging.simp.user.UserSessionRegistry;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.util.Assert;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
@@ -79,6 +79,8 @@ public class StompSubProtocolHandler implements SubProtocolHandler, ApplicationE
private static final Log logger = LogFactory.getLog(StompSubProtocolHandler.class);
private static final byte[] EMPTY_PAYLOAD = new byte[0];
private int messageSizeLimit = 64 * 1024;
@@ -172,9 +174,12 @@ public class StompSubProtocolHandler implements SubProtocolHandler, ApplicationE
for (Message<byte[]> message : messages) {
try {
StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
StompHeaderAccessor headerAccessor =
MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (logger.isTraceEnabled()) {
if (SimpMessageType.HEARTBEAT.equals(headers.getMessageType())) {
if (headerAccessor.isHeartbeat()) {
logger.trace("Received heartbeat from client session=" + session.getId());
}
else {
@@ -182,13 +187,12 @@ public class StompSubProtocolHandler implements SubProtocolHandler, ApplicationE
}
}
headers.setSessionId(session.getId());
headers.setSessionAttributes(session.getAttributes());
headers.setUser(session.getPrincipal());
headerAccessor.setSessionId(session.getId());
headerAccessor.setSessionAttributes(session.getAttributes());
headerAccessor.setUser(session.getPrincipal());
headerAccessor.setImmutable();
message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
if (this.eventPublisher != null && StompCommand.CONNECT.equals(headers.getCommand())) {
if (this.eventPublisher != null && StompCommand.CONNECT.equals(headerAccessor.getCommand())) {
publishEvent(new SessionConnectEvent(this, message));
}
@@ -212,10 +216,9 @@ public class StompSubProtocolHandler implements SubProtocolHandler, ApplicationE
protected void sendErrorMessage(WebSocketSession session, Throwable error) {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.ERROR);
headers.setMessage(error.getMessage());
Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
byte[] bytes = this.stompEncoder.encode(message);
StompHeaderAccessor headerAccessor = StompHeaderAccessor.create(StompCommand.ERROR);
headerAccessor.setMessage(error.getMessage());
byte[] bytes = this.stompEncoder.encode(headerAccessor.getMessageHeaders(), EMPTY_PAYLOAD);
try {
session.sendMessage(new TextMessage(bytes));
}
@@ -231,46 +234,60 @@ public class StompSubProtocolHandler implements SubProtocolHandler, ApplicationE
@Override
public void handleMessageToClient(WebSocketSession session, Message<?> message) {
StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
if (headers.getMessageType() == SimpMessageType.CONNECT_ACK) {
StompHeaderAccessor connectedHeaders = StompHeaderAccessor.create(StompCommand.CONNECTED);
connectedHeaders.setVersion(getVersion(headers));
connectedHeaders.setHeartbeat(0, 0); // no heart-beat support with simple broker
headers = connectedHeaders;
}
else if (SimpMessageType.MESSAGE.equals(headers.getMessageType())) {
headers.updateStompCommandAsServerMessage();
}
if (headers.getCommand() == StompCommand.CONNECTED) {
afterStompSessionConnected(headers, session);
}
if (StompCommand.MESSAGE.equals(headers.getCommand())) {
if (headers.getSubscriptionId() == null) {
logger.error("Ignoring message, no subscriptionId header: " + message);
return;
}
String header = SimpMessageHeaderAccessor.ORIGINAL_DESTINATION;
if (message.getHeaders().containsKey(header)) {
headers.setDestination((String) message.getHeaders().get(header));
}
}
if (!(message.getPayload() instanceof byte[])) {
logger.error("Ignoring message, expected byte[] content: " + message);
return;
}
try {
message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, MessageHeaderAccessor.class);
if (accessor == null) {
logger.error("No header accessor: " + message);
return;
}
if (this.eventPublisher != null && StompCommand.CONNECTED.equals(headers.getCommand())) {
StompHeaderAccessor stompAccessor;
if (accessor instanceof StompHeaderAccessor) {
stompAccessor = (StompHeaderAccessor) accessor;
}
else if (accessor instanceof SimpMessageHeaderAccessor) {
stompAccessor = StompHeaderAccessor.wrap(message);
if (SimpMessageType.CONNECT_ACK.equals(stompAccessor.getMessageType())) {
StompHeaderAccessor connectedHeaders = StompHeaderAccessor.create(StompCommand.CONNECTED);
connectedHeaders.setVersion(getVersion(stompAccessor));
connectedHeaders.setHeartbeat(0, 0); // no heart-beat support with simple broker
stompAccessor = connectedHeaders;
}
else if (stompAccessor.getCommand() == null || StompCommand.SEND.equals(stompAccessor.getCommand())) {
stompAccessor.updateStompCommandAsServerMessage();
}
}
else {
// Should not happen
logger.error("Unexpected header accessor type: " + accessor);
return;
}
StompCommand command = stompAccessor.getCommand();
if (StompCommand.MESSAGE.equals(command)) {
if (stompAccessor.getSubscriptionId() == null) {
logger.error("Ignoring message, no subscriptionId header: " + message);
return;
}
String header = SimpMessageHeaderAccessor.ORIGINAL_DESTINATION;
if (message.getHeaders().containsKey(header)) {
stompAccessor = toMutableAccessor(stompAccessor, message);
stompAccessor.setDestination((String) message.getHeaders().get(header));
}
}
else if (StompCommand.CONNECTED.equals(command)) {
stompAccessor = afterStompSessionConnected(message, stompAccessor, session);
if (this.eventPublisher != null && StompCommand.CONNECTED.equals(command)) {
publishEvent(new SessionConnectedEvent(this, (Message<byte[]>) message));
}
}
byte[] bytes = this.stompEncoder.encode((Message<byte[]>) message);
try {
byte[] bytes = this.stompEncoder.encode(stompAccessor.getMessageHeaders(), (byte[]) message.getPayload());
TextMessage textMessage = new TextMessage(bytes);
session.sendMessage(textMessage);
@@ -283,7 +300,7 @@ public class StompSubProtocolHandler implements SubProtocolHandler, ApplicationE
sendErrorMessage(session, ex);
}
finally {
if (StompCommand.ERROR.equals(headers.getCommand())) {
if (StompCommand.ERROR.equals(command)) {
try {
session.close(CloseStatus.PROTOCOL_ERROR);
}
@@ -294,13 +311,19 @@ public class StompSubProtocolHandler implements SubProtocolHandler, ApplicationE
}
}
protected StompHeaderAccessor toMutableAccessor(StompHeaderAccessor headerAccessor, Message<?> message) {
return (headerAccessor.isMutable() ? headerAccessor : StompHeaderAccessor.wrap(message));
}
private String getVersion(StompHeaderAccessor connectAckHeaders) {
String name = StompHeaderAccessor.CONNECT_MESSAGE_HEADER;
Message<?> connectMessage = (Message<?>) connectAckHeaders.getHeader(name);
StompHeaderAccessor connectHeaders = StompHeaderAccessor.wrap(connectMessage);
Assert.notNull(connectMessage, "CONNECT_ACK does not contain original CONNECT " + connectAckHeaders);
StompHeaderAccessor connectHeaders =
MessageHeaderAccessor.getAccessor(connectMessage, StompHeaderAccessor.class);
Set<String> acceptVersions = connectHeaders.getAcceptVersion();
if (acceptVersions.contains("1.2")) {
return "1.2";
@@ -316,16 +339,19 @@ public class StompSubProtocolHandler implements SubProtocolHandler, ApplicationE
}
}
private void afterStompSessionConnected(StompHeaderAccessor headers, WebSocketSession session) {
private StompHeaderAccessor afterStompSessionConnected(
Message<?> message, StompHeaderAccessor headerAccessor, WebSocketSession session) {
Principal principal = session.getPrincipal();
if (principal != null) {
headers.setNativeHeader(CONNECTED_USER_HEADER, principal.getName());
headerAccessor = toMutableAccessor(headerAccessor, message);
headerAccessor.setNativeHeader(CONNECTED_USER_HEADER, principal.getName());
if (this.userSessionRegistry != null) {
String userName = resolveNameForUserSessionRegistry(principal);
this.userSessionRegistry.registerSessionId(userName, session.getId());
}
}
long[] heartbeat = headers.getHeartbeat();
long[] heartbeat = headerAccessor.getHeartbeat();
if (heartbeat[1] > 0) {
session = WebSocketSessionDecorator.unwrap(session);
if (session instanceof SockJsSession) {
@@ -333,6 +359,7 @@ public class StompSubProtocolHandler implements SubProtocolHandler, ApplicationE
((SockJsSession) session).disableHeartbeat();
}
}
return headerAccessor;
}
private String resolveNameForUserSessionRegistry(Principal principal) {
@@ -345,8 +372,7 @@ public class StompSubProtocolHandler implements SubProtocolHandler, ApplicationE
@Override
public String resolveSessionId(Message<?> message) {
StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
return headers.getSessionId();
return SimpMessageHeaderAccessor.getSessionId(message.getHeaders());
}
@Override
@@ -374,7 +400,7 @@ public class StompSubProtocolHandler implements SubProtocolHandler, ApplicationE
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT);
headers.setSessionId(session.getId());
Message<?> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<?> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
if (this.eventPublisher != null) {
publishEvent(new SessionDisconnectEvent(this, session.getId(), closeStatus));

View File

@@ -16,7 +16,6 @@
package org.springframework.web.socket.messaging;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
@@ -41,7 +40,6 @@ import org.springframework.messaging.simp.stomp.StompEncoder;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.simp.user.DefaultUserSessionRegistry;
import org.springframework.messaging.simp.user.DestinationUserNameProvider;
import org.springframework.messaging.simp.user.UserDestinationMessageHandler;
import org.springframework.messaging.simp.user.UserSessionRegistry;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.socket.CloseStatus;
@@ -61,6 +59,8 @@ import static org.mockito.Mockito.*;
*/
public class StompSubProtocolHandlerTests {
public static final byte[] EMPTY_PAYLOAD = new byte[0];
private StompSubProtocolHandler protocolHandler;
private TestWebSocketSession session;
@@ -89,7 +89,7 @@ public class StompSubProtocolHandlerTests {
this.protocolHandler.setUserSessionRegistry(registry);
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECTED);
Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
this.protocolHandler.handleMessageToClient(this.session, message);
assertEquals(1, this.session.getSentMessages().size());
@@ -108,7 +108,7 @@ public class StompSubProtocolHandlerTests {
this.protocolHandler.setUserSessionRegistry(registry);
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECTED);
Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
this.protocolHandler.handleMessageToClient(this.session, message);
assertEquals(1, this.session.getSentMessages().size());
@@ -126,7 +126,7 @@ public class StompSubProtocolHandlerTests {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECTED);
headers.setHeartbeat(0,10);
Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
this.protocolHandler.handleMessageToClient(sockJsSession, message);
verify(sockJsSession).disableHeartbeat();
@@ -137,12 +137,12 @@ public class StompSubProtocolHandlerTests {
StompHeaderAccessor connectHeaders = StompHeaderAccessor.create(StompCommand.CONNECT);
connectHeaders.setHeartbeat(10000, 10000);
connectHeaders.setNativeHeader(StompHeaderAccessor.STOMP_ACCEPT_VERSION_HEADER, "1.0,1.1");
Message<?> connectMessage = MessageBuilder.withPayload(new byte[0]).setHeaders(connectHeaders).build();
connectHeaders.setAcceptVersion("1.0,1.1");
Message<?> connectMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, connectHeaders.getMessageHeaders());
SimpMessageHeaderAccessor connectAckHeaders = SimpMessageHeaderAccessor.create(SimpMessageType.CONNECT_ACK);
connectAckHeaders.setHeader(SimpMessageHeaderAccessor.CONNECT_MESSAGE_HEADER, connectMessage);
Message<byte[]> connectAckMessage = MessageBuilder.withPayload(new byte[0]).setHeaders(connectAckHeaders).build();
Message<byte[]> connectAckMessage = MessageBuilder.createMessage(EMPTY_PAYLOAD, connectAckHeaders.getMessageHeaders());
this.protocolHandler.handleMessageToClient(this.session, connectAckMessage);
@@ -174,12 +174,12 @@ public class StompSubProtocolHandlerTests {
this.protocolHandler.afterSessionStarted(this.session, this.channel);
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
TextMessage textMessage = new TextMessage(new StompEncoder().encode(message));
this.protocolHandler.handleMessageFromClient(this.session, textMessage, this.channel);
headers = StompHeaderAccessor.create(StompCommand.CONNECTED);
message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
this.protocolHandler.handleMessageToClient(this.session, message);
this.protocolHandler.afterSessionEnded(this.session, CloseStatus.BAD_DATA, this.channel);
@@ -207,7 +207,7 @@ public class StompSubProtocolHandlerTests {
this.protocolHandler.afterSessionStarted(this.session, this.channel);
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
TextMessage textMessage = new TextMessage(new StompEncoder().encode(message));
this.protocolHandler.handleMessageFromClient(this.session, textMessage, this.channel);
@@ -218,7 +218,7 @@ public class StompSubProtocolHandlerTests {
reset(this.channel);
headers = StompHeaderAccessor.create(StompCommand.CONNECTED);
message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
this.protocolHandler.handleMessageToClient(this.session, message);
assertEquals(1, this.session.getSentMessages().size());
@@ -241,7 +241,7 @@ public class StompSubProtocolHandlerTests {
headers.setSubscriptionId("sub0");
headers.setDestination("/queue/foo-user123");
headers.setHeader(StompHeaderAccessor.ORIGINAL_DESTINATION, "/user/queue/foo");
Message<byte[]> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
Message<byte[]> message = MessageBuilder.createMessage(EMPTY_PAYLOAD, headers.getMessageHeaders());
this.protocolHandler.handleMessageToClient(this.session, message);
assertEquals(1, this.session.getSentMessages().size());
@@ -268,7 +268,7 @@ public class StompSubProtocolHandlerTests {
assertNotNull(headers.getSessionAttributes());
assertEquals("joe", headers.getUser().getName());
assertEquals("guest", headers.getLogin());
assertEquals("PROTECTED", headers.getPasscode());
assertEquals("guest", headers.getPasscode());
assertArrayEquals(new long[] {10000, 10000}, headers.getHeartbeat());
assertEquals(new HashSet<>(Arrays.asList("1.1","1.0")), headers.getAcceptVersion());
@@ -278,8 +278,9 @@ public class StompSubProtocolHandlerTests {
@Test
public void handleMessageFromClientInvalidStompCommand() {
TextMessage textMessage = new TextMessage("FOO");
TextMessage textMessage = new TextMessage("FOO\n\n\0");
this.protocolHandler.afterSessionStarted(this.session, this.channel);
this.protocolHandler.handleMessageFromClient(this.session, textMessage, this.channel);
verifyZeroInteractions(this.channel);

View File

@@ -128,7 +128,7 @@ public class StompWebSocketIntegrationTests extends AbstractWebSocketIntegration
assertTrue(clientHandler.latch.await(2, TimeUnit.SECONDS));
String payload = clientHandler.actual.get(0).getPayload();
assertTrue("Expected STOMP Command=MESSAGE, got " + payload, payload.startsWith("MESSAGE\n"));
assertTrue("Expected STOMP MESSAGE, got " + payload, payload.startsWith("MESSAGE\n"));
}
finally {
session.close();