Use CharsetDecoder to decode a DataBuffer into a String.

This commit is contained in:
Mark Paluch
2016-03-31 16:39:39 +02:00
parent 75d006d2f9
commit c4b9d94c33
2 changed files with 21 additions and 3 deletions

View File

@@ -16,6 +16,7 @@
package org.springframework.core.codec.support;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
@@ -38,11 +39,13 @@ import org.springframework.util.MimeType;
* @author Sebastien Deleuze
* @author Brian Clozel
* @author Arjen Poutsma
* @author Mark Paluch
* @see StringEncoder
*/
public class StringDecoder extends AbstractDecoder<String> {
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
public static final String EMPTY = "";
private final boolean reduceToSingleBuffer;
@@ -82,9 +85,13 @@ public class StringDecoder extends AbstractDecoder<String> {
}
Charset charset = getCharset(mimeType);
return inputFlux.map(content -> {
byte[] bytes = new byte[content.readableByteCount()];
content.read(bytes);
return new String(bytes, charset);
// fast-path exit.
if(content.readableByteCount() == 0) {
return EMPTY;
}
CharBuffer charBuffer = charset.decode(content.asByteBuffer());
return charBuffer.toString();
});
}

View File

@@ -33,6 +33,7 @@ import static org.junit.Assert.*;
/**
* @author Sebastien Deleuze
* @author Brian Clozel
* @author Mark Paluch
*/
public class StringDecoderTests extends AbstractAllocatingTestCase {
@@ -92,4 +93,14 @@ public class StringDecoderTests extends AbstractAllocatingTestCase {
assertEquals("foobar", result);
}
@Test
public void decodeEmpty() throws InterruptedException {
Flux<DataBuffer> source = Flux.just(stringBuffer(""));
Single<String> single = RxJava1SingleConverter.from(this.decoder.decode(source,
ResolvableType.forClassWithGenerics(Single.class, String.class),
MediaType.TEXT_PLAIN));
String result = single.toBlocking().value();
assertEquals("", result);
}
}