Skip to content

Commit 00ac46c

Browse files
committed
8310645: CancelledResponse.java does not use HTTP/2 when testing the HttpClient
Reviewed-by: dfuchs
1 parent d6578bf commit 00ac46c

File tree

1 file changed

+258
-0
lines changed

1 file changed

+258
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,258 @@
1+
/*
2+
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
3+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4+
*
5+
* This code is free software; you can redistribute it and/or modify it
6+
* under the terms of the GNU General Public License version 2 only, as
7+
* published by the Free Software Foundation.
8+
*
9+
* This code is distributed in the hope that it will be useful, but WITHOUT
10+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12+
* version 2 for more details (a copy is included in the LICENSE file that
13+
* accompanied this code).
14+
*
15+
* You should have received a copy of the GNU General Public License version
16+
* 2 along with this work; if not, write to the Free Software Foundation,
17+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18+
*
19+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20+
* or visit www.oracle.com if you need additional information or have any
21+
* questions.
22+
*/
23+
24+
import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpTestExchange;
25+
import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpTestServer;
26+
import jdk.test.lib.RandomFactory;
27+
import jdk.test.lib.net.SimpleSSLContext;
28+
import org.testng.annotations.AfterTest;
29+
import org.testng.annotations.BeforeTest;
30+
import org.testng.annotations.DataProvider;
31+
import org.testng.annotations.Test;
32+
33+
import javax.net.ssl.SSLContext;
34+
import java.io.IOException;
35+
import java.io.InputStream;
36+
import java.io.OutputStream;
37+
import java.net.URI;
38+
import java.net.http.HttpClient;
39+
import java.net.http.HttpClient.Version;
40+
import java.net.http.HttpRequest;
41+
import java.net.http.HttpResponse;
42+
import java.net.http.HttpResponse.BodyHandler;
43+
import java.nio.ByteBuffer;
44+
import java.nio.charset.StandardCharsets;
45+
import java.util.List;
46+
import java.util.Random;
47+
import java.util.concurrent.CompletableFuture;
48+
import java.util.concurrent.CompletionStage;
49+
import java.util.concurrent.Flow;
50+
import java.util.concurrent.atomic.AtomicBoolean;
51+
import java.util.concurrent.atomic.AtomicInteger;
52+
53+
import static java.lang.System.out;
54+
import static java.net.http.HttpClient.Version.*;
55+
import static jdk.httpclient.test.lib.common.HttpServerAdapters.*;
56+
import static org.testng.Assert.assertEquals;
57+
import static org.testng.Assert.assertTrue;
58+
59+
/*
60+
* @test
61+
* @library /test/lib /test/jdk/java/net/httpclient/lib
62+
* @build jdk.test.lib.net.SimpleSSLContext
63+
* @run testng/othervm -Djdk.internal.httpclient.debug=true CancelledResponse2
64+
*/
65+
66+
public class CancelledResponse2 {
67+
68+
69+
HttpTestServer h2TestServer;
70+
URI h2TestServerURI;
71+
private SSLContext sslContext;
72+
private static final Random random = RandomFactory.getRandom();
73+
private static final int MAX_CLIENT_DELAY = 160;
74+
75+
@DataProvider(name = "versions")
76+
public Object[][] positive() {
77+
return new Object[][]{
78+
{ HTTP_2, h2TestServerURI },
79+
};
80+
}
81+
82+
private static void delay() {
83+
int delay = random.nextInt(MAX_CLIENT_DELAY);
84+
try {
85+
System.out.println("client delay: " + delay);
86+
Thread.sleep(delay);
87+
} catch (InterruptedException x) {
88+
out.println("Unexpected exception: " + x);
89+
}
90+
}
91+
92+
@Test(dataProvider = "versions")
93+
public void test(Version version, URI uri) throws Exception {
94+
for (int i = 0; i < 5; i++) {
95+
HttpClient httpClient = HttpClient.newBuilder().sslContext(sslContext).version(version).build();
96+
HttpRequest httpRequest = HttpRequest.newBuilder(uri)
97+
.version(version)
98+
.GET()
99+
.build();
100+
AtomicBoolean cancelled = new AtomicBoolean();
101+
BodyHandler<String> bh = ofString(response, cancelled);
102+
CompletableFuture<HttpResponse<String>> cf = httpClient.sendAsync(httpRequest, bh);
103+
try {
104+
cf.get();
105+
} catch (Exception e) {
106+
e.printStackTrace();
107+
assertTrue(e.getCause() instanceof IOException, "HTTP/2 should cancel with an IOException when the Subscription is cancelled.");
108+
}
109+
assertTrue(cf.isCompletedExceptionally());
110+
assertTrue(cancelled.get());
111+
}
112+
}
113+
114+
@BeforeTest
115+
public void setup() throws IOException {
116+
sslContext = new SimpleSSLContext().get();
117+
h2TestServer = HttpTestServer.create(HTTP_2, sslContext);
118+
h2TestServer.addHandler(new CancelledResponseHandler(), "/h2");
119+
h2TestServerURI = URI.create("https://" + h2TestServer.serverAuthority() + "/h2");
120+
121+
h2TestServer.start();
122+
}
123+
124+
@AfterTest
125+
public void teardown() {
126+
h2TestServer.stop();
127+
}
128+
129+
BodyHandler<String> ofString(String expected, AtomicBoolean cancelled) {
130+
return new CancellingHandler(expected, cancelled);
131+
}
132+
133+
static class CancelledResponseHandler implements HttpTestHandler {
134+
135+
@Override
136+
public void handle(HttpTestExchange t) throws IOException {
137+
138+
byte[] resp = response.getBytes(StandardCharsets.UTF_8);
139+
140+
t.sendResponseHeaders(200, resp.length);
141+
System.err.println(resp.length);
142+
try (InputStream is = t.getRequestBody();
143+
OutputStream os = t.getResponseBody()) {
144+
for (byte b : resp) {
145+
// This can be used to verify that varying amounts of the response data are sent.
146+
System.err.print((char) b);
147+
os.write(b);
148+
os.flush();
149+
try {
150+
Thread.sleep(1);
151+
} catch (InterruptedException e) {
152+
throw new RuntimeException(e);
153+
}
154+
}
155+
}
156+
}
157+
}
158+
159+
static final String response = "Lorem ipsum dolor sit amet consectetur adipiscing elit, sed do eiusmod tempor quis" +
160+
" nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
161+
162+
record CancellingHandler(String expected, AtomicBoolean cancelled) implements BodyHandler<String> {
163+
@Override
164+
public HttpResponse.BodySubscriber<String> apply(HttpResponse.ResponseInfo rinfo) {
165+
assert !cancelled.get();
166+
return new CancellingBodySubscriber(expected, cancelled);
167+
}
168+
}
169+
170+
171+
static class CancellingBodySubscriber implements HttpResponse.BodySubscriber<String> {
172+
private final String expected;
173+
private final CompletableFuture<String> result;
174+
private Flow.Subscription subscription;
175+
final AtomicInteger index = new AtomicInteger();
176+
final AtomicBoolean cancelled;
177+
CancellingBodySubscriber(String expected, AtomicBoolean cancelled) {
178+
this.cancelled = cancelled;
179+
this.expected = expected;
180+
result = new CompletableFuture<>();
181+
}
182+
183+
@Override
184+
public CompletionStage<String> getBody() {
185+
return result;
186+
}
187+
188+
@Override
189+
public void onSubscribe(Flow.Subscription subscription) {
190+
this.subscription = subscription;
191+
subscription.request(1);
192+
}
193+
194+
@Override
195+
public void onNext(List<ByteBuffer> item) {
196+
//if (result.isDone())
197+
// Max Delay is 180ms as there is 160 characters in response which gives at least 160ms in some test cases and
198+
// allows a response to complete fully with a lee-way of 20ms in other cases. Otherwise, response body is
199+
// usually partial. Each character is written by the server handler with a 1ms delay.
200+
delay();
201+
for (ByteBuffer b : item) {
202+
while (b.hasRemaining() && !result.isDone()) {
203+
int i = index.getAndIncrement();
204+
char at = expected.charAt(i);
205+
byte[] data = new byte[b.remaining()];
206+
b.get(data); // we know that the server writes 1 char
207+
String s = new String(data);
208+
char c = s.charAt(0);
209+
System.err.print(c);
210+
if (c != at) {
211+
Throwable x = new IllegalStateException("char at "
212+
+ i + " is '" + c + "' expected '"
213+
+ at + "' for \"" + expected +"\"");
214+
out.println("unexpected char received, cancelling");
215+
subscription.cancel();
216+
result.completeExceptionally(x);
217+
return;
218+
}
219+
}
220+
System.err.println();
221+
}
222+
if (index.get() > 0 && !result.isDone()) {
223+
// we should complete the result here, but let's
224+
// see if we get something back...
225+
out.println("Cancelling subscription after reading " + index.get());
226+
cancelled.set(true);
227+
subscription.cancel();
228+
result.completeExceptionally(new CancelException());
229+
return;
230+
}
231+
if (!result.isDone()) {
232+
out.println("requesting 1 more");
233+
subscription.request(1);
234+
}
235+
}
236+
237+
@Override
238+
public void onError(Throwable throwable) {
239+
result.completeExceptionally(throwable);
240+
}
241+
242+
@Override
243+
public void onComplete() {
244+
int len = index.get();
245+
if (len == expected.length()) {
246+
result.complete(expected);
247+
} else {
248+
Throwable x = new IllegalStateException("received only "
249+
+ len + " chars, expected " + expected.length()
250+
+ " for \"" + expected +"\"");
251+
result.completeExceptionally(x);
252+
}
253+
}
254+
}
255+
256+
static class CancelException extends IOException {
257+
}
258+
}

0 commit comments

Comments
 (0)