Skip to content

Commit 292b4e0

Browse files
6.X: drain message body on request/response replacement (#2715)
1 parent 9390de1 commit 292b4e0

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

core/src/main/java/com/predic8/membrane/core/exchange/AbstractExchange.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,9 @@ public Request getRequest() {
108108
}
109109

110110
public void setRequest(Request request) {
111+
112+
if (this.request != null) this.request.discardBody(); // Drain the previous message body to avoid unread bytes on keep-alive connections.
113+
111114
this.request = request;
112115
if (this.request != null) {
113116
this.request.setErrorMessage(errMessage);
@@ -123,6 +126,9 @@ public Response getResponse() {
123126
}
124127

125128
public void setResponse(Response res) {
129+
130+
if (response != null) response.discardBody(); // Drain the previous message body to avoid unread bytes on keep-alive connections.
131+
126132
response = res;
127133
if (response != null) {
128134
response.setErrorMessage(errMessage);
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.predic8.membrane.core.exchange;
2+
3+
import com.predic8.membrane.core.http.Body;
4+
import com.predic8.membrane.core.http.Message;
5+
import com.predic8.membrane.core.http.Request;
6+
import com.predic8.membrane.core.http.Response;
7+
import org.junit.jupiter.api.Test;
8+
9+
import java.io.ByteArrayInputStream;
10+
import java.util.function.BiConsumer;
11+
import java.util.function.Function;
12+
13+
import static org.junit.jupiter.api.Assertions.assertFalse;
14+
import static org.junit.jupiter.api.Assertions.assertTrue;
15+
16+
class AbstractExchangeTest {
17+
18+
private static Body body(String s) {
19+
return new Body(new ByteArrayInputStream(s.getBytes()), s.getBytes().length);
20+
}
21+
22+
private static <M extends Message> void assertOldBodyDrainedOnReplace(Function<Body, M> msgFactory, BiConsumer<Exchange, M> setter) {
23+
Exchange exc = new Exchange(null);
24+
25+
Body oldBody = body("old");
26+
M m1 = msgFactory.apply(oldBody);
27+
setter.accept(exc, m1);
28+
29+
assertFalse(oldBody.isRead());
30+
31+
Body newBody = body("new");
32+
M m2 = msgFactory.apply(newBody);
33+
setter.accept(exc, m2);
34+
35+
assertTrue(oldBody.isRead(), "old body must be read/drained when message is replaced");
36+
}
37+
38+
@Test
39+
void setResponse_readsOldBodyOnReplace() {
40+
assertOldBodyDrainedOnReplace(
41+
b -> {
42+
Response r = Response.ok().build();
43+
r.setBody(b);
44+
return r;
45+
},
46+
Exchange::setResponse
47+
);
48+
}
49+
50+
@Test
51+
void setRequest_readsOldBodyOnReplace() {
52+
assertOldBodyDrainedOnReplace(
53+
b -> new Request() {{setBody(b);}},
54+
Exchange::setRequest
55+
);
56+
}
57+
58+
59+
}

0 commit comments

Comments
 (0)