Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/net/httpclient/ConcurrentResponses.java
41149 views
1
/*
2
* Copyright (c) 2018, 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
/*
25
* @test
26
* @bug 8195823
27
* @summary Buffers given to response body subscribers should not contain
28
* unprocessed HTTP data
29
* @modules java.base/sun.net.www.http
30
* java.net.http/jdk.internal.net.http.common
31
* java.net.http/jdk.internal.net.http.frame
32
* java.net.http/jdk.internal.net.http.hpack
33
* java.logging
34
* jdk.httpserver
35
* @library /test/lib http2/server
36
* @build Http2TestServer
37
* @build jdk.test.lib.net.SimpleSSLContext
38
* @run testng/othervm
39
* -Djdk.httpclient.HttpClient.log=headers,errors,channel
40
* ConcurrentResponses
41
*/
42
43
import java.io.IOException;
44
import java.io.InputStream;
45
import java.io.OutputStream;
46
import java.net.InetAddress;
47
import java.net.InetSocketAddress;
48
import java.net.URI;
49
import java.nio.ByteBuffer;
50
import java.util.HashMap;
51
import java.util.List;
52
import java.util.Map;
53
import java.util.concurrent.CompletableFuture;
54
import java.util.concurrent.CompletionStage;
55
import java.util.concurrent.Flow;
56
import java.util.stream.IntStream;
57
import javax.net.ssl.SSLContext;
58
import com.sun.net.httpserver.HttpExchange;
59
import com.sun.net.httpserver.HttpHandler;
60
import com.sun.net.httpserver.HttpServer;
61
import com.sun.net.httpserver.HttpsConfigurator;
62
import com.sun.net.httpserver.HttpsServer;
63
import java.net.http.HttpClient;
64
import java.net.http.HttpRequest;
65
import java.net.http.HttpResponse;
66
import java.net.http.HttpResponse.BodyHandler;
67
import java.net.http.HttpResponse.BodyHandlers;
68
import java.net.http.HttpResponse.BodySubscriber;
69
import java.net.http.HttpResponse.BodySubscribers;
70
import jdk.test.lib.net.SimpleSSLContext;
71
import org.testng.annotations.AfterTest;
72
import org.testng.annotations.BeforeTest;
73
import org.testng.annotations.DataProvider;
74
import org.testng.annotations.Test;
75
import static java.nio.charset.StandardCharsets.UTF_8;
76
import static java.net.http.HttpResponse.BodyHandlers.discarding;
77
import static org.testng.Assert.assertEquals;
78
import static org.testng.Assert.assertFalse;
79
import static org.testng.Assert.fail;
80
81
public class ConcurrentResponses {
82
83
SSLContext sslContext;
84
HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ]
85
HttpsServer httpsTestServer; // HTTPS/1.1
86
Http2TestServer http2TestServer; // HTTP/2 ( h2c )
87
Http2TestServer https2TestServer; // HTTP/2 ( h2 )
88
String httpFixedURI, httpsFixedURI, httpChunkedURI, httpsChunkedURI;
89
String http2FixedURI, https2FixedURI, http2VariableURI, https2VariableURI;
90
91
static final int CONCURRENT_REQUESTS = 13;
92
93
static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
94
static final int ALPHABET_LENGTH = ALPHABET.length();
95
96
static final String stringOfLength(int requiredLength) {
97
StringBuilder sb = new StringBuilder(requiredLength);
98
IntStream.range(0, requiredLength)
99
.mapToObj(i -> ALPHABET.charAt(i % ALPHABET_LENGTH))
100
.forEach(c -> sb.append(c));
101
return sb.toString();
102
}
103
104
/** An array of different Strings, to be used as bodies. */
105
static final String[] BODIES = bodies();
106
107
static String[] bodies() {
108
String[] bodies = new String[CONCURRENT_REQUESTS];
109
for (int i=0;i<CONCURRENT_REQUESTS; i++) {
110
// slightly, but still, different bodies
111
bodies[i] = "Request-" + i + "-body-" + stringOfLength((1024) + i);
112
}
113
return bodies;
114
}
115
116
/**
117
* Asserts the given response's status code is 200.
118
* Returns a CF that completes with the given response.
119
*/
120
static final <T> CompletionStage<HttpResponse<T>>
121
assert200ResponseCode(HttpResponse<T> response) {
122
assertEquals(response.statusCode(), 200);
123
return CompletableFuture.completedFuture(response);
124
}
125
126
/**
127
* Asserts that the given response's body is equal to the given body.
128
* Returns a CF that completes with the given response.
129
*/
130
static final <T> CompletionStage<HttpResponse<T>>
131
assertbody(HttpResponse<T> response, T body) {
132
assertEquals(response.body(), body);
133
return CompletableFuture.completedFuture(response);
134
}
135
136
@DataProvider(name = "uris")
137
public Object[][] variants() {
138
return new Object[][]{
139
{ httpFixedURI },
140
{ httpsFixedURI },
141
{ httpChunkedURI },
142
{ httpsChunkedURI },
143
{ http2FixedURI },
144
{ https2FixedURI },
145
{ http2VariableURI },
146
{ https2VariableURI }
147
};
148
}
149
150
151
// The ofString implementation accumulates data, below a certain threshold
152
// into the byte buffers it is given.
153
@Test(dataProvider = "uris")
154
void testAsString(String uri) throws Exception {
155
HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();
156
157
Map<HttpRequest, String> requests = new HashMap<>();
158
for (int i=0;i<CONCURRENT_REQUESTS; i++) {
159
HttpRequest request = HttpRequest.newBuilder(URI.create(uri + "?" + i))
160
.build();
161
requests.put(request, BODIES[i]);
162
}
163
164
// initial connection to seed the cache so next parallel connections reuse it
165
client.sendAsync(HttpRequest.newBuilder(URI.create(uri)).build(), discarding()).join();
166
167
// will reuse connection cached from the previous request ( when HTTP/2 )
168
CompletableFuture.allOf(requests.keySet().parallelStream()
169
.map(request -> client.sendAsync(request, BodyHandlers.ofString()))
170
.map(cf -> cf.thenCompose(ConcurrentResponses::assert200ResponseCode))
171
.map(cf -> cf.thenCompose(response -> assertbody(response, requests.get(response.request()))))
172
.toArray(CompletableFuture<?>[]::new))
173
.join();
174
}
175
176
// The custom subscriber aggressively attacks any area, between the limit
177
// and the capacity, in the byte buffers it is given, by writing 'X' into it.
178
@Test(dataProvider = "uris")
179
void testWithCustomSubscriber(String uri) throws Exception {
180
HttpClient client = HttpClient.newBuilder().sslContext(sslContext).build();
181
182
Map<HttpRequest, String> requests = new HashMap<>();
183
for (int i=0;i<CONCURRENT_REQUESTS; i++) {
184
HttpRequest request = HttpRequest.newBuilder(URI.create(uri + "?" + i))
185
.build();
186
requests.put(request, BODIES[i]);
187
}
188
189
// initial connection to seed the cache so next parallel connections reuse it
190
client.sendAsync(HttpRequest.newBuilder(URI.create(uri)).build(), discarding()).join();
191
192
// will reuse connection cached from the previous request ( when HTTP/2 )
193
CompletableFuture.allOf(requests.keySet().parallelStream()
194
.map(request -> client.sendAsync(request, CustomSubscriber.handler))
195
.map(cf -> cf.thenCompose(ConcurrentResponses::assert200ResponseCode))
196
.map(cf -> cf.thenCompose(response -> assertbody(response, requests.get(response.request()))))
197
.toArray(CompletableFuture<?>[]::new))
198
.join();
199
}
200
201
/**
202
* A subscriber that wraps ofString, but mucks with any data between limit
203
* and capacity, if the client mistakenly passes it any that is should not.
204
*/
205
static class CustomSubscriber implements BodySubscriber<String> {
206
static final BodyHandler<String> handler = (r) -> new CustomSubscriber();
207
private final BodySubscriber<String> ofString = BodySubscribers.ofString(UTF_8);
208
209
@Override
210
public CompletionStage<String> getBody() {
211
return ofString.getBody();
212
}
213
214
@Override
215
public void onSubscribe(Flow.Subscription subscription) {
216
ofString.onSubscribe(subscription);
217
}
218
219
@Override
220
public void onNext(List<ByteBuffer> buffers) {
221
// Muck any data beyond the give limit, since there shouldn't
222
// be any of interest to the HTTP Client.
223
for (ByteBuffer buffer : buffers) {
224
if (buffer.isReadOnly())
225
continue;
226
227
if (buffer.limit() != buffer.capacity()) {
228
final int limit = buffer.limit();
229
final int position = buffer.position();
230
buffer.position(buffer.limit());
231
buffer.limit(buffer.capacity());
232
while (buffer.hasRemaining())
233
buffer.put((byte)'X');
234
buffer.position(position); // restore original position
235
buffer.limit(limit); // restore original limit
236
}
237
}
238
ofString.onNext(buffers);
239
}
240
241
@Override
242
public void onError(Throwable throwable) {
243
ofString.onError(throwable);
244
throwable.printStackTrace();
245
fail("UNEXPECTED:" + throwable);
246
}
247
248
@Override
249
public void onComplete() {
250
ofString.onComplete();
251
}
252
}
253
254
static String serverAuthority(HttpServer server) {
255
return InetAddress.getLoopbackAddress().getHostName() + ":"
256
+ server.getAddress().getPort();
257
}
258
259
@BeforeTest
260
public void setup() throws Exception {
261
sslContext = new SimpleSSLContext().get();
262
if (sslContext == null)
263
throw new AssertionError("Unexpected null sslContext");
264
265
InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
266
httpTestServer = HttpServer.create(sa, 0);
267
httpTestServer.createContext("/http1/fixed", new Http1FixedHandler());
268
httpFixedURI = "http://" + serverAuthority(httpTestServer) + "/http1/fixed";
269
httpTestServer.createContext("/http1/chunked", new Http1ChunkedHandler());
270
httpChunkedURI = "http://" + serverAuthority(httpTestServer) + "/http1/chunked";
271
272
httpsTestServer = HttpsServer.create(sa, 0);
273
httpsTestServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
274
httpsTestServer.createContext("/https1/fixed", new Http1FixedHandler());
275
httpsFixedURI = "https://" + serverAuthority(httpsTestServer) + "/https1/fixed";
276
httpsTestServer.createContext("/https1/chunked", new Http1ChunkedHandler());
277
httpsChunkedURI = "https://" + serverAuthority(httpsTestServer) + "/https1/chunked";
278
279
http2TestServer = new Http2TestServer("localhost", false, 0);
280
http2TestServer.addHandler(new Http2FixedHandler(), "/http2/fixed");
281
http2FixedURI = "http://" + http2TestServer.serverAuthority()+ "/http2/fixed";
282
http2TestServer.addHandler(new Http2VariableHandler(), "/http2/variable");
283
http2VariableURI = "http://" + http2TestServer.serverAuthority() + "/http2/variable";
284
285
https2TestServer = new Http2TestServer("localhost", true, sslContext);
286
https2TestServer.addHandler(new Http2FixedHandler(), "/https2/fixed");
287
https2FixedURI = "https://" + https2TestServer.serverAuthority() + "/https2/fixed";
288
https2TestServer.addHandler(new Http2VariableHandler(), "/https2/variable");
289
https2VariableURI = "https://" + https2TestServer.serverAuthority() + "/https2/variable";
290
291
httpTestServer.start();
292
httpsTestServer.start();
293
http2TestServer.start();
294
https2TestServer.start();
295
}
296
297
@AfterTest
298
public void teardown() throws Exception {
299
httpTestServer.stop(0);
300
httpsTestServer.stop(0);
301
http2TestServer.stop();
302
https2TestServer.stop();
303
}
304
305
interface SendResponseHeadersFunction {
306
void apply(int responseCode, long responseLength) throws IOException;
307
}
308
309
// A handler implementation that replies with 200 OK. If the exchange's uri
310
// has a query, then it must be an integer, which is used as an index to
311
// select the particular response body, e.g. /http2/x?5 -> BODIES[5]
312
static void serverHandlerImpl(InputStream inputStream,
313
OutputStream outputStream,
314
URI uri,
315
SendResponseHeadersFunction sendResponseHeadersFunction)
316
throws IOException
317
{
318
try (InputStream is = inputStream;
319
OutputStream os = outputStream) {
320
is.readAllBytes();
321
322
String magicQuery = uri.getQuery();
323
if (magicQuery != null) {
324
int bodyIndex = Integer.valueOf(magicQuery);
325
String body = BODIES[bodyIndex];
326
byte[] bytes = body.getBytes(UTF_8);
327
sendResponseHeadersFunction.apply(200, bytes.length);
328
int offset = 0;
329
// Deliberately attempt to reply with several relatively
330
// small data frames ( each write corresponds to its own
331
// data frame ). Additionally, yield, to encourage other
332
// handlers to execute, therefore increasing the likelihood
333
// of multiple different-stream related frames in the
334
// client's read buffer.
335
while (offset < bytes.length) {
336
int length = Math.min(bytes.length - offset, 64);
337
os.write(bytes, offset, length);
338
os.flush();
339
offset += length;
340
Thread.yield();
341
}
342
} else {
343
sendResponseHeadersFunction.apply(200, 1);
344
os.write('A');
345
}
346
}
347
}
348
349
static class Http1FixedHandler implements HttpHandler {
350
@Override
351
public void handle(HttpExchange t) throws IOException {
352
serverHandlerImpl(t.getRequestBody(),
353
t.getResponseBody(),
354
t.getRequestURI(),
355
(rcode, length) -> t.sendResponseHeaders(rcode, length));
356
}
357
}
358
359
static class Http1ChunkedHandler implements HttpHandler {
360
@Override
361
public void handle(HttpExchange t) throws IOException {
362
serverHandlerImpl(t.getRequestBody(),
363
t.getResponseBody(),
364
t.getRequestURI(),
365
(rcode, ignored) -> t.sendResponseHeaders(rcode, 0 /*chunked*/));
366
}
367
}
368
369
static class Http2FixedHandler implements Http2Handler {
370
@Override
371
public void handle(Http2TestExchange t) throws IOException {
372
serverHandlerImpl(t.getRequestBody(),
373
t.getResponseBody(),
374
t.getRequestURI(),
375
(rcode, length) -> t.sendResponseHeaders(rcode, length));
376
}
377
}
378
379
static class Http2VariableHandler implements Http2Handler {
380
@Override
381
public void handle(Http2TestExchange t) throws IOException {
382
serverHandlerImpl(t.getRequestBody(),
383
t.getResponseBody(),
384
t.getRequestURI(),
385
(rcode, ignored) -> t.sendResponseHeaders(rcode, 0 /* no Content-Length */));
386
}
387
}
388
}
389
390