test/jdk/java/net/httpclient/SmokeTest.java
changeset 49765 ee6f7a61f3a5
parent 48083 b1c1b4ef4be2
child 52121 934969c63223
child 56451 9585061fdb04
--- a/test/jdk/java/net/httpclient/SmokeTest.java	Tue Apr 17 15:39:20 2018 +0200
+++ b/test/jdk/java/net/httpclient/SmokeTest.java	Tue Apr 17 08:54:17 2018 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2018, 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
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 8087112 8178699
- * @modules jdk.incubator.httpclient
+ * @modules java.net.http
  *          java.logging
  *          jdk.httpserver
  * @library /lib/testlibrary/ /
@@ -32,7 +32,10 @@
  * @compile ../../../com/sun/net/httpserver/LogFilter.java
  * @compile ../../../com/sun/net/httpserver/EchoHandler.java
  * @compile ../../../com/sun/net/httpserver/FileServerHandler.java
- * @run main/othervm -Djdk.internal.httpclient.debug=true -Djdk.httpclient.HttpClient.log=errors,trace SmokeTest
+ * @run main/othervm
+ *      -Djdk.internal.httpclient.debug=true
+ *      -Djdk.httpclient.HttpClient.log=errors,ssl,trace
+ *      SmokeTest
  */
 
 import com.sun.net.httpserver.Headers;
@@ -43,17 +46,22 @@
 import com.sun.net.httpserver.HttpsConfigurator;
 import com.sun.net.httpserver.HttpsParameters;
 import com.sun.net.httpserver.HttpsServer;
+
+import java.net.InetAddress;
 import java.net.Proxy;
 import java.net.SocketAddress;
+import java.util.Collections;
+import java.util.Set;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.net.InetSocketAddress;
 import java.net.PasswordAuthentication;
 import java.net.ProxySelector;
 import java.net.URI;
-import jdk.incubator.http.HttpClient;
-import jdk.incubator.http.HttpRequest;
-import jdk.incubator.http.HttpResponse;
-import java.nio.file.StandardOpenOption;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpRequest.BodyPublishers;
+import java.net.http.HttpResponse;
+import java.net.http.HttpResponse.BodyHandlers;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
@@ -81,12 +89,9 @@
 import java.util.List;
 import java.util.Random;
 import jdk.testlibrary.SimpleSSLContext;
-import static jdk.incubator.http.HttpRequest.BodyPublisher.fromFile;
-import static jdk.incubator.http.HttpRequest.BodyPublisher.fromInputStream;
-import static jdk.incubator.http.HttpRequest.BodyPublisher.fromString;
-import static jdk.incubator.http.HttpResponse.*;
-import static jdk.incubator.http.HttpResponse.BodyHandler.asFile;
-import static jdk.incubator.http.HttpResponse.BodyHandler.asString;
+import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
+import static java.nio.file.StandardOpenOption.WRITE;
+
 import java.util.concurrent.CountDownLatch;
 import java.util.logging.ConsoleHandler;
 import java.util.logging.Level;
@@ -250,7 +255,7 @@
 
         HttpRequest request = builder.build();
 
-        HttpResponse<String> response = client.send(request, asString());
+        HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
 
         String body = response.body();
         if (!body.equals("This is foo.txt\r\n")) {
@@ -261,7 +266,7 @@
         }
 
         // repeat async
-        HttpResponse<String> response1 = client.sendAsync(request, asString())
+        HttpResponse<String> response1 = client.sendAsync(request, BodyHandlers.ofString())
                                                .join();
 
         String body1 = response1.body();
@@ -277,10 +282,10 @@
         URI uri = new URI(s);
 
         HttpRequest request = HttpRequest.newBuilder(uri)
-                                         .POST(fromString(body))
+                                         .POST(BodyPublishers.ofString(body))
                                          .build();
 
