Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/net/HttpURLConnection/SetAuthenticator/HTTPTest.java
41152 views
1
/*
2
* Copyright (c) 2016, 2019, 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.io.UncheckedIOException;
26
import java.net.Authenticator;
27
import java.net.HttpURLConnection;
28
import java.net.InetSocketAddress;
29
import java.net.MalformedURLException;
30
import java.net.PasswordAuthentication;
31
import java.net.Proxy;
32
import java.net.URL;
33
import java.util.Locale;
34
import java.util.concurrent.atomic.AtomicInteger;
35
import java.util.logging.Level;
36
import java.util.logging.Logger;
37
import java.util.stream.Stream;
38
import javax.net.ssl.HostnameVerifier;
39
import javax.net.ssl.HttpsURLConnection;
40
import javax.net.ssl.SSLContext;
41
import javax.net.ssl.SSLSession;
42
import jdk.test.lib.net.SimpleSSLContext;
43
import static java.net.Proxy.NO_PROXY;
44
45
/*
46
* @test
47
* @bug 8169415
48
* @library /test/lib
49
* @modules java.logging
50
* java.base/sun.net.www
51
* jdk.httpserver/sun.net.httpserver
52
* @build jdk.test.lib.net.SimpleSSLContext HTTPTest HTTPTestServer HTTPTestClient
53
* @summary A simple HTTP test that starts an echo server supporting Digest
54
* authentication, then starts a regular HTTP client to invoke it.
55
* The client first does a GET request on "/", then follows on
56
* with a POST request that sends "Hello World!" to the server.
57
* The client expects to receive "Hello World!" in return.
58
* The test supports several execution modes:
59
* SERVER: The server performs Digest Server authentication;
60
* PROXY: The server pretends to be a proxy and performs
61
* Digest Proxy authentication;
62
* SERVER307: The server redirects the client (307) to another
63
* server that perform Digest authentication;
64
* PROXY305: The server attempts to redirect
65
* the client to a proxy using 305 code;
66
* @run main/othervm HTTPTest SERVER
67
* @run main/othervm HTTPTest PROXY
68
* @run main/othervm HTTPTest SERVER307
69
* @run main/othervm HTTPTest PROXY305
70
*
71
* @author danielfuchs
72
*/
73
public class HTTPTest {
74
75
public static final boolean DEBUG =
76
Boolean.parseBoolean(System.getProperty("test.debug", "false"));
77
public static enum HttpAuthType { SERVER, PROXY, SERVER307, PROXY305 };
78
public static enum HttpProtocolType { HTTP, HTTPS };
79
public static enum HttpSchemeType { NONE, BASICSERVER, BASIC, DIGEST };
80
public static final HttpAuthType DEFAULT_HTTP_AUTH_TYPE = HttpAuthType.SERVER;
81
public static final HttpProtocolType DEFAULT_PROTOCOL_TYPE = HttpProtocolType.HTTP;
82
public static final HttpSchemeType DEFAULT_SCHEME_TYPE = HttpSchemeType.DIGEST;
83
84
public static class HttpTestAuthenticator extends Authenticator {
85
private final String realm;
86
private final String username;
87
// Used to prevent incrementation of 'count' when calling the
88
// authenticator from the server side.
89
private final ThreadLocal<Boolean> skipCount = new ThreadLocal<>();
90
// count will be incremented every time getPasswordAuthentication()
91
// is called from the client side.
92
final AtomicInteger count = new AtomicInteger();
93
private final String name;
94
95
public HttpTestAuthenticator(String name, String realm, String username) {
96
this.name = name;
97
this.realm = realm;
98
this.username = username;
99
}
100
101
@Override
102
protected PasswordAuthentication getPasswordAuthentication() {
103
if (skipCount.get() == null || skipCount.get().booleanValue() == false) {
104
System.out.println("Authenticator " + name + " called: " + count.incrementAndGet());
105
}
106
return new PasswordAuthentication(getUserName(),
107
new char[] {'b','a','r'});
108
}
109
110
// Called by the server side to get the password of the user
111
// being authentified.
112
public final char[] getPassword(String user) {
113
if (user.equals(username)) {
114
skipCount.set(Boolean.TRUE);
115
try {
116
return getPasswordAuthentication().getPassword();
117
} finally {
118
skipCount.set(Boolean.FALSE);
119
}
120
}
121
throw new SecurityException("User unknown: " + user);
122
}
123
124
@Override
125
public String toString() {
126
return super.toString() + "[name=\"" + name + "\"]";
127
}
128
129
public final String getUserName() {
130
return username;
131
}
132
public final String getRealm() {
133
return realm;
134
}
135
136
}
137
public static final HttpTestAuthenticator AUTHENTICATOR;
138
static {
139
AUTHENTICATOR = new HttpTestAuthenticator("AUTHENTICATOR","dublin", "foox");
140
Authenticator.setDefault(AUTHENTICATOR);
141
}
142
143
static {
144
try {
145
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
146
public boolean verify(String hostname, SSLSession session) {
147
return true;
148
}
149
});
150
SSLContext.setDefault(new SimpleSSLContext().get());
151
} catch (IOException ex) {
152
throw new ExceptionInInitializerError(ex);
153
}
154
}
155
156
static final Logger logger = Logger.getLogger ("com.sun.net.httpserver");
157
static {
158
if (DEBUG) logger.setLevel(Level.ALL);
159
Stream.of(Logger.getLogger("").getHandlers())
160
.forEach(h -> h.setLevel(Level.ALL));
161
}
162
163
static final int EXPECTED_AUTH_CALLS_PER_TEST = 1;
164
165
public static void main(String[] args) throws Exception {
166
// new HTTPTest().execute(HttpAuthType.SERVER.name());
167
new HTTPTest().execute(args);
168
}
169
170
public void execute(String... args) throws Exception {
171
Stream<HttpAuthType> modes;
172
if (args == null || args.length == 0) {
173
modes = Stream.of(HttpAuthType.values());
174
} else {
175
modes = Stream.of(args).map(HttpAuthType::valueOf);
176
}
177
modes.forEach(this::test);
178
System.out.println("Test PASSED - Authenticator called: "
179
+ expected(AUTHENTICATOR.count.get()));
180
}
181
182
public void test(HttpAuthType mode) {
183
for (HttpProtocolType type: HttpProtocolType.values()) {
184
test(type, mode);
185
}
186
}
187
188
public HttpSchemeType getHttpSchemeType() {
189
return DEFAULT_SCHEME_TYPE;
190
}
191
192
public void test(HttpProtocolType protocol, HttpAuthType mode) {
193
if (mode == HttpAuthType.PROXY305 && protocol == HttpProtocolType.HTTPS ) {
194
// silently skip unsupported test combination
195
return;
196
}
197
System.out.println("\n**** Testing " + protocol + " "
198
+ mode + " mode ****\n");
199
int authCount = AUTHENTICATOR.count.get();
200
int expectedIncrement = 0;
201
try {
202
// Creates an HTTP server that echoes back whatever is in the
203
// request body.
204
HTTPTestServer server =
205
HTTPTestServer.create(protocol,
206
mode,
207
AUTHENTICATOR,
208
getHttpSchemeType());
209
try {
210
expectedIncrement += run(server, protocol, mode);
211
} finally {
212
server.stop();
213
}
214
} catch (IOException ex) {
215
ex.printStackTrace(System.err);
216
throw new UncheckedIOException(ex);
217
}
218
int count = AUTHENTICATOR.count.get();
219
if (count != authCount + expectedIncrement) {
220
throw new AssertionError("Authenticator called " + count(count)
221
+ " expected it to be called "
222
+ expected(authCount + expectedIncrement));
223
}
224
}
225
226
/**
227
* Runs the test with the given parameters.
228
* @param server The server
229
* @param protocol The protocol (HTTP/HTTPS)
230
* @param mode The mode (PROXY, SERVER, SERVER307...)
231
* @return The number of times the default authenticator should have been
232
* called.
233
* @throws IOException in case of connection or protocol issues
234
*/
235
public int run(HTTPTestServer server,
236
HttpProtocolType protocol,
237
HttpAuthType mode)
238
throws IOException
239
{
240
// Connect to the server with a GET request, then with a
241
// POST that contains "Hello World!"
242
HTTPTestClient.connect(protocol, server, mode, null);
243
// return the number of times the default authenticator is supposed
244
// to have been called.
245
return EXPECTED_AUTH_CALLS_PER_TEST;
246
}
247
248
public static String count(int count) {
249
switch(count) {
250
case 0: return "not even once";
251
case 1: return "once";
252
case 2: return "twice";
253
default: return String.valueOf(count) + " times";
254
}
255
}
256
257
public static String expected(int count) {
258
switch(count) {
259
default: return count(count);
260
}
261
}
262
public static String protocol(HttpProtocolType type) {
263
return type.name().toLowerCase(Locale.US);
264
}
265
266
public static URL url(HttpProtocolType protocol, InetSocketAddress address,
267
String path) throws MalformedURLException {
268
return new URL(protocol(protocol),
269
address.getAddress().getHostAddress(),
270
address.getPort(), path);
271
}
272
273
public static Proxy proxy(HTTPTestServer server, HttpAuthType authType) {
274
if (authType != HttpAuthType.PROXY) return null;
275
276
InetSocketAddress proxyAddress = server.getProxyAddress();
277
if (!proxyAddress.isUnresolved()) {
278
// Forces the proxy to use an unresolved address created
279
// from the actual IP address to avoid using the proxy
280
// address hostname which would result in resolving to
281
// a posibly different address. For instance we want to
282
// avoid cases such as:
283
// ::1 => "localhost" => 127.0.0.1
284
proxyAddress = InetSocketAddress.
285
createUnresolved(proxyAddress.getAddress().getHostAddress(),
286
proxyAddress.getPort());
287
}
288
289
return new Proxy(Proxy.Type.HTTP, proxyAddress);
290
}
291
292
public static HttpURLConnection openConnection(URL url,
293
HttpAuthType authType,
294
Proxy proxy)
295
throws IOException {
296
297
HttpURLConnection conn = (HttpURLConnection)
298
(authType == HttpAuthType.PROXY
299
? url.openConnection(proxy)
300
: url.openConnection(NO_PROXY));
301
return conn;
302
}
303
}
304
305