/* * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions.
*/
static String getFileContent(String path) throws IOException {
FileInputStream fis = new FileInputStream(path); byte[] buf = newbyte[2000];
StringBuilder sb = new StringBuilder(); int n; while ((n=fis.read(buf)) != -1) {
sb.append(new String(buf, 0, n, "US-ASCII"));
}
fis.close(); return sb.toString();
}
staticvoid cmpFileContent(Path path1, Path path2) throws IOException {
InputStream fis1 = new BufferedInputStream(new FileInputStream(path1.toFile()));
InputStream fis2 = new BufferedInputStream(new FileInputStream(path2.toFile()));
int n1, n2; while ((n1=fis1.read()) != -1) {
n2 = fis2.read(); if (n1 != n2) thrownew IOException("Content not the same");
}
fis1.close();
fis2.close();
}
String body = response.body(); if (!body.equals("This is foo.txt\r\n")) { thrownew RuntimeException("Did not get expected body: "
+ "\n\t expected \"This is foo.txt\\r\\n\""
+ "\n\t received \""
+ body.replace("\r", "\\r").replace("\n","\\n") + "\"");
}
// POST use echo to check reply staticvoid test2a(String s) throws Exception {
System.out.print("test2a: " + s);
URI uri = new URI(s);
Path p = getTempFile(128 * 1024);
staticvoid checkPreviousRedirectResponses(HttpRequest initialRequest,
HttpResponse<?> finalResponse) { // there must be at least one previous response
finalResponse.previousResponse()
.orElseThrow(() -> new RuntimeException("no previous response"));
// initial
check(initialRequest.equals(response.request()), "Expected initial request [%s] to equal last prev req [%s]",
initialRequest, response.request());
}
staticvoid check(boolean cond, Object... msg) { if (cond) return;
StringBuilder sb = new StringBuilder(); for (Object o : msg)
sb.append(o); thrownew RuntimeException(sb.toString());
}
/** * A Proxy Selector that wraps a ProxySelector.of(), and counts the number * of times its select method has been invoked. This can be used to ensure * that the Proxy Selector is invoked only once per HttpClient.sendXXX * invocation.
*/ staticclass CountingProxySelector extends ProxySelector { privatefinal ProxySelector proxySelector; privatevolatileint count; // 0 private CountingProxySelector(InetSocketAddress proxyAddress) {
proxySelector = ProxySelector.of(proxyAddress);
}
@SuppressWarnings("rawtypes") staticvoid test7(String target) throws Exception {
System.out.print("test7: " + target);
Path requestBody = getTempFile(128 * 1024); // First test
URI uri = new URI(target);
HttpRequest request = HttpRequest.newBuilder().uri(uri).GET().build();
for (int i=0; i<4; i++) {
HttpResponse<String> r = client.send(request, BodyHandlers.ofString());
String body = r.body(); if (!body.equals("OK")) { thrownew RuntimeException("Expected OK, got: " + body);
}
}
// Second test: 4 x parallel
request = HttpRequest.newBuilder()
.uri(uri)
.POST(BodyPublishers.ofFile(requestBody))
.build();
List<CompletableFuture<String>> futures = new LinkedList<>(); for (int i=0; i<4; i++) {
futures.add(client.sendAsync(request, BodyHandlers.ofString())
.thenApply((response) -> { if (response.statusCode() == 200) return response.body(); else return"ERROR";
}));
} // all sent?
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
.join();
for (CompletableFuture<String> future : futures) {
String body = future.get(); if (!body.equals("OK")) { thrownew RuntimeException("Expected OK, got: " + body);
}
}
// Third test: Multiple of 4 parallel requests
request = HttpRequest.newBuilder(uri).GET().build();
BlockingQueue<String> q = new LinkedBlockingQueue<>(); for (int i=0; i<4; i++) {
client.sendAsync(request, BodyHandlers.ofString())
.thenApply((HttpResponse<String> resp) -> {
String body = resp.body();
putQ(q, body); return body;
});
} // we've sent four requests. Now, just send another request // as each response is received. The idea is to ensure that // only four sockets ever get used.
for (int i=0; i<100; i++) { // block until response received
String body = takeQ(q); if (!body.equals("OK")) { thrownew RuntimeException(body);
}
client.sendAsync(request, BodyHandlers.ofString())
.thenApply((resp) -> { if (resp.statusCode() == 200)
putQ(q, resp.body()); else
putQ(q, "ERROR"); returnnull;
});
} // should be four left for (int i=0; i<4; i++) {
takeQ(q);
}
System.out.println(" OK");
}
static String takeQ(BlockingQueue<String> q) {
String r = null; try {
r = q.take();
} catch (InterruptedException e) {}
// Redirect loop: return an error after a certain number of redirects staticvoid test10(String s) throws Exception {
System.out.print("test10: " + s);
URI uri = new URI(s);
RedirectErrorHandler handler = uri.getScheme().equals("https")
? redirectErrorHandlerSecure : redirectErrorHandler;
static Path getTempFile(int size) throws IOException {
File f = Files.createTempFile(CWD, "test", "txt").toFile();
f.deleteOnExit(); byte[] buf = newbyte[2048]; for (int i = 0; i < buf.length; i++)
buf[i] = (byte) i;
FileOutputStream fos = new FileOutputStream(f); while (size > 0) { int amount = Math.min(size, buf.length);
fos.write(buf, 0, amount);
size -= amount;
}
fos.close(); return f.toPath();
}
}
// check for simple hardcoded sequence and use remote address // to check. // First 4 requests executed in sequence (should use same connection/address) // Next 4 requests parallel (should use different addresses) // Then send 4 requests in parallel x 100 times (same four addresses used all time)
class KeepAliveHandler implements HttpHandler { final AtomicInteger counter = new AtomicInteger(0); final AtomicInteger nparallel = new AtomicInteger(0);
final Set<Integer> portSet = Collections.synchronizedSet(new HashSet<>());
staticfinal CountDownLatch latch = new CountDownLatch(4); staticfinal CountDownLatch latch7 = new CountDownLatch(4); staticfinal CountDownLatch latch8 = new CountDownLatch(1);
@Override publicvoid handle (HttpExchange t) throws IOException
{ int np = nparallel.incrementAndGet(); int remotePort = t.getRemoteAddress().getPort();
String result = "OK"; int[] lports = newint[4];
int n = counter.getAndIncrement();
/// First test if (n < 4) {
setPort(n, remotePort);
} if (n == 3) {
getPorts(lports, 0); // check all values in ports[] are the same if (lports[0] != lports[1] || lports[2] != lports[3]
|| lports[0] != lports[2]) {
result = "Error " + Integer.toString(n);
System.out.println(result);
}
} // Second test if (n >=4 && n < 8) { // delay so that this connection doesn't get reused // before all 4 requests sent
setPort(n, remotePort);
latch.countDown(); try {latch.await();} catch (InterruptedException e) {}
latch7.countDown();
} if (n == 7) { // wait until all n <= 7 have called setPort(...) try {latch7.await();} catch (InterruptedException e) {}
getPorts(lports, 4); // should be all different if (lports[0] == lports[1] || lports[2] == lports[3]
|| lports[0] == lports[2]) {
result = "Error " + Integer.toString(n);
System.out.println(result);
} // setup for third test for (int i=0; i<4; i++) {
portSet.add(lports[i]);
}
System.out.printf("Ports: %d, %d, %d, %d\n", lports[0], lports[1], lports[2], lports[3]);
latch8.countDown();
} // Third test if (n > 7) { // wait until all n == 7 has updated portSet try {latch8.await();} catch (InterruptedException e) {} if (np > 4) {
System.err.println("XXX np = " + np);
} // just check that port is one of the ones in portSet if (!portSet.contains(remotePort)) {
System.out.println ("UNEXPECTED REMOTE PORT "
+ remotePort + " not in " + portSet);
result = "Error " + Integer.toString(n);
System.out.println(result);
}
}
try (InputStream is = t.getRequestBody()) {
is.readAllBytes();
}
t.sendResponseHeaders(200, result.length());
OutputStream o = t.getResponseBody();
o.write(result.getBytes(StandardCharsets.UTF_8));
t.close();
nparallel.getAndDecrement();
}
}
¤ Dauer der Verarbeitung: 0.19 Sekunden
(vorverarbeitet)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung ist noch experimentell.