Skip to content

Commit 05bdc2c

Browse files
committed
Consistent declaration and use of UTF-8 Charset constants, plus related polishing
1 parent 53eec48 commit 05bdc2c

File tree

16 files changed

+99
-100
lines changed

16 files changed

+99
-100
lines changed

spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompDecoder.java

Lines changed: 17 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -67,21 +67,20 @@ public void setHeaderInitializer(MessageHeaderInitializer headerInitializer) {
6767
}
6868

6969
/**
70-
* @return the configured {@code MessageHeaderInitializer} if any.
70+
* Return the configured {@code MessageHeaderInitializer}, if any.
7171
*/
7272
public MessageHeaderInitializer getHeaderInitializer() {
7373
return this.headerInitializer;
7474
}
7575

76+
7677
/**
7778
* Decodes one or more STOMP frames from the given {@code ByteBuffer} into a
78-
* list of {@link Message}s. If the input buffer contains any incplcontains partial STOMP frame content, or additional
79-
* content with a partial STOMP frame, the buffer is reset and {@code null} is
80-
* returned.
81-
*
79+
* list of {@link Message}s. If the input buffer contains partial STOMP frame
80+
* content, or additional content with a partial STOMP frame, the buffer is
81+
* reset and {@code null} is returned.
8282
* @param buffer The buffer to decode the STOMP frame from
83-
*
84-
* @return the decoded messages or an empty list
83+
* @return the decoded messages, or an empty list if none
8584
*/
8685
public List<Message<byte[]>> decode(ByteBuffer buffer) {
8786
return decode(buffer, null);
@@ -90,33 +89,28 @@ public List<Message<byte[]>> decode(ByteBuffer buffer) {
9089
/**
9190
* Decodes one or more STOMP frames from the given {@code buffer} and returns
9291
* a list of {@link Message}s.
93-
*
9492
* <p>If the given ByteBuffer contains only partial STOMP frame content and no
9593
* complete STOMP frames, an empty list is returned, and the buffer is reset to
9694
* to where it was.
97-
*
9895
* <p>If the buffer contains one ore more STOMP frames, those are returned and
9996
* the buffer reset to point to the beginning of the unused partial content.
100-
*
10197
* <p>The output partialMessageHeaders map is used to store successfully parsed
10298
* headers in case of partial content. The caller can then check if a
10399
* "content-length" header was read, which helps to determine how much more
104100
* content is needed before the next attempt to decode.
105-
*
106101
* @param buffer The buffer to decode the STOMP frame from
107102
* @param partialMessageHeaders an empty output map that will store the last
108103
* successfully parsed partialMessageHeaders in case of partial message content
109104
* in cases where the partial buffer ended with a partial STOMP frame
110-
*
111105
* @return decoded messages or an empty list
112106
* @throws StompConversionException raised in case of decoding issues
113107
*/
114108
public List<Message<byte[]>> decode(ByteBuffer buffer, MultiValueMap<String, String> partialMessageHeaders) {
115109
List<Message<byte[]>> messages = new ArrayList<Message<byte[]>>();
116110
while (buffer.hasRemaining()) {
117-
Message<byte[]> m = decodeMessage(buffer, partialMessageHeaders);
118-
if (m != null) {
119-
messages.add(m);
111+
Message<byte[]> message = decodeMessage(buffer, partialMessageHeaders);
112+
if (message != null) {
113+
messages.add(message);
120114
}
121115
else {
122116
break;
@@ -129,28 +123,23 @@ public List<Message<byte[]>> decode(ByteBuffer buffer, MultiValueMap<String, Str
129123
* Decode a single STOMP frame from the given {@code buffer} into a {@link Message}.
130124
*/
131125
private Message<byte[]> decodeMessage(ByteBuffer buffer, MultiValueMap<String, String> headers) {
132-
133126
Message<byte[]> decodedMessage = null;
134127
skipLeadingEol(buffer);
135128
buffer.mark();
136129

137130
String command = readCommand(buffer);
138131
if (command.length() > 0) {
139-
140132
StompHeaderAccessor headerAccessor = null;
141133
byte[] payload = null;
142-
143134
if (buffer.remaining() > 0) {
144135
StompCommand stompCommand = StompCommand.valueOf(command);
145136
headerAccessor = StompHeaderAccessor.create(stompCommand);
146137
initHeaders(headerAccessor);
147-
148138
readHeaders(buffer, headerAccessor);
149139
payload = readPayload(buffer, headerAccessor);
150140
}
151-
152141
if (payload != null) {
153-
if ((payload.length > 0) && (!headerAccessor.getCommand().isBodyAllowed())) {
142+
if (payload.length > 0 && !headerAccessor.getCommand().isBodyAllowed()) {
154143
throw new StompConversionException(headerAccessor.getCommand() +
155144
" shouldn't have a payload: length=" + payload.length + ", headers=" + headers);
156145
}
@@ -185,12 +174,14 @@ private Message<byte[]> decodeMessage(ByteBuffer buffer, MultiValueMap<String, S
185174
logger.trace("Decoded " + headerAccessor.getDetailedLogMessage(null));
186175
}
187176
}
177+
188178
return decodedMessage;
189179
}
190180

191181
private void initHeaders(StompHeaderAccessor headerAccessor) {
192-
if (getHeaderInitializer() != null) {
193-
getHeaderInitializer().initHeaders(headerAccessor);
182+
MessageHeaderInitializer initializer = getHeaderInitializer();
183+
if (initializer != null) {
184+
initializer.initHeaders(headerAccessor);
194185
}
195186
}
196187

@@ -253,14 +244,13 @@ private void readHeaders(ByteBuffer buffer, StompHeaderAccessor headerAccessor)
253244
* <a href="http://stomp.github.io/stomp-specification-1.2.html#Value_Encoding">"Value Encoding"</a>.
254245
*/
255246
private String unescape(String inString) {
256-
257-
StringBuilder sb = new StringBuilder();
258-
int pos = 0; // position in the old string
247+
StringBuilder sb = new StringBuilder(inString.length());
248+
int pos = 0; // position in the old string
259249
int index = inString.indexOf("\\");
260250

261251
while (index >= 0) {
262252
sb.append(inString.substring(pos, index));
263-
if((index + 1) >= inString.length()) {
253+
if (index + 1 >= inString.length()) {
264254
throw new StompConversionException("Illegal escape sequence at index " + index + ": " + inString);
265255
}
266256
Character c = inString.charAt(index + 1);
@@ -289,7 +279,6 @@ else if (c == '\\') {
289279
}
290280

291281
private byte[] readPayload(ByteBuffer buffer, StompHeaderAccessor headerAccessor) {
292-
293282
Integer contentLength;
294283
try {
295284
contentLength = headerAccessor.getContentLength();
@@ -329,7 +318,6 @@ private byte[] readPayload(ByteBuffer buffer, StompHeaderAccessor headerAccessor
329318

330319
/**
331320
* Try to read an EOL incrementing the buffer position if successful.
332-
*
333321
* @return whether an EOL was consumed
334322
*/
335323
private boolean tryConsumeEndOfLine(ByteBuffer buffer) {

spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompEncoder.java

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,6 @@ public final class StompEncoder {
5151

5252
/**
5353
* Encodes the given STOMP {@code message} into a {@code byte[]}
54-
*
5554
* @param message the message to encode
5655
* @return the encoded message
5756
*/
@@ -61,14 +60,14 @@ public byte[] encode(Message<byte[]> message) {
6160

6261
/**
6362
* Encodes the given payload and headers into a {@code byte[]}.
64-
*
6563
* @param headers the headers
6664
* @param payload the payload
6765
* @return the encoded message
6866
*/
6967
public byte[] encode(Map<String, Object> headers, byte[] payload) {
7068
Assert.notNull(headers, "'headers' is required");
7169
Assert.notNull(payload, "'payload' is required");
70+
7271
try {
7372
ByteArrayOutputStream baos = new ByteArrayOutputStream(128 + payload.length);
7473
DataOutputStream output = new DataOutputStream(baos);
@@ -89,8 +88,8 @@ public byte[] encode(Map<String, Object> headers, byte[] payload) {
8988

9089
return baos.toByteArray();
9190
}
92-
catch (IOException e) {
93-
throw new StompConversionException("Failed to encode STOMP frame, headers=" + headers + ".", e);
91+
catch (IOException ex) {
92+
throw new StompConversionException("Failed to encode STOMP frame, headers=" + headers, ex);
9493
}
9594
}
9695

@@ -102,7 +101,7 @@ private void writeHeaders(StompCommand command, Map<String, Object> headers, byt
102101
(Map<String, List<String>>) headers.get(NativeMessageHeaderAccessor.NATIVE_HEADERS);
103102

104103
if (logger.isTraceEnabled()) {
105-
logger.trace("Encoding STOMP " + command + ", headers=" + nativeHeaders + ".");
104+
logger.trace("Encoding STOMP " + command + ", headers=" + nativeHeaders);
106105
}
107106

108107
if (nativeHeaders == null) {
@@ -137,8 +136,8 @@ private void writeHeaders(StompCommand command, Map<String, Object> headers, byt
137136
}
138137

139138
private byte[] encodeHeaderString(String input, boolean escape) {
140-
input = escape ? escape(input) : input;
141-
return input.getBytes(StompDecoder.UTF8_CHARSET);
139+
String inputToUse = (escape ? escape(input) : input);
140+
return inputToUse.getBytes(StompDecoder.UTF8_CHARSET);
142141
}
143142

144143
/**

spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,14 +86,16 @@
8686
*/
8787
public class FormHttpMessageConverter implements HttpMessageConverter<MultiValueMap<String, ?>> {
8888

89+
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
90+
8991
private static final byte[] BOUNDARY_CHARS =
9092
new byte[] {'-', '_', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
9193
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A',
9294
'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
9395
'V', 'W', 'X', 'Y', 'Z'};
9496

9597

96-
private Charset charset = Charset.forName("UTF-8");
98+
private Charset charset = DEFAULT_CHARSET;
9799

98100
private Charset multipartCharset;
99101

spring-web/src/main/java/org/springframework/http/converter/StringHttpMessageConverter.java

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2013 the original author or authors.
2+
* Copyright 2002-2014 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -41,6 +41,7 @@ public class StringHttpMessageConverter extends AbstractHttpMessageConverter<Str
4141

4242
public static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1");
4343

44+
4445
private final Charset defaultCharset;
4546

4647
private final List<Charset> availableCharsets;
@@ -66,6 +67,7 @@ public StringHttpMessageConverter(Charset defaultCharset) {
6667
this.availableCharsets = new ArrayList<Charset>(Charset.availableCharsets().values());
6768
}
6869

70+
6971
/**
7072
* Indicates whether the {@code Accept-Charset} should be written to any outgoing request.
7173
* <p>Default is {@code true}.
@@ -74,6 +76,7 @@ public void setWriteAcceptCharset(boolean writeAcceptCharset) {
7476
this.writeAcceptCharset = writeAcceptCharset;
7577
}
7678

79+
7780
@Override
7881
public boolean supports(Class<?> clazz) {
7982
return String.class.equals(clazz);
@@ -86,10 +89,10 @@ protected String readInternal(Class<? extends String> clazz, HttpInputMessage in
8689
}
8790

8891
@Override
89-
protected Long getContentLength(String s, MediaType contentType) {
92+
protected Long getContentLength(String str, MediaType contentType) {
9093
Charset charset = getContentTypeCharset(contentType);
9194
try {
92-
return (long) s.getBytes(charset.name()).length;
95+
return (long) str.getBytes(charset.name()).length;
9396
}
9497
catch (UnsupportedEncodingException ex) {
9598
// should not occur
@@ -98,17 +101,19 @@ protected Long getContentLength(String s, MediaType contentType) {
98101
}
99102

100103
@Override
101-
protected void writeInternal(String s, HttpOutputMessage outputMessage) throws IOException {
104+
protected void writeInternal(String str, HttpOutputMessage outputMessage) throws IOException {
102105
if (this.writeAcceptCharset) {
103106
outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
104107
}
105108
Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType());
106-
StreamUtils.copy(s, charset, outputMessage.getBody());
109+
StreamUtils.copy(str, charset, outputMessage.getBody());
107110
}
108111

112+
109113
/**
110-
* Return the list of supported {@link Charset}.
111-
* <p>By default, returns {@link Charset#availableCharsets()}. Can be overridden in subclasses.
114+
* Return the list of supported {@link Charset}s.
115+
* <p>By default, returns {@link Charset#availableCharsets()}.
116+
* Can be overridden in subclasses.
112117
* @return the list of accepted charsets
113118
*/
114119
protected List<Charset> getAcceptedCharsets() {
@@ -123,4 +128,5 @@ private Charset getContentTypeCharset(MediaType contentType) {
123128
return this.defaultCharset;
124129
}
125130
}
131+
126132
}

spring-websocket/src/main/java/org/springframework/web/socket/TextMessage.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
*/
2727
public final class TextMessage extends AbstractWebSocketMessage<String> {
2828

29-
private static final Charset UTF_8 = Charset.forName("UTF-8");
29+
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
3030

3131
private final byte[] bytes;
3232

@@ -46,7 +46,7 @@ public TextMessage(CharSequence payload) {
4646
* @param payload the non-null payload
4747
*/
4848
public TextMessage(byte[] payload) {
49-
super(new String(payload, UTF_8));
49+
super(new String(payload, UTF8_CHARSET));
5050
this.bytes = payload;
5151
}
5252

@@ -70,7 +70,7 @@ public int getPayloadLength() {
7070
}
7171

7272
public byte[] asBytes() {
73-
return (this.bytes != null ? this.bytes : getPayload().getBytes(UTF_8));
73+
return (this.bytes != null ? this.bytes : getPayload().getBytes(UTF8_CHARSET));
7474
}
7575

7676
@Override

spring-websocket/src/main/java/org/springframework/web/socket/server/support/DefaultHandshakeHandler.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package org.springframework.web.socket.server.support;
1818

1919
import java.io.IOException;
20+
import java.nio.charset.Charset;
2021
import java.security.Principal;
2122
import java.util.ArrayList;
2223
import java.util.Arrays;
@@ -60,6 +61,9 @@
6061
*/
6162
public class DefaultHandshakeHandler implements HandshakeHandler {
6263

64+
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
65+
66+
6367
private static final boolean jettyWsPresent = ClassUtils.isPresent(
6468
"org.eclipse.jetty.websocket.server.WebSocketServerFactory", DefaultHandshakeHandler.class.getClassLoader());
6569

@@ -223,15 +227,15 @@ protected void handleInvalidUpgradeHeader(ServerHttpRequest request, ServerHttpR
223227
logger.error("Handshake failed due to invalid Upgrade header: " + request.getHeaders().getUpgrade());
224228
}
225229
response.setStatusCode(HttpStatus.BAD_REQUEST);
226-
response.getBody().write("Can \"Upgrade\" only to \"WebSocket\".".getBytes("UTF-8"));
230+
response.getBody().write("Can \"Upgrade\" only to \"WebSocket\".".getBytes(UTF8_CHARSET));
227231
}
228232

229233
protected void handleInvalidConnectHeader(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
230234
if (logger.isErrorEnabled()) {
231235
logger.error("Handshake failed due to invalid Connection header " + request.getHeaders().getConnection());
232236
}
233237
response.setStatusCode(HttpStatus.BAD_REQUEST);
234-
response.getBody().write("\"Connection\" must be \"upgrade\".".getBytes("UTF-8"));
238+
response.getBody().write("\"Connection\" must be \"upgrade\".".getBytes(UTF8_CHARSET));
235239
}
236240

237241
protected boolean isWebSocketVersionSupported(WebSocketHttpHeaders httpHeaders) {

spring-websocket/src/main/java/org/springframework/web/socket/sockjs/support/AbstractSockJsService.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -337,8 +337,8 @@ public final void handleRequest(ServerHttpRequest request, ServerHttpResponse re
337337
try {
338338
if (sockJsPath.equals("") || sockJsPath.equals("/")) {
339339
logger.debug(requestInfo);
340-
response.getHeaders().setContentType(new MediaType("text", "plain", Charset.forName("UTF-8")));
341-
response.getBody().write("Welcome to SockJS!\n".getBytes("UTF-8"));
340+
response.getHeaders().setContentType(new MediaType("text", "plain", UTF8_CHARSET));
341+
response.getBody().write("Welcome to SockJS!\n".getBytes(UTF8_CHARSET));
342342
}
343343
else if (sockJsPath.equals("/info")) {
344344
logger.debug(requestInfo);

spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/AbstractHttpReceivingTransportHandler.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ protected void handleRequestInternal(ServerHttpRequest request, ServerHttpRespon
8787
private void handleReadError(ServerHttpResponse response, String error, String sessionId) {
8888
try {
8989
response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
90-
response.getBody().write(error.getBytes("UTF-8"));
90+
response.getBody().write(error.getBytes(UTF8_CHARSET));
9191
}
9292
catch (IOException ex) {
9393
throw new SockJsException("Failed to send error: " + error, sessionId, ex);

0 commit comments

Comments
 (0)