Top Description Inners Fields Constructors Methods
org.springframework.messaging.support

public Class MessageHeaderAccessor

extends Object
Class Inheritance
Known Direct Subclasses
org.springframework.messaging.support.NativeMessageHeaderAccessor
Imports
java.nio.charset.Charset, .StandardCharsets, java.util.ArrayList, .Arrays, .Collections, .HashMap, .List, .Map, .UUID, org.springframework.lang.Nullable, org.springframework.messaging.Message, .MessageChannel, .MessageHeaders, org.springframework.util.Assert, .IdGenerator, .MimeType, .MimeTypeUtils, .ObjectUtils, .PatternMatchUtils, .StringUtils

Wrapper around MessageHeaders that provides extra features such as strongly typed accessors for specific headers, the ability to leave headers in a Message mutable, and the option to suppress automatic generation of id and timestamp headers. Subclasses such as NativeMessageHeaderAccessor and others provide support for managing processing vs external source headers as well as protocol specific headers.

Below is a workflow to initialize headers via MessageHeaderAccessor, or one of its subclasses, then create a Message, and then re-obtain the accessor possibly from a different component:

// Create a message with headers
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setHeader("foo", "bar");
MessageHeaders headers = accessor.getMessageHeaders();
Message message = MessageBuilder.createMessage("payload", headers);

// Later on
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message);
Assert.notNull(accessor, "No MessageHeaderAccessor");

In order for the above to work, all participating components must use MessageHeaders to create, access, or modify headers, or otherwise MessageHeaderAccessor#getAccessor(Message, Class) will return null. Below is a workflow that shows how headers are created and left mutable, then modified possibly by a different component, and finally made immutable perhaps before the possibility of being accessed on a different thread:

// Create a message with mutable headers
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setHeader("foo", "bar");
accessor.setLeaveMutable(true);
MessageHeaders headers = accessor.getMessageHeaders();
Message message = MessageBuilder.createMessage("payload", headers);

// Later on
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message);
if (accessor.isMutable()) {
    // It's mutable, just change the headers
    accessor.setHeader("bar", "baz");
}
else {
    // It's not, so get a mutable copy, change and re-create
    accessor = MessageHeaderAccessor.getMutableAccessor(message);
    accessor.setHeader("bar", "baz");
    accessor.setLeaveMutable(true); // leave mutable again or not?
    message = MessageBuilder.createMessage(message.getPayload(), accessor);
}

// Make the accessor immutable
MessageHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message);
accessor.setImmutable();
Authors
Rossen Stoyanchev, Juergen Hoeller
Since
4.0

Nested and Inner Type Summary

Modifier and TypeClass and Description
private class
MessageHeaderAccessor.MutableMessageHeaders

Extension of MessageHeaders that helps to preserve the link to the outer MessageHeaderAccessor instance that created it as well as keeps track of whether headers are still mutable.

Field Summary

Modifier and TypeField and Description
public static final Charset
DEFAULT_CHARSET

The default charset used for headers.

private boolean
private final MessageHeaderAccessor.MutableMessageHeaders
private IdGenerator
private boolean
private boolean
private static final MimeType[]

Constructor Summary

AccessConstructor and Description
public
MessageHeaderAccessor()

A constructor to create new headers.

public
MessageHeaderAccessor(Message<?>
a message to copy the headers from, or null if none
message
)

A constructor accepting the headers of an existing message to copy.

Method Summary

Modifier and TypeMethod and Description
public void
copyHeaders(Map<String, ?> headersToCopy)

Copy the name-value pairs from the provided Map.

public void
copyHeadersIfAbsent(Map<String, ?> headersToCopy)

Copy the name-value pairs from the provided Map.

protected MessageHeaderAccessor

Returns:

the nested accessor (typically a specific subclass)
createAccessor
(Message<?>
the message to build a new accessor for
message
)

Build a 'nested' accessor for the given message.

public static MessageHeaderAccessor

Returns:

an accessor instance of the specified type, or null if none
getAccessor
(Message<?>
the message to get an accessor for
message
)

Return the original MessageHeaderAccessor used to create the headers of the given Message, or null if that's not available or if its type does not match the required type.

public static <T extends MessageHeaderAccessor> T

Returns:

an accessor instance of the specified type, or null if none
getAccessor
(Message<?>
the message to get an accessor for
message
,
Class<T>
the required accessor type (or null for any)
requiredType
)

Return the original MessageHeaderAccessor used to create the headers of the given Message, or null if that's not available or if its type does not match the required type.

public static <T extends MessageHeaderAccessor> T

Returns:

