Skip to content

Commit

Permalink
request body should not be reset - some controllers might need to rea…
Browse files Browse the repository at this point in the history
…d it
  • Loading branch information
asolntsev authored and Andrei Solntsev, Elina Matvejeva committed Feb 20, 2018
1 parent 83159ae commit 91cae9f
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 14 deletions.
13 changes: 4 additions & 9 deletions framework/src/play/data/parsing/TextParser.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,22 @@
import play.exceptions.UnexpectedException;
import play.mvc.Http;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

public class TextParser extends DataParser {
import static org.apache.commons.io.IOUtils.toByteArray;

public class TextParser extends DataParser {
@Override
public Map<String, String[]> parse(Http.Request request) {
try {
Map<String, String[]> params = new HashMap<>();
ByteArrayOutputStream os = new ByteArrayOutputStream();
int b;
while ((b = request.body.read()) != -1) {
os.write(b);
}
byte[] data = os.toByteArray();
byte[] data = toByteArray(request.body);
params.put("body", new String[] {new String(data, request.encoding)});
request.body.reset();
return params;
} catch (Exception e) {
throw new UnexpectedException(e);
}
}

}
5 changes: 0 additions & 5 deletions framework/src/play/mvc/Scope.java
Original file line number Diff line number Diff line change
Expand Up @@ -342,11 +342,6 @@ public void checkAndParse() {
_mergeWith(dataParser.parse(request));
}
}
try {
request.body.close();
} catch (Exception e) {
//
}
requestIsParsed = true;
}
}
Expand Down
30 changes: 30 additions & 0 deletions framework/test/play/data/parsing/TextParserTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package play.data.parsing;

import org.junit.Test;
import play.mvc.Http;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.commons.io.IOUtils.toByteArray;
import static org.assertj.core.api.Assertions.assertThat;

public class TextParserTest {
TextParser parser = new TextParser();

@Test
public void parsesRequestBodyAsText() throws IOException {
Http.Request request = new Http.Request();
request.encoding = UTF_8.name();
request.body = new ByteArrayInputStream("Don't reset me please".getBytes(UTF_8));

assertThat(parser.parse(request).get("body"))
.as("returns request body as <'body', body> map")
.isEqualTo(new String[] {"Don't reset me please"});

assertThat(toByteArray(request.body))
.as("Important: request body should not be reset - some controllers might need to read it")
.isEqualTo("Don't reset me please".getBytes(UTF_8));
}
}

0 comments on commit 91cae9f

Please sign in to comment.