MessageHeaders.java 7.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/*
 * Copyright 2002-2013 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;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
28
import java.util.LinkedHashMap;
29 30 31 32 33 34 35 36 37
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
P
Phillip Webb 已提交
38
 * The headers for a {@link Message}
39
 *
P
Phillip Webb 已提交
40 41 42 43 44 45
 * <p><b>IMPORTANT</b>: This class is immutable. Any mutating operation
 * (e.g., put(..), putAll(..) etc.) will throw {@link UnsupportedOperationException}.
 *
 * <p>To create MessageHeaders instance use fluent
 * {@link org.springframework.messaging.support.MessageBuilder MessageBuilder} API
 * <pre class="code">
46 47 48
 * MessageBuilder.withPayload("foo").setHeader("key1", "value1").setHeader("key2", "value2");
 * </pre>
 * or create an instance of GenericMessage passing payload as {@link Object} and headers as a regular {@link Map}
P
Phillip Webb 已提交
49
 * <pre class="code">
50 51 52 53 54 55 56 57 58 59
 * Map headers = new HashMap();
 * headers.put("key1", "value1");
 * headers.put("key2", "value2");
 * new GenericMessage("foo", headers);
 * </pre>
 *
 * @author Arjen Poutsma
 * @author Mark Fisher
 * @author Gary Russell
 * @since 4.0
P
Phillip Webb 已提交
60
 * @see org.springframework.messaging.support.MessageBuilder
61
 */
62
public final class MessageHeaders implements Map<String, Object>, Serializable {
63

64
	private static final long serialVersionUID = -4615750558355702881L;
65 66 67

	private static final Log logger = LogFactory.getLog(MessageHeaders.class);

P
Phillip Webb 已提交
68

69 70 71 72 73 74 75 76 77 78 79 80
	private static volatile IdGenerator idGenerator = null;

	/**
	 * The key for the Message ID. This is an automatically generated UUID and
	 * should never be explicitly set in the header map <b>except</b> in the
	 * case of Message deserialization where the serialized Message's generated
	 * UUID is being restored.
	 */
	public static final String ID = "id";

	public static final String TIMESTAMP = "timestamp";

81 82 83 84 85 86
	public static final String REPLY_CHANNEL = "replyChannel";

	public static final String ERROR_CHANNEL = "errorChannel";

	public static final String CONTENT_TYPE = "contentType";

87
	public static final List<String> HEADER_NAMES = Arrays.asList(ID, TIMESTAMP);
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112


	private final Map<String, Object> headers;


	public MessageHeaders(Map<String, Object> headers) {
		this.headers = (headers != null) ? new HashMap<String, Object>(headers) : new HashMap<String, Object>();
		if (MessageHeaders.idGenerator == null){
			this.headers.put(ID, UUID.randomUUID());
		}
		else {
			this.headers.put(ID, MessageHeaders.idGenerator.generateId());
		}

		this.headers.put(TIMESTAMP, new Long(System.currentTimeMillis()));
	}

	public UUID getId() {
		return this.get(ID, UUID.class);
	}

	public Long getTimestamp() {
		return this.get(TIMESTAMP, Long.class);
	}

113 114 115 116 117 118 119 120
	public Object getReplyChannel() {
        return this.get(REPLY_CHANNEL);
    }

    public Object getErrorChannel() {
        return this.get(ERROR_CHANNEL);
    }

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
	@SuppressWarnings("unchecked")
	public <T> T get(Object key, Class<T> type) {
		Object value = this.headers.get(key);
		if (value == null) {
			return null;
		}
		if (!type.isAssignableFrom(value.getClass())) {
			throw new IllegalArgumentException("Incorrect type specified for header '" + key + "'. Expected [" + type
					+ "] but actual type is [" + value.getClass() + "]");
		}
		return (T) value;
	}

	@Override
	public int hashCode() {
		return this.headers.hashCode();
	}

	@Override
	public boolean equals(Object object) {
		if (this == object) {
			return true;
		}
		if (object != null && object instanceof MessageHeaders) {
			MessageHeaders other = (MessageHeaders) object;
			return this.headers.equals(other.headers);
		}
		return false;
	}

	@Override
	public String toString() {
153 154 155 156
		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();
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
	}

	/*
	 * Map implementation
	 */

	public boolean containsKey(Object key) {
		return this.headers.containsKey(key);
	}

	public boolean containsValue(Object value) {
		return this.headers.containsValue(value);
	}

	public Set<Map.Entry<String, Object>> entrySet() {
		return Collections.unmodifiableSet(this.headers.entrySet());
	}

	public Object get(Object key) {
		return this.headers.get(key);
	}

	public boolean isEmpty() {
		return this.headers.isEmpty();
	}

	public Set<String> keySet() {
		return Collections.unmodifiableSet(this.headers.keySet());
	}

	public int size() {
		return this.headers.size();
	}

	public Collection<Object> values() {
		return Collections.unmodifiableCollection(this.headers.values());
	}

	// Unsupported operations

	/**
	 * Since MessageHeaders are immutable the call to this method will result in {@link UnsupportedOperationException}
	 */
	public Object put(String key, Object value) {
		throw new UnsupportedOperationException("MessageHeaders is immutable.");
	}

	/**
	 * Since MessageHeaders are immutable the call to this method will result in {@link UnsupportedOperationException}
	 */
	public void putAll(Map<? extends String, ? extends Object> t) {
		throw new UnsupportedOperationException("MessageHeaders is immutable.");
	}

	/**
	 * Since MessageHeaders are immutable the call to this method will result in {@link UnsupportedOperationException}
	 */
	public Object remove(Object key) {
		throw new UnsupportedOperationException("MessageHeaders is immutable.");
	}

	/**
	 * Since MessageHeaders are immutable the call to this method will result in {@link UnsupportedOperationException}
	 */
	public void clear() {
		throw new UnsupportedOperationException("MessageHeaders is immutable.");
	}

	// Serialization methods

	private void writeObject(ObjectOutputStream out) throws IOException {
		List<String> keysToRemove = new ArrayList<String>();
		for (Map.Entry<String, Object> entry : this.headers.entrySet()) {
			if (!(entry.getValue() instanceof Serializable)) {
				keysToRemove.add(entry.getKey());
			}
		}
		for (String key : keysToRemove) {
			if (logger.isInfoEnabled()) {
				logger.info("removing non-serializable header: " + key);
			}
			this.headers.remove(key);
		}
		out.defaultWriteObject();
	}

	private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
		in.defaultReadObject();
	}

	public static interface IdGenerator {
		UUID generateId();
	}
}