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 import java.io.IOException;
  25 import java.net.ServerSocket;
  26 import java.net.URI;
  27 import jdk.incubator.http.HttpClient;
  28 import jdk.incubator.http.HttpRequest;
  29 import jdk.incubator.http.HttpResponse;
  30 import jdk.incubator.http.HttpTimeoutException;
  31 import java.time.Duration;
  32 import java.util.concurrent.CompletableFuture;
  33 import java.util.concurrent.ExecutorService;
  34 import java.util.concurrent.Executors;
  35 import java.util.concurrent.LinkedBlockingQueue;
  36 import static java.lang.System.out;
  37 import static jdk.incubator.http.HttpResponse.BodyHandler.discard;
  38 
  39 /**
  40  * @test
  41  * @bug 8178147
  42  * @summary Ensures that small timeouts do not cause hangs due to race conditions
  43  * @run main/othervm -Djdk.incubator.http.internal.common.DEBUG=true SmallTimeout
  44  */
  45 
  46 // To enable logging use. Not enabled by default as it changes the dynamics
  47 // of the test.
  48 // @run main/othervm -Djdk.httpclient.HttpClient.log=all,frames:all SmallTimeout
  49 
  50 public class SmallTimeout {
  51 
  52     static int[] TIMEOUTS = {2, 1, 3, 2, 100, 1};
  53 
  54     // A queue for placing timed out requests so that their order can be checked.
  55     static LinkedBlockingQueue<HttpResult> queue = new LinkedBlockingQueue<>();
  56 
  57     static final class HttpResult {
  58          final HttpRequest request;
  59          final Throwable   failed;
  60          HttpResult(HttpRequest request, Throwable   failed) {
  61              this.request = request;
  62              this.failed = failed;
  63          }
  64 
  65          static HttpResult of(HttpRequest request) {
  66              return new HttpResult(request, null);
  67          }
  68 
  69          static HttpResult of(HttpRequest request, Throwable t) {
  70              return new HttpResult(request, t);
  71          }
  72 
  73     }
  74 
  75     static volatile boolean error;
  76 
  77     public static void main(String[] args) throws Exception {
  78         HttpClient client = HttpClient.newHttpClient();
  79 
  80         try (ServerSocket ss = new ServerSocket(0, 20)) {
  81             int port = ss.getLocalPort();
  82             URI uri = new URI("http://127.0.0.1:" + port + "/");
  83 
  84             HttpRequest[] requests = new HttpRequest[TIMEOUTS.length];
  85 
  86             out.println("--- TESTING Async");
  87             for (int i = 0; i < TIMEOUTS.length; i++) {
  88                 requests[i] = HttpRequest.newBuilder(uri)
  89                                          .timeout(Duration.ofMillis(TIMEOUTS[i]))
  90                                          .GET()
  91                                          .build();
  92 
  93                 final HttpRequest req = requests[i];
  94                 CompletableFuture<HttpResponse<Object>> response = client
  95                     .sendAsync(req, discard(null))
  96                     .whenComplete((HttpResponse<Object> r, Throwable t) -> {
  97                         Throwable cause = null;
  98                         if (r != null) {
  99                             out.println("Unexpected response: " + r);
 100                             cause = new RuntimeException("Unexpected response");
 101                             error = true;
 102                         }
 103                         if (t != null) {
 104                             if (!(t.getCause() instanceof HttpTimeoutException)) {
 105                                 out.println("Wrong exception type:" + t.toString());
 106                                 Throwable c = t.getCause() == null ? t : t.getCause();
 107                                 c.printStackTrace();
 108                                 cause = c;
 109                                 error = true;
 110                             } else {
 111                                 out.println("Caught expected timeout: " + t.getCause());
 112                             }
 113                         }
 114                         if (t == null && r == null) {
 115                             out.println("Both response and throwable are null!");
 116                             cause = new RuntimeException("Both response and throwable are null!");
 117                             error = true;
 118                         }
 119                         queue.add(HttpResult.of(req,cause));
 120                     });
 121             }
 122             System.out.println("All requests submitted. Waiting ...");
 123 
 124             checkReturn(requests);
 125 
 126             if (error)
 127                 throw new RuntimeException("Failed. Check output");
 128 
 129             // Repeat blocking in separate threads. Use queue to wait.
 130             out.println("--- TESTING Sync");
 131 
 132             // For running blocking response tasks
 133             ExecutorService executor = Executors.newCachedThreadPool();
 134 
 135             for (int i = 0; i < TIMEOUTS.length; i++) {
 136                 requests[i] = HttpRequest.newBuilder(uri)
 137                                          .timeout(Duration.ofMillis(TIMEOUTS[i]))
 138                                          .GET()
 139                                          .build();
 140 
 141                 final HttpRequest req = requests[i];
 142                 executor.execute(() -> {
 143                     Throwable cause = null;
 144                     try {
 145                         client.send(req, discard(null));
 146                     } catch (HttpTimeoutException e) {
 147                         out.println("Caught expected timeout: " + e);
 148                     } catch (Throwable ee) {
 149                         Throwable c = ee.getCause() == null ? ee : ee.getCause();
 150                         c.printStackTrace();
 151                         cause = c;
 152                         error = true;
 153                     } finally {
 154                         queue.offer(HttpResult.of(req, cause));
 155                     }
 156                 });
 157             }
 158             System.out.println("All requests submitted. Waiting ...");
 159 
 160             checkReturn(requests);
 161 
 162             executor.shutdownNow();
 163 
 164             if (error)
 165                 throw new RuntimeException("Failed. Check output");
 166 
 167         }
 168     }
 169 
 170     static void checkReturn(HttpRequest[] requests) throws InterruptedException {
 171         // wait for exceptions and check order
 172         boolean ok = true;
 173         for (int j = 0; j < TIMEOUTS.length; j++) {
 174             HttpResult res = queue.take();
 175             HttpRequest req = res.request;
 176             out.println("Got request from queue " + req + ", order: " + getRequest(req, requests)
 177                          + (res.failed == null ? "" : " failed: " + res.failed));
 178             ok = ok && res.failed == null;
 179         }
 180         out.println("Return " + (ok ? "ok" : "nok"));
 181     }
 182 
 183     /** Returns the index of the request in the array. */
 184     static String getRequest(HttpRequest req, HttpRequest[] requests) {
 185         for (int i=0; i<requests.length; i++) {
 186             if (req == requests[i]) {
 187                 return "r" + i;
 188             }
 189         }
 190         throw new AssertionError("Unknown request: " + req);
 191     }
 192 }