/
StompEncoder.java
234 lines (199 loc) · 6.97 KB
/
StompEncoder.java
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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
113
114
115
116
117
118
119
120
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
153
154
155
156
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
/*
* Copyright 2002-2020 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
*
* https://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 java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
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.
*
* @author Andy Wilkinson
* @author Rossen Stoyanchev
* @since 4.0
* @see StompDecoder
*/
public class StompEncoder {
private static final byte LF = '\n';
private static final byte COLON = ':';
private static final Log logger = LogFactory.getLog(StompEncoder.class);
private static final int HEADER_KEY_CACHE_LIMIT = 32;
private final Map<String, byte[]> headerKeyAccessCache =
new ConcurrentHashMap<String, byte[]>(HEADER_KEY_CACHE_LIMIT);
@SuppressWarnings("serial")
private final Map<String, byte[]> headerKeyUpdateCache =
new LinkedHashMap<String, byte[]>(HEADER_KEY_CACHE_LIMIT, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, byte[]> eldest) {
if (size() > HEADER_KEY_CACHE_LIMIT) {
headerKeyAccessCache.remove(eldest.getKey());
return true;
}
else {
return false;
}
}
};
/**
* 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 + payload.length);
DataOutputStream output = new DataOutputStream(baos);
if (SimpMessageType.HEARTBEAT.equals(SimpMessageHeaderAccessor.getMessageType(headers))) {
logger.trace("Encoding heartbeat");
output.write(StompDecoder.HEARTBEAT_PAYLOAD);
}
else {
StompCommand command = StompHeaderAccessor.getCommand(headers);
if (command == null) {
throw new IllegalStateException("Missing STOMP command: " + headers);
}
output.write(command.toString().getBytes(StompDecoder.UTF8_CHARSET));
output.write(LF);
writeHeaders(command, headers, payload, output);
output.write(LF);
writeBody(payload, output);
output.write((byte) 0);
}
return baos.toByteArray();
}
catch (IOException ex) {
throw new StompConversionException("Failed to encode STOMP frame, headers=" + headers, ex);
}
}
private void writeHeaders(StompCommand command, Map<String, Object> headers, byte[] payload,
DataOutputStream output) throws IOException {
@SuppressWarnings("unchecked")
Map<String,List<String>> nativeHeaders =
(Map<String, List<String>>) headers.get(NativeMessageHeaderAccessor.NATIVE_HEADERS);
if (logger.isTraceEnabled()) {
logger.trace("Encoding STOMP " + command + ", headers=" + nativeHeaders);
}
if (nativeHeaders == null) {
return;
}
boolean shouldEscape = (command != StompCommand.CONNECT && command != StompCommand.CONNECTED);
for (Entry<String, List<String>> entry : nativeHeaders.entrySet()) {
if (command.requiresContentLength() && "content-length".equals(entry.getKey())) {
continue;
}
List<String> values = entry.getValue();
if (StompCommand.CONNECT.equals(command) &&
StompHeaderAccessor.STOMP_PASSCODE_HEADER.equals(entry.getKey())) {
values = Collections.singletonList(StompHeaderAccessor.getPasscode(headers));
}
byte[] encodedKey = encodeHeaderKey(entry.getKey(), shouldEscape);
for (String value : values) {
output.write(encodedKey);
output.write(COLON);
output.write(encodeHeaderValue(value, shouldEscape));
output.write(LF);
}
}
if (command.requiresContentLength()) {
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[] encodeHeaderKey(String input, boolean escape) {
String inputToUse = (escape ? escape(input) : input);
if (this.headerKeyAccessCache.containsKey(inputToUse)) {
return this.headerKeyAccessCache.get(inputToUse);
}
synchronized (this.headerKeyUpdateCache) {
byte[] bytes = this.headerKeyUpdateCache.get(inputToUse);
if (bytes == null) {
bytes = inputToUse.getBytes(StompDecoder.UTF8_CHARSET);
this.headerKeyAccessCache.put(inputToUse, bytes);
this.headerKeyUpdateCache.put(inputToUse, bytes);
}
return bytes;
}
}
private byte[] encodeHeaderValue(String input, boolean escape) {
String inputToUse = (escape ? escape(input) : input);
return inputToUse.getBytes(StompDecoder.UTF8_CHARSET);
}
/**
* See STOMP Spec 1.2:
* <a href="https://stomp.github.io/stomp-specification-1.2.html#Value_Encoding">"Value Encoding"</a>.
*/
private String escape(String inString) {
StringBuilder sb = null;
for (int i = 0; i < inString.length(); i++) {
char c = inString.charAt(i);
if (c == '\\') {
sb = getStringBuilder(sb, inString, i);
sb.append("\\\\");
}
else if (c == ':') {
sb = getStringBuilder(sb, inString, i);
sb.append("\\c");
}
else if (c == '\n') {
sb = getStringBuilder(sb, inString, i);
sb.append("\\n");
}
else if (c == '\r') {
sb = getStringBuilder(sb, inString, i);
sb.append("\\r");
}
else if (sb != null){
sb.append(c);
}
}
return (sb != null ? sb.toString() : inString);
}
private StringBuilder getStringBuilder(StringBuilder sb, String inString, int i) {
if (sb == null) {
sb = new StringBuilder(inString.length());
sb.append(inString, 0, i);
}
return sb;
}
private void writeBody(byte[] payload, DataOutputStream output) throws IOException {
output.write(payload);
}
}