an accessor instance of the specified type, or null if none
getAccessor
(MessageHeaders
the message headers to get an accessor for
messageHeaders
,
Class<T>
the required accessor type (or null for any)
requiredType
)

A variation of getAccessor(org.springframework.messaging.Message, Class) with a MessageHeaders instance instead of a Message.

private Charset
public MimeType
public String

Returns:

the message
getDetailedLogMessage
(Object
the payload that corresponds to the headers.
payload
)

Return a more detailed message for logging purposes.

protected String
public Object
public Object

Returns:

the associated value, or null if none found
getHeader
(String
the name of the header
headerName
)

Retrieve the value for the header with the given name.

public UUID
private List<String>
public MessageHeaders
getMessageHeaders()

Return the underlying MessageHeaders instance.

public static MessageHeaderAccessor

Returns:

an accessor of the required type (never null)
getMutableAccessor
(Message<?> message)

Return a mutable 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 MessageHeaderAccessor instance.

public Object
public String

Returns:

the message
getShortLogMessage
(Object
the payload that corresponds to the headers.
payload
)

Return a concise message for logging purposes.

protected String
public Long
public boolean

Returns:

true if the flag has been set, false otherwise
isModified
()

Check whether the underlying message headers have been marked as modified.

public boolean
isMutable()

Whether the underlying headers can still be modified.

protected boolean
protected boolean
isReadOnly(String headerName)

public void
removeHeader(String headerName)

Remove the value for the given header name.

public void
removeHeaders(String... headerPatterns)

Removes all headers provided via array of 'headerPatterns'.

public void
setContentType(MimeType contentType)

pack-priv void
setEnableTimestamp(boolean enableTimestamp)

A package private mechanism to enables the automatic addition of the org.springframework.messaging.MessageHeaders#TIMESTAMP header.

public void
public void
setErrorChannelName(String errorChannelName)

public void
setHeader(String name, Object value)

Set the value for the given header name.

public void
setHeaderIfAbsent(String name, Object value)

Set the value for the given header name only if the header name is not already associated with a value.

pack-priv void
setIdGenerator(IdGenerator idGenerator)

A package-private mechanism to configure the IdGenerator strategy to use.

public void
setImmutable()

By default, when getMessageHeaders() is called, "this" MessageHeaderAccessor instance can no longer be used to modify the underlying message headers.

public void
setLeaveMutable(boolean leaveMutable)

By default, when getMessageHeaders() is called, "this" MessageHeaderAccessor instance can no longer be used to modify the underlying message headers and the returned MessageHeaders is immutable.

protected void
setModified(boolean
typically true, or false to reset the flag
modified
)

Mark the underlying message headers as modified.

public void
public void
setReplyChannelName(String replyChannelName)

public Map<String, Object>
toMap()

Return a copy of the underlying header values as a plain Map object.

public MessageHeaders
toMessageHeaders()

Return a copy of the underlying header values as a MessageHeaders object.

public String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.
protected void
verifyType(String headerName, Object headerValue)

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait

Field Detail

DEFAULT_CHARSETback to summary
public static final Charset DEFAULT_CHARSET

The default charset used for headers.

enableTimestampback to summary
private boolean enableTimestamp
headersback to summary
private final MessageHeaderAccessor.MutableMessageHeaders headers
idGeneratorback to summary
private IdGenerator idGenerator
Annotations
@Nullable
leaveMutableback to summary
private boolean leaveMutable
modifiedback to summary
private boolean modified
READABLE_MIME_TYPESback to summary
private static final MimeType[] READABLE_MIME_TYPES

Constructor Detail

MessageHeaderAccessorback to summary
public MessageHeaderAccessor()

A constructor to create new headers.

MessageHeaderAccessorback to summary
public MessageHeaderAccessor(Message<?> message)

A constructor accepting the headers of an existing message to copy.

Parameters
message:Message<?>

a message to copy the headers from, or null if none

Method Detail

copyHeadersback to summary
public void copyHeaders(Map<String, ?> headersToCopy)

Copy the name-value pairs from the provided Map.

This operation will overwrite any existing values. Use copyHeadersIfAbsent(Map) to avoid overwriting values.

copyHeadersIfAbsentback to summary
public void copyHeadersIfAbsent(Map<String, ?> headersToCopy)

Copy the name-value pairs from the provided Map.

This operation will not overwrite any existing values.

createAccessorback to summary
protected MessageHeaderAccessor createAccessor(Message<?> message)

Build a 'nested' accessor for the given message.

Parameters
message:Message<?>

the message to build a new accessor for

Returns:MessageHeaderAccessor

the nested accessor (typically a specific subclass)