-        HttpResponse<String> response = client.send(request, asString());
+        HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
 
         if (response.statusCode() != 200) {
             throw new RuntimeException(
@@ -301,16 +306,13 @@
         Path p = getTempFile(128 * 1024);
 
         HttpRequest request = HttpRequest.newBuilder(uri)
-                                         .POST(fromFile(p))
+                                         .POST(BodyPublishers.ofFile(p))
                                          .build();
 
         Path resp = getTempFile(1); // will be overwritten
 
-        HttpResponse<Path> response =
-                client.send(request,
-                            BodyHandler.asFile(resp,
-                                               StandardOpenOption.TRUNCATE_EXISTING,
-                                               StandardOpenOption.WRITE));
+        HttpResponse<Path> response = client.send(request,
+                BodyHandlers.ofFile(resp, TRUNCATE_EXISTING, WRITE));
 
         if (response.statusCode() != 200) {
             throw new RuntimeException(
@@ -340,7 +342,7 @@
                                          .build();
 
         HttpResponse<Path> response = client.send(request,
-                                                  asFile(Paths.get("redir1.txt")));
+                BodyHandlers.ofFile(Paths.get("redir1.txt")));
 
         if (response.statusCode() != 200) {
             throw new RuntimeException(
@@ -361,7 +363,8 @@
 
         request = HttpRequest.newBuilder(uri).build();
 
-        response = client.sendAsync(request, asFile(Paths.get("redir2.txt"))).join();
+        response = client.sendAsync(request,
+                BodyHandlers.ofFile(Paths.get("redir2.txt"))).join();
 
         if (response.statusCode() != 200) {
             throw new RuntimeException(
@@ -449,7 +452,8 @@
     static void test4(String s) throws Exception {
         System.out.print("test4: " + s);
         URI uri = new URI(s);
-        InetSocketAddress proxyAddr = new InetSocketAddress("127.0.0.1", proxyPort);
+        InetSocketAddress proxyAddr = new InetSocketAddress(InetAddress.getLoopbackAddress(),
+                                                            proxyPort);
         String filename = fileroot + uri.getPath();
 
         ExecutorService e = Executors.newCachedThreadPool();
@@ -464,7 +468,7 @@
 
         HttpRequest request = HttpRequest.newBuilder(uri).GET().build();
 
-        CompletableFuture<String> fut = cl.sendAsync(request, asString())
+        CompletableFuture<String> fut = cl.sendAsync(request, BodyHandlers.ofString())
                 .thenApply((response) -> response.body());
 
         String body = fut.get(5, TimeUnit.HOURS);
@@ -490,7 +494,7 @@
 
         HttpRequest.Builder builder = HttpRequest.newBuilder(uri)
                                             .expectContinue(true)
-                                            .POST(fromString(requestBody));
+                                            .POST(BodyPublishers.ofString(requestBody));
 
         if (fixedLen) {
             builder.header("XFixed", "yes");
@@ -498,7 +502,7 @@
 
         HttpRequest request = builder.build();
 
-        HttpResponse<String> response = client.send(request, asString());
+        HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
 
         String body = response.body();
 
@@ -523,7 +527,7 @@
 
         HttpRequest request = builder.build();
 
-        HttpResponse<String> response = client.send(request, asString());
+        HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
 
         if (response.statusCode() != 200) {
             throw new RuntimeException(
@@ -548,7 +552,7 @@
         HttpRequest request = HttpRequest.newBuilder().uri(uri).GET().build();
 
         for (int i=0; i<4; i++) {
-            HttpResponse<String> r = client.send(request, asString());
+            HttpResponse<String> r = client.send(request, BodyHandlers.ofString());
             String body = r.body();
             if (!body.equals("OK")) {
                 throw new RuntimeException("Expected OK, got: " + body);
@@ -556,10 +560,13 @@
         }
 
         // Second test: 4 x parallel
-        request = HttpRequest.newBuilder().uri(uri).POST(fromFile(requestBody)).build();
+        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, asString())
+            futures.add(client.sendAsync(request, BodyHandlers.ofString())
                               .thenApply((response) -> {
                                   if (response.statusCode() == 200)
                                       return response.body();
@@ -582,7 +589,7 @@
         request = HttpRequest.newBuilder(uri).GET().build();
         BlockingQueue<String> q = new LinkedBlockingQueue<>();
         for (int i=0; i<4; i++) {
-            client.sendAsync(request, asString())
+            client.sendAsync(request, BodyHandlers.ofString())
                   .thenApply((HttpResponse<String> resp) -> {
                       String body = resp.body();
                       putQ(q, body);
@@ -599,7 +606,7 @@
             if (!body.equals("OK")) {
                 throw new RuntimeException(body);
             }
-            client.sendAsync(request, asString())
+            client.sendAsync(request, BodyHandlers.ofString())
                   .thenApply((resp) -> {
                       if (resp.statusCode() == 200)
                           putQ(q, resp.body());
@@ -645,12 +652,12 @@
         URI uri = new URI(target);
 
         HttpRequest request = HttpRequest.newBuilder(uri)
-                                         .POST(fromInputStream(SmokeTest::newStream))
-                                         .build();
+                .POST(BodyPublishers.ofInputStream(SmokeTest::newStream))
+                .build();
 
         Path download = Paths.get("test11.txt");
 
-        HttpResponse<Path> response = client.send(request, asFile(download));
+        HttpResponse<Path> response = client.send(request, BodyHandlers.ofFile(download));
 
         if (response.statusCode() != 200) {
             throw new RuntimeException("Wrong response code");
@@ -683,7 +690,7 @@
 
         HttpRequest request = HttpRequest.newBuilder(uri).GET().build();
         CompletableFuture<HttpResponse<String>> cf =
-                client.sendAsync(request, asString());
+                client.sendAsync(request, BodyHandlers.ofString());
 
         try {
             HttpResponse<String> response = cf.join();
@@ -722,7 +729,7 @@
         logger.addHandler(ch);
 
         String root = System.getProperty ("test.src", ".")+ "/docs";
-        InetSocketAddress addr = new InetSocketAddress (0);
+        InetSocketAddress addr = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
         s1 = HttpServer.create (addr, 0);
         if (s1 instanceof HttpsServer) {
             throw new RuntimeException ("should not be httpsserver");
@@ -751,7 +758,8 @@
         s1.setExecutor(executor);
         s2.setExecutor(executor);
         ctx = new SimpleSSLContext().get();
-        sslparams = ctx.getSupportedSSLParameters();
+        sslparams = ctx.getDefaultSSLParameters();
+        //sslparams.setProtocols(new String[]{"TLSv1.2"});
         s2.setHttpsConfigurator(new Configurator(ctx));
         s1.start();
         s2.start();
@@ -760,8 +768,8 @@
         System.out.println("HTTP server port = " + port);
         httpsport = s2.getAddress().getPort();
         System.out.println("HTTPS server port = " + httpsport);
-        httproot = "http://127.0.0.1:" + port + "/";
-        httpsroot = "https://127.0.0.1:" + httpsport + "/";
+        httproot = "http://localhost:" + port + "/";
+        httpsroot = "https://localhost:" + httpsport + "/";
 
         proxy = new ProxyServer(0, false);
         proxyPort = proxy.getPort();
@@ -872,12 +880,16 @@
         }
 
         public void configure (HttpsParameters params) {
-            params.setSSLParameters (getSSLContext().getSupportedSSLParameters());
+            SSLParameters p = getSSLContext().getDefaultSSLParameters();
+            //p.setProtocols(new String[]{"TLSv1.2"});
+            params.setSSLParameters (p);
         }
     }
 
+    static final Path CWD = Paths.get(".");
+
     static Path getTempFile(int size) throws IOException {
-        File f = File.createTempFile("test", "txt");
+        File f = Files.createTempFile(CWD, "test", "txt").toFile();
         f.deleteOnExit();
         byte[] buf = new byte[2048];
         for (int i = 0; i < buf.length; i++)
@@ -901,12 +913,12 @@
 // Then send 4 requests in parallel x 100 times (same four addresses used all time)
 
 class KeepAliveHandler implements HttpHandler {
-    AtomicInteger counter = new AtomicInteger(0);
-    AtomicInteger nparallel = new AtomicInteger(0);
+    final AtomicInteger counter = new AtomicInteger(0);
+    final AtomicInteger nparallel = new AtomicInteger(0);
 
-    HashSet<Integer> portSet = new HashSet<>();
+    final Set<Integer> portSet = Collections.synchronizedSet(new HashSet<>());
 
-    int[] ports = new int[8];
+    final int[] ports = new int[8];
 
     void sleep(int n) {
         try {
@@ -929,7 +941,9 @@
         dest[3] = ports[from+3];
     }
 
-    static CountDownLatch latch = new CountDownLatch(4);
+    static final CountDownLatch latch = new CountDownLatch(4);
+    static final CountDownLatch latch7 = new CountDownLatch(4);
+    static final CountDownLatch latch8 = new CountDownLatch(1);
 
     @Override
     public void handle (HttpExchange t)
@@ -962,8 +976,11 @@
             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]
@@ -976,15 +993,19 @@
                 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);
+                System.out.println ("UNEXPECTED REMOTE PORT "
+                        + remotePort + " not in " + portSet);
                 result = "Error " + Integer.toString(n);
                 System.out.println(result);
             }