StompMessageConverter.java 6.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * 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.
 */
16
package org.springframework.messaging.simp.stomp;
17 18 19

import java.io.ByteArrayOutputStream;
import java.io.IOException;
20
import java.nio.charset.Charset;
21
import java.util.List;
22 23
import java.util.Map.Entry;

24
import org.springframework.messaging.Message;
R
Rossen Stoyanchev 已提交
25
import org.springframework.messaging.support.MessageBuilder;
26
import org.springframework.util.Assert;
27 28
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
29

30 31 32

/**
 * @author Gary Russell
33
 * @author Rossen Stoyanchev
34 35
 * @since 4.0
 */
36
public class StompMessageConverter {
37

38 39
	private static final Charset STOMP_CHARSET = Charset.forName("UTF-8");

40 41 42 43 44 45 46
	public static final byte LF = 0x0a;

	public static final byte CR = 0x0d;

	private static final byte COLON = ':';

	/**
47
	 * @param stompContent a complete STOMP message (without the trailing 0x00) as byte[] or String.
48
	 */
49
	public Message<?> toMessage(Object stompContent) {
50 51 52 53 54 55 56

		byte[] byteContent = null;
		if (stompContent instanceof String) {
			byteContent = ((String) stompContent).getBytes(STOMP_CHARSET);
		}
		else if (stompContent instanceof byte[]){
			byteContent = (byte[]) stompContent;
57 58
		}
		else {
59 60
			throw new IllegalArgumentException(
					"stompContent is neither String nor byte[]: " + stompContent.getClass());
61
		}
62 63 64

		int totalLength = byteContent.length;
		if (byteContent[totalLength-1] == 0) {
65 66
			totalLength--;
		}
67 68

		int payloadIndex = findIndexOfPayload(byteContent);
69
		if (payloadIndex == 0) {
70
			throw new StompConversionException("No command found");
71
		}
72 73 74 75

		String headerContent = new String(byteContent, 0, payloadIndex, STOMP_CHARSET);
		Parser parser = new Parser(headerContent);

76 77
		StompCommand command = StompCommand.valueOf(parser.nextToken(LF).trim());
		Assert.notNull(command, "No command found");
78

79
		MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
80 81 82 83 84
		while (parser.hasNext()) {
			String header = parser.nextToken(COLON);
			if (header != null) {
				if (parser.hasNext()) {
					String value = parser.nextToken(LF);
85
					headers.add(header, value);
86 87
				}
				else {
88
					throw new StompConversionException("Parse exception for " + headerContent);
89 90 91
				}
			}
		}
92

93
		byte[] payload = new byte[totalLength - payloadIndex];
94
		System.arraycopy(byteContent, payloadIndex, payload, 0, totalLength - payloadIndex);
95
		StompHeaderAccessor stompHeaders = StompHeaderAccessor.create(command, headers);
96
		return MessageBuilder.withPayloadAndHeaders(payload, stompHeaders).build();
97 98
	}

99
	private int findIndexOfPayload(byte[] bytes) {
100 101 102
		int i;
		// ignore any leading EOL from the previous message
		for (i = 0; i < bytes.length; i++) {
103
			if (bytes[i] != '\n' && bytes[i] != '\r') {
104 105 106 107
				break;
			}
			bytes[i] = ' ';
		}
108
		int index = 0;
109
		for (; i < bytes.length - 1; i++) {
110 111
			if (bytes[i] == LF && bytes[i+1] == LF) {
				index = i + 2;
112 113
				break;
			}
114 115 116
			if ((i < (bytes.length - 3)) &&
					(bytes[i] == CR && bytes[i+1] == LF && bytes[i+2] == CR && bytes[i+3] == LF)) {
				index = i + 4;
117 118 119 120
				break;
			}
		}
		if (i >= bytes.length) {
121
			throw new StompConversionException("No end of headers found");
122
		}
123 124 125
		return index;
	}

126
	public byte[] fromMessage(Message<?> message) {
127 128 129 130 131 132 133 134 135 136

		byte[] payload;
		if (message.getPayload() instanceof byte[]) {
			payload = (byte[]) message.getPayload();
		}
		else {
			throw new IllegalArgumentException(
					"stompContent is not byte[]: " + message.getPayload().getClass());
		}

137
		ByteArrayOutputStream out = new ByteArrayOutputStream();
138
		StompHeaderAccessor stompHeaders = StompHeaderAccessor.wrap(message);
139

140
		try {
141
			out.write(stompHeaders.getCommand().toString().getBytes("UTF-8"));
142
			out.write(LF);
143
			for (Entry<String, List<String>> entry : stompHeaders.toStompHeaderMap().entrySet()) {
144 145
				String key = entry.getKey();
				key = replaceAllOutbound(key);
146 147 148 149 150 151 152
				for (String value : entry.getValue()) {
					out.write(key.getBytes("UTF-8"));
					out.write(COLON);
					value = replaceAllOutbound(value);
					out.write(value.getBytes("UTF-8"));
					out.write(LF);
				}
153 154
			}
			out.write(LF);
155
			out.write(payload);
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
			out.write(0);
			return out.toByteArray();
		}
		catch (IOException e) {
			throw new StompConversionException("Failed to serialize " + message, e);
		}
	}

	private String replaceAllOutbound(String key) {
		return key.replaceAll("\\\\", "\\\\")
				.replaceAll(":", "\\\\c")
				.replaceAll("\n", "\\\\n")
				.replaceAll("\r", "\\\\r");
	}


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
	private class Parser {

		private final String content;

		private int offset;

		public Parser(String content) {
			this.content = content;
		}

		public boolean hasNext() {
			return this.offset < this.content.length();
		}

		public String nextToken(byte delimiter) {
			if (this.offset >= this.content.length()) {
				return null;
			}
			int delimAt = this.content.indexOf(delimiter, this.offset);
			if (delimAt == -1) {
				if (this.offset == this.content.length() - 1 && delimiter == COLON &&
						this.content.charAt(this.offset) == LF) {
					this.offset++;
					return null;
				}
				else if (this.offset == this.content.length() - 2 && delimiter == COLON &&
						this.content.charAt(this.offset) == CR &&
						this.content.charAt(this.offset + 1) == LF) {
					this.offset += 2;
					return null;
				}
				else {
204
					throw new StompConversionException("No delimiter found at offset " + offset + " in " + this.content);
205 206 207 208 209 210 211 212 213 214 215 216 217 218
				}
			}
			int escapeAt = this.content.indexOf('\\', this.offset);
			String token = this.content.substring(this.offset, delimAt + 1);
			this.offset += token.length();
			if (escapeAt >= 0 && escapeAt < delimAt) {
				char escaped = this.content.charAt(escapeAt + 1);
				if (escaped == 'n' || escaped == 'c' || escaped == '\\') {
					token = token.replaceAll("\\\\n", "\n")
							.replaceAll("\\\\r", "\r")
							.replaceAll("\\\\c", ":")
							.replaceAll("\\\\\\\\", "\\\\");
				}
				else {
219
					throw new StompConversionException("Invalid escape sequence \\" + escaped);
220 221 222 223 224 225 226 227 228 229 230 231
				}
			}
			int length = token.length();
			if (delimiter == LF && length > 1 && token.charAt(length - 2) == CR) {
				return token.substring(0, length - 2);
			}
			else {
				return token.substring(0, length - 1);
			}
		}
	}
}