Revise encoding steps towards use of JDK Charset and StandardCharsets

Issue: SPR-14492
This commit is contained in:
Juergen Hoeller 2016-07-19 23:43:05 +02:00
parent 79d30d8c8a
commit 99be15f58b
95 changed files with 480 additions and 569 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -19,6 +19,7 @@ package org.springframework.beans.propertyeditors;
import java.beans.PropertyEditorSupport; import java.beans.PropertyEditorSupport;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import java.util.Properties; import java.util.Properties;
@ -49,7 +50,7 @@ public class PropertiesEditor extends PropertyEditorSupport {
if (text != null) { if (text != null) {
try { try {
// Must use the ISO-8859-1 encoding because Properties.load(stream) expects it. // Must use the ISO-8859-1 encoding because Properties.load(stream) expects it.
props.load(new ByteArrayInputStream(text.getBytes("ISO-8859-1"))); props.load(new ByteArrayInputStream(text.getBytes(StandardCharsets.ISO_8859_1)));
} }
catch (IOException ex) { catch (IOException ex) {
// Should never happen. // Should never happen.

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,6 +17,7 @@
package org.springframework.core.convert.support; package org.springframework.core.convert.support;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Properties; import java.util.Properties;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
@ -35,7 +36,7 @@ final class StringToPropertiesConverter implements Converter<String, Properties>
try { try {
Properties props = new Properties(); Properties props = new Properties();
// Must use the ISO-8859-1 encoding because Properties.load(stream) expects it. // Must use the ISO-8859-1 encoding because Properties.load(stream) expects it.
props.load(new ByteArrayInputStream(source.getBytes("ISO-8859-1"))); props.load(new ByteArrayInputStream(source.getBytes(StandardCharsets.ISO_8859_1)));
return props; return props;
} }
catch (Exception ex) { catch (Exception ex) {

View File

@ -17,6 +17,7 @@
package org.springframework.util; package org.springframework.util;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64; import java.util.Base64;
/** /**
@ -31,7 +32,7 @@ import java.util.Base64;
*/ */
public abstract class Base64Utils { public abstract class Base64Utils {
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
/** /**

View File

@ -21,6 +21,7 @@ import java.lang.reflect.Method;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.ZoneId; import java.time.ZoneId;
import java.util.AbstractList; import java.util.AbstractList;
import java.util.ArrayList; import java.util.ArrayList;
@ -277,12 +278,12 @@ public class DefaultConversionServiceTests {
@Test @Test
public void testStringToCharset() { public void testStringToCharset() {
assertEquals(Charset.forName("UTF-8"), conversionService.convert("UTF-8", Charset.class)); assertEquals(StandardCharsets.UTF_8, conversionService.convert("UTF-8", Charset.class));
} }
@Test @Test
public void testCharsetToString() { public void testCharsetToString() {
assertEquals("UTF-8", conversionService.convert(Charset.forName("UTF-8"), String.class)); assertEquals("UTF-8", conversionService.convert(StandardCharsets.UTF_8, String.class));
} }
@Test @Test

View File

@ -17,6 +17,7 @@
package org.springframework.util; package org.springframework.util;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -27,7 +28,7 @@ import org.junit.Test;
import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.convert.support.DefaultConversionService;
import static java.util.Collections.singletonMap; import static java.util.Collections.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
/** /**
@ -84,7 +85,7 @@ public class MimeTypeTests {
MimeType mimeType = MimeType.valueOf(s); MimeType mimeType = MimeType.valueOf(s);
assertEquals("Invalid type", "application", mimeType.getType()); assertEquals("Invalid type", "application", mimeType.getType());
assertEquals("Invalid subtype", "xml", mimeType.getSubtype()); assertEquals("Invalid subtype", "xml", mimeType.getSubtype());
assertEquals("Invalid charset", Charset.forName("UTF-8"), mimeType.getCharset()); assertEquals("Invalid charset", StandardCharsets.UTF_8, mimeType.getCharset());
} }
@Test @Test

View File

@ -19,7 +19,7 @@ package org.springframework.expression.spel;
import java.lang.reflect.Array; import java.lang.reflect.Array;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
@ -2091,7 +2091,7 @@ public class SpelReproTests extends AbstractExpressionTests {
Expression ex = parser.parseExpression("T(java.nio.charset.Charset).forName(#encoding)"); Expression ex = parser.parseExpression("T(java.nio.charset.Charset).forName(#encoding)");
Object result = ex.getValue(context); Object result = ex.getValue(context);
assertEquals(Charset.forName("UTF-8"), result); assertEquals(StandardCharsets.UTF_8, result);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -25,6 +25,7 @@ import java.io.Reader;
import java.io.StringReader; import java.io.StringReader;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.io.Writer; import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.sql.Clob; import java.sql.Clob;
import java.sql.SQLException; import java.sql.SQLException;
@ -91,11 +92,11 @@ class PassThroughClob implements Clob {
public InputStream getAsciiStream() throws SQLException { public InputStream getAsciiStream() throws SQLException {
try { try {
if (this.content != null) { if (this.content != null) {
return new ByteArrayInputStream(this.content.getBytes("US-ASCII")); return new ByteArrayInputStream(this.content.getBytes(StandardCharsets.US_ASCII));
} }
else if (this.characterStream != null) { else if (this.characterStream != null) {
String tempContent = FileCopyUtils.copyToString(this.characterStream); String tempContent = FileCopyUtils.copyToString(this.characterStream);
return new ByteArrayInputStream(tempContent.getBytes("US-ASCII")); return new ByteArrayInputStream(tempContent.getBytes(StandardCharsets.US_ASCII));
} }
else { else {
return this.asciiStream; return this.asciiStream;

View File

@ -22,6 +22,7 @@ import java.io.StringWriter;
import java.io.Writer; import java.io.Writer;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@ -70,7 +71,7 @@ public class MappingJackson2MessageConverter extends AbstractMessageConverter {
* the {@code application/json} MIME type with {@code UTF-8} character set. * the {@code application/json} MIME type with {@code UTF-8} character set.
*/ */
public MappingJackson2MessageConverter() { public MappingJackson2MessageConverter() {
super(new MimeType("application", "json", Charset.forName("UTF-8"))); super(new MimeType("application", "json", StandardCharsets.UTF_8));
initObjectMapper(); initObjectMapper();
} }

View File

@ -17,6 +17,7 @@
package org.springframework.messaging.converter; package org.springframework.messaging.converter;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.springframework.messaging.Message; import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.MessageHeaders;
@ -35,7 +36,7 @@ public class StringMessageConverter extends AbstractMessageConverter {
public StringMessageConverter() { public StringMessageConverter() {
this(Charset.forName("UTF-8")); this(StandardCharsets.UTF_8);
} }
public StringMessageConverter(Charset defaultCharset) { public StringMessageConverter(Charset defaultCharset) {

View File

@ -19,6 +19,7 @@ package org.springframework.messaging.simp.stomp;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -47,13 +48,10 @@ import org.springframework.util.MultiValueMap;
*/ */
public class StompDecoder { public class StompDecoder {
static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
static final byte[] HEARTBEAT_PAYLOAD = new byte[] {'\n'}; static final byte[] HEARTBEAT_PAYLOAD = new byte[] {'\n'};
private static final Log logger = LogFactory.getLog(StompDecoder.class); private static final Log logger = LogFactory.getLog(StompDecoder.class);
private MessageHeaderInitializer headerInitializer; private MessageHeaderInitializer headerInitializer;
@ -202,7 +200,7 @@ public class StompDecoder {
while (buffer.remaining() > 0 && !tryConsumeEndOfLine(buffer)) { while (buffer.remaining() > 0 && !tryConsumeEndOfLine(buffer)) {
command.write(buffer.get()); command.write(buffer.get());
} }
return new String(command.toByteArray(), UTF8_CHARSET); return new String(command.toByteArray(), StandardCharsets.UTF_8);
} }
private void readHeaders(ByteBuffer buffer, StompHeaderAccessor headerAccessor) { private void readHeaders(ByteBuffer buffer, StompHeaderAccessor headerAccessor) {
@ -217,7 +215,7 @@ public class StompDecoder {
headerStream.write(buffer.get()); headerStream.write(buffer.get());
} }
if (headerStream.size() > 0 && headerComplete) { if (headerStream.size() > 0 && headerComplete) {
String header = new String(headerStream.toByteArray(), UTF8_CHARSET); String header = new String(headerStream.toByteArray(), StandardCharsets.UTF_8);
int colonIndex = header.indexOf(':'); int colonIndex = header.indexOf(':');
if (colonIndex <= 0) { if (colonIndex <= 0) {
if (buffer.remaining() > 0) { if (buffer.remaining() > 0) {

View File

@ -19,6 +19,7 @@ package org.springframework.messaging.simp.stomp;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -81,7 +82,7 @@ public final class StompEncoder {
else { else {
StompCommand command = StompHeaderAccessor.getCommand(headers); StompCommand command = StompHeaderAccessor.getCommand(headers);
Assert.notNull(command, "Missing STOMP command: " + headers); Assert.notNull(command, "Missing STOMP command: " + headers);
output.write(command.toString().getBytes(StompDecoder.UTF8_CHARSET)); output.write(command.toString().getBytes(StandardCharsets.UTF_8));
output.write(LF); output.write(LF);
writeHeaders(command, headers, payload, output); writeHeaders(command, headers, payload, output);
output.write(LF); output.write(LF);
@ -132,15 +133,15 @@ public final class StompEncoder {
} }
if (command.requiresContentLength()) { if (command.requiresContentLength()) {
int contentLength = payload.length; int contentLength = payload.length;
output.write("content-length:".getBytes(StompDecoder.UTF8_CHARSET)); output.write("content-length:".getBytes(StandardCharsets.UTF_8));
output.write(Integer.toString(contentLength).getBytes(StompDecoder.UTF8_CHARSET)); output.write(Integer.toString(contentLength).getBytes(StandardCharsets.UTF_8));
output.write(LF); output.write(LF);
} }
} }
private byte[] encodeHeaderString(String input, boolean escape) { private byte[] encodeHeaderString(String input, boolean escape) {
String inputToUse = (escape ? escape(input) : input); String inputToUse = (escape ? escape(input) : input);
return inputToUse.getBytes(StompDecoder.UTF8_CHARSET); return inputToUse.getBytes(StandardCharsets.UTF_8);
} }
/** /**

View File

@ -17,6 +17,7 @@
package org.springframework.messaging.simp.stomp; package org.springframework.messaging.simp.stomp;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -441,7 +442,7 @@ public class StompHeaderAccessor extends SimpMessageHeaderAccessor {
return contentType; return contentType;
} }
Charset charset = getContentType().getCharset(); Charset charset = getContentType().getCharset();
charset = (charset != null ? charset : StompDecoder.UTF8_CHARSET); charset = (charset != null ? charset : StandardCharsets.UTF_8);
return (bytes.length < 80) ? return (bytes.length < 80) ?
contentType + " payload=" + new String(bytes, charset) : contentType + " payload=" + new String(bytes, charset) :
contentType + " payload=" + new String(Arrays.copyOf(bytes, 80), charset) + "...(truncated)"; contentType + " payload=" + new String(Arrays.copyOf(bytes, 80), charset) + "...(truncated)";

View File

@ -17,6 +17,7 @@
package org.springframework.messaging.support; package org.springframework.messaging.support;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
@ -115,7 +116,7 @@ import org.springframework.util.StringUtils;
*/ */
public class MessageHeaderAccessor { public class MessageHeaderAccessor {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private static final MimeType[] READABLE_MIME_TYPES = new MimeType[] { private static final MimeType[] READABLE_MIME_TYPES = new MimeType[] {
MimeTypeUtils.APPLICATION_JSON, MimeTypeUtils.APPLICATION_XML, MimeTypeUtils.APPLICATION_JSON, MimeTypeUtils.APPLICATION_XML,

View File

@ -19,6 +19,7 @@ package org.springframework.messaging.converter;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -44,19 +45,16 @@ import static org.junit.Assert.*;
*/ */
public class MappingJackson2MessageConverterTests { public class MappingJackson2MessageConverterTests {
private static Charset UTF_8 = Charset.forName("UTF-8");
@Test @Test
public void defaultConstructor() { public void defaultConstructor() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
assertThat(converter.getSupportedMimeTypes(), contains(new MimeType("application", "json", UTF_8))); assertThat(converter.getSupportedMimeTypes(), contains(new MimeType("application", "json", StandardCharsets.UTF_8)));
assertFalse(converter.getObjectMapper().getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); assertFalse(converter.getObjectMapper().getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
} }
@Test // SPR-12724 @Test // SPR-12724
public void mimetypeParametrizedConstructor() { public void mimetypeParametrizedConstructor() {
MimeType mimetype = new MimeType("application", "xml", UTF_8); MimeType mimetype = new MimeType("application", "xml", StandardCharsets.UTF_8);
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(mimetype); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(mimetype);
assertThat(converter.getSupportedMimeTypes(), contains(mimetype)); assertThat(converter.getSupportedMimeTypes(), contains(mimetype));
assertFalse(converter.getObjectMapper().getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); assertFalse(converter.getObjectMapper().getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
@ -64,8 +62,8 @@ public class MappingJackson2MessageConverterTests {
@Test // SPR-12724 @Test // SPR-12724
public void mimetypesParametrizedConstructor() { public void mimetypesParametrizedConstructor() {
MimeType jsonMimetype = new MimeType("application", "json", UTF_8); MimeType jsonMimetype = new MimeType("application", "json", StandardCharsets.UTF_8);
MimeType xmlMimetype = new MimeType("application", "xml", UTF_8); MimeType xmlMimetype = new MimeType("application", "xml", StandardCharsets.UTF_8);
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(jsonMimetype, xmlMimetype); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(jsonMimetype, xmlMimetype);
assertThat(converter.getSupportedMimeTypes(), contains(jsonMimetype, xmlMimetype)); assertThat(converter.getSupportedMimeTypes(), contains(jsonMimetype, xmlMimetype));
assertFalse(converter.getObjectMapper().getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)); assertFalse(converter.getObjectMapper().getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
@ -75,7 +73,7 @@ public class MappingJackson2MessageConverterTests {
public void fromMessage() throws Exception { public void fromMessage() throws Exception {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
String payload = "{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}"; String payload = "{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}";
Message<?> message = MessageBuilder.withPayload(payload.getBytes(UTF_8)).build(); Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build();
MyBean actual = (MyBean) converter.fromMessage(message, MyBean.class); MyBean actual = (MyBean) converter.fromMessage(message, MyBean.class);
assertEquals("Foo", actual.getString()); assertEquals("Foo", actual.getString());
@ -91,7 +89,7 @@ public class MappingJackson2MessageConverterTests {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
String payload = "{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"]," String payload = "{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],"
+ "\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}"; + "\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}";
Message<?> message = MessageBuilder.withPayload(payload.getBytes(UTF_8)).build(); Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
HashMap<String, Object> actual = (HashMap<String, Object>) converter.fromMessage(message, HashMap.class); HashMap<String, Object> actual = (HashMap<String, Object>) converter.fromMessage(message, HashMap.class);
@ -107,7 +105,7 @@ public class MappingJackson2MessageConverterTests {
public void fromMessageInvalidJson() throws Exception { public void fromMessageInvalidJson() throws Exception {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
String payload = "FooBar"; String payload = "FooBar";
Message<?> message = MessageBuilder.withPayload(payload.getBytes(UTF_8)).build(); Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build();
converter.fromMessage(message, MyBean.class); converter.fromMessage(message, MyBean.class);
} }
@ -115,7 +113,7 @@ public class MappingJackson2MessageConverterTests {
public void fromMessageValidJsonWithUnknownProperty() throws IOException { public void fromMessageValidJsonWithUnknownProperty() throws IOException {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
String payload = "{\"string\":\"string\",\"unknownProperty\":\"value\"}"; String payload = "{\"string\":\"string\",\"unknownProperty\":\"value\"}";
Message<?> message = MessageBuilder.withPayload(payload.getBytes(UTF_8)).build(); Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build();
MyBean myBean = (MyBean)converter.fromMessage(message, MyBean.class); MyBean myBean = (MyBean)converter.fromMessage(message, MyBean.class);
assertEquals("string", myBean.getString()); assertEquals("string", myBean.getString());
} }
@ -132,7 +130,7 @@ public class MappingJackson2MessageConverterTests {
payload.setBytes(new byte[]{0x1, 0x2}); payload.setBytes(new byte[]{0x1, 0x2});
Message<?> message = converter.toMessage(payload, null); Message<?> message = converter.toMessage(payload, null);
String actual = new String((byte[]) message.getPayload(), UTF_8); String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
assertTrue(actual.contains("\"string\":\"Foo\"")); assertTrue(actual.contains("\"string\":\"Foo\""));
assertTrue(actual.contains("\"number\":42")); assertTrue(actual.contains("\"number\":42"));
@ -140,7 +138,7 @@ public class MappingJackson2MessageConverterTests {
assertTrue(actual.contains("\"array\":[\"Foo\",\"Bar\"]")); assertTrue(actual.contains("\"array\":[\"Foo\",\"Bar\"]"));
assertTrue(actual.contains("\"bool\":true")); assertTrue(actual.contains("\"bool\":true"));
assertTrue(actual.contains("\"bytes\":\"AQI=\"")); assertTrue(actual.contains("\"bytes\":\"AQI=\""));
assertEquals("Invalid content-type", new MimeType("application", "json", UTF_8), assertEquals("Invalid content-type", new MimeType("application", "json", StandardCharsets.UTF_8),
message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class)); message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class));
} }
@ -184,7 +182,7 @@ public class MappingJackson2MessageConverterTests {
Method method = getClass().getDeclaredMethod("jsonViewResponse"); Method method = getClass().getDeclaredMethod("jsonViewResponse");
MethodParameter returnType = new MethodParameter(method, -1); MethodParameter returnType = new MethodParameter(method, -1);
Message<?> message = converter.toMessage(jsonViewResponse(), new MessageHeaders(map), returnType); Message<?> message = converter.toMessage(jsonViewResponse(), new MessageHeaders(map), returnType);
String actual = new String((byte[]) message.getPayload(), UTF_8); String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
assertThat(actual, containsString("\"withView1\":\"with\"")); assertThat(actual, containsString("\"withView1\":\"with\""));
assertThat(actual, containsString("\"withView2\":\"with\"")); assertThat(actual, containsString("\"withView2\":\"with\""));

View File

@ -17,7 +17,7 @@
package org.springframework.messaging.converter; package org.springframework.messaging.converter;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import org.junit.Before; import org.junit.Before;
@ -27,17 +27,15 @@ import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder; import org.springframework.messaging.support.MessageBuilder;
import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import static org.custommonkey.xmlunit.XMLAssert.assertXMLEqual; import static org.custommonkey.xmlunit.XMLAssert.*;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/** /**
* @author Arjen Poutsma * @author Arjen Poutsma
*/ */
public class MarshallingMessageConverterTests { public class MarshallingMessageConverterTests {
private static Charset UTF_8 = Charset.forName("UTF-8");
private MarshallingMessageConverter converter; private MarshallingMessageConverter converter;
@ -50,10 +48,11 @@ public class MarshallingMessageConverterTests {
this.converter = new MarshallingMessageConverter(marshaller); this.converter = new MarshallingMessageConverter(marshaller);
} }
@Test @Test
public void fromMessage() throws Exception { public void fromMessage() throws Exception {
String payload = "<myBean><name>Foo</name></myBean>"; String payload = "<myBean><name>Foo</name></myBean>";
Message<?> message = MessageBuilder.withPayload(payload.getBytes(UTF_8)).build(); Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build();
MyBean actual = (MyBean) this.converter.fromMessage(message, MyBean.class); MyBean actual = (MyBean) this.converter.fromMessage(message, MyBean.class);
assertNotNull(actual); assertNotNull(actual);
@ -63,14 +62,14 @@ public class MarshallingMessageConverterTests {
@Test(expected = MessageConversionException.class) @Test(expected = MessageConversionException.class)
public void fromMessageInvalidXml() throws Exception { public void fromMessageInvalidXml() throws Exception {
String payload = "<myBean><name>Foo</name><myBean>"; String payload = "<myBean><name>Foo</name><myBean>";
Message<?> message = MessageBuilder.withPayload(payload.getBytes(UTF_8)).build(); Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build();
this.converter.fromMessage(message, MyBean.class); this.converter.fromMessage(message, MyBean.class);
} }
@Test(expected = MessageConversionException.class) @Test(expected = MessageConversionException.class)
public void fromMessageValidXmlWithUnknownProperty() throws IOException { public void fromMessageValidXmlWithUnknownProperty() throws IOException {
String payload = "<myBean><age>42</age><myBean>"; String payload = "<myBean><age>42</age><myBean>";
Message<?> message = MessageBuilder.withPayload(payload.getBytes(UTF_8)).build(); Message<?> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build();
this.converter.fromMessage(message, MyBean.class); this.converter.fromMessage(message, MyBean.class);
} }
@ -81,7 +80,7 @@ public class MarshallingMessageConverterTests {
Message<?> message = this.converter.toMessage(payload, null); Message<?> message = this.converter.toMessage(payload, null);
assertNotNull(message); assertNotNull(message);
String actual = new String((byte[]) message.getPayload(), UTF_8); String actual = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
assertXMLEqual("<myBean><name>Foo</name></myBean>", actual); assertXMLEqual("<myBean><name>Foo</name></myBean>", actual);
} }

View File

@ -17,6 +17,7 @@
package org.springframework.messaging.converter; package org.springframework.messaging.converter;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -73,16 +74,13 @@ public class StringMessageConverterTests {
String payload = "H\u00e9llo W\u00f6rld"; String payload = "H\u00e9llo W\u00f6rld";
Message<byte[]> message = MessageBuilder.withPayload(payload.getBytes(iso88591)) Message<byte[]> message = MessageBuilder.withPayload(payload.getBytes(iso88591))
.setHeader(MessageHeaders.CONTENT_TYPE, new MimeType("text", "plain", iso88591)).build(); .setHeader(MessageHeaders.CONTENT_TYPE, new MimeType("text", "plain", iso88591)).build();
assertEquals(payload, this.converter.fromMessage(message, String.class)); assertEquals(payload, this.converter.fromMessage(message, String.class));
} }
@Test @Test
public void fromMessageDefaultCharset() { public void fromMessageDefaultCharset() {
Charset utf8 = Charset.forName("UTF-8");
String payload = "H\u00e9llo W\u00f6rld"; String payload = "H\u00e9llo W\u00f6rld";
Message<byte[]> message = MessageBuilder.withPayload(payload.getBytes(utf8)).build(); Message<byte[]> message = MessageBuilder.withPayload(payload.getBytes(StandardCharsets.UTF_8)).build();
assertEquals(payload, this.converter.fromMessage(message, String.class)); assertEquals(payload, this.converter.fromMessage(message, String.class));
} }

View File

@ -16,7 +16,7 @@
package org.springframework.messaging.core; package org.springframework.messaging.core;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -141,7 +141,7 @@ public class MessageSendingTemplateTests {
MessageHeaders actual = this.template.message.getHeaders(); MessageHeaders actual = this.template.message.getHeaders();
assertSame(messageHeaders, actual); assertSame(messageHeaders, actual);
assertEquals(new MimeType("text", "plain", Charset.forName("UTF-8")), actual.get(MessageHeaders.CONTENT_TYPE)); assertEquals(new MimeType("text", "plain", StandardCharsets.UTF_8), actual.get(MessageHeaders.CONTENT_TYPE));
assertEquals("bar", actual.get("foo")); assertEquals("bar", actual.get("foo"));
} }

View File

@ -68,7 +68,7 @@ import static org.springframework.messaging.support.MessageHeaderAccessor.*;
*/ */
public class SendToMethodReturnValueHandlerTests { public class SendToMethodReturnValueHandlerTests {
private static final MimeType MIME_TYPE = new MimeType("text", "plain", Charset.forName("UTF-8")); private static final MimeType MIME_TYPE = new MimeType("text", "plain", StandardCharsets.UTF_8);
private static final String PAYLOAD = "payload"; private static final String PAYLOAD = "payload";

View File

@ -57,7 +57,7 @@ import static org.mockito.BDDMockito.*;
*/ */
public class SubscriptionMethodReturnValueHandlerTests { public class SubscriptionMethodReturnValueHandlerTests {
public static final MimeType MIME_TYPE = new MimeType("text", "plain", Charset.forName("UTF-8")); public static final MimeType MIME_TYPE = new MimeType("text", "plain", StandardCharsets.UTF_8);
private static final String PAYLOAD = "payload"; private static final String PAYLOAD = "payload";

View File

@ -18,6 +18,7 @@ package org.springframework.messaging.simp.stomp;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -205,7 +206,7 @@ public class BufferingStompDecoderTests {
} }
private ByteBuffer toByteBuffer(String chunk) { private ByteBuffer toByteBuffer(String chunk) {
return ByteBuffer.wrap(chunk.getBytes(Charset.forName("UTF-8"))); return ByteBuffer.wrap(chunk.getBytes(StandardCharsets.UTF_8));
} }
} }

View File

@ -16,12 +16,7 @@
package org.springframework.messaging.simp.stomp; package org.springframework.messaging.simp.stomp;
import static org.hamcrest.Matchers.*; import java.nio.charset.StandardCharsets;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
import java.nio.charset.Charset;
import java.util.Date; import java.util.Date;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
@ -51,6 +46,14 @@ import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils; import org.springframework.util.MimeTypeUtils;
import org.springframework.util.concurrent.SettableListenableFuture; import org.springframework.util.concurrent.SettableListenableFuture;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.notNull;
import static org.mockito.Mockito.same;
/** /**
* Unit tests for {@link DefaultStompSession}. * Unit tests for {@link DefaultStompSession}.
* *
@ -58,9 +61,6 @@ import org.springframework.util.concurrent.SettableListenableFuture;
*/ */
public class DefaultStompSessionTests { public class DefaultStompSessionTests {
private static Charset UTF_8 = Charset.forName("UTF-8");
private DefaultStompSession session; private DefaultStompSession session;
@Mock @Mock
@ -80,7 +80,6 @@ public class DefaultStompSessionTests {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
this.sessionHandler = mock(StompSessionHandler.class); this.sessionHandler = mock(StompSessionHandler.class);
@ -96,7 +95,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void afterConnected() throws Exception { public void afterConnected() throws Exception {
assertFalse(this.session.isConnected()); assertFalse(this.session.isConnected());
this.connectHeaders.setHost("my-host"); this.connectHeaders.setHost("my-host");
this.connectHeaders.setHeartbeat(new long[] {11, 12}); this.connectHeaders.setHeartbeat(new long[] {11, 12});
@ -122,7 +120,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void handleConnectedFrame() throws Exception { public void handleConnectedFrame() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
assertTrue(this.session.isConnected()); assertTrue(this.session.isConnected());
@ -141,7 +138,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void heartbeatValues() throws Exception { public void heartbeatValues() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
assertTrue(this.session.isConnected()); assertTrue(this.session.isConnected());
@ -164,7 +160,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void heartbeatNotSupportedByServer() throws Exception { public void heartbeatNotSupportedByServer() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
verify(this.connection).send(any()); verify(this.connection).send(any());
@ -181,7 +176,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void heartbeatTasks() throws Exception { public void heartbeatTasks() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
verify(this.connection).send(any()); verify(this.connection).send(any());
@ -217,9 +211,8 @@ public class DefaultStompSessionTests {
@Test @Test
public void handleErrorFrame() throws Exception { public void handleErrorFrame() throws Exception {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR);
accessor.setContentType(new MimeType("text", "plain", UTF_8)); accessor.setContentType(new MimeType("text", "plain", StandardCharsets.UTF_8));
accessor.addNativeHeader("foo", "bar"); accessor.addNativeHeader("foo", "bar");
accessor.setLeaveMutable(true); accessor.setLeaveMutable(true);
String payload = "Oops"; String payload = "Oops";
@ -227,7 +220,7 @@ public class DefaultStompSessionTests {
StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
when(this.sessionHandler.getPayloadType(stompHeaders)).thenReturn(String.class); when(this.sessionHandler.getPayloadType(stompHeaders)).thenReturn(String.class);
this.session.handleMessage(MessageBuilder.createMessage(payload.getBytes(UTF_8), accessor.getMessageHeaders())); this.session.handleMessage(MessageBuilder.createMessage(payload.getBytes(StandardCharsets.UTF_8), accessor.getMessageHeaders()));
verify(this.sessionHandler).getPayloadType(stompHeaders); verify(this.sessionHandler).getPayloadType(stompHeaders);
verify(this.sessionHandler).handleFrame(stompHeaders, payload); verify(this.sessionHandler).handleFrame(stompHeaders, payload);
@ -236,7 +229,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void handleErrorFrameWithEmptyPayload() throws Exception { public void handleErrorFrameWithEmptyPayload() throws Exception {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR);
accessor.addNativeHeader("foo", "bar"); accessor.addNativeHeader("foo", "bar");
accessor.setLeaveMutable(true); accessor.setLeaveMutable(true);
@ -249,12 +241,11 @@ public class DefaultStompSessionTests {
@Test @Test
public void handleErrorFrameWithConversionException() throws Exception { public void handleErrorFrameWithConversionException() throws Exception {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.ERROR);
accessor.setContentType(MimeTypeUtils.APPLICATION_JSON); accessor.setContentType(MimeTypeUtils.APPLICATION_JSON);
accessor.addNativeHeader("foo", "bar"); accessor.addNativeHeader("foo", "bar");
accessor.setLeaveMutable(true); accessor.setLeaveMutable(true);
byte[] payload = "{'foo':'bar'}".getBytes(UTF_8); byte[] payload = "{'foo':'bar'}".getBytes(StandardCharsets.UTF_8);
StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
when(this.sessionHandler.getPayloadType(stompHeaders)).thenReturn(Map.class); when(this.sessionHandler.getPayloadType(stompHeaders)).thenReturn(Map.class);
@ -269,7 +260,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void handleMessageFrame() throws Exception { public void handleMessageFrame() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
StompFrameHandler frameHandler = mock(StompFrameHandler.class); StompFrameHandler frameHandler = mock(StompFrameHandler.class);
@ -287,7 +277,8 @@ public class DefaultStompSessionTests {
StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
when(frameHandler.getPayloadType(stompHeaders)).thenReturn(String.class); when(frameHandler.getPayloadType(stompHeaders)).thenReturn(String.class);
this.session.handleMessage(MessageBuilder.createMessage(payload.getBytes(UTF_8), accessor.getMessageHeaders())); this.session.handleMessage(MessageBuilder.createMessage(payload.getBytes(StandardCharsets.UTF_8),
accessor.getMessageHeaders()));
verify(frameHandler).getPayloadType(stompHeaders); verify(frameHandler).getPayloadType(stompHeaders);
verify(frameHandler).handleFrame(stompHeaders, payload); verify(frameHandler).handleFrame(stompHeaders, payload);
@ -296,7 +287,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void handleMessageFrameWithConversionException() throws Exception { public void handleMessageFrameWithConversionException() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
assertTrue(this.session.isConnected()); assertTrue(this.session.isConnected());
@ -310,7 +300,7 @@ public class DefaultStompSessionTests {
accessor.setContentType(MimeTypeUtils.APPLICATION_JSON); accessor.setContentType(MimeTypeUtils.APPLICATION_JSON);
accessor.setMessageId("1"); accessor.setMessageId("1");
accessor.setLeaveMutable(true); accessor.setLeaveMutable(true);
byte[] payload = "{'foo':'bar'}".getBytes(UTF_8); byte[] payload = "{'foo':'bar'}".getBytes(StandardCharsets.UTF_8);
StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders()); StompHeaders stompHeaders = StompHeaders.readOnlyStompHeaders(accessor.getNativeHeaders());
when(frameHandler.getPayloadType(stompHeaders)).thenReturn(Map.class); when(frameHandler.getPayloadType(stompHeaders)).thenReturn(Map.class);
@ -344,7 +334,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void send() throws Exception { public void send() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
assertTrue(this.session.isConnected()); assertTrue(this.session.isConnected());
@ -360,14 +349,13 @@ public class DefaultStompSessionTests {
assertEquals(stompHeaders.toString(), 2, stompHeaders.size()); assertEquals(stompHeaders.toString(), 2, stompHeaders.size());
assertEquals(destination, stompHeaders.getDestination()); assertEquals(destination, stompHeaders.getDestination());
assertEquals(new MimeType("text", "plain", UTF_8), stompHeaders.getContentType()); assertEquals(new MimeType("text", "plain", StandardCharsets.UTF_8), stompHeaders.getContentType());
assertEquals(-1, stompHeaders.getContentLength()); // StompEncoder isn't involved assertEquals(-1, stompHeaders.getContentLength()); // StompEncoder isn't involved
assertEquals(payload, new String(message.getPayload(), UTF_8)); assertEquals(payload, new String(message.getPayload(), StandardCharsets.UTF_8));
} }
@Test @Test
public void sendWithReceipt() throws Exception { public void sendWithReceipt() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
assertTrue(this.session.isConnected()); assertTrue(this.session.isConnected());
@ -391,7 +379,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void sendWithConversionException() throws Exception { public void sendWithConversionException() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
assertTrue(this.session.isConnected()); assertTrue(this.session.isConnected());
@ -407,7 +394,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void sendWithExecutionException() throws Exception { public void sendWithExecutionException() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
assertTrue(this.session.isConnected()); assertTrue(this.session.isConnected());
@ -419,14 +405,13 @@ public class DefaultStompSessionTests {
this.expected.expect(MessageDeliveryException.class); this.expected.expect(MessageDeliveryException.class);
this.expected.expectCause(Matchers.sameInstance(exception)); this.expected.expectCause(Matchers.sameInstance(exception));
this.session.send("/topic/foo", "sample payload".getBytes(UTF_8)); this.session.send("/topic/foo", "sample payload".getBytes(StandardCharsets.UTF_8));
verifyNoMoreInteractions(this.connection); verifyNoMoreInteractions(this.connection);
} }
@Test @Test
public void subscribe() throws Exception { public void subscribe() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
assertTrue(this.session.isConnected()); assertTrue(this.session.isConnected());
@ -446,7 +431,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void subscribeWithHeaders() throws Exception { public void subscribeWithHeaders() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
assertTrue(this.session.isConnected()); assertTrue(this.session.isConnected());
@ -473,7 +457,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void unsubscribe() throws Exception { public void unsubscribe() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
assertTrue(this.session.isConnected()); assertTrue(this.session.isConnected());
@ -493,7 +476,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void ack() throws Exception { public void ack() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
assertTrue(this.session.isConnected()); assertTrue(this.session.isConnected());
@ -511,7 +493,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void nack() throws Exception { public void nack() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
assertTrue(this.session.isConnected()); assertTrue(this.session.isConnected());
@ -529,7 +510,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void receiptReceived() throws Exception { public void receiptReceived() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
this.session.setTaskScheduler(mock(TaskScheduler.class)); this.session.setTaskScheduler(mock(TaskScheduler.class));
@ -554,7 +534,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void receiptReceivedBeforeTaskAdded() throws Exception { public void receiptReceivedBeforeTaskAdded() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
this.session.setTaskScheduler(mock(TaskScheduler.class)); this.session.setTaskScheduler(mock(TaskScheduler.class));
@ -579,7 +558,6 @@ public class DefaultStompSessionTests {
@Test @Test
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
public void receiptNotReceived() throws Exception { public void receiptNotReceived() throws Exception {
TaskScheduler taskScheduler = mock(TaskScheduler.class); TaskScheduler taskScheduler = mock(TaskScheduler.class);
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
@ -611,7 +589,6 @@ public class DefaultStompSessionTests {
@Test @Test
public void disconnect() throws Exception { public void disconnect() throws Exception {
this.session.afterConnected(this.connection); this.session.afterConnected(this.connection);
assertTrue(this.session.isConnected()); assertTrue(this.session.isConnected());

View File

@ -16,7 +16,7 @@
package org.springframework.messaging.simp.stomp; package org.springframework.messaging.simp.stomp;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -33,6 +33,7 @@ import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.TestName; import org.junit.rules.TestName;
import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisher;
import org.springframework.messaging.Message; import org.springframework.messaging.Message;
@ -48,9 +49,7 @@ import org.springframework.messaging.support.MessageBuilder;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.SocketUtils; import org.springframework.util.SocketUtils;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/** /**
* Integration tests for {@link StompBrokerRelayMessageHandler} running against ActiveMQ. * Integration tests for {@link StompBrokerRelayMessageHandler} running against ActiveMQ.
@ -64,8 +63,6 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
private static final Log logger = LogFactory.getLog(StompBrokerRelayMessageHandlerIntegrationTests.class); private static final Log logger = LogFactory.getLog(StompBrokerRelayMessageHandlerIntegrationTests.class);
private static final Charset UTF_8 = Charset.forName("UTF-8");
private StompBrokerRelayMessageHandler relay; private StompBrokerRelayMessageHandler relay;
private BrokerService activeMQBroker; private BrokerService activeMQBroker;
@ -142,9 +139,9 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
logger.debug("Broker stopped"); logger.debug("Broker stopped");
} }
@Test @Test
public void publishSubscribe() throws Exception { public void publishSubscribe() throws Exception {
logger.debug("Starting test publishSubscribe()"); logger.debug("Starting test publishSubscribe()");
String sess1 = "sess1"; String sess1 = "sess1";
@ -167,7 +164,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
this.responseHandler.expectMessages(send); this.responseHandler.expectMessages(send);
} }
@Test(expected=MessageDeliveryException.class) @Test(expected = MessageDeliveryException.class)
public void messageDeliveryExceptionIfSystemSessionForwardFails() throws Exception { public void messageDeliveryExceptionIfSystemSessionForwardFails() throws Exception {
logger.debug("Starting test messageDeliveryExceptionIfSystemSessionForwardFails()"); logger.debug("Starting test messageDeliveryExceptionIfSystemSessionForwardFails()");
@ -181,7 +178,6 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
@Test @Test
public void brokerBecomingUnvailableTriggersErrorFrame() throws Exception { public void brokerBecomingUnvailableTriggersErrorFrame() throws Exception {
logger.debug("Starting test brokerBecomingUnvailableTriggersErrorFrame()"); logger.debug("Starting test brokerBecomingUnvailableTriggersErrorFrame()");
String sess1 = "sess1"; String sess1 = "sess1";
@ -197,7 +193,6 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
@Test @Test
public void brokerAvailabilityEventWhenStopped() throws Exception { public void brokerAvailabilityEventWhenStopped() throws Exception {
logger.debug("Starting test brokerAvailabilityEventWhenStopped()"); logger.debug("Starting test brokerAvailabilityEventWhenStopped()");
stopActiveMqBrokerAndAwait(); stopActiveMqBrokerAndAwait();
@ -206,7 +201,6 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
@Test @Test
public void relayReconnectsIfBrokerComesBackUp() throws Exception { public void relayReconnectsIfBrokerComesBackUp() throws Exception {
logger.debug("Starting test relayReconnectsIfBrokerComesBackUp()"); logger.debug("Starting test relayReconnectsIfBrokerComesBackUp()");
String sess1 = "sess1"; String sess1 = "sess1";
@ -232,7 +226,6 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
@Test @Test
public void disconnectWithReceipt() throws Exception { public void disconnectWithReceipt() throws Exception {
logger.debug("Starting test disconnectWithReceipt()"); logger.debug("Starting test disconnectWithReceipt()");
MessageExchange connect = MessageExchangeBuilder.connect("sess1").build(); MessageExchange connect = MessageExchangeBuilder.connect("sess1").build();
@ -270,6 +263,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
} }
} }
private static class TestMessageHandler implements MessageHandler { private static class TestMessageHandler implements MessageHandler {
private final BlockingQueue<Message<?>> queue = new LinkedBlockingQueue<>(); private final BlockingQueue<Message<?>> queue = new LinkedBlockingQueue<>();
@ -283,17 +277,13 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
} }
public void expectMessages(MessageExchange... messageExchanges) throws InterruptedException { public void expectMessages(MessageExchange... messageExchanges) throws InterruptedException {
List<MessageExchange> expectedMessages = List<MessageExchange> expectedMessages =
new ArrayList<>(Arrays.<MessageExchange>asList(messageExchanges)); new ArrayList<>(Arrays.<MessageExchange>asList(messageExchanges));
while (expectedMessages.size() > 0) { while (expectedMessages.size() > 0) {
Message<?> message = this.queue.poll(10000, TimeUnit.MILLISECONDS); Message<?> message = this.queue.poll(10000, TimeUnit.MILLISECONDS);
assertNotNull("Timed out waiting for messages, expected [" + expectedMessages + "]", message); assertNotNull("Timed out waiting for messages, expected [" + expectedMessages + "]", message);
MessageExchange match = findMatch(expectedMessages, message); MessageExchange match = findMatch(expectedMessages, message);
assertNotNull("Unexpected message=" + message + ", expected [" + expectedMessages + "]", match); assertNotNull("Unexpected message=" + message + ", expected [" + expectedMessages + "]", match);
expectedMessages.remove(match); expectedMessages.remove(match);
} }
} }
@ -308,6 +298,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
} }
} }
/** /**
* Holds a message as well as expected and actual messages matched against expectations. * Holds a message as well as expected and actual messages matched against expectations.
*/ */
@ -343,6 +334,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
} }
} }
private static class MessageExchangeBuilder { private static class MessageExchangeBuilder {
private final Message<?> message; private final Message<?> message;
@ -351,8 +343,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
private final List<MessageMatcher> expected = new ArrayList<>(); private final List<MessageMatcher> expected = new ArrayList<>();
public MessageExchangeBuilder(Message<?> message) {
private MessageExchangeBuilder(Message<?> message) {
this.message = message; this.message = message;
this.headers = StompHeaderAccessor.wrap(message); this.headers = StompHeaderAccessor.wrap(message);
} }
@ -402,7 +393,8 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
public static MessageExchangeBuilder send(String destination, String payload) { public static MessageExchangeBuilder send(String destination, String payload) {
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE); SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headers.setDestination(destination); headers.setDestination(destination);
Message<?> message = MessageBuilder.createMessage(payload.getBytes(UTF_8), headers.getMessageHeaders()); Message<?> message = MessageBuilder.createMessage(payload.getBytes(StandardCharsets.UTF_8),
headers.getMessageHeaders());
return new MessageExchangeBuilder(message); return new MessageExchangeBuilder(message);
} }
@ -442,25 +434,24 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
} }
} }
private static interface MessageMatcher {
private interface MessageMatcher {
boolean match(Message<?> message); boolean match(Message<?> message);
} }
private static class StompFrameMessageMatcher implements MessageMatcher { private static class StompFrameMessageMatcher implements MessageMatcher {
private final StompCommand command; private final StompCommand command;
private final String sessionId; private final String sessionId;
public StompFrameMessageMatcher(StompCommand command, String sessionId) { public StompFrameMessageMatcher(StompCommand command, String sessionId) {
this.command = command; this.command = command;
this.sessionId = sessionId; this.sessionId = sessionId;
} }
@Override @Override
public final boolean match(Message<?> message) { public final boolean match(Message<?> message) {
StompHeaderAccessor headers = StompHeaderAccessor.wrap(message); StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
@ -480,6 +471,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
} }
} }
private static class StompReceiptFrameMessageMatcher extends StompFrameMessageMatcher { private static class StompReceiptFrameMessageMatcher extends StompFrameMessageMatcher {
private final String receiptId; private final String receiptId;
@ -500,6 +492,7 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
} }
} }
private static class StompMessageFrameMessageMatcher extends StompFrameMessageMatcher { private static class StompMessageFrameMessageMatcher extends StompFrameMessageMatcher {
private final String subscriptionId; private final String subscriptionId;
@ -508,7 +501,6 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
private final Object payload; private final Object payload;
public StompMessageFrameMessageMatcher(String sessionId, String subscriptionId, String destination, Object payload) { public StompMessageFrameMessageMatcher(String sessionId, String subscriptionId, String destination, Object payload) {
super(StompCommand.MESSAGE, sessionId); super(StompCommand.MESSAGE, sessionId);
this.subscriptionId = subscriptionId; this.subscriptionId = subscriptionId;
@ -536,18 +528,17 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
} }
protected String getPayloadAsText() { protected String getPayloadAsText() {
return (this.payload instanceof byte[]) return (this.payload instanceof byte[]) ?
? new String((byte[]) this.payload, UTF_8) : payload.toString(); new String((byte[]) this.payload, StandardCharsets.UTF_8) : this.payload.toString();
} }
} }
private static class StompConnectedFrameMessageMatcher extends StompFrameMessageMatcher { private static class StompConnectedFrameMessageMatcher extends StompFrameMessageMatcher {
public StompConnectedFrameMessageMatcher(String sessionId) { public StompConnectedFrameMessageMatcher(String sessionId) {
super(StompCommand.CONNECTED, sessionId); super(StompCommand.CONNECTED, sessionId);
} }
} }
} }

View File

@ -17,7 +17,7 @@
package org.springframework.messaging.simp.stomp; package org.springframework.messaging.simp.stomp;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -46,11 +46,8 @@ import static org.junit.Assert.*;
*/ */
public class StompHeaderAccessorTests { public class StompHeaderAccessorTests {
private static final Charset UTF_8 = Charset.forName("UTF-8");
@Test @Test
public void createWithCommand() { public void createWithCommand() {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECTED); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.CONNECTED);
assertEquals(StompCommand.CONNECTED, accessor.getCommand()); assertEquals(StompCommand.CONNECTED, accessor.getCommand());
@ -60,7 +57,6 @@ public class StompHeaderAccessorTests {
@Test @Test
public void createWithSubscribeNativeHeaders() { public void createWithSubscribeNativeHeaders() {
MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>(); MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>();
extHeaders.add(StompHeaderAccessor.STOMP_ID_HEADER, "s1"); extHeaders.add(StompHeaderAccessor.STOMP_ID_HEADER, "s1");
extHeaders.add(StompHeaderAccessor.STOMP_DESTINATION_HEADER, "/d"); extHeaders.add(StompHeaderAccessor.STOMP_DESTINATION_HEADER, "/d");
@ -75,7 +71,6 @@ public class StompHeaderAccessorTests {
@Test @Test
public void createWithUnubscribeNativeHeaders() { public void createWithUnubscribeNativeHeaders() {
MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>(); MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>();
extHeaders.add(StompHeaderAccessor.STOMP_ID_HEADER, "s1"); extHeaders.add(StompHeaderAccessor.STOMP_ID_HEADER, "s1");
@ -88,7 +83,6 @@ public class StompHeaderAccessorTests {
@Test @Test
public void createWithMessageFrameNativeHeaders() { public void createWithMessageFrameNativeHeaders() {
MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>(); MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>();
extHeaders.add(StompHeaderAccessor.DESTINATION_HEADER, "/d"); extHeaders.add(StompHeaderAccessor.DESTINATION_HEADER, "/d");
extHeaders.add(StompHeaderAccessor.STOMP_SUBSCRIPTION_HEADER, "s1"); extHeaders.add(StompHeaderAccessor.STOMP_SUBSCRIPTION_HEADER, "s1");
@ -103,7 +97,6 @@ public class StompHeaderAccessorTests {
@Test @Test
public void createWithConnectNativeHeaders() { public void createWithConnectNativeHeaders() {
MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>(); MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>();
extHeaders.add(StompHeaderAccessor.STOMP_LOGIN_HEADER, "joe"); extHeaders.add(StompHeaderAccessor.STOMP_LOGIN_HEADER, "joe");
extHeaders.add(StompHeaderAccessor.STOMP_PASSCODE_HEADER, "joe123"); extHeaders.add(StompHeaderAccessor.STOMP_PASSCODE_HEADER, "joe123");
@ -124,7 +117,6 @@ public class StompHeaderAccessorTests {
@Test @Test
public void toNativeHeadersSubscribe() { public void toNativeHeadersSubscribe() {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE); StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
headers.setSubscriptionId("s1"); headers.setSubscriptionId("s1");
headers.setDestination("/d"); headers.setDestination("/d");
@ -138,7 +130,6 @@ public class StompHeaderAccessorTests {
@Test @Test
public void toNativeHeadersUnsubscribe() { public void toNativeHeadersUnsubscribe() {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.UNSUBSCRIBE); StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.UNSUBSCRIBE);
headers.setSubscriptionId("s1"); headers.setSubscriptionId("s1");
@ -150,7 +141,6 @@ public class StompHeaderAccessorTests {
@Test @Test
public void toNativeHeadersMessageFrame() { public void toNativeHeadersMessageFrame() {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE); StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.MESSAGE);
headers.setSubscriptionId("s1"); headers.setSubscriptionId("s1");
headers.setDestination("/d"); headers.setDestination("/d");
@ -168,7 +158,6 @@ public class StompHeaderAccessorTests {
@Test @Test
public void toNativeHeadersContentType() { public void toNativeHeadersContentType() {
SimpMessageHeaderAccessor simpHeaderAccessor = SimpMessageHeaderAccessor.create(); SimpMessageHeaderAccessor simpHeaderAccessor = SimpMessageHeaderAccessor.create();
simpHeaderAccessor.setContentType(MimeTypeUtils.APPLICATION_ATOM_XML); simpHeaderAccessor.setContentType(MimeTypeUtils.APPLICATION_ATOM_XML);
Message<byte[]> message = MessageBuilder.createMessage(new byte[0], simpHeaderAccessor.getMessageHeaders()); Message<byte[]> message = MessageBuilder.createMessage(new byte[0], simpHeaderAccessor.getMessageHeaders());
@ -181,7 +170,6 @@ public class StompHeaderAccessorTests {
@Test @Test
public void encodeConnectWithLoginAndPasscode() throws UnsupportedEncodingException { public void encodeConnectWithLoginAndPasscode() throws UnsupportedEncodingException {
MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>(); MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>();
extHeaders.add(StompHeaderAccessor.STOMP_LOGIN_HEADER, "joe"); extHeaders.add(StompHeaderAccessor.STOMP_LOGIN_HEADER, "joe");
extHeaders.add(StompHeaderAccessor.STOMP_PASSCODE_HEADER, "joe123"); extHeaders.add(StompHeaderAccessor.STOMP_PASSCODE_HEADER, "joe123");
@ -195,7 +183,6 @@ public class StompHeaderAccessorTests {
@Test @Test
public void modifyCustomNativeHeader() { public void modifyCustomNativeHeader() {
MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>(); MultiValueMap<String, String> extHeaders = new LinkedMultiValueMap<>();
extHeaders.add(StompHeaderAccessor.STOMP_ID_HEADER, "s1"); extHeaders.add(StompHeaderAccessor.STOMP_ID_HEADER, "s1");
extHeaders.add(StompHeaderAccessor.STOMP_DESTINATION_HEADER, "/d"); extHeaders.add(StompHeaderAccessor.STOMP_DESTINATION_HEADER, "/d");
@ -249,7 +236,7 @@ public class StompHeaderAccessorTests {
accessor.setDestination("/foo"); accessor.setDestination("/foo");
accessor.setContentType(MimeTypeUtils.APPLICATION_JSON); accessor.setContentType(MimeTypeUtils.APPLICATION_JSON);
accessor.setSessionId("123"); accessor.setSessionId("123");
String actual = accessor.getShortLogMessage("payload".getBytes(Charset.forName("UTF-8"))); String actual = accessor.getShortLogMessage("payload".getBytes(StandardCharsets.UTF_8));
assertEquals("SEND /foo session=123 application/json payload=payload", actual); assertEquals("SEND /foo session=123 application/json payload=payload", actual);
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -257,7 +244,7 @@ public class StompHeaderAccessorTests {
sb.append("a"); sb.append("a");
} }
final String payload = sb.toString() + " > 80"; final String payload = sb.toString() + " > 80";
actual = accessor.getShortLogMessage(payload.getBytes(UTF_8)); actual = accessor.getShortLogMessage(payload.getBytes(StandardCharsets.UTF_8));
assertEquals("SEND /foo session=123 application/json payload=" + sb + "...(truncated)", actual); assertEquals("SEND /foo session=123 application/json payload=" + sb + "...(truncated)", actual);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -21,6 +21,7 @@ import static org.mockito.BDDMockito.*;
import static org.springframework.messaging.simp.SimpMessageHeaderAccessor.*; import static org.springframework.messaging.simp.SimpMessageHeaderAccessor.*;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -45,7 +46,6 @@ public class UserDestinationMessageHandlerTests {
private static final String SESSION_ID = "123"; private static final String SESSION_ID = "123";
private UserDestinationMessageHandler handler; private UserDestinationMessageHandler handler;
private SimpUserRegistry registry; private SimpUserRegistry registry;
@ -138,7 +138,7 @@ public class UserDestinationMessageHandlerTests {
accessor.setNativeHeader(ORIGINAL_DESTINATION, "/user/joe/queue/foo"); accessor.setNativeHeader(ORIGINAL_DESTINATION, "/user/joe/queue/foo");
accessor.setNativeHeader("customHeader", "customHeaderValue"); accessor.setNativeHeader("customHeader", "customHeaderValue");
accessor.setLeaveMutable(true); accessor.setLeaveMutable(true);
byte[] payload = "payload".getBytes(Charset.forName("UTF-8")); byte[] payload = "payload".getBytes(StandardCharsets.UTF_8);
this.handler.handleMessage(MessageBuilder.createMessage(payload, accessor.getMessageHeaders())); this.handler.handleMessage(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));
ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class); ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
@ -161,7 +161,7 @@ public class UserDestinationMessageHandlerTests {
accessor.setDestination("/topic/unresolved"); accessor.setDestination("/topic/unresolved");
accessor.setNativeHeader(ORIGINAL_DESTINATION, "/user/joe/queue/foo"); accessor.setNativeHeader(ORIGINAL_DESTINATION, "/user/joe/queue/foo");
accessor.setLeaveMutable(true); accessor.setLeaveMutable(true);
byte[] payload = "payload".getBytes(Charset.forName("UTF-8")); byte[] payload = "payload".getBytes(StandardCharsets.UTF_8);
this.handler.handleMessage(MessageBuilder.createMessage(payload, accessor.getMessageHeaders())); this.handler.handleMessage(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));
// No re-broadcast // No re-broadcast

View File

@ -16,7 +16,7 @@
package org.springframework.messaging.support; package org.springframework.messaging.support;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
@ -45,8 +45,6 @@ import static org.junit.Assert.*;
*/ */
public class MessageHeaderAccessorTests { public class MessageHeaderAccessorTests {
private static final Charset UTF_8 = Charset.forName("UTF-8");
@Rule @Rule
public final ExpectedException thrown = ExpectedException.none(); public final ExpectedException thrown = ExpectedException.none();
@ -334,7 +332,7 @@ public class MessageHeaderAccessorTests {
accessor.setContentType(MimeTypeUtils.TEXT_PLAIN); accessor.setContentType(MimeTypeUtils.TEXT_PLAIN);
assertEquals("headers={contentType=text/plain} payload=p", accessor.getShortLogMessage("p")); assertEquals("headers={contentType=text/plain} payload=p", accessor.getShortLogMessage("p"));
assertEquals("headers={contentType=text/plain} payload=p", accessor.getShortLogMessage("p".getBytes(UTF_8))); assertEquals("headers={contentType=text/plain} payload=p", accessor.getShortLogMessage("p".getBytes(StandardCharsets.UTF_8)));
assertEquals("headers={contentType=text/plain} payload=p", accessor.getShortLogMessage(new Object() { assertEquals("headers={contentType=text/plain} payload=p", accessor.getShortLogMessage(new Object() {
@Override @Override
public String toString() { public String toString() {
@ -351,7 +349,7 @@ public class MessageHeaderAccessorTests {
String actual = accessor.getShortLogMessage(payload); String actual = accessor.getShortLogMessage(payload);
assertEquals("headers={contentType=text/plain} payload=" + sb + "...(truncated)", actual); assertEquals("headers={contentType=text/plain} payload=" + sb + "...(truncated)", actual);
actual = accessor.getShortLogMessage(payload.getBytes(UTF_8)); actual = accessor.getShortLogMessage(payload.getBytes(StandardCharsets.UTF_8));
assertEquals("headers={contentType=text/plain} payload=" + sb + "...(truncated)", actual); assertEquals("headers={contentType=text/plain} payload=" + sb + "...(truncated)", actual);
actual = accessor.getShortLogMessage(new Object() { actual = accessor.getShortLogMessage(new Object() {
@ -369,7 +367,7 @@ public class MessageHeaderAccessorTests {
accessor.setContentType(MimeTypeUtils.TEXT_PLAIN); accessor.setContentType(MimeTypeUtils.TEXT_PLAIN);
assertEquals("headers={contentType=text/plain} payload=p", accessor.getDetailedLogMessage("p")); assertEquals("headers={contentType=text/plain} payload=p", accessor.getDetailedLogMessage("p"));
assertEquals("headers={contentType=text/plain} payload=p", accessor.getDetailedLogMessage("p".getBytes(UTF_8))); assertEquals("headers={contentType=text/plain} payload=p", accessor.getDetailedLogMessage("p".getBytes(StandardCharsets.UTF_8)));
assertEquals("headers={contentType=text/plain} payload=p", accessor.getDetailedLogMessage(new Object() { assertEquals("headers={contentType=text/plain} payload=p", accessor.getDetailedLogMessage(new Object() {
@Override @Override
public String toString() { public String toString() {
@ -386,7 +384,7 @@ public class MessageHeaderAccessorTests {
String actual = accessor.getDetailedLogMessage(payload); String actual = accessor.getDetailedLogMessage(payload);
assertEquals("headers={contentType=text/plain} payload=" + sb + " > 80", actual); assertEquals("headers={contentType=text/plain} payload=" + sb + " > 80", actual);
actual = accessor.getDetailedLogMessage(payload.getBytes(UTF_8)); actual = accessor.getDetailedLogMessage(payload.getBytes(StandardCharsets.UTF_8));
assertEquals("headers={contentType=text/plain} payload=" + sb + " > 80", actual); assertEquals("headers={contentType=text/plain} payload=" + sb + " > 80", actual);
actual = accessor.getDetailedLogMessage(new Object() { actual = accessor.getDetailedLogMessage(new Object() {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -21,6 +21,7 @@ import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpOutputMessage; import org.springframework.http.HttpOutputMessage;
@ -33,7 +34,7 @@ import org.springframework.http.HttpOutputMessage;
*/ */
public class MockHttpOutputMessage implements HttpOutputMessage { public class MockHttpOutputMessage implements HttpOutputMessage {
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private final HttpHeaders headers = new HttpHeaders(); private final HttpHeaders headers = new HttpHeaders();

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,6 +18,7 @@ package org.springframework.test.web.client;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
@ -50,6 +51,7 @@ public class MockMvcClientHttpRequestFactory implements ClientHttpRequestFactory
this.mockMvc = mockMvc; this.mockMvc = mockMvc;
} }
@Override @Override
public ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException { public ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException {
return new MockClientHttpRequest(httpMethod, uri) { return new MockClientHttpRequest(httpMethod, uri) {
@ -73,7 +75,7 @@ public class MockMvcClientHttpRequestFactory implements ClientHttpRequestFactory
return clientResponse; return clientResponse;
} }
catch (Exception ex) { catch (Exception ex) {
byte[] body = ex.toString().getBytes("UTF-8"); byte[] body = ex.toString().getBytes(StandardCharsets.UTF_8);
return new MockClientHttpResponse(body, HttpStatus.INTERNAL_SERVER_ERROR); return new MockClientHttpResponse(body, HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2012 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -13,12 +13,13 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.test.web.client.response; package org.springframework.test.web.client.response;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
@ -56,6 +57,7 @@ public class DefaultResponseCreator implements ResponseCreator {
this.statusCode = statusCode; this.statusCode = statusCode;
} }
@Override @Override
public ClientHttpResponse createResponse(ClientHttpRequest request) throws IOException { public ClientHttpResponse createResponse(ClientHttpRequest request) throws IOException {
MockClientHttpResponse response; MockClientHttpResponse response;
@ -74,13 +76,7 @@ public class DefaultResponseCreator implements ResponseCreator {
* Set the body as a UTF-8 String. * Set the body as a UTF-8 String.
*/ */
public DefaultResponseCreator body(String content) { public DefaultResponseCreator body(String content) {
try { this.content = content.getBytes(StandardCharsets.UTF_8);
this.content = content.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e) {
// should not happen, UTF-8 is always supported
throw new IllegalStateException(e);
}
return this; return this;
} }

View File

@ -21,6 +21,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.Principal; import java.security.Principal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -272,12 +273,7 @@ public class MockHttpServletRequestBuilder
* @param content the body content * @param content the body content
*/ */
public MockHttpServletRequestBuilder content(String content) { public MockHttpServletRequestBuilder content(String content) {
try { this.content = content.getBytes(StandardCharsets.UTF_8);
this.content = content.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e) {
// should never happen
}
return this; return this;
} }
@ -286,7 +282,6 @@ public class MockHttpServletRequestBuilder
* @param cookies the cookies to add * @param cookies the cookies to add
*/ */
public MockHttpServletRequestBuilder cookie(Cookie... cookies) { public MockHttpServletRequestBuilder cookie(Cookie... cookies) {
Assert.notNull(cookies, "'cookies' must not be null");
Assert.notEmpty(cookies, "'cookies' must not be empty"); Assert.notEmpty(cookies, "'cookies' must not be empty");
this.cookies.addAll(Arrays.asList(cookies)); this.cookies.addAll(Arrays.asList(cookies));
return this; return this;

View File

@ -13,9 +13,10 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.test.web.client.match; package org.springframework.test.web.client.match;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -100,7 +101,7 @@ public class ContentRequestMatchersTests {
String body = "name+1=value+1&name+2=value+A&name+2=value+B&name+3"; String body = "name+1=value+1&name+2=value+A&name+2=value+B&name+3";
this.request.getHeaders().setContentType(MediaType.parseMediaType(contentType)); this.request.getHeaders().setContentType(MediaType.parseMediaType(contentType));
this.request.getBody().write(body.getBytes(Charset.forName("UTF-8"))); this.request.getBody().write(body.getBytes(StandardCharsets.UTF_8));
MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("name 1", "value 1"); map.add("name 1", "value 1");

View File

@ -13,12 +13,14 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.test.web.servlet.request; package org.springframework.test.web.servlet.request;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.Principal; import java.security.Principal;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
@ -279,7 +281,7 @@ public class MockHttpServletRequestBuilderTests {
String body = "name+1=value+1&name+2=value+A&name+2=value+B&name+3"; String body = "name+1=value+1&name+2=value+A&name+2=value+B&name+3";
MockHttpServletRequest request = new MockHttpServletRequestBuilder(HttpMethod.POST, "/foo") MockHttpServletRequest request = new MockHttpServletRequestBuilder(HttpMethod.POST, "/foo")
.contentType(contentType).content(body.getBytes(Charset.forName("UTF-8"))) .contentType(contentType).content(body.getBytes(StandardCharsets.UTF_8))
.buildRequest(this.servletContext); .buildRequest(this.servletContext);
assertArrayEquals(new String[] {"value 1"}, request.getParameterMap().get("name 1")); assertArrayEquals(new String[] {"value 1"}, request.getParameterMap().get("name 1"));

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,10 +16,9 @@
package org.springframework.test.web.servlet.result; package org.springframework.test.web.servlet.result;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.Test; import org.junit.Test;
import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpServletResponse;
@ -33,6 +32,9 @@ import org.springframework.util.StreamUtils;
*/ */
public class XpathResultMatchersTests { public class XpathResultMatchersTests {
private static final String RESPONSE_CONTENT = "<foo><bar>111</bar><bar>true</bar></foo>";
@Test @Test
public void node() throws Exception { public void node() throws Exception {
new XpathResultMatchers("/foo/bar", null).node(Matchers.notNullValue()).match(getStubMvcResult()); new XpathResultMatchers("/foo/bar", null).node(Matchers.notNullValue()).match(getStubMvcResult());
@ -107,7 +109,7 @@ public class XpathResultMatchersTests {
public void stringEncodingDetection() throws Exception { public void stringEncodingDetection() throws Exception {
String content = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + String content = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<person><name>Jürgen</name></person>"; "<person><name>Jürgen</name></person>";
byte[] bytes = content.getBytes(Charset.forName("UTF-8")); byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", "application/xml"); response.addHeader("Content-Type", "application/xml");
StreamUtils.copy(bytes, response.getOutputStream()); StreamUtils.copy(bytes, response.getOutputStream());
@ -117,12 +119,10 @@ public class XpathResultMatchersTests {
} }
private static final String RESPONSE_CONTENT = "<foo><bar>111</bar><bar>true</bar></foo>";
private StubMvcResult getStubMvcResult() throws Exception { private StubMvcResult getStubMvcResult() throws Exception {
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
response.addHeader("Content-Type", "application/xml"); response.addHeader("Content-Type", "application/xml");
response.getWriter().print(new String(RESPONSE_CONTENT.getBytes("ISO-8859-1"))); response.getWriter().print(new String(RESPONSE_CONTENT.getBytes(StandardCharsets.ISO_8859_1)));
return new StubMvcResult(null, null, null, null, null, null, response); return new StubMvcResult(null, null, null, null, null, null, response);
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,7 +17,7 @@
package org.springframework.test.web.servlet.samples.standalone; package org.springframework.test.web.servlet.samples.standalone;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
import javax.servlet.Filter; import javax.servlet.Filter;
@ -40,25 +40,21 @@ import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
/** /**
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
*/ */
public class FileUploadControllerTests { public class FileUploadControllerTests {
private static final Charset CHARSET = Charset.forName("UTF-8");
@Test @Test
public void multipartRequest() throws Exception { public void multipartRequest() throws Exception {
byte[] fileContent = "bar".getBytes(StandardCharsets.UTF_8);
byte[] fileContent = "bar".getBytes(CHARSET);
MockMultipartFile filePart = new MockMultipartFile("file", "orig", null, fileContent); MockMultipartFile filePart = new MockMultipartFile("file", "orig", null, fileContent);
byte[] json = "{\"name\":\"yeeeah\"}".getBytes(CHARSET); byte[] json = "{\"name\":\"yeeeah\"}".getBytes(StandardCharsets.UTF_8);
MockMultipartFile jsonPart = new MockMultipartFile("json", "json", "application/json", json); MockMultipartFile jsonPart = new MockMultipartFile("json", "json", "application/json", json);
MockMvc mockMvc = standaloneSetup(new MultipartController()).build(); MockMvc mockMvc = standaloneSetup(new MultipartController()).build();
@ -67,12 +63,9 @@ public class FileUploadControllerTests {
.andExpect(model().attribute("jsonContent", Collections.singletonMap("name", "yeeeah"))); .andExpect(model().attribute("jsonContent", Collections.singletonMap("name", "yeeeah")));
} }
// SPR-13317 @Test // SPR-13317
@Test
public void multipartRequestWrapped() throws Exception { public void multipartRequestWrapped() throws Exception {
byte[] json = "{\"name\":\"yeeeah\"}".getBytes(StandardCharsets.UTF_8);
byte[] json = "{\"name\":\"yeeeah\"}".getBytes(CHARSET);
MockMultipartFile jsonPart = new MockMultipartFile("json", "json", "application/json", json); MockMultipartFile jsonPart = new MockMultipartFile("json", "json", "application/json", json);
Filter filter = new RequestWrappingFilter(); Filter filter = new RequestWrappingFilter();
@ -103,6 +96,7 @@ public class FileUploadControllerTests {
} }
} }
private static class RequestWrappingFilter extends OncePerRequestFilter { private static class RequestWrappingFilter extends OncePerRequestFilter {
@Override @Override

View File

@ -17,7 +17,7 @@ package org.springframework.web.reactive.result.method.annotation;
import java.net.URI; import java.net.URI;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -56,12 +56,8 @@ import org.springframework.web.server.ServerWebInputException;
import org.springframework.web.server.adapter.DefaultServerWebExchange; import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.MockWebSessionManager; import org.springframework.web.server.session.MockWebSessionManager;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertFalse; import static org.springframework.core.ResolvableType.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.core.ResolvableType.forClassWithGenerics;
/** /**
* Unit tests for {@link HttpEntityArgumentResolver}.When adding a test also * Unit tests for {@link HttpEntityArgumentResolver}.When adding a test also
@ -288,7 +284,7 @@ public class HttpEntityArgumentResolverTests {
} }
private DataBuffer dataBuffer(String body) { private DataBuffer dataBuffer(String body) {
byte[] bytes = body.getBytes(Charset.forName("UTF-8")); byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
return new DefaultDataBufferFactory().wrap(byteBuffer); return new DefaultDataBufferFactory().wrap(byteBuffer);
} }

View File

@ -13,12 +13,13 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.web.reactive.result.method.annotation; package org.springframework.web.reactive.result.method.annotation;
import java.io.Serializable; import java.io.Serializable;
import java.net.URI; import java.net.URI;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -64,12 +65,8 @@ import org.springframework.web.server.UnsupportedMediaTypeStatusException;
import org.springframework.web.server.adapter.DefaultServerWebExchange; import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.MockWebSessionManager; import org.springframework.web.server.session.MockWebSessionManager;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals; import static org.springframework.core.ResolvableType.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.core.ResolvableType.forClass;
import static org.springframework.core.ResolvableType.forClassWithGenerics;
/** /**
* Unit tests for {@link AbstractMessageReaderArgumentResolver}. * Unit tests for {@link AbstractMessageReaderArgumentResolver}.
@ -289,7 +286,7 @@ public class MessageReaderArgumentResolverTests {
} }
private DataBuffer dataBuffer(String body) { private DataBuffer dataBuffer(String body) {
byte[] bytes = body.getBytes(Charset.forName("UTF-8")); byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
return new DefaultDataBufferFactory().wrap(byteBuffer); return new DefaultDataBufferFactory().wrap(byteBuffer);
} }

View File

@ -13,13 +13,14 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.web.reactive.result.method.annotation; package org.springframework.web.reactive.result.method.annotation;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.Serializable; import java.io.Serializable;
import java.net.URI; import java.net.URI;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -63,11 +64,9 @@ import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange; import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.MockWebSessionManager; import org.springframework.web.server.session.MockWebSessionManager;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertNull; import static org.springframework.http.MediaType.*;
import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.web.reactive.HandlerMapping.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8;
import static org.springframework.web.reactive.HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE;
/** /**
* Unit tests for {@link AbstractMessageWriterResultHandler}. * Unit tests for {@link AbstractMessageWriterResultHandler}.
@ -201,7 +200,7 @@ public class MessageWriterResultHandlerTests {
private void assertResponseBody(String responseBody) { private void assertResponseBody(String responseBody) {
TestSubscriber.subscribe(this.response.getBody()) TestSubscriber.subscribe(this.response.getBody())
.assertValuesWith(buf -> assertEquals(responseBody, .assertValuesWith(buf -> assertEquals(responseBody,
DataBufferTestUtils.dumpString(buf, Charset.forName("UTF-8")))); DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8)));
} }

View File

@ -19,6 +19,7 @@ package org.springframework.web.reactive.result.method.annotation;
import java.net.URI; import java.net.URI;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -246,7 +247,7 @@ public class RequestBodyArgumentResolverTests {
} }
private DataBuffer dataBuffer(String body) { private DataBuffer dataBuffer(String body) {
byte[] bytes = body.getBytes(Charset.forName("UTF-8")); byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
return new DefaultDataBufferFactory().wrap(byteBuffer); return new DefaultDataBufferFactory().wrap(byteBuffer);
} }

View File

@ -13,10 +13,11 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.web.reactive.result.method.annotation; package org.springframework.web.reactive.result.method.annotation;
import java.net.URI; import java.net.URI;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -58,11 +59,8 @@ import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.adapter.DefaultServerWebExchange; import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.MockWebSessionManager; import org.springframework.web.server.session.MockWebSessionManager;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertFalse; import static org.springframework.core.ResolvableType.*;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.core.ResolvableType.forClassWithGenerics;
/** /**
* Unit tests for {@link ResponseEntityResultHandler}. When adding a test also * Unit tests for {@link ResponseEntityResultHandler}. When adding a test also
@ -206,7 +204,7 @@ public class ResponseEntityResultHandlerTests {
private void assertResponseBody(String responseBody) { private void assertResponseBody(String responseBody) {
TestSubscriber.subscribe(this.response.getBody()) TestSubscriber.subscribe(this.response.getBody())
.assertValuesWith(buf -> assertEquals(responseBody, .assertValuesWith(buf -> assertEquals(responseBody,
DataBufferTestUtils.dumpString(buf, Charset.forName("UTF-8")))); DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8)));
} }

View File

@ -172,7 +172,7 @@ public class HttpMessageWriterViewTests {
TestSubscriber TestSubscriber
.subscribe(response.getBody()) .subscribe(response.getBody())
.assertValuesWith(buf -> assertEquals("{\"foo\":\"f\",\"bar\":\"b\"}", .assertValuesWith(buf -> assertEquals("{\"foo\":\"f\",\"bar\":\"b\"}",
DataBufferTestUtils.dumpString(buf, Charset.forName("UTF-8")))); DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8)));
} }

View File

@ -19,7 +19,7 @@ package org.springframework.web.reactive.result.view;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.time.Duration; import java.time.Duration;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
@ -62,13 +62,13 @@ import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.DefaultWebSessionManager; import org.springframework.web.server.session.DefaultWebSessionManager;
import org.springframework.web.server.session.WebSessionManager; import org.springframework.web.server.session.WebSessionManager;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock; import static org.springframework.http.MediaType.*;
import static org.springframework.http.MediaType.APPLICATION_JSON;
/** /**
* Unit tests for {@link ViewResolutionResultHandler}. * Unit tests for {@link ViewResolutionResultHandler}.
*
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
*/ */
public class ViewResolutionResultHandlerTests { public class ViewResolutionResultHandlerTests {
@ -289,7 +289,7 @@ public class ViewResolutionResultHandlerTests {
private void assertResponseBody(String responseBody) { private void assertResponseBody(String responseBody) {
TestSubscriber.subscribe(this.response.getBody()) TestSubscriber.subscribe(this.response.getBody())
.assertValuesWith(buf -> assertEquals(responseBody, .assertValuesWith(buf -> assertEquals(responseBody,
DataBufferTestUtils.dumpString(buf, Charset.forName("UTF-8")))); DataBufferTestUtils.dumpString(buf, StandardCharsets.UTF_8)));
} }
@ -299,7 +299,6 @@ public class ViewResolutionResultHandlerTests {
private int order = Ordered.LOWEST_PRECEDENCE; private int order = Ordered.LOWEST_PRECEDENCE;
TestViewResolver(String... viewNames) { TestViewResolver(String... viewNames) {
Arrays.stream(viewNames).forEach(name -> this.views.put(name, new TestView(name))); Arrays.stream(viewNames).forEach(name -> this.views.put(name, new TestView(name)));
} }
@ -318,9 +317,9 @@ public class ViewResolutionResultHandlerTests {
View view = this.views.get(viewName); View view = this.views.get(viewName);
return Mono.justOrEmpty(view); return Mono.justOrEmpty(view);
} }
} }
private static final class TestView implements View { private static final class TestView implements View {
private final String name; private final String name;
@ -355,12 +354,13 @@ public class ViewResolutionResultHandlerTests {
if (mediaType != null) { if (mediaType != null) {
response.getHeaders().setContentType(mediaType); response.getHeaders().setContentType(mediaType);
} }
ByteBuffer byteBuffer = ByteBuffer.wrap(value.getBytes(Charset.forName("UTF-8"))); ByteBuffer byteBuffer = ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8));
DataBuffer dataBuffer = new DefaultDataBufferFactory().wrap(byteBuffer); DataBuffer dataBuffer = new DefaultDataBufferFactory().wrap(byteBuffer);
return response.writeWith(Flux.just(dataBuffer)); return response.writeWith(Flux.just(dataBuffer));
} }
} }
private static class TestBean { private static class TestBean {
private final String name; private final String name;
@ -379,6 +379,7 @@ public class ViewResolutionResultHandlerTests {
} }
} }
@SuppressWarnings("unused") @SuppressWarnings("unused")
private static class TestController { private static class TestController {

View File

@ -17,7 +17,7 @@ package org.springframework.web.reactive.result.view.freemarker;
import java.net.URI; import java.net.URI;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.Locale; import java.util.Locale;
import freemarker.template.Configuration; import freemarker.template.Configuration;
@ -42,8 +42,7 @@ import org.springframework.web.server.adapter.DefaultServerWebExchange;
import org.springframework.web.server.session.DefaultWebSessionManager; import org.springframework.web.server.session.DefaultWebSessionManager;
import org.springframework.web.server.session.WebSessionManager; import org.springframework.web.server.session.WebSessionManager;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.*;
import static org.junit.Assert.assertTrue;
/** /**
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
@ -52,8 +51,6 @@ public class FreeMarkerViewTests {
public static final String TEMPLATE_PATH = "classpath*:org/springframework/web/reactive/view/freemarker/"; public static final String TEMPLATE_PATH = "classpath*:org/springframework/web/reactive/view/freemarker/";
private static final Charset UTF_8 = Charset.forName("UTF-8");
private ServerWebExchange exchange; private ServerWebExchange exchange;
@ -140,7 +137,7 @@ public class FreeMarkerViewTests {
ByteBuffer byteBuffer = dataBuffer.asByteBuffer(); ByteBuffer byteBuffer = dataBuffer.asByteBuffer();
final byte[] bytes = new byte[byteBuffer.remaining()]; final byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes); byteBuffer.get(bytes);
return new String(bytes, UTF_8); return new String(bytes, StandardCharsets.UTF_8);
} }

View File

@ -17,7 +17,7 @@
package org.springframework.http.client.support; package org.springframework.http.client.support;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import org.springframework.http.HttpRequest; import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestExecution;
@ -34,8 +34,6 @@ import org.springframework.util.Base64Utils;
*/ */
public class BasicAuthorizationInterceptor implements ClientHttpRequestInterceptor { public class BasicAuthorizationInterceptor implements ClientHttpRequestInterceptor {
private static final Charset UTF_8 = Charset.forName("UTF-8");
private final String username; private final String username;
private final String password; private final String password;
@ -58,7 +56,8 @@ public class BasicAuthorizationInterceptor implements ClientHttpRequestIntercept
public ClientHttpResponse intercept(HttpRequest request, byte[] body, public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException { ClientHttpRequestExecution execution) throws IOException {
String token = Base64Utils.encodeToString((this.username + ":" + this.password).getBytes(UTF_8)); String token = Base64Utils.encodeToString(
(this.username + ":" + this.password).getBytes(StandardCharsets.UTF_8));
request.getHeaders().add("Authorization", "Basic " + token); request.getHeaders().add("Authorization", "Basic " + token);
return execution.execute(request, body); return execution.execute(request, body);
} }

View File

@ -22,6 +22,7 @@ import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
@ -88,7 +89,7 @@ import org.springframework.util.StringUtils;
*/ */
public class FormHttpMessageConverter implements HttpMessageConverter<MultiValueMap<String, ?>> { public class FormHttpMessageConverter implements HttpMessageConverter<MultiValueMap<String, ?>> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private List<MediaType> supportedMediaTypes = new ArrayList<>(); private List<MediaType> supportedMediaTypes = new ArrayList<>();
@ -303,7 +304,7 @@ public class FormHttpMessageConverter implements HttpMessageConverter<MultiValue
builder.append('&'); builder.append('&');
} }
} }
final byte[] bytes = builder.toString().getBytes(charset.name()); final byte[] bytes = builder.toString().getBytes(charset);
outputMessage.getHeaders().setContentLength(bytes.length); outputMessage.getHeaders().setContentLength(bytes.length);
if (outputMessage instanceof StreamingHttpOutputMessage) { if (outputMessage instanceof StreamingHttpOutputMessage) {
@ -494,13 +495,7 @@ public class FormHttpMessageConverter implements HttpMessageConverter<MultiValue
} }
private byte[] getAsciiBytes(String name) { private byte[] getAsciiBytes(String name) {
try { return name.getBytes(StandardCharsets.US_ASCII);
return name.getBytes("US-ASCII");
}
catch (UnsupportedEncodingException ex) {
// Should not happen - US-ASCII is always supported.
throw new IllegalStateException(ex);
}
} }
} }

View File

@ -21,6 +21,7 @@ import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Collection; import java.util.Collection;
import org.springframework.core.io.support.ResourceRegion; import org.springframework.core.io.support.ResourceRegion;
@ -184,7 +185,7 @@ public class ResourceRegionHttpMessageConverter extends AbstractGenericHttpMessa
} }
private static void print(OutputStream os, String buf) throws IOException { private static void print(OutputStream os, String buf) throws IOException {
os.write(buf.getBytes("US-ASCII")); os.write(buf.getBytes(StandardCharsets.US_ASCII));
} }
} }

View File

@ -17,7 +17,6 @@
package org.springframework.http.converter; package org.springframework.http.converter;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -89,13 +88,7 @@ public class StringHttpMessageConverter extends AbstractHttpMessageConverter<Str
@Override @Override
protected Long getContentLength(String str, MediaType contentType) { protected Long getContentLength(String str, MediaType contentType) {
Charset charset = getContentTypeCharset(contentType); Charset charset = getContentTypeCharset(contentType);
try { return (long) str.getBytes(charset).length;
return (long) str.getBytes(charset.name()).length;
}
catch (UnsupportedEncodingException ex) {
// should not occur
throw new IllegalStateException(ex);
}
} }
@Override @Override

View File

@ -22,6 +22,7 @@ import java.io.OutputStreamWriter;
import java.io.Reader; import java.io.Reader;
import java.io.Writer; import java.io.Writer;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import com.rometools.rome.feed.WireFeed; import com.rometools.rome.feed.WireFeed;
import com.rometools.rome.io.FeedException; import com.rometools.rome.io.FeedException;
@ -50,7 +51,7 @@ import org.springframework.util.StringUtils;
*/ */
public abstract class AbstractWireFeedHttpMessageConverter<T extends WireFeed> extends AbstractHttpMessageConverter<T> { public abstract class AbstractWireFeedHttpMessageConverter<T extends WireFeed> extends AbstractHttpMessageConverter<T> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
protected AbstractWireFeedHttpMessageConverter(MediaType supportedMediaType) { protected AbstractWireFeedHttpMessageConverter(MediaType supportedMediaType) {

View File

@ -20,6 +20,7 @@ import java.io.IOException;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable; import java.lang.reflect.TypeVariable;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonEncoding;
@ -60,7 +61,7 @@ import org.springframework.util.TypeUtils;
*/ */
public abstract class AbstractJackson2HttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> { public abstract class AbstractJackson2HttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
protected ObjectMapper objectMapper; protected ObjectMapper objectMapper;

View File

@ -22,6 +22,7 @@ import java.io.OutputStreamWriter;
import java.io.Reader; import java.io.Reader;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonIOException; import com.google.gson.JsonIOException;
@ -56,7 +57,7 @@ import org.springframework.util.Assert;
*/ */
public class GsonHttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> { public class GsonHttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private Gson gson = new Gson(); private Gson gson = new Gson();

View File

@ -21,6 +21,7 @@ import java.io.InputStreamReader;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import com.google.protobuf.ExtensionRegistry; import com.google.protobuf.ExtensionRegistry;
@ -39,7 +40,6 @@ import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
/** /**
* An {@code HttpMessageConverter} that reads and writes {@link com.google.protobuf.Message}s * An {@code HttpMessageConverter} that reads and writes {@link com.google.protobuf.Message}s
* using <a href="https://developers.google.com/protocol-buffers/">Google Protocol Buffers</a>. * using <a href="https://developers.google.com/protocol-buffers/">Google Protocol Buffers</a>.
@ -58,7 +58,7 @@ import org.springframework.util.FileCopyUtils;
*/ */
public class ProtobufHttpMessageConverter extends AbstractHttpMessageConverter<Message> { public class ProtobufHttpMessageConverter extends AbstractHttpMessageConverter<Message> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
public static final MediaType PROTOBUF = new MediaType("application", "x-protobuf", DEFAULT_CHARSET); public static final MediaType PROTOBUF = new MediaType("application", "x-protobuf", DEFAULT_CHARSET);

View File

@ -27,6 +27,7 @@ import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.Principal; import java.security.Principal;
import java.util.Arrays; import java.util.Arrays;
import java.util.Enumeration; import java.util.Enumeration;
@ -54,7 +55,7 @@ public class ServletServerHttpRequest implements ServerHttpRequest {
protected static final String FORM_CONTENT_TYPE = "application/x-www-form-urlencoded"; protected static final String FORM_CONTENT_TYPE = "application/x-www-form-urlencoded";
protected static final String FORM_CHARSET = "UTF-8"; protected static final Charset FORM_CHARSET = StandardCharsets.UTF_8;
private final HttpServletRequest servletRequest; private final HttpServletRequest servletRequest;
@ -210,10 +211,10 @@ public class ServletServerHttpRequest implements ServerHttpRequest {
List<String> values = Arrays.asList(form.get(name)); List<String> values = Arrays.asList(form.get(name));
for (Iterator<String> valueIterator = values.iterator(); valueIterator.hasNext();) { for (Iterator<String> valueIterator = values.iterator(); valueIterator.hasNext();) {
String value = valueIterator.next(); String value = valueIterator.next();
writer.write(URLEncoder.encode(name, FORM_CHARSET)); writer.write(URLEncoder.encode(name, FORM_CHARSET.name()));
if (value != null) { if (value != null) {
writer.write('='); writer.write('=');
writer.write(URLEncoder.encode(value, FORM_CHARSET)); writer.write(URLEncoder.encode(value, FORM_CHARSET.name()));
if (valueIterator.hasNext()) { if (valueIterator.hasNext()) {
writer.write('&'); writer.write('&');
} }

View File

@ -17,7 +17,7 @@
package org.springframework.web.cors; package org.springframework.web.cors;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -52,8 +52,6 @@ import org.springframework.web.util.WebUtils;
*/ */
public class DefaultCorsProcessor implements CorsProcessor { public class DefaultCorsProcessor implements CorsProcessor {
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
private static final Log logger = LogFactory.getLog(DefaultCorsProcessor.class); private static final Log logger = LogFactory.getLog(DefaultCorsProcessor.class);
@ -109,7 +107,7 @@ public class DefaultCorsProcessor implements CorsProcessor {
*/ */
protected void rejectRequest(ServerHttpResponse response) throws IOException { protected void rejectRequest(ServerHttpResponse response) throws IOException {
response.setStatusCode(HttpStatus.FORBIDDEN); response.setStatusCode(HttpStatus.FORBIDDEN);
response.getBody().write("Invalid CORS request".getBytes(UTF8_CHARSET)); response.getBody().write("Invalid CORS request".getBytes(StandardCharsets.UTF_8));
} }
/** /**

View File

@ -95,21 +95,21 @@ public class RequestPartServletServerHttpRequest extends ServletServerHttpReques
} }
else { else {
String paramValue = this.multipartRequest.getParameter(this.partName); String paramValue = this.multipartRequest.getParameter(this.partName);
return new ByteArrayInputStream(paramValue.getBytes(determineEncoding())); return new ByteArrayInputStream(paramValue.getBytes(determineCharset()));
} }
} }
} }
private String determineEncoding() { private Charset determineCharset() {
MediaType contentType = getHeaders().getContentType(); MediaType contentType = getHeaders().getContentType();
if (contentType != null) { if (contentType != null) {
Charset charset = contentType.getCharset(); Charset charset = contentType.getCharset();
if (charset != null) { if (charset != null) {
return charset.name(); return charset;
} }
} }
String encoding = this.multipartRequest.getCharacterEncoding(); String encoding = this.multipartRequest.getCharacterEncoding();
return (encoding != null ? encoding : FORM_CHARSET); return (encoding != null ? Charset.forName(encoding) : FORM_CHARSET);
} }
} }

View File

@ -21,6 +21,8 @@ import java.io.Serializable;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
@ -61,6 +63,7 @@ final class HierarchicalUriComponents extends UriComponents {
private final boolean encoded; private final boolean encoded;
/** /**
* Package-private constructor. All arguments are optional, and can be {@code null}. * Package-private constructor. All arguments are optional, and can be {@code null}.
* @param scheme the scheme * @param scheme the scheme
@ -178,34 +181,33 @@ final class HierarchicalUriComponents extends UriComponents {
/** /**
* Encode all URI components using their specific encoding rules and return * Encode all URI components using their specific encoding rules and return
* the result as a new {@code UriComponents} instance. * the result as a new {@code UriComponents} instance.
* @param encoding the encoding of the values contained in this map * @param charset the encoding of the values contained in this map
* @return the encoded uri components * @return the encoded uri components
* @throws UnsupportedEncodingException if the given encoding is not supported * @throws UnsupportedEncodingException if the given encoding is not supported
*/ */
@Override @Override
public HierarchicalUriComponents encode(String encoding) throws UnsupportedEncodingException { public HierarchicalUriComponents encode(Charset charset) throws UnsupportedEncodingException {
if (this.encoded) { if (this.encoded) {
return this; return this;
} }
Assert.hasLength(encoding, "Encoding must not be empty"); String schemeTo = encodeUriComponent(getScheme(), charset, Type.SCHEME);
String schemeTo = encodeUriComponent(getScheme(), encoding, Type.SCHEME); String userInfoTo = encodeUriComponent(this.userInfo, charset, Type.USER_INFO);
String userInfoTo = encodeUriComponent(this.userInfo, encoding, Type.USER_INFO); String hostTo = encodeUriComponent(this.host, charset, getHostType());
String hostTo = encodeUriComponent(this.host, encoding, getHostType()); PathComponent pathTo = this.path.encode(charset);
PathComponent pathTo = this.path.encode(encoding); MultiValueMap<String, String> paramsTo = encodeQueryParams(charset);
MultiValueMap<String, String> paramsTo = encodeQueryParams(encoding); String fragmentTo = encodeUriComponent(this.getFragment(), charset, Type.FRAGMENT);
String fragmentTo = encodeUriComponent(this.getFragment(), encoding, Type.FRAGMENT);
return new HierarchicalUriComponents(schemeTo, userInfoTo, hostTo, this.port, return new HierarchicalUriComponents(schemeTo, userInfoTo, hostTo, this.port,
pathTo, paramsTo, fragmentTo, true, false); pathTo, paramsTo, fragmentTo, true, false);
} }
private MultiValueMap<String, String> encodeQueryParams(String encoding) throws UnsupportedEncodingException { private MultiValueMap<String, String> encodeQueryParams(Charset charset) throws UnsupportedEncodingException {
int size = this.queryParams.size(); int size = this.queryParams.size();
MultiValueMap<String, String> result = new LinkedMultiValueMap<>(size); MultiValueMap<String, String> result = new LinkedMultiValueMap<>(size);
for (Map.Entry<String, List<String>> entry : this.queryParams.entrySet()) { for (Map.Entry<String, List<String>> entry : this.queryParams.entrySet()) {
String name = encodeUriComponent(entry.getKey(), encoding, Type.QUERY_PARAM); String name = encodeUriComponent(entry.getKey(), charset, Type.QUERY_PARAM);
List<String> values = new ArrayList<>(entry.getValue().size()); List<String> values = new ArrayList<>(entry.getValue().size());
for (String value : entry.getValue()) { for (String value : entry.getValue()) {
values.add(encodeUriComponent(value, encoding, Type.QUERY_PARAM)); values.add(encodeUriComponent(value, charset, Type.QUERY_PARAM));
} }
result.put(name, values); result.put(name, values);
} }
@ -221,15 +223,25 @@ final class HierarchicalUriComponents extends UriComponents {
* @return the encoded URI * @return the encoded URI
* @throws IllegalArgumentException when the given uri parameter is not a valid URI * @throws IllegalArgumentException when the given uri parameter is not a valid URI
*/ */
static String encodeUriComponent(String source, String encoding, Type type) static String encodeUriComponent(String source, String encoding, Type type) {
throws UnsupportedEncodingException { return encodeUriComponent(source, Charset.forName(encoding), type);
}
/**
* Encode the given source into an encoded String using the rules specified
* by the given component and with the given options.
* @param source the source string
* @param charset the encoding of the source string
* @param type the URI component for the source
* @return the encoded URI
* @throws IllegalArgumentException when the given uri parameter is not a valid URI
*/
static String encodeUriComponent(String source, Charset charset, Type type) {
if (source == null) { if (source == null) {
return null; return null;
} }
Assert.hasLength(encoding, "Encoding must not be empty"); byte[] bytes = encodeBytes(source.getBytes(charset), type);
byte[] bytes = encodeBytes(source.getBytes(encoding), type); return new String(bytes, StandardCharsets.US_ASCII);
return new String(bytes, "US-ASCII");
} }
private static byte[] encodeBytes(byte[] source, Type type) { private static byte[] encodeBytes(byte[] source, Type type) {
@ -637,7 +649,7 @@ final class HierarchicalUriComponents extends UriComponents {
List<String> getPathSegments(); List<String> getPathSegments();
PathComponent encode(String encoding) throws UnsupportedEncodingException; PathComponent encode(Charset charset) throws UnsupportedEncodingException;
void verify(); void verify();
@ -666,15 +678,16 @@ final class HierarchicalUriComponents extends UriComponents {
@Override @Override
public List<String> getPathSegments() { public List<String> getPathSegments() {
String delimiter = new String(new char[]{PATH_DELIMITER}); String delimiter = new String(new char[] {PATH_DELIMITER});
String[] pathSegments = StringUtils.tokenizeToStringArray(path, delimiter); String[] pathSegments = StringUtils.tokenizeToStringArray(path, delimiter);
return Collections.unmodifiableList(Arrays.asList(pathSegments)); return Collections.unmodifiableList(Arrays.asList(pathSegments));
} }
@Override @Override
public PathComponent encode(String encoding) throws UnsupportedEncodingException { public PathComponent encode(Charset charset) throws UnsupportedEncodingException {
String encodedPath = encodeUriComponent(getPath(),encoding, Type.PATH); String encodedPath = encodeUriComponent(getPath(), charset, Type.PATH);
return new FullPathComponent(encodedPath); } return new FullPathComponent(encodedPath);
}
@Override @Override
public void verify() { public void verify() {
@ -737,11 +750,11 @@ final class HierarchicalUriComponents extends UriComponents {
} }
@Override @Override
public PathComponent encode(String encoding) throws UnsupportedEncodingException { public PathComponent encode(Charset charset) throws UnsupportedEncodingException {
List<String> pathSegments = getPathSegments(); List<String> pathSegments = getPathSegments();
List<String> encodedPathSegments = new ArrayList<>(pathSegments.size()); List<String> encodedPathSegments = new ArrayList<>(pathSegments.size());
for (String pathSegment : pathSegments) { for (String pathSegment : pathSegments) {
String encodedPathSegment = encodeUriComponent(pathSegment, encoding, Type.PATH_SEGMENT); String encodedPathSegment = encodeUriComponent(pathSegment, charset, Type.PATH_SEGMENT);
encodedPathSegments.add(encodedPathSegment); encodedPathSegments.add(encodedPathSegment);
} }
return new PathSegmentComponent(encodedPathSegments); return new PathSegmentComponent(encodedPathSegments);
@ -814,10 +827,10 @@ final class HierarchicalUriComponents extends UriComponents {
} }
@Override @Override
public PathComponent encode(String encoding) throws UnsupportedEncodingException { public PathComponent encode(Charset charset) throws UnsupportedEncodingException {
List<PathComponent> encodedComponents = new ArrayList<>(this.pathComponents.size()); List<PathComponent> encodedComponents = new ArrayList<>(this.pathComponents.size());
for (PathComponent pathComponent : this.pathComponents) { for (PathComponent pathComponent : this.pathComponents) {
encodedComponents.add(pathComponent.encode(encoding)); encodedComponents.add(pathComponent.encode(charset));
} }
return new PathComponentComposite(encodedComponents); return new PathComponentComposite(encodedComponents);
} }
@ -860,7 +873,7 @@ final class HierarchicalUriComponents extends UriComponents {
return Collections.emptyList(); return Collections.emptyList();
} }
@Override @Override
public PathComponent encode(String encoding) throws UnsupportedEncodingException { public PathComponent encode(Charset charset) throws UnsupportedEncodingException {
return this; return this;
} }
@Override @Override

View File

@ -19,6 +19,7 @@ package org.springframework.web.util;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -89,7 +90,7 @@ final class OpaqueUriComponents extends UriComponents {
} }
@Override @Override
public UriComponents encode(String encoding) throws UnsupportedEncodingException { public UriComponents encode(Charset charset) throws UnsupportedEncodingException {
return this; return this;
} }

View File

@ -19,6 +19,8 @@ package org.springframework.web.util;
import java.io.Serializable; import java.io.Serializable;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URI; import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -42,8 +44,6 @@ import org.springframework.util.MultiValueMap;
@SuppressWarnings("serial") @SuppressWarnings("serial")
public abstract class UriComponents implements Serializable { public abstract class UriComponents implements Serializable {
private static final String DEFAULT_ENCODING = "UTF-8";
/** Captures URI template variable names. */ /** Captures URI template variable names. */
private static final Pattern NAMES_PATTERN = Pattern.compile("\\{([^/]+?)\\}"); private static final Pattern NAMES_PATTERN = Pattern.compile("\\{([^/]+?)\\}");
@ -123,7 +123,7 @@ public abstract class UriComponents implements Serializable {
*/ */
public final UriComponents encode() { public final UriComponents encode() {
try { try {
return encode(DEFAULT_ENCODING); return encode(StandardCharsets.UTF_8);
} }
catch (UnsupportedEncodingException ex) { catch (UnsupportedEncodingException ex) {
// should not occur // should not occur
@ -134,11 +134,11 @@ public abstract class UriComponents implements Serializable {
/** /**
* Encode all URI components using their specific encoding rules, and * Encode all URI components using their specific encoding rules, and
* returns the result as a new {@code UriComponents} instance. * returns the result as a new {@code UriComponents} instance.
* @param encoding the encoding of the values contained in this map * @param charset the encoding of the values contained in this map
* @return the encoded URI components * @return the encoded URI components
* @throws UnsupportedEncodingException if the given encoding is not supported * @throws UnsupportedEncodingException if the given encoding is not supported
*/ */
public abstract UriComponents encode(String encoding) throws UnsupportedEncodingException; public abstract UriComponents encode(Charset charset) throws UnsupportedEncodingException;
/** /**
* Replace all URI template variables with the values from a given map. * Replace all URI template variables with the values from a given map.

View File

@ -19,6 +19,7 @@ package org.springframework.http;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
@ -32,7 +33,7 @@ import java.util.TimeZone;
import org.hamcrest.Matchers; import org.hamcrest.Matchers;
import org.junit.Test; import org.junit.Test;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
/** /**
@ -76,7 +77,7 @@ public class HttpHeadersTests {
@Test @Test
public void acceptCharsets() { public void acceptCharsets() {
Charset charset1 = Charset.forName("UTF-8"); Charset charset1 = StandardCharsets.UTF_8;
Charset charset2 = Charset.forName("ISO-8859-1"); Charset charset2 = Charset.forName("ISO-8859-1");
List<Charset> charsets = new ArrayList<>(2); List<Charset> charsets = new ArrayList<>(2);
charsets.add(charset1); charsets.add(charset1);
@ -89,7 +90,7 @@ public class HttpHeadersTests {
@Test @Test
public void acceptCharsetWildcard() { public void acceptCharsetWildcard() {
headers.set("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); headers.set("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
assertEquals("Invalid Accept header", Arrays.asList(Charset.forName("ISO-8859-1"), Charset.forName("UTF-8")), assertEquals("Invalid Accept header", Arrays.asList(Charset.forName("ISO-8859-1"), StandardCharsets.UTF_8),
headers.getAcceptCharset()); headers.getAcceptCharset());
} }
@ -111,7 +112,7 @@ public class HttpHeadersTests {
@Test @Test
public void contentType() { public void contentType() {
MediaType contentType = new MediaType("text", "html", Charset.forName("UTF-8")); MediaType contentType = new MediaType("text", "html", StandardCharsets.UTF_8);
headers.setContentType(contentType); headers.setContentType(contentType);
assertEquals("Invalid Content-Type header", contentType, headers.getContentType()); assertEquals("Invalid Content-Type header", contentType, headers.getContentType());
assertEquals("Invalid Content-Type header", "text/html;charset=UTF-8", headers.getFirst("Content-Type")); assertEquals("Invalid Content-Type header", "text/html;charset=UTF-8", headers.getFirst("Content-Type"));

View File

@ -17,7 +17,7 @@
package org.springframework.http; package org.springframework.http;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -112,7 +112,7 @@ public class HttpRangeTests {
@Test @Test
public void toResourceRegion() { public void toResourceRegion() {
byte[] bytes = "Spring Framework".getBytes(Charset.forName("UTF-8")); byte[] bytes = "Spring Framework".getBytes(StandardCharsets.UTF_8);
ByteArrayResource resource = new ByteArrayResource(bytes); ByteArrayResource resource = new ByteArrayResource(bytes);
HttpRange range = HttpRange.createByteRange(0, 5); HttpRange range = HttpRange.createByteRange(0, 5);
ResourceRegion region = range.toResourceRegion(resource); ResourceRegion region = range.toResourceRegion(resource);

View File

@ -19,6 +19,7 @@ package org.springframework.http;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -94,7 +95,6 @@ public class RequestEntityTests {
@Test @Test
public void headers() throws URISyntaxException { public void headers() throws URISyntaxException {
MediaType accept = MediaType.TEXT_PLAIN; MediaType accept = MediaType.TEXT_PLAIN;
Charset charset = Charset.forName("UTF-8");
long ifModifiedSince = 12345L; long ifModifiedSince = 12345L;
String ifNoneMatch = "\"foo\""; String ifNoneMatch = "\"foo\"";
long contentLength = 67890; long contentLength = 67890;
@ -102,7 +102,7 @@ public class RequestEntityTests {
RequestEntity<Void> responseEntity = RequestEntity.post(new URI("http://example.com")). RequestEntity<Void> responseEntity = RequestEntity.post(new URI("http://example.com")).
accept(accept). accept(accept).
acceptCharset(charset). acceptCharset(StandardCharsets.UTF_8).
ifModifiedSince(ifModifiedSince). ifModifiedSince(ifModifiedSince).
ifNoneMatch(ifNoneMatch). ifNoneMatch(ifNoneMatch).
contentLength(contentLength). contentLength(contentLength).

View File

@ -16,68 +16,66 @@
package org.springframework.http.client; package org.springframework.http.client;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.util.StreamUtils; import org.springframework.util.StreamUtils;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/** /**
* @author Brian Clozel * @author Brian Clozel
*/ */
public class SimpleClientHttpResponseTests { public class SimpleClientHttpResponseTests {
private final Charset UTF8 = Charset.forName("UTF-8");
private SimpleClientHttpResponse response; private SimpleClientHttpResponse response;
private HttpURLConnection connection; private HttpURLConnection connection;
@Before @Before
public void setup() throws Exception { public void setup() throws Exception {
this.connection = mock(HttpURLConnection.class); this.connection = mock(HttpURLConnection.class);
this.response = new SimpleClientHttpResponse(this.connection); this.response = new SimpleClientHttpResponse(this.connection);
} }
// SPR-14040
@Test @Test // SPR-14040
public void shouldNotCloseConnectionWhenResponseClosed() throws Exception { public void shouldNotCloseConnectionWhenResponseClosed() throws Exception {
TestByteArrayInputStream is = new TestByteArrayInputStream("Spring".getBytes(UTF8)); TestByteArrayInputStream is = new TestByteArrayInputStream("Spring".getBytes(StandardCharsets.UTF_8));
given(this.connection.getErrorStream()).willReturn(null); given(this.connection.getErrorStream()).willReturn(null);
given(this.connection.getInputStream()).willReturn(is); given(this.connection.getInputStream()).willReturn(is);
InputStream responseStream = this.response.getBody(); InputStream responseStream = this.response.getBody();
assertThat(StreamUtils.copyToString(responseStream, UTF8), is("Spring")); assertThat(StreamUtils.copyToString(responseStream, StandardCharsets.UTF_8), is("Spring"));
this.response.close(); this.response.close();
assertTrue(is.isClosed()); assertTrue(is.isClosed());
verify(this.connection, never()).disconnect(); verify(this.connection, never()).disconnect();
} }
// SPR-14040 @Test // SPR-14040
@Test
public void shouldDrainStreamWhenResponseClosed() throws Exception { public void shouldDrainStreamWhenResponseClosed() throws Exception {
byte[] buf = new byte[6]; byte[] buf = new byte[6];
TestByteArrayInputStream is = new TestByteArrayInputStream("SpringSpring".getBytes(UTF8)); TestByteArrayInputStream is = new TestByteArrayInputStream("SpringSpring".getBytes(StandardCharsets.UTF_8));
given(this.connection.getErrorStream()).willReturn(null); given(this.connection.getErrorStream()).willReturn(null);
given(this.connection.getInputStream()).willReturn(is); given(this.connection.getInputStream()).willReturn(is);
InputStream responseStream = this.response.getBody(); InputStream responseStream = this.response.getBody();
responseStream.read(buf); responseStream.read(buf);
assertThat(new String(buf, UTF8), is("Spring")); assertThat(new String(buf, StandardCharsets.UTF_8), is("Spring"));
assertThat(is.available(), is(6)); assertThat(is.available(), is(6));
this.response.close(); this.response.close();
@ -86,16 +84,15 @@ public class SimpleClientHttpResponseTests {
verify(this.connection, never()).disconnect(); verify(this.connection, never()).disconnect();
} }
// SPR-14040 @Test // SPR-14040
@Test
public void shouldDrainErrorStreamWhenResponseClosed() throws Exception { public void shouldDrainErrorStreamWhenResponseClosed() throws Exception {
byte[] buf = new byte[6]; byte[] buf = new byte[6];
TestByteArrayInputStream is = new TestByteArrayInputStream("SpringSpring".getBytes(UTF8)); TestByteArrayInputStream is = new TestByteArrayInputStream("SpringSpring".getBytes(StandardCharsets.UTF_8));
given(this.connection.getErrorStream()).willReturn(is); given(this.connection.getErrorStream()).willReturn(is);
InputStream responseStream = this.response.getBody(); InputStream responseStream = this.response.getBody();
responseStream.read(buf); responseStream.read(buf);
assertThat(new String(buf, UTF8), is("Spring")); assertThat(new String(buf, StandardCharsets.UTF_8), is("Spring"));
assertThat(is.available(), is(6)); assertThat(is.available(), is(6));
this.response.close(); this.response.close();

View File

@ -21,8 +21,8 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.StringReader; import java.io.StringReader;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import javax.xml.transform.Source; import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamSource;
@ -31,8 +31,6 @@ import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload; import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.RequestContext; import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
@ -47,14 +45,10 @@ import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertEquals; import static org.hamcrest.CoreMatchers.endsWith;
import static org.junit.Assert.assertFalse; import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.*;
import static org.junit.Assert.assertNull; import static org.mockito.BDDMockito.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.BDDMockito.never;
import static org.mockito.BDDMockito.verify;
/** /**
* @author Arjen Poutsma * @author Arjen Poutsma
@ -62,16 +56,7 @@ import static org.mockito.BDDMockito.verify;
*/ */
public class FormHttpMessageConverterTests { public class FormHttpMessageConverterTests {
public static final Charset UTF_8 = Charset.forName("UTF-8"); private final FormHttpMessageConverter converter = new AllEncompassingFormHttpMessageConverter();
private FormHttpMessageConverter converter;
@Before
public void setUp() {
this.converter = new AllEncompassingFormHttpMessageConverter();
}
@Test @Test
@ -89,7 +74,7 @@ public class FormHttpMessageConverterTests {
assertTrue(this.converter.canWrite(MultiValueMap.class, assertTrue(this.converter.canWrite(MultiValueMap.class,
new MediaType("multipart", "form-data"))); new MediaType("multipart", "form-data")));
assertTrue(this.converter.canWrite(MultiValueMap.class, assertTrue(this.converter.canWrite(MultiValueMap.class,
new MediaType("multipart", "form-data", Charset.forName("UTF-8")))); new MediaType("multipart", "form-data", StandardCharsets.UTF_8)));
assertTrue(this.converter.canWrite(MultiValueMap.class, MediaType.ALL)); assertTrue(this.converter.canWrite(MultiValueMap.class, MediaType.ALL));
} }
@ -121,7 +106,7 @@ public class FormHttpMessageConverterTests {
this.converter.write(body, MediaType.APPLICATION_FORM_URLENCODED, outputMessage); this.converter.write(body, MediaType.APPLICATION_FORM_URLENCODED, outputMessage);
assertEquals("Invalid result", "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3", assertEquals("Invalid result", "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3",
outputMessage.getBodyAsString(UTF_8)); outputMessage.getBodyAsString(StandardCharsets.UTF_8));
assertEquals("Invalid content-type", new MediaType("application", "x-www-form-urlencoded"), assertEquals("Invalid content-type", new MediaType("application", "x-www-form-urlencoded"),
outputMessage.getHeaders().getContentType()); outputMessage.getHeaders().getContentType());
assertEquals("Invalid content-length", outputMessage.getBodyAsBytes().length, assertEquals("Invalid content-length", outputMessage.getBodyAsBytes().length,
@ -155,8 +140,8 @@ public class FormHttpMessageConverterTests {
parts.add("xml", entity); parts.add("xml", entity);
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
this.converter.setMultipartCharset(UTF_8); this.converter.setMultipartCharset(StandardCharsets.UTF_8);
this.converter.write(parts, new MediaType("multipart", "form-data", UTF_8), outputMessage); this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);
final MediaType contentType = outputMessage.getHeaders().getContentType(); final MediaType contentType = outputMessage.getHeaders().getContentType();
assertNotNull("No boundary found", contentType.getParameter("boundary")); assertNotNull("No boundary found", contentType.getParameter("boundary"));
@ -218,8 +203,8 @@ public class FormHttpMessageConverterTests {
parts.add("part2", entity); parts.add("part2", entity);
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
this.converter.setMultipartCharset(UTF_8); this.converter.setMultipartCharset(StandardCharsets.UTF_8);
this.converter.write(parts, new MediaType("multipart", "form-data", UTF_8), outputMessage); this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);
final MediaType contentType = outputMessage.getHeaders().getContentType(); final MediaType contentType = outputMessage.getHeaders().getContentType();
assertNotNull("No boundary found", contentType.getParameter("boundary")); assertNotNull("No boundary found", contentType.getParameter("boundary"));

View File

@ -17,7 +17,7 @@
package org.springframework.http.converter; package org.springframework.http.converter;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -82,7 +82,7 @@ public class ResourceRegionHttpMessageConverterTests {
assertThat(headers.getContentLength(), is(6L)); assertThat(headers.getContentLength(), is(6L));
assertThat(headers.get(HttpHeaders.CONTENT_RANGE).size(), is(1)); assertThat(headers.get(HttpHeaders.CONTENT_RANGE).size(), is(1));
assertThat(headers.get(HttpHeaders.CONTENT_RANGE).get(0), is("bytes 0-5/39")); assertThat(headers.get(HttpHeaders.CONTENT_RANGE).get(0), is("bytes 0-5/39"));
assertThat(outputMessage.getBodyAsString(Charset.forName("UTF-8")), is("Spring")); assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8), is("Spring"));
} }
@Test @Test
@ -97,7 +97,7 @@ public class ResourceRegionHttpMessageConverterTests {
assertThat(headers.getContentLength(), is(32L)); assertThat(headers.getContentLength(), is(32L));
assertThat(headers.get(HttpHeaders.CONTENT_RANGE).size(), is(1)); assertThat(headers.get(HttpHeaders.CONTENT_RANGE).size(), is(1));
assertThat(headers.get(HttpHeaders.CONTENT_RANGE).get(0), is("bytes 7-38/39")); assertThat(headers.get(HttpHeaders.CONTENT_RANGE).get(0), is("bytes 7-38/39"));
assertThat(outputMessage.getBodyAsString(Charset.forName("UTF-8")), is("Framework test resource content.")); assertThat(outputMessage.getBodyAsString(StandardCharsets.UTF_8), is("Framework test resource content."));
} }
@Test @Test
@ -115,7 +115,7 @@ public class ResourceRegionHttpMessageConverterTests {
HttpHeaders headers = outputMessage.getHeaders(); HttpHeaders headers = outputMessage.getHeaders();
assertThat(headers.getContentType().toString(), Matchers.startsWith("multipart/byteranges;boundary=")); assertThat(headers.getContentType().toString(), Matchers.startsWith("multipart/byteranges;boundary="));
String boundary = "--" + headers.getContentType().toString().substring(30); String boundary = "--" + headers.getContentType().toString().substring(30);
String content = outputMessage.getBodyAsString(Charset.forName("UTF-8")); String content = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
String[] ranges = StringUtils.tokenizeToStringArray(content, "\r\n", false, true); String[] ranges = StringUtils.tokenizeToStringArray(content, "\r\n", false, true);
assertThat(ranges[0], is(boundary)); assertThat(ranges[0], is(boundary));

View File

@ -18,6 +18,7 @@ package org.springframework.http.converter;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -35,10 +36,7 @@ import static org.junit.Assert.*;
*/ */
public class StringHttpMessageConverterTests { public class StringHttpMessageConverterTests {
public static final Charset UTF_8 = Charset.forName("UTF-8"); public static final MediaType TEXT_PLAIN_UTF_8 = new MediaType("text", "plain", StandardCharsets.UTF_8);
public static final MediaType TEXT_PLAIN_UTF_8 = new MediaType("text", "plain", UTF_8);
private StringHttpMessageConverter converter; private StringHttpMessageConverter converter;
@ -66,7 +64,7 @@ public class StringHttpMessageConverterTests {
@Test @Test
public void read() throws IOException { public void read() throws IOException {
String body = "Hello World"; String body = "Hello World";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(UTF_8)); MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8));
inputMessage.getHeaders().setContentType(TEXT_PLAIN_UTF_8); inputMessage.getHeaders().setContentType(TEXT_PLAIN_UTF_8);
String result = this.converter.read(String.class, inputMessage); String result = this.converter.read(String.class, inputMessage);
@ -92,15 +90,13 @@ public class StringHttpMessageConverterTests {
this.converter.write(body, TEXT_PLAIN_UTF_8, this.outputMessage); this.converter.write(body, TEXT_PLAIN_UTF_8, this.outputMessage);
HttpHeaders headers = this.outputMessage.getHeaders(); HttpHeaders headers = this.outputMessage.getHeaders();
assertEquals(body, this.outputMessage.getBodyAsString(UTF_8)); assertEquals(body, this.outputMessage.getBodyAsString(StandardCharsets.UTF_8));
assertEquals(TEXT_PLAIN_UTF_8, headers.getContentType()); assertEquals(TEXT_PLAIN_UTF_8, headers.getContentType());
assertEquals(body.getBytes(UTF_8).length, headers.getContentLength()); assertEquals(body.getBytes(StandardCharsets.UTF_8).length, headers.getContentLength());
assertFalse(headers.getAcceptCharset().isEmpty()); assertFalse(headers.getAcceptCharset().isEmpty());
} }
// SPR-8867 @Test // SPR-8867
@Test
public void writeOverrideRequestedContentType() throws IOException { public void writeOverrideRequestedContentType() throws IOException {
String body = "H\u00e9llo W\u00f6rld"; String body = "H\u00e9llo W\u00f6rld";
MediaType requestedContentType = new MediaType("text", "html"); MediaType requestedContentType = new MediaType("text", "html");
@ -109,9 +105,9 @@ public class StringHttpMessageConverterTests {
headers.setContentType(TEXT_PLAIN_UTF_8); headers.setContentType(TEXT_PLAIN_UTF_8);
this.converter.write(body, requestedContentType, this.outputMessage); this.converter.write(body, requestedContentType, this.outputMessage);
assertEquals(body, this.outputMessage.getBodyAsString(UTF_8)); assertEquals(body, this.outputMessage.getBodyAsString(StandardCharsets.UTF_8));
assertEquals(TEXT_PLAIN_UTF_8, headers.getContentType()); assertEquals(TEXT_PLAIN_UTF_8, headers.getContentType());
assertEquals(body.getBytes(UTF_8).length, headers.getContentLength()); assertEquals(body.getBytes(StandardCharsets.UTF_8).length, headers.getContentLength());
assertFalse(headers.getAcceptCharset().isEmpty()); assertFalse(headers.getAcceptCharset().isEmpty());
} }

View File

@ -19,6 +19,7 @@ package org.springframework.http.converter.feed;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -44,32 +45,31 @@ public class AtomFeedHttpMessageConverterTests {
private AtomFeedHttpMessageConverter converter; private AtomFeedHttpMessageConverter converter;
private Charset utf8;
@Before @Before
public void setUp() { public void setUp() {
utf8 = Charset.forName("UTF-8");
converter = new AtomFeedHttpMessageConverter(); converter = new AtomFeedHttpMessageConverter();
XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreWhitespace(true);
} }
@Test @Test
public void canRead() { public void canRead() {
assertTrue(converter.canRead(Feed.class, new MediaType("application", "atom+xml"))); assertTrue(converter.canRead(Feed.class, new MediaType("application", "atom+xml")));
assertTrue(converter.canRead(Feed.class, new MediaType("application", "atom+xml", utf8))); assertTrue(converter.canRead(Feed.class, new MediaType("application", "atom+xml", StandardCharsets.UTF_8)));
} }
@Test @Test
public void canWrite() { public void canWrite() {
assertTrue(converter.canWrite(Feed.class, new MediaType("application", "atom+xml"))); assertTrue(converter.canWrite(Feed.class, new MediaType("application", "atom+xml")));
assertTrue(converter.canWrite(Feed.class, new MediaType("application", "atom+xml", Charset.forName("UTF-8")))); assertTrue(converter.canWrite(Feed.class, new MediaType("application", "atom+xml", StandardCharsets.UTF_8)));
} }
@Test @Test
public void read() throws IOException { public void read() throws IOException {
InputStream is = getClass().getResourceAsStream("atom.xml"); InputStream is = getClass().getResourceAsStream("atom.xml");
MockHttpInputMessage inputMessage = new MockHttpInputMessage(is); MockHttpInputMessage inputMessage = new MockHttpInputMessage(is);
inputMessage.getHeaders().setContentType(new MediaType("application", "atom+xml", utf8)); inputMessage.getHeaders().setContentType(new MediaType("application", "atom+xml", StandardCharsets.UTF_8));
Feed result = converter.read(Feed.class, inputMessage); Feed result = converter.read(Feed.class, inputMessage);
assertEquals("title", result.getTitle()); assertEquals("title", result.getTitle());
assertEquals("subtitle", result.getSubtitle().getValue()); assertEquals("subtitle", result.getSubtitle().getValue());
@ -106,12 +106,12 @@ public class AtomFeedHttpMessageConverterTests {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(feed, null, outputMessage); converter.write(feed, null, outputMessage);
assertEquals("Invalid content-type", new MediaType("application", "atom+xml", utf8), assertEquals("Invalid content-type", new MediaType("application", "atom+xml", StandardCharsets.UTF_8),
outputMessage.getHeaders().getContentType()); outputMessage.getHeaders().getContentType());
String expected = "<feed xmlns=\"http://www.w3.org/2005/Atom\">" + "<title>title</title>" + String expected = "<feed xmlns=\"http://www.w3.org/2005/Atom\">" + "<title>title</title>" +
"<entry><id>id1</id><title>title1</title></entry>" + "<entry><id>id1</id><title>title1</title></entry>" +
"<entry><id>id2</id><title>title2</title></entry></feed>"; "<entry><id>id2</id><title>title2</title></entry></feed>";
assertXMLEqual(expected, outputMessage.getBodyAsString(utf8)); assertXMLEqual(expected, outputMessage.getBodyAsString(StandardCharsets.UTF_8));
} }
@Test @Test

View File

@ -19,6 +19,7 @@ package org.springframework.http.converter.feed;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -44,32 +45,31 @@ public class RssChannelHttpMessageConverterTests {
private RssChannelHttpMessageConverter converter; private RssChannelHttpMessageConverter converter;
private Charset utf8;
@Before @Before
public void setUp() { public void setUp() {
utf8 = Charset.forName("UTF-8");
converter = new RssChannelHttpMessageConverter(); converter = new RssChannelHttpMessageConverter();
XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreWhitespace(true);
} }
@Test @Test
public void canRead() { public void canRead() {
assertTrue(converter.canRead(Channel.class, new MediaType("application", "rss+xml"))); assertTrue(converter.canRead(Channel.class, new MediaType("application", "rss+xml")));
assertTrue(converter.canRead(Channel.class, new MediaType("application", "rss+xml", utf8))); assertTrue(converter.canRead(Channel.class, new MediaType("application", "rss+xml", StandardCharsets.UTF_8)));
} }
@Test @Test
public void canWrite() { public void canWrite() {
assertTrue(converter.canWrite(Channel.class, new MediaType("application", "rss+xml"))); assertTrue(converter.canWrite(Channel.class, new MediaType("application", "rss+xml")));
assertTrue(converter.canWrite(Channel.class, new MediaType("application", "rss+xml", Charset.forName("UTF-8")))); assertTrue(converter.canWrite(Channel.class, new MediaType("application", "rss+xml", StandardCharsets.UTF_8)));
} }
@Test @Test
public void read() throws IOException { public void read() throws IOException {
InputStream is = getClass().getResourceAsStream("rss.xml"); InputStream is = getClass().getResourceAsStream("rss.xml");
MockHttpInputMessage inputMessage = new MockHttpInputMessage(is); MockHttpInputMessage inputMessage = new MockHttpInputMessage(is);
inputMessage.getHeaders().setContentType(new MediaType("application", "rss+xml", utf8)); inputMessage.getHeaders().setContentType(new MediaType("application", "rss+xml", StandardCharsets.UTF_8));
Channel result = converter.read(Channel.class, inputMessage); Channel result = converter.read(Channel.class, inputMessage);
assertEquals("title", result.getTitle()); assertEquals("title", result.getTitle());
assertEquals("http://example.com", result.getLink()); assertEquals("http://example.com", result.getLink());
@ -106,14 +106,14 @@ public class RssChannelHttpMessageConverterTests {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(channel, null, outputMessage); converter.write(channel, null, outputMessage);
assertEquals("Invalid content-type", new MediaType("application", "rss+xml", utf8), assertEquals("Invalid content-type", new MediaType("application", "rss+xml", StandardCharsets.UTF_8),
outputMessage.getHeaders().getContentType()); outputMessage.getHeaders().getContentType());
String expected = "<rss version=\"2.0\">" + String expected = "<rss version=\"2.0\">" +
"<channel><title>title</title><link>http://example.com</link><description>description</description>" + "<channel><title>title</title><link>http://example.com</link><description>description</description>" +
"<item><title>title1</title></item>" + "<item><title>title1</title></item>" +
"<item><title>title2</title></item>" + "<item><title>title2</title></item>" +
"</channel></rss>"; "</channel></rss>";
assertXMLEqual(expected, outputMessage.getBodyAsString(utf8)); assertXMLEqual(expected, outputMessage.getBodyAsString(StandardCharsets.UTF_8));
} }
@Test @Test

View File

@ -19,6 +19,7 @@ package org.springframework.http.converter.json;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -42,8 +43,6 @@ import static org.junit.Assert.*;
*/ */
public class GsonHttpMessageConverterTests { public class GsonHttpMessageConverterTests {
private static final Charset UTF8 = Charset.forName("UTF-8");
private GsonHttpMessageConverter converter = new GsonHttpMessageConverter(); private GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
@ -118,7 +117,7 @@ public class GsonHttpMessageConverterTests {
body.setBool(true); body.setBool(true);
body.setBytes(new byte[]{0x1, 0x2}); body.setBytes(new byte[]{0x1, 0x2});
this.converter.write(body, null, outputMessage); this.converter.write(body, null, outputMessage);
Charset utf8 = Charset.forName("UTF-8"); Charset utf8 = StandardCharsets.UTF_8;
String result = outputMessage.getBodyAsString(utf8); String result = outputMessage.getBodyAsString(utf8);
assertTrue(result.contains("\"string\":\"Foo\"")); assertTrue(result.contains("\"string\":\"Foo\""));
assertTrue(result.contains("\"number\":42")); assertTrue(result.contains("\"number\":42"));
@ -166,8 +165,7 @@ public class GsonHttpMessageConverterTests {
}; };
String body = "[{\"bytes\":[1,2],\"array\":[\"Foo\",\"Bar\"]," + String body = "[{\"bytes\":[1,2],\"array\":[\"Foo\",\"Bar\"]," +
"\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]"; "\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]";
MockHttpInputMessage inputMessage = new MockHttpInputMessage( MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8));
body.getBytes(UTF8));
inputMessage.getHeaders().setContentType(new MediaType("application", "json")); inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
List<MyBean> results = (List<MyBean>) converter.read(List.class, inputMessage); List<MyBean> results = (List<MyBean>) converter.read(List.class, inputMessage);
@ -189,8 +187,7 @@ public class GsonHttpMessageConverterTests {
String body = "[{\"bytes\":[1,2],\"array\":[\"Foo\",\"Bar\"]," + String body = "[{\"bytes\":[1,2],\"array\":[\"Foo\",\"Bar\"]," +
"\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]"; "\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]";
MockHttpInputMessage inputMessage = new MockHttpInputMessage( MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8));
body.getBytes(UTF8));
inputMessage.getHeaders().setContentType(new MediaType("application", "json")); inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
GsonHttpMessageConverter converter = new GsonHttpMessageConverter(); GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
@ -210,7 +207,7 @@ public class GsonHttpMessageConverterTests {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
this.converter.setPrefixJson(true); this.converter.setPrefixJson(true);
this.converter.writeInternal("foo", null, outputMessage); this.converter.writeInternal("foo", null, outputMessage);
assertEquals(")]}', \"foo\"", outputMessage.getBodyAsString(UTF8)); assertEquals(")]}', \"foo\"", outputMessage.getBodyAsString(StandardCharsets.UTF_8));
} }
@Test @Test
@ -218,7 +215,7 @@ public class GsonHttpMessageConverterTests {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
this.converter.setJsonPrefix(")))"); this.converter.setJsonPrefix(")))");
this.converter.writeInternal("foo", null, outputMessage); this.converter.writeInternal("foo", null, outputMessage);
assertEquals(")))\"foo\"", outputMessage.getBodyAsString(UTF8)); assertEquals(")))\"foo\"", outputMessage.getBodyAsString(StandardCharsets.UTF_8));
} }

View File

@ -19,6 +19,7 @@ package org.springframework.http.converter.json;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -118,15 +119,14 @@ public class MappingJackson2HttpMessageConverterTests {
body.setBool(true); body.setBool(true);
body.setBytes(new byte[]{0x1, 0x2}); body.setBytes(new byte[]{0x1, 0x2});
converter.write(body, null, outputMessage); converter.write(body, null, outputMessage);
Charset utf8 = Charset.forName("UTF-8"); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
String result = outputMessage.getBodyAsString(utf8);
assertTrue(result.contains("\"string\":\"Foo\"")); assertTrue(result.contains("\"string\":\"Foo\""));
assertTrue(result.contains("\"number\":42")); assertTrue(result.contains("\"number\":42"));
assertTrue(result.contains("fraction\":42.0")); assertTrue(result.contains("fraction\":42.0"));
assertTrue(result.contains("\"array\":[\"Foo\",\"Bar\"]")); assertTrue(result.contains("\"array\":[\"Foo\",\"Bar\"]"));
assertTrue(result.contains("\"bool\":true")); assertTrue(result.contains("\"bool\":true"));
assertTrue(result.contains("\"bytes\":\"AQI=\"")); assertTrue(result.contains("\"bytes\":\"AQI=\""));
assertEquals("Invalid content-type", new MediaType("application", "json", utf8), assertEquals("Invalid content-type", new MediaType("application", "json", StandardCharsets.UTF_8),
outputMessage.getHeaders().getContentType()); outputMessage.getHeaders().getContentType());
} }
@ -220,7 +220,7 @@ public class MappingJackson2HttpMessageConverterTests {
this.converter.setPrettyPrint(true); this.converter.setPrettyPrint(true);
this.converter.writeInternal(bean, null, outputMessage); this.converter.writeInternal(bean, null, outputMessage);
String result = outputMessage.getBodyAsString(Charset.forName("UTF-8")); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
assertEquals("{" + NEWLINE_SYSTEM_PROPERTY + " \"name\" : \"Jason\"" + NEWLINE_SYSTEM_PROPERTY + "}", result); assertEquals("{" + NEWLINE_SYSTEM_PROPERTY + " \"name\" : \"Jason\"" + NEWLINE_SYSTEM_PROPERTY + "}", result);
} }
@ -231,7 +231,7 @@ public class MappingJackson2HttpMessageConverterTests {
this.converter.setPrefixJson(true); this.converter.setPrefixJson(true);
this.converter.writeInternal("foo", null, outputMessage); this.converter.writeInternal("foo", null, outputMessage);
assertEquals(")]}', \"foo\"", outputMessage.getBodyAsString(Charset.forName("UTF-8"))); assertEquals(")]}', \"foo\"", outputMessage.getBodyAsString(StandardCharsets.UTF_8));
} }
@Test @Test
@ -240,7 +240,7 @@ public class MappingJackson2HttpMessageConverterTests {
this.converter.setJsonPrefix(")))"); this.converter.setJsonPrefix(")))");
this.converter.writeInternal("foo", null, outputMessage); this.converter.writeInternal("foo", null, outputMessage);
assertEquals(")))\"foo\"", outputMessage.getBodyAsString(Charset.forName("UTF-8"))); assertEquals(")))\"foo\"", outputMessage.getBodyAsString(StandardCharsets.UTF_8));
} }
@Test @Test
@ -255,7 +255,7 @@ public class MappingJackson2HttpMessageConverterTests {
jacksonValue.setSerializationView(MyJacksonView1.class); jacksonValue.setSerializationView(MyJacksonView1.class);
this.converter.writeInternal(jacksonValue, null, outputMessage); this.converter.writeInternal(jacksonValue, null, outputMessage);
String result = outputMessage.getBodyAsString(Charset.forName("UTF-8")); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
assertThat(result, containsString("\"withView1\":\"with\"")); assertThat(result, containsString("\"withView1\":\"with\""));
assertThat(result, not(containsString("\"withView2\":\"with\""))); assertThat(result, not(containsString("\"withView2\":\"with\"")));
assertThat(result, not(containsString("\"withoutView\":\"without\""))); assertThat(result, not(containsString("\"withoutView\":\"without\"")));
@ -274,7 +274,7 @@ public class MappingJackson2HttpMessageConverterTests {
jacksonValue.setFilters(filters); jacksonValue.setFilters(filters);
this.converter.writeInternal(jacksonValue, null, outputMessage); this.converter.writeInternal(jacksonValue, null, outputMessage);
String result = outputMessage.getBodyAsString(Charset.forName("UTF-8")); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
assertThat(result, containsString("\"property1\":\"value\"")); assertThat(result, containsString("\"property1\":\"value\""));
assertThat(result, not(containsString("\"property2\":\"value\""))); assertThat(result, not(containsString("\"property2\":\"value\"")));
} }
@ -288,7 +288,7 @@ public class MappingJackson2HttpMessageConverterTests {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
this.converter.writeInternal(jacksonValue, null, outputMessage); this.converter.writeInternal(jacksonValue, null, outputMessage);
assertEquals("/**/callback(\"foo\");", outputMessage.getBodyAsString(Charset.forName("UTF-8"))); assertEquals("/**/callback(\"foo\");", outputMessage.getBodyAsString(StandardCharsets.UTF_8));
} }
@Test @Test
@ -304,7 +304,7 @@ public class MappingJackson2HttpMessageConverterTests {
jacksonValue.setJsonpFunction("callback"); jacksonValue.setJsonpFunction("callback");
this.converter.writeInternal(jacksonValue, null, outputMessage); this.converter.writeInternal(jacksonValue, null, outputMessage);
String result = outputMessage.getBodyAsString(Charset.forName("UTF-8")); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
assertThat(result, startsWith("/**/callback(")); assertThat(result, startsWith("/**/callback("));
assertThat(result, endsWith(");")); assertThat(result, endsWith(");"));
assertThat(result, containsString("\"withView1\":\"with\"")); assertThat(result, containsString("\"withView1\":\"with\""));
@ -321,7 +321,7 @@ public class MappingJackson2HttpMessageConverterTests {
this.converter.writeInternal(bean, MyInterface.class, outputMessage); this.converter.writeInternal(bean, MyInterface.class, outputMessage);
String result = outputMessage.getBodyAsString(Charset.forName("UTF-8")); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
assertTrue(result.contains("\"string\":\"Foo\"")); assertTrue(result.contains("\"string\":\"Foo\""));
assertTrue(result.contains("\"number\":42")); assertTrue(result.contains("\"number\":42"));
} }
@ -343,7 +343,7 @@ public class MappingJackson2HttpMessageConverterTests {
this.converter.writeInternal(beans, typeReference.getType(), outputMessage); this.converter.writeInternal(beans, typeReference.getType(), outputMessage);
String result = outputMessage.getBodyAsString(Charset.forName("UTF-8")); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
assertTrue(result.contains("\"string\":\"Foo\"")); assertTrue(result.contains("\"string\":\"Foo\""));
assertTrue(result.contains("\"number\":42")); assertTrue(result.contains("\"number\":42"));
assertTrue(result.contains("\"string\":\"Bar\"")); assertTrue(result.contains("\"string\":\"Bar\""));

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,7 +16,7 @@
package org.springframework.http.converter.xml; package org.springframework.http.converter.xml;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import javax.xml.bind.Marshaller; import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller; import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlAttribute;
@ -176,7 +176,7 @@ public class Jaxb2RootElementHttpMessageConverterTests {
assertEquals("Invalid content-type", new MediaType("application", "xml"), assertEquals("Invalid content-type", new MediaType("application", "xml"),
outputMessage.getHeaders().getContentType()); outputMessage.getHeaders().getContentType());
assertXMLEqual("Invalid result", "<rootElement><type s=\"Hello World\"/></rootElement>", assertXMLEqual("Invalid result", "<rootElement><type s=\"Hello World\"/></rootElement>",
outputMessage.getBodyAsString(Charset.forName("UTF-8"))); outputMessage.getBodyAsString(StandardCharsets.UTF_8));
} }
@Test @Test
@ -186,7 +186,7 @@ public class Jaxb2RootElementHttpMessageConverterTests {
assertEquals("Invalid content-type", new MediaType("application", "xml"), assertEquals("Invalid content-type", new MediaType("application", "xml"),
outputMessage.getHeaders().getContentType()); outputMessage.getHeaders().getContentType());
assertXMLEqual("Invalid result", "<rootElement><type s=\"Hello World\"/></rootElement>", assertXMLEqual("Invalid result", "<rootElement><type s=\"Hello World\"/></rootElement>",
outputMessage.getBodyAsString(Charset.forName("UTF-8"))); outputMessage.getBodyAsString(StandardCharsets.UTF_8));
} }
// SPR-11488 // SPR-11488
@ -197,7 +197,7 @@ public class Jaxb2RootElementHttpMessageConverterTests {
MyJaxb2RootElementHttpMessageConverter myConverter = new MyJaxb2RootElementHttpMessageConverter(); MyJaxb2RootElementHttpMessageConverter myConverter = new MyJaxb2RootElementHttpMessageConverter();
myConverter.write(new MyRootElement(new MyCustomElement("a", "b")), null, outputMessage); myConverter.write(new MyRootElement(new MyCustomElement("a", "b")), null, outputMessage);
assertXMLEqual("Invalid result", "<myRootElement><element>a|||b</element></myRootElement>", assertXMLEqual("Invalid result", "<myRootElement><element>a|||b</element></myRootElement>",
outputMessage.getBodyAsString(Charset.forName("UTF-8"))); outputMessage.getBodyAsString(StandardCharsets.UTF_8));
} }
@Test @Test

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,7 +18,7 @@ package org.springframework.http.converter.xml;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import com.fasterxml.jackson.annotation.JsonView; import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper;
@ -91,15 +91,14 @@ public class MappingJackson2XmlHttpMessageConverterTests {
body.setBool(true); body.setBool(true);
body.setBytes(new byte[]{0x1, 0x2}); body.setBytes(new byte[]{0x1, 0x2});
converter.write(body, null, outputMessage); converter.write(body, null, outputMessage);
Charset utf8 = Charset.forName("UTF-8"); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
String result = outputMessage.getBodyAsString(utf8);
assertTrue(result.contains("<string>Foo</string>")); assertTrue(result.contains("<string>Foo</string>"));
assertTrue(result.contains("<number>42</number>")); assertTrue(result.contains("<number>42</number>"));
assertTrue(result.contains("<fraction>42.0</fraction>")); assertTrue(result.contains("<fraction>42.0</fraction>"));
assertTrue(result.contains("<array><array>Foo</array><array>Bar</array></array>")); assertTrue(result.contains("<array><array>Foo</array><array>Bar</array></array>"));
assertTrue(result.contains("<bool>true</bool>")); assertTrue(result.contains("<bool>true</bool>"));
assertTrue(result.contains("<bytes>AQI=</bytes>")); assertTrue(result.contains("<bytes>AQI=</bytes>"));
assertEquals("Invalid content-type", new MediaType("application", "xml", utf8), assertEquals("Invalid content-type", new MediaType("application", "xml", StandardCharsets.UTF_8),
outputMessage.getHeaders().getContentType()); outputMessage.getHeaders().getContentType());
} }
@ -132,7 +131,7 @@ public class MappingJackson2XmlHttpMessageConverterTests {
jacksonValue.setSerializationView(MyJacksonView1.class); jacksonValue.setSerializationView(MyJacksonView1.class);
this.writeInternal(jacksonValue, outputMessage); this.writeInternal(jacksonValue, outputMessage);
String result = outputMessage.getBodyAsString(Charset.forName("UTF-8")); String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
assertThat(result, containsString("<withView1>with</withView1>")); assertThat(result, containsString("<withView1>with</withView1>"));
assertThat(result, not(containsString("<withView2>with</withView2>"))); assertThat(result, not(containsString("<withView2>with</withView2>")));
assertThat(result, not(containsString("<withoutView>without</withoutView>"))); assertThat(result, not(containsString("<withoutView>without</withoutView>")));

View File

@ -20,6 +20,7 @@ import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.StringReader; import java.io.StringReader;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamReader;
@ -300,7 +301,7 @@ public class SourceHttpMessageConverterTests {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(domSource, null, outputMessage); converter.write(domSource, null, outputMessage);
assertXMLEqual("Invalid result", "<root>Hello World</root>", assertXMLEqual("Invalid result", "<root>Hello World</root>",
outputMessage.getBodyAsString(Charset.forName("UTF-8"))); outputMessage.getBodyAsString(StandardCharsets.UTF_8));
assertEquals("Invalid content-type", new MediaType("application", "xml"), assertEquals("Invalid content-type", new MediaType("application", "xml"),
outputMessage.getHeaders().getContentType()); outputMessage.getHeaders().getContentType());
assertEquals("Invalid content-length", outputMessage.getBodyAsBytes().length, assertEquals("Invalid content-length", outputMessage.getBodyAsBytes().length,
@ -315,7 +316,7 @@ public class SourceHttpMessageConverterTests {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(saxSource, null, outputMessage); converter.write(saxSource, null, outputMessage);
assertXMLEqual("Invalid result", "<root>Hello World</root>", assertXMLEqual("Invalid result", "<root>Hello World</root>",
outputMessage.getBodyAsString(Charset.forName("UTF-8"))); outputMessage.getBodyAsString(StandardCharsets.UTF_8));
assertEquals("Invalid content-type", new MediaType("application", "xml"), assertEquals("Invalid content-type", new MediaType("application", "xml"),
outputMessage.getHeaders().getContentType()); outputMessage.getHeaders().getContentType());
} }
@ -328,7 +329,7 @@ public class SourceHttpMessageConverterTests {
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage(); MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(streamSource, null, outputMessage); converter.write(streamSource, null, outputMessage);
assertXMLEqual("Invalid result", "<root>Hello World</root>", assertXMLEqual("Invalid result", "<root>Hello World</root>",
outputMessage.getBodyAsString(Charset.forName("UTF-8"))); outputMessage.getBodyAsString(StandardCharsets.UTF_8));
assertEquals("Invalid content-type", new MediaType("application", "xml"), assertEquals("Invalid content-type", new MediaType("application", "xml"),
outputMessage.getHeaders().getContentType()); outputMessage.getHeaders().getContentType());
} }

View File

@ -17,7 +17,7 @@
package org.springframework.http.server; package org.springframework.http.server;
import java.net.URI; import java.net.URI;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import org.junit.Before; import org.junit.Before;
@ -93,7 +93,7 @@ public class ServletServerHttpRequestTests {
assertEquals("Invalid header values returned", 2, headerValues.size()); assertEquals("Invalid header values returned", 2, headerValues.size());
assertTrue("Invalid header values returned", headerValues.contains(headerValue1)); assertTrue("Invalid header values returned", headerValues.contains(headerValue1));
assertTrue("Invalid header values returned", headerValues.contains(headerValue2)); assertTrue("Invalid header values returned", headerValues.contains(headerValue2));
assertEquals("Invalid Content-Type", new MediaType("text", "plain", Charset.forName("UTF-8")), assertEquals("Invalid Content-Type", new MediaType("text", "plain", StandardCharsets.UTF_8),
headers.getContentType()); headers.getContentType());
} }

View File

@ -16,7 +16,7 @@
package org.springframework.http.server; package org.springframework.http.server;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -64,7 +64,7 @@ public class ServletServerHttpResponseTests {
headers.add(headerName, headerValue1); headers.add(headerName, headerValue1);
String headerValue2 = "value2"; String headerValue2 = "value2";
headers.add(headerName, headerValue2); headers.add(headerName, headerValue2);
headers.setContentType(new MediaType("text", "plain", Charset.forName("UTF-8"))); headers.setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));
response.close(); response.close();
assertTrue("Header not set", mockResponse.getHeaderNames().contains(headerName)); assertTrue("Header not set", mockResponse.getHeaderNames().contains(headerName));

View File

@ -17,7 +17,7 @@
package org.springframework.http.server.reactive; package org.springframework.http.server.reactive;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -31,7 +31,10 @@ import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.ResponseCookie; import org.springframework.http.ResponseCookie;
import static junit.framework.TestCase.assertTrue; import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
/** /**
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
@ -39,9 +42,6 @@ import static org.junit.Assert.*;
*/ */
public class ServerHttpResponseTests { public class ServerHttpResponseTests {
public static final Charset UTF_8 = Charset.forName("UTF-8");
@Test @Test
public void writeWith() throws Exception { public void writeWith() throws Exception {
TestServerHttpResponse response = new TestServerHttpResponse(); TestServerHttpResponse response = new TestServerHttpResponse();
@ -52,9 +52,9 @@ public class ServerHttpResponseTests {
assertTrue(response.cookiesWritten); assertTrue(response.cookiesWritten);
assertEquals(3, response.body.size()); assertEquals(3, response.body.size());
assertEquals("a", new String(response.body.get(0).asByteBuffer().array(), UTF_8)); assertEquals("a", new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8));
assertEquals("b", new String(response.body.get(1).asByteBuffer().array(), UTF_8)); assertEquals("b", new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8));
assertEquals("c", new String(response.body.get(2).asByteBuffer().array(), UTF_8)); assertEquals("c", new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8));
} }
@Test @Test
@ -96,9 +96,9 @@ public class ServerHttpResponseTests {
assertSame(cookie, response.getCookies().getFirst("ID")); assertSame(cookie, response.getCookies().getFirst("ID"));
assertEquals(3, response.body.size()); assertEquals(3, response.body.size());
assertEquals("a", new String(response.body.get(0).asByteBuffer().array(), UTF_8)); assertEquals("a", new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8));
assertEquals("b", new String(response.body.get(1).asByteBuffer().array(), UTF_8)); assertEquals("b", new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8));
assertEquals("c", new String(response.body.get(2).asByteBuffer().array(), UTF_8)); assertEquals("c", new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8));
} }
@Test @Test
@ -114,9 +114,9 @@ public class ServerHttpResponseTests {
assertNull(response.getCookies().get("ID")); assertNull(response.getCookies().get("ID"));
assertEquals(3, response.body.size()); assertEquals(3, response.body.size());
assertEquals("a", new String(response.body.get(0).asByteBuffer().array(), UTF_8)); assertEquals("a", new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8));
assertEquals("b", new String(response.body.get(1).asByteBuffer().array(), UTF_8)); assertEquals("b", new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8));
assertEquals("c", new String(response.body.get(2).asByteBuffer().array(), UTF_8)); assertEquals("c", new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8));
} }
@Test @Test
@ -139,7 +139,7 @@ public class ServerHttpResponseTests {
private DataBuffer wrap(String a) { private DataBuffer wrap(String a) {
return new DefaultDataBufferFactory().wrap(ByteBuffer.wrap(a.getBytes(UTF_8))); return new DefaultDataBufferFactory().wrap(ByteBuffer.wrap(a.getBytes(StandardCharsets.UTF_8)));
} }

View File

@ -20,6 +20,7 @@ import java.io.UnsupportedEncodingException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.List; import java.util.List;
@ -27,6 +28,7 @@ import java.util.Set;
import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonView;
import org.junit.Test; import org.junit.Test;
import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.ParameterizedTypeReference;
@ -44,8 +46,6 @@ import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import com.fasterxml.jackson.annotation.JsonView;
import static org.junit.Assert.*; import static org.junit.Assert.*;
/** /**
@ -215,7 +215,7 @@ public class RestTemplateIntegrationTests extends AbstractJettyServerTestCase {
@Test @Test
public void jsonPostForObject() throws URISyntaxException { public void jsonPostForObject() throws URISyntaxException {
HttpHeaders entityHeaders = new HttpHeaders(); HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.setContentType(new MediaType("application", "json", Charset.forName("UTF-8"))); entityHeaders.setContentType(new MediaType("application", "json", StandardCharsets.UTF_8));
MySampleBean bean = new MySampleBean(); MySampleBean bean = new MySampleBean();
bean.setWith1("with"); bean.setWith1("with");
bean.setWith2("with"); bean.setWith2("with");
@ -230,7 +230,7 @@ public class RestTemplateIntegrationTests extends AbstractJettyServerTestCase {
@Test @Test
public void jsonPostForObjectWithJacksonView() throws URISyntaxException { public void jsonPostForObjectWithJacksonView() throws URISyntaxException {
HttpHeaders entityHeaders = new HttpHeaders(); HttpHeaders entityHeaders = new HttpHeaders();
entityHeaders.setContentType(new MediaType("application", "json", Charset.forName("UTF-8"))); entityHeaders.setContentType(new MediaType("application", "json", StandardCharsets.UTF_8));
MySampleBean bean = new MySampleBean("with", "with", "without"); MySampleBean bean = new MySampleBean("with", "with", "without");
MappingJacksonValue jacksonValue = new MappingJacksonValue(bean); MappingJacksonValue jacksonValue = new MappingJacksonValue(bean);
jacksonValue.setSerializationView(MyJacksonView1.class); jacksonValue.setSerializationView(MyJacksonView1.class);
@ -257,7 +257,7 @@ public class RestTemplateIntegrationTests extends AbstractJettyServerTestCase {
ParameterizedTypeReference<?> typeReference = new ParameterizedTypeReference<List<ParentClass>>() {}; ParameterizedTypeReference<?> typeReference = new ParameterizedTypeReference<List<ParentClass>>() {};
RequestEntity<List<ParentClass>> entity = RequestEntity RequestEntity<List<ParentClass>> entity = RequestEntity
.post(new URI(baseUrl + "/jsonpost")) .post(new URI(baseUrl + "/jsonpost"))
.contentType(new MediaType("application", "json", Charset.forName("UTF-8"))) .contentType(new MediaType("application", "json", StandardCharsets.UTF_8))
.body(list, typeReference.getType()); .body(list, typeReference.getType());
String content = template.exchange(entity, String.class).getBody(); String content = template.exchange(entity, String.class).getBody();
assertTrue(content.contains("\"type\":\"foo\"")); assertTrue(content.contains("\"type\":\"foo\""));

View File

@ -17,7 +17,7 @@
package org.springframework.web.servlet.mvc.method.annotation; package org.springframework.web.servlet.mvc.method.annotation;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.Set; import java.util.Set;
@ -36,9 +36,9 @@ import org.springframework.http.server.ServerHttpResponse;
*/ */
public class SseEmitter extends ResponseBodyEmitter { public class SseEmitter extends ResponseBodyEmitter {
static final MediaType TEXT_PLAIN = new MediaType("text", "plain", Charset.forName("UTF-8")); static final MediaType TEXT_PLAIN = new MediaType("text", "plain", StandardCharsets.UTF_8);
static final MediaType UTF8_TEXT_EVENTSTREAM = new MediaType("text", "event-stream", Charset.forName("UTF-8")); static final MediaType UTF8_TEXT_EVENTSTREAM = new MediaType("text", "event-stream", StandardCharsets.UTF_8);
/** /**

View File

@ -20,6 +20,7 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -60,7 +61,7 @@ public class AppCacheManifestTransformer extends ResourceTransformerSupport {
private static final String MANIFEST_HEADER = "CACHE MANIFEST"; private static final String MANIFEST_HEADER = "CACHE MANIFEST";
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private static final Log logger = LogFactory.getLog(AppCacheManifestTransformer.class); private static final Log logger = LogFactory.getLog(AppCacheManifestTransformer.class);

View File

@ -19,6 +19,7 @@ package org.springframework.web.servlet.resource;
import java.io.IOException; import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
@ -49,7 +50,7 @@ import org.springframework.util.StringUtils;
*/ */
public class CssLinkResourceTransformer extends ResourceTransformerSupport { public class CssLinkResourceTransformer extends ResourceTransformerSupport {
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private static final Log logger = LogFactory.getLog(CssLinkResourceTransformer.class); private static final Log logger = LogFactory.getLog(CssLinkResourceTransformer.class);

View File

@ -19,6 +19,7 @@ package org.springframework.web.servlet.view.script;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -68,7 +69,7 @@ public class ScriptTemplateView extends AbstractUrlBasedView {
public static final String DEFAULT_CONTENT_TYPE = "text/html"; public static final String DEFAULT_CONTENT_TYPE = "text/html";
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private static final String DEFAULT_RESOURCE_LOADER_PATH = "classpath:"; private static final String DEFAULT_RESOURCE_LOADER_PATH = "classpath:";

View File

@ -16,13 +16,9 @@
package org.springframework.web.servlet.mvc.method.annotation; package org.springframework.web.servlet.mvc.method.annotation;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
import static org.springframework.web.servlet.HandlerMapping.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URI; import java.net.URI;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -56,6 +52,10 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.method.support.ModelAndViewContainer;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
import static org.springframework.web.servlet.HandlerMapping.*;
/** /**
* Test fixture for {@link HttpEntityMethodProcessor} delegating to a mock * Test fixture for {@link HttpEntityMethodProcessor} delegating to a mock
* {@link HttpMessageConverter}. * {@link HttpMessageConverter}.
@ -158,7 +158,7 @@ public class HttpEntityMethodProcessorMockTests {
MediaType contentType = MediaType.TEXT_PLAIN; MediaType contentType = MediaType.TEXT_PLAIN;
servletRequest.addHeader("Content-Type", contentType.toString()); servletRequest.addHeader("Content-Type", contentType.toString());
servletRequest.setContent(body.getBytes(Charset.forName("UTF-8"))); servletRequest.setContent(body.getBytes(StandardCharsets.UTF_8));
given(stringHttpMessageConverter.canRead(String.class, contentType)).willReturn(true); given(stringHttpMessageConverter.canRead(String.class, contentType)).willReturn(true);
given(stringHttpMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body); given(stringHttpMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body);
@ -180,7 +180,7 @@ public class HttpEntityMethodProcessorMockTests {
servletRequest.setServerName("www.example.com"); servletRequest.setServerName("www.example.com");
servletRequest.setServerPort(80); servletRequest.setServerPort(80);
servletRequest.setRequestURI("/path"); servletRequest.setRequestURI("/path");
servletRequest.setContent(body.getBytes(Charset.forName("UTF-8"))); servletRequest.setContent(body.getBytes(StandardCharsets.UTF_8));
given(stringHttpMessageConverter.canRead(String.class, contentType)).willReturn(true); given(stringHttpMessageConverter.canRead(String.class, contentType)).willReturn(true);
given(stringHttpMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body); given(stringHttpMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body);
@ -213,7 +213,7 @@ public class HttpEntityMethodProcessorMockTests {
@Test(expected = HttpMediaTypeNotSupportedException.class) @Test(expected = HttpMediaTypeNotSupportedException.class)
public void resolveArgumentNoContentType() throws Exception { public void resolveArgumentNoContentType() throws Exception {
servletRequest.setMethod("POST"); servletRequest.setMethod("POST");
servletRequest.setContent("some content".getBytes(Charset.forName("UTF-8"))); servletRequest.setContent("some content".getBytes(StandardCharsets.UTF_8));
processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null); processor.resolveArgument(paramHttpEntity, mavContainer, webRequest, null);
fail("Expected exception"); fail("Expected exception");
} }
@ -522,7 +522,7 @@ public class HttpEntityMethodProcessorMockTests {
@Test @Test
public void handleReturnTypeResource() throws Exception { public void handleReturnTypeResource() throws Exception {
ResponseEntity<Resource> returnValue = ResponseEntity ResponseEntity<Resource> returnValue = ResponseEntity
.ok(new ByteArrayResource("Content".getBytes(Charset.forName("UTF-8")))); .ok(new ByteArrayResource("Content".getBytes(StandardCharsets.UTF_8)));
given(resourceMessageConverter.canWrite(ByteArrayResource.class, null)).willReturn(true); given(resourceMessageConverter.canWrite(ByteArrayResource.class, null)).willReturn(true);
given(resourceMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL)); given(resourceMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL));

View File

@ -17,7 +17,7 @@
package org.springframework.web.servlet.mvc.method.annotation; package org.springframework.web.servlet.mvc.method.annotation;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@ -131,7 +131,7 @@ public class RequestPartMethodArgumentResolverTests {
resolver = new RequestPartMethodArgumentResolver(Collections.<HttpMessageConverter<?>>singletonList(messageConverter)); resolver = new RequestPartMethodArgumentResolver(Collections.<HttpMessageConverter<?>>singletonList(messageConverter));
reset(messageConverter); reset(messageConverter);
byte[] content = "doesn't matter as long as not empty".getBytes(Charset.forName("UTF-8")); byte[] content = "doesn't matter as long as not empty".getBytes(StandardCharsets.UTF_8);
multipartFile1 = new MockMultipartFile("requestPart", "", "text/plain", content); multipartFile1 = new MockMultipartFile("requestPart", "", "text/plain", content);
multipartFile2 = new MockMultipartFile("requestPart", "", "text/plain", content); multipartFile2 = new MockMultipartFile("requestPart", "", "text/plain", content);

View File

@ -16,15 +16,11 @@
package org.springframework.web.servlet.mvc.method.annotation; package org.springframework.web.servlet.mvc.method.annotation;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.constraints.NotNull; import javax.validation.constraints.NotNull;
@ -54,6 +50,9 @@ import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer; import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.HandlerMapping;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;
/** /**
* Test fixture for {@link RequestResponseBodyMethodProcessor} delegating to a * Test fixture for {@link RequestResponseBodyMethodProcessor} delegating to a
* mock HttpMessageConverter. * mock HttpMessageConverter.
@ -136,7 +135,7 @@ public class RequestResponseBodyMethodProcessorMockTests {
servletRequest.addHeader("Content-Type", contentType.toString()); servletRequest.addHeader("Content-Type", contentType.toString());
String body = "Foo"; String body = "Foo";
servletRequest.setContent(body.getBytes(Charset.forName("UTF-8"))); servletRequest.setContent(body.getBytes(StandardCharsets.UTF_8));
given(stringMessageConverter.canRead(String.class, contentType)).willReturn(true); given(stringMessageConverter.canRead(String.class, contentType)).willReturn(true);
given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body); given(stringMessageConverter.read(eq(String.class), isA(HttpInputMessage.class))).willReturn(body);
@ -168,7 +167,7 @@ public class RequestResponseBodyMethodProcessorMockTests {
private void testResolveArgumentWithValidation(SimpleBean simpleBean) throws Exception { private void testResolveArgumentWithValidation(SimpleBean simpleBean) throws Exception {
MediaType contentType = MediaType.TEXT_PLAIN; MediaType contentType = MediaType.TEXT_PLAIN;
servletRequest.addHeader("Content-Type", contentType.toString()); servletRequest.addHeader("Content-Type", contentType.toString());
servletRequest.setContent("payload".getBytes(Charset.forName("UTF-8"))); servletRequest.setContent("payload".getBytes(StandardCharsets.UTF_8));
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
HttpMessageConverter<SimpleBean> beanConverter = mock(HttpMessageConverter.class); HttpMessageConverter<SimpleBean> beanConverter = mock(HttpMessageConverter.class);
@ -184,7 +183,7 @@ public class RequestResponseBodyMethodProcessorMockTests {
public void resolveArgumentCannotRead() throws Exception { public void resolveArgumentCannotRead() throws Exception {
MediaType contentType = MediaType.TEXT_PLAIN; MediaType contentType = MediaType.TEXT_PLAIN;
servletRequest.addHeader("Content-Type", contentType.toString()); servletRequest.addHeader("Content-Type", contentType.toString());
servletRequest.setContent("payload".getBytes(Charset.forName("UTF-8"))); servletRequest.setContent("payload".getBytes(StandardCharsets.UTF_8));
given(stringMessageConverter.canRead(String.class, contentType)).willReturn(false); given(stringMessageConverter.canRead(String.class, contentType)).willReturn(false);
@ -193,7 +192,7 @@ public class RequestResponseBodyMethodProcessorMockTests {
@Test(expected = HttpMediaTypeNotSupportedException.class) @Test(expected = HttpMediaTypeNotSupportedException.class)
public void resolveArgumentNoContentType() throws Exception { public void resolveArgumentNoContentType() throws Exception {
servletRequest.setContent("payload".getBytes(Charset.forName("UTF-8"))); servletRequest.setContent("payload".getBytes(StandardCharsets.UTF_8));
given(stringMessageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(false); given(stringMessageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).willReturn(false);
processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
} }
@ -201,7 +200,7 @@ public class RequestResponseBodyMethodProcessorMockTests {
@Test(expected = HttpMediaTypeNotSupportedException.class) @Test(expected = HttpMediaTypeNotSupportedException.class)
public void resolveArgumentInvalidContentType() throws Exception { public void resolveArgumentInvalidContentType() throws Exception {
this.servletRequest.setContentType("bad"); this.servletRequest.setContentType("bad");
servletRequest.setContent("payload".getBytes(Charset.forName("UTF-8"))); servletRequest.setContent("payload".getBytes(StandardCharsets.UTF_8));
processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
} }
@ -299,7 +298,7 @@ public class RequestResponseBodyMethodProcessorMockTests {
@Test @Test
public void handleReturnTypeResource() throws Exception { public void handleReturnTypeResource() throws Exception {
Resource returnValue = new ByteArrayResource("Content".getBytes(Charset.forName("UTF-8"))); Resource returnValue = new ByteArrayResource("Content".getBytes(StandardCharsets.UTF_8));
given(resourceMessageConverter.canWrite(ByteArrayResource.class, null)).willReturn(true); given(resourceMessageConverter.canWrite(ByteArrayResource.class, null)).willReturn(true);
given(resourceMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL)); given(resourceMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.ALL));

View File

@ -17,6 +17,7 @@ package org.springframework.web.servlet.mvc.method.annotation;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -62,7 +63,6 @@ public class StreamingResponseBodyReturnValueHandlerTests {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
this.handler = new StreamingResponseBodyReturnValueHandler(); this.handler = new StreamingResponseBodyReturnValueHandler();
this.mavContainer = new ModelAndViewContainer(); this.mavContainer = new ModelAndViewContainer();
@ -86,12 +86,11 @@ public class StreamingResponseBodyReturnValueHandlerTests {
@Test @Test
public void streamingResponseBody() throws Exception { public void streamingResponseBody() throws Exception {
CountDownLatch latch = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(1);
MethodParameter returnType = returnType(TestController.class, "handle"); MethodParameter returnType = returnType(TestController.class, "handle");
StreamingResponseBody streamingBody = outputStream -> { StreamingResponseBody streamingBody = outputStream -> {
outputStream.write("foo".getBytes(Charset.forName("UTF-8"))); outputStream.write("foo".getBytes(StandardCharsets.UTF_8));
latch.countDown(); latch.countDown();
}; };
this.handler.handleReturnValue(streamingBody, returnType, this.mavContainer, this.webRequest); this.handler.handleReturnValue(streamingBody, returnType, this.mavContainer, this.webRequest);
@ -104,13 +103,12 @@ public class StreamingResponseBodyReturnValueHandlerTests {
@Test @Test
public void responseEntity() throws Exception { public void responseEntity() throws Exception {
CountDownLatch latch = new CountDownLatch(1); CountDownLatch latch = new CountDownLatch(1);
MethodParameter returnType = returnType(TestController.class, "handleResponseEntity"); MethodParameter returnType = returnType(TestController.class, "handleResponseEntity");
ResponseEntity<StreamingResponseBody> emitter = ResponseEntity.ok().header("foo", "bar") ResponseEntity<StreamingResponseBody> emitter = ResponseEntity.ok().header("foo", "bar")
.body(outputStream -> { .body(outputStream -> {
outputStream.write("foo".getBytes(Charset.forName("UTF-8"))); outputStream.write("foo".getBytes(StandardCharsets.UTF_8));
latch.countDown(); latch.countDown();
}); });
this.handler.handleReturnValue(emitter, returnType, this.mavContainer, this.webRequest); this.handler.handleReturnValue(emitter, returnType, this.mavContainer, this.webRequest);

View File

@ -16,7 +16,7 @@
package org.springframework.web.socket; package org.springframework.web.socket;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
/** /**
* A text WebSocket message. * A text WebSocket message.
@ -26,8 +26,6 @@ import java.nio.charset.Charset;
*/ */
public final class TextMessage extends AbstractWebSocketMessage<String> { public final class TextMessage extends AbstractWebSocketMessage<String> {
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
private final byte[] bytes; private final byte[] bytes;
@ -46,7 +44,7 @@ public final class TextMessage extends AbstractWebSocketMessage<String> {
* @param payload the non-null payload * @param payload the non-null payload
*/ */
public TextMessage(byte[] payload) { public TextMessage(byte[] payload) {
super(new String(payload, UTF8_CHARSET)); super(new String(payload, StandardCharsets.UTF_8));
this.bytes = payload; this.bytes = payload;
} }
@ -70,7 +68,7 @@ public final class TextMessage extends AbstractWebSocketMessage<String> {
} }
public byte[] asBytes() { public byte[] asBytes() {
return (this.bytes != null ? this.bytes : getPayload().getBytes(UTF8_CHARSET)); return (this.bytes != null ? this.bytes : getPayload().getBytes(StandardCharsets.UTF_8));
} }
@Override @Override

View File

@ -17,7 +17,7 @@
package org.springframework.web.socket.server.support; package org.springframework.web.socket.server.support;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.security.Principal; import java.security.Principal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -70,9 +70,6 @@ import org.springframework.web.socket.server.RequestUpgradeStrategy;
*/ */
public abstract class AbstractHandshakeHandler implements HandshakeHandler, Lifecycle { public abstract class AbstractHandshakeHandler implements HandshakeHandler, Lifecycle {
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
private static final boolean jettyWsPresent = ClassUtils.isPresent( private static final boolean jettyWsPresent = ClassUtils.isPresent(
"org.eclipse.jetty.websocket.server.WebSocketServerFactory", AbstractHandshakeHandler.class.getClassLoader()); "org.eclipse.jetty.websocket.server.WebSocketServerFactory", AbstractHandshakeHandler.class.getClassLoader());
@ -286,7 +283,7 @@ public abstract class AbstractHandshakeHandler implements HandshakeHandler, Life
logger.error("Handshake failed due to invalid Upgrade header: " + request.getHeaders().getUpgrade()); logger.error("Handshake failed due to invalid Upgrade header: " + request.getHeaders().getUpgrade());
} }
response.setStatusCode(HttpStatus.BAD_REQUEST); response.setStatusCode(HttpStatus.BAD_REQUEST);
response.getBody().write("Can \"Upgrade\" only to \"WebSocket\".".getBytes(UTF8_CHARSET)); response.getBody().write("Can \"Upgrade\" only to \"WebSocket\".".getBytes(StandardCharsets.UTF_8));
} }
protected void handleInvalidConnectHeader(ServerHttpRequest request, ServerHttpResponse response) throws IOException { protected void handleInvalidConnectHeader(ServerHttpRequest request, ServerHttpResponse response) throws IOException {
@ -294,7 +291,7 @@ public abstract class AbstractHandshakeHandler implements HandshakeHandler, Life
logger.error("Handshake failed due to invalid Connection header " + request.getHeaders().getConnection()); logger.error("Handshake failed due to invalid Connection header " + request.getHeaders().getConnection());
} }
response.setStatusCode(HttpStatus.BAD_REQUEST); response.setStatusCode(HttpStatus.BAD_REQUEST);
response.getBody().write("\"Connection\" must be \"upgrade\".".getBytes(UTF8_CHARSET)); response.getBody().write("\"Connection\" must be \"upgrade\".".getBytes(StandardCharsets.UTF_8));
} }
protected boolean isWebSocketVersionSupported(WebSocketHttpHeaders httpHeaders) { protected boolean isWebSocketVersionSupported(WebSocketHttpHeaders httpHeaders) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2015 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,6 +17,7 @@
package org.springframework.web.socket.sockjs.frame; package org.springframework.web.socket.sockjs.frame;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -28,7 +29,7 @@ import org.springframework.util.Assert;
*/ */
public class SockJsFrame { public class SockJsFrame {
public static final Charset CHARSET = Charset.forName("UTF-8"); public static final Charset CHARSET = StandardCharsets.UTF_8;
private static final SockJsFrame OPEN_FRAME = new SockJsFrame("o"); private static final SockJsFrame OPEN_FRAME = new SockJsFrame("o");

View File

@ -17,7 +17,7 @@
package org.springframework.web.socket.sockjs.support; package org.springframework.web.socket.sockjs.support;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
@ -67,8 +67,6 @@ import org.springframework.web.util.WebUtils;
*/ */
public abstract class AbstractSockJsService implements SockJsService, CorsConfigurationSource { public abstract class AbstractSockJsService implements SockJsService, CorsConfigurationSource {
private static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
private static final long ONE_YEAR = TimeUnit.DAYS.toSeconds(365); private static final long ONE_YEAR = TimeUnit.DAYS.toSeconds(365);
private static final Random random = new Random(); private static final Random random = new Random();
@ -354,8 +352,8 @@ public abstract class AbstractSockJsService implements SockJsService, CorsConfig
if (requestInfo != null) { if (requestInfo != null) {
logger.debug("Processing transport request: " + requestInfo); logger.debug("Processing transport request: " + requestInfo);
} }
response.getHeaders().setContentType(new MediaType("text", "plain", UTF8_CHARSET)); response.getHeaders().setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));
response.getBody().write("Welcome to SockJS!\n".getBytes(UTF8_CHARSET)); response.getBody().write("Welcome to SockJS!\n".getBytes(StandardCharsets.UTF_8));
} }
else if (sockJsPath.equals("/info")) { else if (sockJsPath.equals("/info")) {
@ -547,7 +545,7 @@ public abstract class AbstractSockJsService implements SockJsService, CorsConfig
if (HttpMethod.GET == request.getMethod()) { if (HttpMethod.GET == request.getMethod()) {
addNoCacheHeaders(response); addNoCacheHeaders(response);
if (checkOrigin(request, response)) { if (checkOrigin(request, response)) {
response.getHeaders().setContentType(new MediaType("application", "json", UTF8_CHARSET)); response.getHeaders().setContentType(new MediaType("application", "json", StandardCharsets.UTF_8));
String content = String.format( String content = String.format(
INFO_CONTENT, random.nextInt(), isSessionCookieNeeded(), isWebSocketEnabled()); INFO_CONTENT, random.nextInt(), isSessionCookieNeeded(), isWebSocketEnabled());
response.getBody().write(content.getBytes()); response.getBody().write(content.getBytes());
@ -595,7 +593,7 @@ public abstract class AbstractSockJsService implements SockJsService, CorsConfig
} }
String content = String.format(IFRAME_CONTENT, getSockJsClientLibraryUrl()); String content = String.format(IFRAME_CONTENT, getSockJsClientLibraryUrl());
byte[] contentBytes = content.getBytes(UTF8_CHARSET); byte[] contentBytes = content.getBytes(StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder("\"0"); StringBuilder builder = new StringBuilder("\"0");
DigestUtils.appendMd5DigestAsHex(contentBytes, builder); DigestUtils.appendMd5DigestAsHex(contentBytes, builder);
builder.append('"'); builder.append('"');
@ -607,7 +605,7 @@ public abstract class AbstractSockJsService implements SockJsService, CorsConfig
return; return;
} }
response.getHeaders().setContentType(new MediaType("text", "html", UTF8_CHARSET)); response.getHeaders().setContentType(new MediaType("text", "html", StandardCharsets.UTF_8));
response.getHeaders().setContentLength(contentBytes.length); response.getHeaders().setContentLength(contentBytes.length);
// No cache in order to check every time if IFrame are authorized // No cache in order to check every time if IFrame are authorized

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,6 +17,7 @@
package org.springframework.web.socket.sockjs.transport.handler; package org.springframework.web.socket.sockjs.transport.handler;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@ -79,7 +80,7 @@ public abstract class AbstractHttpReceivingTransportHandler extends AbstractTran
logger.trace("Received message(s): " + Arrays.asList(messages)); logger.trace("Received message(s): " + Arrays.asList(messages));
} }
response.setStatusCode(getResponseStatus()); response.setStatusCode(getResponseStatus());
response.getHeaders().setContentType(new MediaType("text", "plain", UTF8_CHARSET)); response.getHeaders().setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));
sockJsSession.delegateMessages(messages); sockJsSession.delegateMessages(messages);
} }
@ -87,7 +88,7 @@ public abstract class AbstractHttpReceivingTransportHandler extends AbstractTran
private void handleReadError(ServerHttpResponse response, String error, String sessionId) { private void handleReadError(ServerHttpResponse response, String error, String sessionId) {
try { try {
response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
response.getBody().write(error.getBytes(UTF8_CHARSET)); response.getBody().write(error.getBytes(StandardCharsets.UTF_8));
} }
catch (IOException ex) { catch (IOException ex) {
throw new SockJsException("Failed to send error: " + error, sessionId, ex); throw new SockJsException("Failed to send error: " + error, sessionId, ex);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,8 +16,6 @@
package org.springframework.web.socket.sockjs.transport.handler; package org.springframework.web.socket.sockjs.transport.handler;
import java.nio.charset.Charset;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -30,9 +28,6 @@ import org.springframework.web.socket.sockjs.transport.TransportHandler;
*/ */
public abstract class AbstractTransportHandler implements TransportHandler { public abstract class AbstractTransportHandler implements TransportHandler {
protected static final Charset UTF8_CHARSET = Charset.forName("UTF-8");
protected final Log logger = LogFactory.getLog(this.getClass()); protected final Log logger = LogFactory.getLog(this.getClass());
private SockJsServiceConfig serviceConfig; private SockJsServiceConfig serviceConfig;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,6 +16,7 @@
package org.springframework.web.socket.sockjs.transport.handler; package org.springframework.web.socket.sockjs.transport.handler;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@ -43,7 +44,7 @@ public class EventSourceTransportHandler extends AbstractHttpSendingTransportHan
@Override @Override
protected MediaType getContentType() { protected MediaType getContentType() {
return new MediaType("text", "event-stream", UTF8_CHARSET); return new MediaType("text", "event-stream", StandardCharsets.UTF_8);
} }
@Override @Override

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,6 +17,7 @@
package org.springframework.web.socket.sockjs.transport.handler; package org.springframework.web.socket.sockjs.transport.handler;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@ -84,7 +85,7 @@ public class HtmlFileTransportHandler extends AbstractHttpSendingTransportHandle
@Override @Override
protected MediaType getContentType() { protected MediaType getContentType() {
return new MediaType("text", "html", UTF8_CHARSET); return new MediaType("text", "html", StandardCharsets.UTF_8);
} }
@Override @Override
@ -102,7 +103,7 @@ public class HtmlFileTransportHandler extends AbstractHttpSendingTransportHandle
if (!StringUtils.hasText(callback)) { if (!StringUtils.hasText(callback)) {
response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
try { try {
response.getBody().write("\"callback\" parameter required".getBytes(UTF8_CHARSET)); response.getBody().write("\"callback\" parameter required".getBytes(StandardCharsets.UTF_8));
} }
catch (IOException ex) { catch (IOException ex) {
sockJsSession.tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR); sockJsSession.tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
@ -138,7 +139,7 @@ public class HtmlFileTransportHandler extends AbstractHttpSendingTransportHandle
// We already validated the parameter above... // We already validated the parameter above...
String callback = getCallbackParam(request); String callback = getCallbackParam(request);
String html = String.format(PARTIAL_HTML_CONTENT, callback); String html = String.format(PARTIAL_HTML_CONTENT, callback);
return html.getBytes(UTF8_CHARSET); return html.getBytes(StandardCharsets.UTF_8);
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,6 +16,7 @@
package org.springframework.web.socket.sockjs.transport.handler; package org.springframework.web.socket.sockjs.transport.handler;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@ -49,7 +50,7 @@ public class JsonpPollingTransportHandler extends AbstractHttpSendingTransportHa
@Override @Override
protected MediaType getContentType() { protected MediaType getContentType() {
return new MediaType("application", "javascript", UTF8_CHARSET); return new MediaType("application", "javascript", StandardCharsets.UTF_8);
} }
@Override @Override
@ -67,7 +68,7 @@ public class JsonpPollingTransportHandler extends AbstractHttpSendingTransportHa
String callback = getCallbackParam(request); String callback = getCallbackParam(request);
if (!StringUtils.hasText(callback)) { if (!StringUtils.hasText(callback)) {
response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
response.getBody().write("\"callback\" parameter required".getBytes(UTF8_CHARSET)); response.getBody().write("\"callback\" parameter required".getBytes(StandardCharsets.UTF_8));
return; return;
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,6 +17,7 @@
package org.springframework.web.socket.sockjs.transport.handler; package org.springframework.web.socket.sockjs.transport.handler;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@ -53,7 +54,7 @@ public class JsonpReceivingTransportHandler extends AbstractHttpReceivingTranspo
super.handleRequestInternal(request, response, wsHandler, sockJsSession); super.handleRequestInternal(request, response, wsHandler, sockJsSession);
try { try {
response.getBody().write("ok".getBytes(UTF8_CHARSET)); response.getBody().write("ok".getBytes(StandardCharsets.UTF_8));
} }
catch (IOException ex) { catch (IOException ex) {
throw new SockJsException("Failed to write to the response body", sockJsSession.getId(), ex); throw new SockJsException("Failed to write to the response body", sockJsSession.getId(), ex);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,6 +16,7 @@
package org.springframework.web.socket.sockjs.transport.handler; package org.springframework.web.socket.sockjs.transport.handler;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@ -42,7 +43,7 @@ public class XhrPollingTransportHandler extends AbstractHttpSendingTransportHand
@Override @Override
protected MediaType getContentType() { protected MediaType getContentType() {
return new MediaType("application", "javascript", UTF8_CHARSET); return new MediaType("application", "javascript", StandardCharsets.UTF_8);
} }
@Override @Override

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2016 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,6 +16,7 @@
package org.springframework.web.socket.sockjs.transport.handler; package org.springframework.web.socket.sockjs.transport.handler;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@ -53,7 +54,7 @@ public class XhrStreamingTransportHandler extends AbstractHttpSendingTransportHa
@Override @Override
protected MediaType getContentType() { protected MediaType getContentType() {
return new MediaType("application", "javascript", UTF8_CHARSET); return new MediaType("application", "javascript", StandardCharsets.UTF_8);
} }
@Override @Override

View File

@ -17,7 +17,7 @@
package org.springframework.web.socket.messaging; package org.springframework.web.socket.messaging;
import java.net.URI; import java.net.URI;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import org.junit.Before; import org.junit.Before;
@ -56,9 +56,6 @@ import static org.mockito.Mockito.*;
*/ */
public class WebSocketStompClientTests { public class WebSocketStompClientTests {
private static final Charset UTF_8 = Charset.forName("UTF-8");
private TestWebSocketStompClient stompClient; private TestWebSocketStompClient stompClient;
@Mock @Mock
@ -137,7 +134,7 @@ public class WebSocketStompClientTests {
StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap()); StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap());
assertEquals(StompCommand.SEND, accessor.getCommand()); assertEquals(StompCommand.SEND, accessor.getCommand());
assertEquals("alpha", headers.getFirst("a")); assertEquals("alpha", headers.getFirst("a"));
assertEquals("Message payload", new String(message.getPayload(), UTF_8)); assertEquals("Message payload", new String(message.getPayload(), StandardCharsets.UTF_8));
} }
@Test @Test
@ -162,14 +159,14 @@ public class WebSocketStompClientTests {
StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap()); StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap());
assertEquals(StompCommand.SEND, accessor.getCommand()); assertEquals(StompCommand.SEND, accessor.getCommand());
assertEquals("alpha", headers.getFirst("a")); assertEquals("alpha", headers.getFirst("a"));
assertEquals("Message payload", new String(message.getPayload(), UTF_8)); assertEquals("Message payload", new String(message.getPayload(), StandardCharsets.UTF_8));
} }
@Test @Test
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({ "unchecked", "rawtypes" })
public void handleWebSocketMessageBinary() throws Exception { public void handleWebSocketMessageBinary() throws Exception {
String text = "SEND\na:alpha\n\nMessage payload\0"; String text = "SEND\na:alpha\n\nMessage payload\0";
connect().handleMessage(this.webSocketSession, new BinaryMessage(text.getBytes(UTF_8))); connect().handleMessage(this.webSocketSession, new BinaryMessage(text.getBytes(StandardCharsets.UTF_8)));
ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class); ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
verify(this.stompSession).handleMessage(captor.capture()); verify(this.stompSession).handleMessage(captor.capture());
@ -180,7 +177,7 @@ public class WebSocketStompClientTests {
StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap()); StompHeaders headers = StompHeaders.readOnlyStompHeaders(accessor.toNativeHeaderMap());
assertEquals(StompCommand.SEND, accessor.getCommand()); assertEquals(StompCommand.SEND, accessor.getCommand());
assertEquals("alpha", headers.getFirst("a")); assertEquals("alpha", headers.getFirst("a"));
assertEquals("Message payload", new String(message.getPayload(), UTF_8)); assertEquals("Message payload", new String(message.getPayload(), StandardCharsets.UTF_8));
} }
@Test @Test
@ -193,7 +190,7 @@ public class WebSocketStompClientTests {
public void sendWebSocketMessage() throws Exception { public void sendWebSocketMessage() throws Exception {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
accessor.setDestination("/topic/foo"); accessor.setDestination("/topic/foo");
byte[] payload = "payload".getBytes(UTF_8); byte[] payload = "payload".getBytes(StandardCharsets.UTF_8);
getTcpConnection().send(MessageBuilder.createMessage(payload, accessor.getMessageHeaders())); getTcpConnection().send(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));
@ -209,7 +206,7 @@ public class WebSocketStompClientTests {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
accessor.setDestination("/b"); accessor.setDestination("/b");
accessor.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM); accessor.setContentType(MimeTypeUtils.APPLICATION_OCTET_STREAM);
byte[] payload = "payload".getBytes(UTF_8); byte[] payload = "payload".getBytes(StandardCharsets.UTF_8);
getTcpConnection().send(MessageBuilder.createMessage(payload, accessor.getMessageHeaders())); getTcpConnection().send(MessageBuilder.createMessage(payload, accessor.getMessageHeaders()));
@ -218,7 +215,7 @@ public class WebSocketStompClientTests {
BinaryMessage binaryMessage = binaryMessageCaptor.getValue(); BinaryMessage binaryMessage = binaryMessageCaptor.getValue();
assertNotNull(binaryMessage); assertNotNull(binaryMessage);
assertEquals("SEND\ndestination:/b\ncontent-type:application/octet-stream\ncontent-length:7\n\npayload\0", assertEquals("SEND\ndestination:/b\ncontent-type:application/octet-stream\ncontent-length:7\n\npayload\0",
new String(binaryMessage.getPayload().array(), UTF_8)); new String(binaryMessage.getPayload().array(), StandardCharsets.UTF_8));
} }
@Test @Test

View File

@ -20,7 +20,7 @@ import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URI; import java.net.URI;
import java.nio.charset.Charset; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Queue; import java.util.Queue;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
@ -109,7 +109,7 @@ public class RestTemplateXhrTransportTests {
StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND); StompHeaderAccessor accessor = StompHeaderAccessor.create(StompCommand.SEND);
accessor.setDestination("/destination"); accessor.setDestination("/destination");
MessageHeaders headers = accessor.getMessageHeaders(); MessageHeaders headers = accessor.getMessageHeaders();
Message<byte[]> message = MessageBuilder.createMessage("body".getBytes(Charset.forName("UTF-8")), headers); Message<byte[]> message = MessageBuilder.createMessage("body".getBytes(StandardCharsets.UTF_8), headers);
byte[] bytes = new StompEncoder().encode(message); byte[] bytes = new StompEncoder().encode(message);
TextMessage textMessage = new TextMessage(bytes); TextMessage textMessage = new TextMessage(bytes);
SockJsFrame frame = SockJsFrame.messageFrame(new Jackson2SockJsMessageCodec(), textMessage.getPayload()); SockJsFrame frame = SockJsFrame.messageFrame(new Jackson2SockJsMessageCodec(), textMessage.getPayload());
@ -197,7 +197,7 @@ public class RestTemplateXhrTransportTests {
} }
private InputStream getInputStream(String content) { private InputStream getInputStream(String content) {
byte[] bytes = content.getBytes(Charset.forName("UTF-8")); byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
return new ByteArrayInputStream(bytes); return new ByteArrayInputStream(bytes);
} }