getAccessorback to summary
public static MessageHeaderAccessor getAccessor(Message<?> message)

Return the original MessageHeaderAccessor used to create the headers of the given Message, or null if that's not available or if its type does not match the required type.

This is for cases where the existence of an accessor is strongly expected (followed up with an assertion) or where an accessor will be created otherwise.

Parameters
message:Message<?>

the message to get an accessor for

Returns:MessageHeaderAccessor

an accessor instance of the specified type, or null if none

Annotations
@Nullable
Since
5.1.19
getAccessorback to summary
public static <T extends MessageHeaderAccessor> T getAccessor(Message<?> message, Class<T> requiredType)

Return the original MessageHeaderAccessor used to create the headers of the given Message, or null if that's not available or if its type does not match the required type.

This is for cases where the existence of an accessor is strongly expected (followed up with an assertion) or where an accessor will be created otherwise.

Parameters
message:Message<?>

the message to get an accessor for

requiredType:Class<T>

the required accessor type (or null for any)

Returns:T

an accessor instance of the specified type, or null if none

Annotations
@Nullable
Since
4.1
getAccessorback to summary
public static <T extends MessageHeaderAccessor> T getAccessor(MessageHeaders messageHeaders, Class<T> requiredType)

A variation of getAccessor(org.springframework.messaging.Message, Class) with a MessageHeaders instance instead of a Message.

This is for cases when a full message may not have been created yet.

Parameters
messageHeaders:MessageHeaders

the message headers to get an accessor for

requiredType:Class<T>

the required accessor type (or null for any)

Returns:T

an accessor instance of the specified type, or null if none

Annotations
@SuppressWarnings:unchecked
@Nullable
Since
4.1
getCharsetback to summary
private Charset getCharset()
getContentTypeback to summary
public MimeType getContentType()
Annotations
@Nullable
getDetailedLogMessageback to summary
public String getDetailedLogMessage(Object payload)

Return a more detailed message for logging purposes.

Parameters
payload:Object

the payload that corresponds to the headers.

Returns:String

the message

getDetailedPayloadLogMessageback to summary
protected String getDetailedPayloadLogMessage(Object payload)
getErrorChannelback to summary
public Object getErrorChannel()
Annotations
@Nullable
getHeaderback to summary
public Object getHeader(String headerName)

Retrieve the value for the header with the given name.

Parameters
headerName:String

the name of the header

Returns:Object

the associated value, or null if none found

Annotations
@Nullable
getIdback to summary
public UUID getId()
Annotations
@Nullable
getMatchingHeaderNamesback to summary
private List<String> getMatchingHeaderNames(String pattern, Map<String, Object> headers)
getMessageHeadersback to summary
public MessageHeaders getMessageHeaders()

Return the underlying MessageHeaders instance.

Unless setLeaveMutable(boolean) was set to true, after this call, the headers are immutable and this accessor can no longer modify them.

This method always returns the same MessageHeaders instance if invoked multiples times. To obtain a copy of the underlying headers, use toMessageHeaders() or toMap() instead.

Since
4.1
getMutableAccessorback to summary
public static MessageHeaderAccessor getMutableAccessor(Message<?> message)

Return a mutable 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 MessageHeaderAccessor instance.

This is for cases where a header needs to be updated in generic code while preserving the accessor type for downstream processing.

Returns:MessageHeaderAccessor

an accessor of the required type (never null)

Since
4.1
getReplyChannelback to summary
public Object getReplyChannel()
Annotations
@Nullable
getShortLogMessageback to summary
public String getShortLogMessage(Object payload)

Return a concise message for logging purposes.

Parameters
payload:Object

the payload that corresponds to the headers.

Returns:String

the message

getShortPayloadLogMessageback to summary
protected String getShortPayloadLogMessage(Object payload)
getTimestampback to summary
public Long getTimestamp()
Annotations
@Nullable
isModifiedback to summary
public boolean isModified()

Check whether the underlying message headers have been marked as modified.

Returns:boolean

true if the flag has been set, false otherwise

isMutableback to summary
public boolean isMutable()

Whether the underlying headers can still be modified.

Since
4.1
isReadableContentTypeback to summary
protected boolean isReadableContentType()
isReadOnlyback to summary
protected boolean isReadOnly(String headerName)
removeHeaderback to summary
public void removeHeader(String headerName)

Remove the value for the given header name.

removeHeadersback to summary
public void removeHeaders(String... headerPatterns)

Removes all headers provided via array of 'headerPatterns'.

As the name suggests, array may contain simple matching patterns for header names. Supported pattern styles are: "xxx*", "*xxx", "*xxx*" and "xxx*yyy".

