Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/net/httpclient/AbstractConnectTimeoutHandshake.java
41149 views
1
/*
2
* Copyright (c) 2018, 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.BufferedInputStream;
25
import java.io.IOException;
26
import java.io.InputStream;
27
import java.io.UncheckedIOException;
28
import java.net.ConnectException;
29
import java.net.InetAddress;
30
import java.net.InetSocketAddress;
31
import java.net.ServerSocket;
32
import java.net.Socket;
33
import java.net.URI;
34
import java.time.Duration;
35
import java.util.ArrayList;
36
import java.util.Arrays;
37
import java.util.List;
38
import java.util.concurrent.CompletableFuture;
39
import java.util.concurrent.CompletionException;
40
import java.net.http.HttpClient;
41
import java.net.http.HttpClient.Version;
42
import java.net.http.HttpConnectTimeoutException;
43
import java.net.http.HttpRequest;
44
import java.net.http.HttpRequest.BodyPublishers;
45
import java.net.http.HttpResponse;
46
import java.net.http.HttpResponse.BodyHandlers;
47
import org.testng.annotations.AfterTest;
48
import org.testng.annotations.BeforeTest;
49
import org.testng.annotations.DataProvider;
50
import static java.lang.String.format;
51
import static java.lang.System.out;
52
import static java.net.http.HttpClient.Builder.NO_PROXY;
53
import static java.net.http.HttpClient.Version.HTTP_1_1;
54
import static java.net.http.HttpClient.Version.HTTP_2;
55
import static java.time.Duration.*;
56
import static java.util.concurrent.TimeUnit.NANOSECONDS;
57
import static org.testng.Assert.fail;
58
59
public abstract class AbstractConnectTimeoutHandshake {
60
61
// The number of iterations each testXXXClient performs.
62
static final int TIMES = 2;
63
64
Server server;
65
URI httpsURI;
66
67
static final Duration NO_DURATION = null;
68
69
static List<List<Duration>> TIMEOUTS = List.of(
70
// connectTimeout HttpRequest timeout
71
Arrays.asList( NO_DURATION, ofSeconds(1) ),
72
Arrays.asList( NO_DURATION, ofSeconds(2) ),
73
Arrays.asList( NO_DURATION, ofMillis(500) ),
74
75
Arrays.asList( ofSeconds(1), NO_DURATION ),
76
Arrays.asList( ofSeconds(2), NO_DURATION ),
77
Arrays.asList( ofMillis(500), NO_DURATION ),
78
79
Arrays.asList( ofSeconds(1), ofMinutes(1) ),
80
Arrays.asList( ofSeconds(2), ofMinutes(1) ),
81
Arrays.asList( ofMillis(500), ofMinutes(1) )
82
);
83
84
static final List<String> METHODS = List.of("GET" , "POST");
85
static final List<Version> VERSIONS = List.of(HTTP_2, HTTP_1_1);
86
87
@DataProvider(name = "variants")
88
public Object[][] variants() {
89
List<Object[]> l = new ArrayList<>();
90
for (List<Duration> timeouts : TIMEOUTS) {
91
Duration connectTimeout = timeouts.get(0);
92
Duration requestTimeout = timeouts.get(1);
93
for (String method: METHODS) {
94
for (Version requestVersion : VERSIONS) {
95
l.add(new Object[] {requestVersion, method, connectTimeout, requestTimeout});
96
}}}
97
return l.stream().toArray(Object[][]::new);
98
}
99
100
//@Test(dataProvider = "variants")
101
protected void timeoutSync(Version requestVersion,
102
String method,
103
Duration connectTimeout,
104
Duration requestTimeout)
105
throws Exception
106
{
107
out.printf("%n--- timeoutSync requestVersion=%s, method=%s, "
108
+ "connectTimeout=%s, requestTimeout=%s ---%n",
109
requestVersion, method, connectTimeout, requestTimeout);
110
HttpClient client = newClient(connectTimeout);
111
HttpRequest request = newRequest(requestVersion, method, requestTimeout);
112
113
for (int i = 0; i < TIMES; i++) {
114
out.printf("iteration %d%n", i);
115
long startTime = System.nanoTime();
116
try {
117
HttpResponse<String> resp = client.send(request, BodyHandlers.ofString());
118
printResponse(resp);
119
fail("Unexpected response: " + resp);
120
} catch (HttpConnectTimeoutException expected) {
121
long elapsedTime = NANOSECONDS.toMillis(System.nanoTime() - startTime);
122
out.printf("Client: received in %d millis%n", elapsedTime);
123
out.printf("Client: caught expected HttpConnectTimeoutException: %s%n", expected);
124
checkExceptionOrCause(ConnectException.class, expected);
125
}
126
}
127
}
128
129
//@Test(dataProvider = "variants")
130
protected void timeoutAsync(Version requestVersion,
131
String method,
132
Duration connectTimeout,
133
Duration requestTimeout) {
134
out.printf("%n--- timeoutAsync requestVersion=%s, method=%s, "
135
+ "connectTimeout=%s, requestTimeout=%s ---%n",
136
requestVersion, method, connectTimeout, requestTimeout);
137
HttpClient client = newClient(connectTimeout);
138
HttpRequest request = newRequest(requestVersion, method, requestTimeout);
139
140
for (int i = 0; i < TIMES; i++) {
141
out.printf("iteration %d%n", i);
142
long startTime = System.nanoTime();
143
CompletableFuture<HttpResponse<String>> cf =
144
client.sendAsync(request, BodyHandlers.ofString());
145
try {
146
HttpResponse<String> resp = cf.join();
147
printResponse(resp);
148
fail("Unexpected response: " + resp);
149
} catch (CompletionException ce) {
150
long elapsedTime = NANOSECONDS.toMillis(System.nanoTime() - startTime);
151
out.printf("Client: received in %d millis%n", elapsedTime);
152
Throwable expected = ce.getCause();
153
if (expected instanceof HttpConnectTimeoutException) {
154
out.printf("Client: caught expected HttpConnectTimeoutException: %s%n", expected);
155
checkExceptionOrCause(ConnectException.class, expected);
156
} else {
157
out.printf("Client: caught UNEXPECTED exception: %s%n", expected);
158
throw ce;
159
}
160
}
161
}
162
}
163
164
static HttpClient newClient(Duration connectTimeout) {
165
HttpClient.Builder builder = HttpClient.newBuilder().proxy(NO_PROXY);
166
if (connectTimeout != NO_DURATION)
167
builder.connectTimeout(connectTimeout);
168
return builder.build();
169
}
170
171
HttpRequest newRequest(Version reqVersion,
172
String method,
173
Duration requestTimeout) {
174
HttpRequest.Builder reqBuilder = HttpRequest.newBuilder(httpsURI);
175
reqBuilder = reqBuilder.version(reqVersion);
176
switch (method) {
177
case "GET" : reqBuilder.GET(); break;
178
case "POST" : reqBuilder.POST(BodyPublishers.noBody()); break;
179
default: throw new AssertionError("Unknown method:" + method);
180
}
181
if (requestTimeout != NO_DURATION)
182
reqBuilder.timeout(requestTimeout);
183
return reqBuilder.build();
184
}
185
186
static void checkExceptionOrCause(Class<? extends Throwable> clazz, Throwable t) {
187
final Throwable original = t;
188
do {
189
if (clazz.isInstance(t)) {
190
System.out.println("Found expected exception/cause: " + t);
191
return; // found
192
}
193
} while ((t = t.getCause()) != null);
194
original.printStackTrace(System.out);
195
throw new RuntimeException("Expected " + clazz + "in " + original);
196
}
197
198
static void printResponse(HttpResponse<?> response) {
199
out.println("Unexpected response: " + response);
200
out.println("Headers: " + response.headers());
201
out.println("Body: " + response.body());
202
}
203
204
// -- Infrastructure
205
206
static String serverAuthority(Server server) {
207
return InetAddress.getLoopbackAddress().getHostName() + ":"
208
+ server.getPort();
209
}
210
211
@BeforeTest
212
public void setup() throws Exception {
213
server = new Server();
214
httpsURI = URI.create("https://" + serverAuthority(server) + "/foo");
215
out.println("HTTPS URI: " + httpsURI);
216
}
217
218
@AfterTest
219
public void teardown() throws Exception {
220
server.close();
221
out.printf("%n--- teardown ---%n");
222
223
int numClientConnections = variants().length * TIMES;
224
int serverCount = server.count;
225
out.printf("Client made %d connections.%n", numClientConnections);
226
out.printf("Server received %d connections.%n", serverCount);
227
228
// This is usually the case, but not always, do not assert. Remains
229
// as an informative message only.
230
//if (numClientConnections != serverCount)
231
// fail(format("[numTests: %d] != [serverCount: %d]",
232
// numClientConnections, serverCount));
233
}
234
235
/**
236
* Emulates a server-side, using plain cleartext Sockets, that just reads
237
* initial client hello and does nothing more.
238
*/
239
static class Server extends Thread implements AutoCloseable {
240
private final ServerSocket ss;
241
private volatile boolean closed;
242
volatile int count;
243
244
Server() throws IOException {
245
super("Server");
246
ss = new ServerSocket();
247
ss.setReuseAddress(false);
248
ss.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));
249
this.start();
250
}
251
252
int getPort() {
253
return ss.getLocalPort();
254
}
255
256
@Override
257
public void close() {
258
if (closed)
259
return;
260
closed = true;
261
try {
262
ss.close();
263
} catch (IOException e) {
264
throw new UncheckedIOException("Unexpected", e);
265
}
266
}
267
268
@Override
269
public void run() {
270
while (!closed) {
271
try (Socket s = ss.accept()) {
272
count++;
273
out.println("Server: accepted new connection");
274
InputStream is = new BufferedInputStream(s.getInputStream());
275
276
out.println("Server: starting to read");
277
while (is.read() != -1) ;
278
279
out.println("Server: closing connection");
280
s.close(); // close without giving any reply
281
} catch (IOException e) {
282
if (!closed)
283
out.println("UNEXPECTED " + e);
284
}
285
}
286
}
287
}
288
}
289
290