55763
|
1 |
/*
|
|
2 |
* Copyright (c) 2015, 2017, 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 |
* @modules jdk.incubator.httpclient
|
|
27 |
* java.logging
|
|
28 |
* jdk.httpserver
|
|
29 |
* @library /lib/testlibrary/ /
|
|
30 |
* @build jdk.testlibrary.SimpleSSLContext
|
|
31 |
* @compile ../../../com/sun/net/httpserver/LogFilter.java
|
|
32 |
* @compile ../../../com/sun/net/httpserver/EchoHandler.java
|
|
33 |
* @compile ../../../com/sun/net/httpserver/FileServerHandler.java
|
|
34 |
* @run main/othervm/timeout=40 ManyRequestsLegacy
|
|
35 |
* @run main/othervm/timeout=40 -Dtest.insertDelay=true ManyRequestsLegacy
|
|
36 |
* @run main/othervm/timeout=40 -Dtest.chunkSize=64 ManyRequestsLegacy
|
|
37 |
* @run main/othervm/timeout=40 -Dtest.insertDelay=true -Dtest.chunkSize=64 ManyRequestsLegacy
|
|
38 |
* @summary Send a large number of requests asynchronously using the legacy URL.openConnection(), to help sanitize results of the test ManyRequest.java.
|
|
39 |
*/
|
|
40 |
|
|
41 |
import javax.net.ssl.HttpsURLConnection;
|
|
42 |
import javax.net.ssl.HostnameVerifier;
|
|
43 |
import com.sun.net.httpserver.HttpsConfigurator;
|
|
44 |
import com.sun.net.httpserver.HttpsParameters;
|
|
45 |
import com.sun.net.httpserver.HttpsServer;
|
|
46 |
import com.sun.net.httpserver.HttpExchange;
|
|
47 |
import java.io.IOException;
|
|
48 |
import java.io.InputStream;
|
|
49 |
import java.io.OutputStream;
|
|
50 |
import java.net.HttpURLConnection;
|
|
51 |
import java.net.URI;
|
|
52 |
import java.net.URLConnection;
|
|
53 |
import java.security.NoSuchAlgorithmException;
|
|
54 |
import java.util.concurrent.CompletableFuture;
|
|
55 |
import java.util.stream.Collectors;
|
|
56 |
import javax.net.ssl.SSLContext;
|
|
57 |
import javax.net.ssl.SSLParameters;
|
|
58 |
import javax.net.ssl.SSLSession;
|
|
59 |
import jdk.incubator.http.HttpClient;
|
|
60 |
import jdk.incubator.http.HttpClient.Version;
|
|
61 |
import jdk.incubator.http.HttpHeaders;
|
|
62 |
import jdk.incubator.http.HttpRequest;
|
|
63 |
import jdk.incubator.http.HttpResponse;
|
|
64 |
import java.net.InetSocketAddress;
|
|
65 |
import java.util.Arrays;
|
|
66 |
import java.util.Formatter;
|
|
67 |
import java.util.HashMap;
|
|
68 |
import java.util.LinkedList;
|
|
69 |
import java.util.Random;
|
|
70 |
import java.util.concurrent.ExecutorService;
|
|
71 |
import java.util.logging.Logger;
|
|
72 |
import java.util.logging.Level;
|
|
73 |
import jdk.testlibrary.SimpleSSLContext;
|
|
74 |
import static jdk.incubator.http.HttpRequest.BodyPublisher.fromByteArray;
|
|
75 |
import static jdk.incubator.http.HttpResponse.BodyHandler.asByteArray;
|
|
76 |
|
|
77 |
public class ManyRequestsLegacy {
|
|
78 |
|
|
79 |
volatile static int counter = 0;
|
|
80 |
|
|
81 |
public static void main(String[] args) throws Exception {
|
|
82 |
Logger logger = Logger.getLogger("com.sun.net.httpserver");
|
|
83 |
logger.setLevel(Level.ALL);
|
|
84 |
logger.info("TEST");
|
|
85 |
System.out.println("Sending " + REQUESTS
|
|
86 |
+ " requests; delay=" + INSERT_DELAY
|
|
87 |
+ ", chunks=" + CHUNK_SIZE
|
|
88 |
+ ", XFixed=" + XFIXED);
|
|
89 |
SSLContext ctx = new SimpleSSLContext().get();
|
|
90 |
SSLContext.setDefault(ctx);
|
|
91 |
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
|
|
92 |
public boolean verify(String hostname, SSLSession session) {
|
|
93 |
return true;
|
|
94 |
}
|
|
95 |
});
|
|
96 |
InetSocketAddress addr = new InetSocketAddress(0);
|
|
97 |
HttpsServer server = HttpsServer.create(addr, 0);
|
|
98 |
server.setHttpsConfigurator(new Configurator(ctx));
|
|
99 |
|
|
100 |
LegacyHttpClient client = new LegacyHttpClient();
|
|
101 |
|
|
102 |
try {
|
|
103 |
test(server, client);
|
|
104 |
System.out.println("OK");
|
|
105 |
} finally {
|
|
106 |
server.stop(0);
|
|
107 |
}
|
|
108 |
}
|
|
109 |
|
|
110 |
//static final int REQUESTS = 1000;
|
|
111 |
static final int REQUESTS = 20;
|
|
112 |
static final boolean INSERT_DELAY = Boolean.getBoolean("test.insertDelay");
|
|
113 |
static final int CHUNK_SIZE = Math.max(0,
|
|
114 |
Integer.parseInt(System.getProperty("test.chunkSize", "0")));
|
|
115 |
static final boolean XFIXED = Boolean.getBoolean("test.XFixed");
|
|
116 |
|
|
117 |
static class LegacyHttpClient {
|
|
118 |
static final class LegacyHttpResponse extends HttpResponse<byte[]> {
|
|
119 |
final HttpRequest request;
|
|
120 |
final byte[] response;
|
|
121 |
final int statusCode;
|
|
122 |
public LegacyHttpResponse(HttpRequest request, int statusCode, byte[] response) {
|
|
123 |
this.request = request;
|
|
124 |
this.statusCode = statusCode;
|
|
125 |
this.response = response;
|
|
126 |
}
|
|
127 |
private <T> T error() {
|
|
128 |
throw new UnsupportedOperationException("Not supported yet.");
|
|
129 |
}
|
|
130 |
@Override
|
|
131 |
public int statusCode() { return statusCode;}
|
|
132 |
@Override
|
|
133 |
public HttpRequest request() {return request;}
|
|
134 |
@Override
|
|
135 |
public HttpRequest finalRequest() {return request;}
|
|
136 |
@Override
|
|
137 |
public HttpHeaders headers() { return error(); }
|
|
138 |
@Override
|
|
139 |
public byte[] body() {return response;}
|
|
140 |
@Override
|
|
141 |
public SSLParameters sslParameters() {
|
|
142 |
try {
|
|
143 |
return SSLContext.getDefault().getDefaultSSLParameters();
|
|
144 |
} catch (NoSuchAlgorithmException ex) {
|
|
145 |
throw new UnsupportedOperationException(ex);
|
|
146 |
}
|
|
147 |
}
|
|
148 |
@Override
|
|
149 |
public URI uri() { return request.uri();}
|
|
150 |
@Override
|
|
151 |
public HttpClient.Version version() { return Version.HTTP_1_1;}
|
|
152 |
}
|
|
153 |
|
|
154 |
private void debugCompleted(String tag, long startNanos, HttpRequest req) {
|
|
155 |
System.err.println(tag + " elapsed "
|
|
156 |
+ (System.nanoTime() - startNanos)/1000_000L
|
|
157 |
+ " millis for " + req.method()
|
|
158 |
+ " to " + req.uri());
|
|
159 |
}
|
|
160 |
|
|
161 |
CompletableFuture<? extends HttpResponse<byte[]>> sendAsync(HttpRequest r, byte[] buf) {
|
|
162 |
long start = System.nanoTime();
|
|
163 |
try {
|
|
164 |
CompletableFuture<LegacyHttpResponse> cf = new CompletableFuture<>();
|
|
165 |
URLConnection urlc = r.uri().toURL().openConnection();
|
|
166 |
HttpURLConnection httpc = (HttpURLConnection)urlc;
|
|
167 |
httpc.setRequestMethod(r.method());
|
|
168 |
for (String s : r.headers().map().keySet()) {
|
|
169 |
httpc.setRequestProperty(s, r.headers().allValues(s)
|
|
170 |
.stream().collect(Collectors.joining(",")));
|
|
171 |
}
|
|
172 |
httpc.setDoInput(true);
|
|
173 |
if (buf != null) httpc.setDoOutput(true);
|
|
174 |
Thread t = new Thread(() -> {
|
|
175 |
try {
|
|
176 |
if (buf != null) {
|
|
177 |
try (OutputStream os = httpc.getOutputStream()) {
|
|
178 |
os.write(buf);
|
|
179 |
os.flush();
|
|
180 |
}
|
|
181 |
}
|
|
182 |
LegacyHttpResponse response = new LegacyHttpResponse(r,
|
|
183 |
httpc.getResponseCode(),httpc.getInputStream().readAllBytes());
|
|
184 |
cf.complete(response);
|
|
185 |
} catch(Throwable x) {
|
|
186 |
cf.completeExceptionally(x);
|
|
187 |
}
|
|
188 |
});
|
|
189 |
t.start();
|
|
190 |
return cf.whenComplete((b,x) -> debugCompleted("ClientImpl (async)", start, r));
|
|
191 |
} catch(Throwable t) {
|
|
192 |
debugCompleted("ClientImpl (async)", start, r);
|
|
193 |
return CompletableFuture.failedFuture(t);
|
|
194 |
}
|
|
195 |
}
|
|
196 |
}
|
|
197 |
|
|
198 |
static class TestEchoHandler extends EchoHandler {
|
|
199 |
final Random rand = new Random();
|
|
200 |
@Override
|
|
201 |
public void handle(HttpExchange e) throws IOException {
|
|
202 |
System.out.println("Server: received " + e.getRequestURI());
|
|
203 |
super.handle(e);
|
|
204 |
}
|
|
205 |
@Override
|
|
206 |
protected void close(OutputStream os) throws IOException {
|
|
207 |
if (INSERT_DELAY) {
|
|
208 |
try { Thread.sleep(rand.nextInt(200)); }
|
|
209 |
catch (InterruptedException e) {}
|
|
210 |
}
|
|
211 |
os.close();
|
|
212 |
}
|
|
213 |
@Override
|
|
214 |
protected void close(InputStream is) throws IOException {
|
|
215 |
if (INSERT_DELAY) {
|
|
216 |
try { Thread.sleep(rand.nextInt(200)); }
|
|
217 |
catch (InterruptedException e) {}
|
|
218 |
}
|
|
219 |
is.close();
|
|
220 |
}
|
|
221 |
}
|
|
222 |
|
|
223 |
static void test(HttpsServer server, LegacyHttpClient client) throws Exception {
|
|
224 |
int port = server.getAddress().getPort();
|
|
225 |
URI baseURI = new URI("https://127.0.0.1:" + port + "/foo/x");
|
|
226 |
server.createContext("/foo", new TestEchoHandler());
|
|
227 |
server.start();
|
|
228 |
|
|
229 |
RequestLimiter limiter = new RequestLimiter(40);
|
|
230 |
Random rand = new Random();
|
|
231 |
CompletableFuture<?>[] results = new CompletableFuture<?>[REQUESTS];
|
|
232 |
HashMap<HttpRequest,byte[]> bodies = new HashMap<>();
|
|
233 |
|
|
234 |
for (int i=0; i<REQUESTS; i++) {
|
|
235 |
byte[] buf = new byte[(i+1)*CHUNK_SIZE+i+1]; // different size bodies
|
|
236 |
rand.nextBytes(buf);
|
|
237 |
URI uri = new URI(baseURI.toString() + String.valueOf(i+1));
|
|
238 |
HttpRequest r = HttpRequest.newBuilder(uri)
|
|
239 |
.header("XFixed", "true")
|
|
240 |
.POST(fromByteArray(buf))
|
|
241 |
.build();
|
|
242 |
bodies.put(r, buf);
|
|
243 |
|
|
244 |
results[i] =
|
|
245 |
limiter.whenOkToSend()
|
|
246 |
.thenCompose((v) -> {
|
|
247 |
System.out.println("Client: sendAsync: " + r.uri());
|
|
248 |
return client.sendAsync(r, buf);
|
|
249 |
})
|
|
250 |
.thenCompose((resp) -> {
|
|
251 |
limiter.requestComplete();
|
|
252 |
if (resp.statusCode() != 200) {
|
|
253 |
String s = "Expected 200, got: " + resp.statusCode();
|
|
254 |
System.out.println(s + " from "
|
|
255 |
+ resp.request().uri().getPath());
|
|
256 |
return completedWithIOException(s);
|
|
257 |
} else {
|
|
258 |
counter++;
|
|
259 |
System.out.println("Result (" + counter + ") from "
|
|
260 |
+ resp.request().uri().getPath());
|
|
261 |
}
|
|
262 |
return CompletableFuture.completedStage(resp.body())
|
|
263 |
.thenApply((b) -> new Pair<>(resp, b));
|
|
264 |
})
|
|
265 |
.thenAccept((pair) -> {
|
|
266 |
HttpRequest request = pair.t.request();
|
|
267 |
byte[] requestBody = bodies.get(request);
|
|
268 |
check(Arrays.equals(requestBody, pair.u),
|
|
269 |
"bodies not equal:[" + bytesToHexString(requestBody)
|
|
270 |
+ "] [" + bytesToHexString(pair.u) + "]");
|
|
271 |
|
|
272 |
});
|
|
273 |
}
|
|
274 |
|
|
275 |
// wait for them all to complete and throw exception in case of error
|
|
276 |
CompletableFuture.allOf(results).join();
|
|
277 |
}
|
|
278 |
|
|
279 |
static <T> CompletableFuture<T> completedWithIOException(String message) {
|
|
280 |
return CompletableFuture.failedFuture(new IOException(message));
|
|
281 |
}
|
|
282 |
|
|
283 |
static String bytesToHexString(byte[] bytes) {
|
|
284 |
if (bytes == null)
|
|
285 |
return "null";
|
|
286 |
|
|
287 |
StringBuilder sb = new StringBuilder(bytes.length * 2);
|
|
288 |
|
|
289 |
Formatter formatter = new Formatter(sb);
|
|
290 |
for (byte b : bytes) {
|
|
291 |
formatter.format("%02x", b);
|
|
292 |
}
|
|
293 |
|
|
294 |
return sb.toString();
|
|
295 |
}
|
|
296 |
|
|
297 |
static final class Pair<T,U> {
|
|
298 |
Pair(T t, U u) {
|
|
299 |
this.t = t; this.u = u;
|
|
300 |
}
|
|
301 |
T t;
|
|
302 |
U u;
|
|
303 |
}
|
|
304 |
|
|
305 |
/**
|
|
306 |
* A simple limiter for controlling the number of requests to be run in
|
|
307 |
* parallel whenOkToSend() is called which returns a CF<Void> that allows
|
|
308 |
* each individual request to proceed, or block temporarily (blocking occurs
|
|
309 |
* on the waiters list here. As each request actually completes
|
|
310 |
* requestComplete() is called to notify this object, and allow some
|
|
311 |
* requests to continue.
|
|
312 |
*/
|
|
313 |
static class RequestLimiter {
|
|
314 |
|
|
315 |
static final CompletableFuture<Void> COMPLETED_FUTURE =
|
|
316 |
CompletableFuture.completedFuture(null);
|
|
317 |
|
|
318 |
final int maxnumber;
|
|
319 |
final LinkedList<CompletableFuture<Void>> waiters;
|
|
320 |
int number;
|
|
321 |
boolean blocked;
|
|
322 |
|
|
323 |
RequestLimiter(int maximum) {
|
|
324 |
waiters = new LinkedList<>();
|
|
325 |
maxnumber = maximum;
|
|
326 |
}
|
|
327 |
|
|
328 |
synchronized void requestComplete() {
|
|
329 |
number--;
|
|
330 |
// don't unblock until number of requests has halved.
|
|
331 |
if ((blocked && number <= maxnumber / 2) ||
|
|
332 |
(!blocked && waiters.size() > 0)) {
|
|
333 |
int toRelease = Math.min(maxnumber - number, waiters.size());
|
|
334 |
for (int i=0; i<toRelease; i++) {
|
|
335 |
CompletableFuture<Void> f = waiters.remove();
|
|
336 |
number ++;
|
|
337 |
f.complete(null);
|
|
338 |
}
|
|
339 |
blocked = number >= maxnumber;
|
|
340 |
}
|
|
341 |
}
|
|
342 |
|
|
343 |
synchronized CompletableFuture<Void> whenOkToSend() {
|
|
344 |
if (blocked || number + 1 >= maxnumber) {
|
|
345 |
blocked = true;
|
|
346 |
CompletableFuture<Void> r = new CompletableFuture<>();
|
|
347 |
waiters.add(r);
|
|
348 |
return r;
|
|
349 |
} else {
|
|
350 |
number++;
|
|
351 |
return COMPLETED_FUTURE;
|
|
352 |
}
|
|
353 |
}
|
|
354 |
}
|
|
355 |
|
|
356 |
static void check(boolean cond, Object... msg) {
|
|
357 |
if (cond)
|
|
358 |
return;
|
|
359 |
StringBuilder sb = new StringBuilder();
|
|
360 |
for (Object o : msg)
|
|
361 |
sb.append(o);
|
|
362 |
throw new RuntimeException(sb.toString());
|
|
363 |
}
|
|
364 |
|
|
365 |
static class Configurator extends HttpsConfigurator {
|
|
366 |
public Configurator(SSLContext ctx) {
|
|
367 |
super(ctx);
|
|
368 |
}
|
|
369 |
|
|
370 |
public void configure(HttpsParameters params) {
|
|
371 |
params.setSSLParameters(getSSLContext().getSupportedSSLParameters());
|
|
372 |
}
|
|
373 |
}
|
|
374 |
}
|