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