setContentTypeback to summary
public void setContentType(MimeType contentType)
setEnableTimestampback to summary
pack-priv void setEnableTimestamp(boolean enableTimestamp)

A package private mechanism to enables the automatic addition of the org.springframework.messaging.MessageHeaders#TIMESTAMP header.

By default, this property is set to false.

See Also
IdTimestampMessageHeaderInitializer
setErrorChannelback to summary
public void setErrorChannel(MessageChannel errorChannel)
setErrorChannelNameback to summary
public void setErrorChannelName(String errorChannelName)
setHeaderback to summary
public void setHeader(String name, Object value)

Set the value for the given header name.

If the provided value is null, the header will be removed.

setHeaderIfAbsentback to summary
public void setHeaderIfAbsent(String name, Object value)

Set the value for the given header name only if the header name is not already associated with a value.

setIdGeneratorback to summary
pack-priv void setIdGenerator(IdGenerator idGenerator)

A package-private mechanism to configure the IdGenerator strategy to use.

By default this property is not set in which case the default IdGenerator in org.springframework.messaging.MessageHeaders is used.

See Also
IdTimestampMessageHeaderInitializer
setImmutableback to summary
public void setImmutable()

By default, when getMessageHeaders() is called, "this" MessageHeaderAccessor instance can no longer be used to modify the underlying message headers. However if setLeaveMutable(boolean) is used, this method is necessary to indicate explicitly when the MessageHeaders instance should no longer be modified.

Since
4.1
setLeaveMutableback to summary
public void setLeaveMutable(boolean leaveMutable)

By default, when getMessageHeaders() is called, "this" MessageHeaderAccessor instance can no longer be used to modify the underlying message headers and the returned MessageHeaders is immutable.

However when this is set to true, the returned (underlying) MessageHeaders instance remains mutable. To make further modifications continue to use the same accessor instance or re-obtain it via:
MessageHeaderAccessor.getAccessor(Message, Class)

When modifications are complete use setImmutable() to prevent further changes. The intended use case for this mechanism is initialization of a Message within a single thread.

By default this is set to false.

Since
4.1
setModifiedback to summary
protected void setModified(boolean modified)

Mark the underlying message headers as modified.

Parameters
modified:boolean

typically true, or false to reset the flag

Since
4.1
setReplyChannelback to summary
public void setReplyChannel(MessageChannel replyChannel)
setReplyChannelNameback to summary
public void setReplyChannelName(String replyChannelName)
toMapback to summary
public Map<String, Object> toMap()

Return a copy of the underlying header values as a plain Map object.

This method can be invoked many times, with modifications in between where each new call returns a fresh copy of the current header values.

toMessageHeadersback to summary
public MessageHeaders toMessageHeaders()

Return a copy of the underlying header values as a MessageHeaders object.

This method can be invoked many times, with modifications in between where each new call returns a fresh copy of the current header values.

Since
4.1
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object.

Returns:String

a string representation of the object.

Annotations
@Override
verifyTypeback to summary
protected void verifyType(String headerName, Object headerValue)
org.springframework.messaging.support back to summary

private Class MessageHeaderAccessor.MutableMessageHeaders

extends MessageHeaders
Class Inheritance
Annotations
@SuppressWarnings:serial

Extension of MessageHeaders that helps to preserve the link to the outer MessageHeaderAccessor instance that created it as well as keeps track of whether headers are still mutable.

Field Summary

Modifier and TypeField and Description
private boolean
Inherited from org.springframework.messaging.MessageHeaders:
CONTENT_TYPEERROR_CHANNELIDID_VALUE_NONEREPLY_CHANNELTIMESTAMP

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public MessageHeaderAccessor
public Map<String, Object>
public boolean
public void
protected Object
Inherited from org.springframework.messaging.MessageHeaders:
clearcontainsKeycontainsValueentrySetequalsgetgetgetErrorChannelgetIdgetIdGeneratorgetReplyChannelgetTimestamphashCodeisEmptykeySetputputAllremovesizetoStringvalues

Field Detail

mutableback to summary
private boolean mutable

Constructor Detail

MutableMessageHeadersback to summary
public MutableMessageHeaders(Map<String, Object> headers)

Method Detail

getAccessorback to summary
public MessageHeaderAccessor getAccessor()
getRawHeadersback to summary
public Map<String, Object> getRawHeaders()

Overrides org.springframework.messaging.MessageHeaders.getRawHeaders.

Annotations
@Override
isMutableback to summary
public boolean isMutable()
setImmutableback to summary
public void setImmutable()
writeReplaceback to summary
protected Object writeReplace()