File: HttpServerAdapters.java

package info (click to toggle)
openjdk-11 11.0.4%2B11-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 757,028 kB
  • sloc: java: 5,016,041; xml: 1,191,974; cpp: 934,731; ansic: 555,697; sh: 24,299; objc: 12,703; python: 3,602; asm: 3,415; makefile: 2,772; awk: 351; sed: 172; perl: 114; jsp: 24; csh: 3
file content (627 lines) | stat: -rw-r--r-- 25,247 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
/*
 * Copyright (c) 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
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import jdk.internal.net.http.common.HttpHeadersBuilder;

import java.net.InetAddress;
import java.io.ByteArrayInputStream;
import java.net.http.HttpClient.Version;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UncheckedIOException;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpHeaders;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;

/**
 * Defines an adaptation layers so that a test server handlers and filters
 * can be implemented independently of the underlying server version.
 * <p>
 * For instance:
 * <pre>{@code
 *
 *  URI http1URI, http2URI;
 *
 *  InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
 *  HttpTestServer server1 = HttpTestServer.of(HttpServer.create(sa, 0));
 *  HttpTestContext context = server.addHandler(new HttpTestEchoHandler(), "/http1/echo");
 *  http2URI = "http://localhost:" + server1.getAddress().getPort() + "/http1/echo";
 *
 *  Http2TestServer http2TestServer = new Http2TestServer("localhost", false, 0);
 *  HttpTestServer server2 = HttpTestServer.of(http2TestServer);
 *  server2.addHandler(new HttpTestEchoHandler(), "/http2/echo");
 *  http1URI = "http://localhost:" + server2.getAddress().getPort() + "/http2/echo";
 *
 *  }</pre>
 */
public interface HttpServerAdapters {

    static final boolean PRINTSTACK =
            Boolean.getBoolean("jdk.internal.httpclient.debug");

    static void uncheckedWrite(ByteArrayOutputStream baos, byte[] ba) {
        try {
            baos.write(ba);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    static void printBytes(PrintStream out, String prefix, byte[] bytes) {
        int padding = 4 + 4 - (bytes.length % 4);
        padding = padding > 4 ? padding - 4 : 4;
        byte[] bigbytes = new byte[bytes.length + padding];
        System.arraycopy(bytes, 0, bigbytes, padding, bytes.length);
        out.println(prefix + bytes.length + " "
                    + new BigInteger(bigbytes).toString(16));
    }

    /**
     * A version agnostic adapter class for HTTP request Headers.
     */
    public static abstract class HttpTestRequestHeaders {
        public abstract Optional<String> firstValue(String name);
        public abstract Set<String> keySet();
        public abstract Set<Map.Entry<String, List<String>>> entrySet();
        public abstract List<String> get(String name);
        public abstract boolean containsKey(String name);

        public static HttpTestRequestHeaders of(Headers headers) {
            return new Http1TestRequestHeaders(headers);
        }

        public static HttpTestRequestHeaders of(HttpHeaders headers) {
            return new Http2TestRequestHeaders(headers);
        }

        private static final class Http1TestRequestHeaders extends HttpTestRequestHeaders {
            private final Headers headers;
            Http1TestRequestHeaders(Headers h) { this.headers = h; }
            @Override
            public Optional<String> firstValue(String name) {
                if (headers.containsKey(name)) {
                    return Optional.ofNullable(headers.getFirst(name));
                }
                return Optional.empty();
            }
            @Override
            public Set<String> keySet() { return headers.keySet(); }
            @Override
            public Set<Map.Entry<String, List<String>>> entrySet() {
                return headers.entrySet();
            }
            @Override
            public List<String> get(String name) {
                return headers.get(name);
            }
            @Override
            public boolean containsKey(String name) {
                return headers.containsKey(name);
            }
        }
        private static final class Http2TestRequestHeaders extends HttpTestRequestHeaders {
            private final HttpHeaders headers;
            Http2TestRequestHeaders(HttpHeaders h) { this.headers = h; }
            @Override
            public Optional<String> firstValue(String name) {
                return headers.firstValue(name);
            }
            @Override
            public Set<String> keySet() { return headers.map().keySet(); }
            @Override
            public Set<Map.Entry<String, List<String>>> entrySet() {
                return headers.map().entrySet();
            }
            @Override
            public List<String> get(String name) {
                return headers.allValues(name);
            }
            @Override
            public boolean containsKey(String name) {
                return headers.firstValue(name).isPresent();
            }
        }
    }

    /**
     * A version agnostic adapter class for HTTP response Headers.
     */
    public static abstract class HttpTestResponseHeaders {
        public abstract void addHeader(String name, String value);

        public static HttpTestResponseHeaders of(Headers headers) {
            return new Http1TestResponseHeaders(headers);
        }
        public static HttpTestResponseHeaders of(HttpHeadersBuilder headersBuilder) {
            return new Http2TestResponseHeaders(headersBuilder);
        }

        private final static class Http1TestResponseHeaders extends HttpTestResponseHeaders {
            private final Headers headers;
            Http1TestResponseHeaders(Headers h) { this.headers = h; }
            @Override
            public void addHeader(String name, String value) {
                headers.add(name, value);
            }
        }
        private final static class Http2TestResponseHeaders extends HttpTestResponseHeaders {
            private final HttpHeadersBuilder headersBuilder;
            Http2TestResponseHeaders(HttpHeadersBuilder hb) { this.headersBuilder = hb; }
            @Override
            public void addHeader(String name, String value) {
                headersBuilder.addHeader(name, value);
            }
        }
    }

    /**
     * A version agnostic adapter class for HTTP Server Exchange.
     */
    public static abstract class HttpTestExchange {
        public abstract Version getServerVersion();
        public abstract Version getExchangeVersion();
        public abstract InputStream   getRequestBody();
        public abstract OutputStream  getResponseBody();
        public abstract HttpTestRequestHeaders getRequestHeaders();
        public abstract HttpTestResponseHeaders getResponseHeaders();
        public abstract void sendResponseHeaders(int code, int contentLength) throws IOException;
        public abstract URI getRequestURI();
        public abstract String getRequestMethod();
        public abstract void close();
        public void serverPush(URI uri, HttpHeaders headers, byte[] body) {
            ByteArrayInputStream bais = new ByteArrayInputStream(body);
            serverPush(uri, headers, bais);
        }
        public void serverPush(URI uri, HttpHeaders headers, InputStream body) {
            throw new UnsupportedOperationException("serverPush with " + getExchangeVersion());
        }
        public boolean serverPushAllowed() {
            return false;
        }
        public static HttpTestExchange of(HttpExchange exchange) {
            return new Http1TestExchange(exchange);
        }
        public static HttpTestExchange of(Http2TestExchange exchange) {
            return new Http2TestExchangeImpl(exchange);
        }

        abstract void doFilter(Filter.Chain chain) throws IOException;

        // implementations...
        private static final class Http1TestExchange extends HttpTestExchange {
            private final HttpExchange exchange;
            Http1TestExchange(HttpExchange exch) {
                this.exchange = exch;
            }
            @Override
            public Version getServerVersion() { return Version.HTTP_1_1; }
            @Override
            public Version getExchangeVersion() { return Version.HTTP_1_1; }
            @Override
            public InputStream getRequestBody() {
                return exchange.getRequestBody();
            }
            @Override
            public OutputStream getResponseBody() {
                return exchange.getResponseBody();
            }
            @Override
            public HttpTestRequestHeaders getRequestHeaders() {
                return HttpTestRequestHeaders.of(exchange.getRequestHeaders());
            }
            @Override
            public HttpTestResponseHeaders getResponseHeaders() {
                return HttpTestResponseHeaders.of(exchange.getResponseHeaders());
            }
            @Override
            public void sendResponseHeaders(int code, int contentLength) throws IOException {
                if (contentLength == 0) contentLength = -1;
                else if (contentLength < 0) contentLength = 0;
                exchange.sendResponseHeaders(code, contentLength);
            }
            @Override
            void doFilter(Filter.Chain chain) throws IOException {
                chain.doFilter(exchange);
            }
            @Override
            public void close() { exchange.close(); }
            @Override
            public URI getRequestURI() { return exchange.getRequestURI(); }
            @Override
            public String getRequestMethod() { return exchange.getRequestMethod(); }
            @Override
            public String toString() {
                return this.getClass().getSimpleName() + ": " + exchange.toString();
            }
        }

        private static final class Http2TestExchangeImpl extends HttpTestExchange {
            private final Http2TestExchange exchange;
            Http2TestExchangeImpl(Http2TestExchange exch) {
                this.exchange = exch;
            }
            @Override
            public Version getServerVersion() { return Version.HTTP_2; }
            @Override
            public Version getExchangeVersion() { return Version.HTTP_2; }
            @Override
            public InputStream getRequestBody() {
                return exchange.getRequestBody();
            }
            @Override
            public OutputStream getResponseBody() {
                return exchange.getResponseBody();
            }
            @Override
            public HttpTestRequestHeaders getRequestHeaders() {
                return HttpTestRequestHeaders.of(exchange.getRequestHeaders());
            }

            @Override
            public HttpTestResponseHeaders getResponseHeaders() {
                return HttpTestResponseHeaders.of(exchange.getResponseHeaders());
            }
            @Override
            public void sendResponseHeaders(int code, int contentLength) throws IOException {
                if (contentLength == 0) contentLength = -1;
                else if (contentLength < 0) contentLength = 0;
                exchange.sendResponseHeaders(code, contentLength);
            }
            @Override
            public boolean serverPushAllowed() {
                return exchange.serverPushAllowed();
            }
            @Override
            public void serverPush(URI uri, HttpHeaders headers, InputStream body) {
                exchange.serverPush(uri, headers, body);
            }
            void doFilter(Filter.Chain filter) throws IOException {
                throw new IOException("cannot use HTTP/1.1 filter with HTTP/2 server");
            }
            @Override
            public void close() { exchange.close();}
            @Override
            public URI getRequestURI() { return exchange.getRequestURI(); }
            @Override
            public String getRequestMethod() { return exchange.getRequestMethod(); }
            @Override
            public String toString() {
                return this.getClass().getSimpleName() + ": " + exchange.toString();
            }
        }

    }


    /**
     * A version agnostic adapter class for HTTP Server Handlers.
     */
    public interface HttpTestHandler {
        void handle(HttpTestExchange t) throws IOException;

        default HttpHandler toHttpHandler() {
            return (t) -> doHandle(HttpTestExchange.of(t));
        }
        default Http2Handler toHttp2Handler() {
            return (t) -> doHandle(HttpTestExchange.of(t));
        }
        private void doHandle(HttpTestExchange t) throws IOException {
            try {
                handle(t);
            } catch (Throwable x) {
                System.out.println("WARNING: exception caught in HttpTestHandler::handle " + x);
                System.err.println("WARNING: exception caught in HttpTestHandler::handle " + x);
                if (PRINTSTACK && !expectException(t)) x.printStackTrace(System.out);
                throw x;
            }
        }
    }


    public static class HttpTestEchoHandler implements HttpTestHandler {
        @Override
        public void handle(HttpTestExchange t) throws IOException {
            try (InputStream is = t.getRequestBody();
                 OutputStream os = t.getResponseBody()) {
                byte[] bytes = is.readAllBytes();
                printBytes(System.out,"Echo server got "
                        + t.getExchangeVersion() + " bytes: ", bytes);
                if (t.getRequestHeaders().firstValue("Content-type").isPresent()) {
                    t.getResponseHeaders().addHeader("Content-type",
                            t.getRequestHeaders().firstValue("Content-type").get());
                }
                t.sendResponseHeaders(200, bytes.length);
                os.write(bytes);
            }
        }
    }

    public static boolean expectException(HttpTestExchange e) {
        HttpTestRequestHeaders h = e.getRequestHeaders();
        Optional<String> expectException = h.firstValue("X-expect-exception");
        if (expectException.isPresent()) {
            return expectException.get().equalsIgnoreCase("true");
        }
        return false;
    }

    /**
     * A version agnostic adapter class for HTTP Server Filter Chains.
     */
    public abstract class HttpChain {

        public abstract void doFilter(HttpTestExchange exchange) throws IOException;
        public static HttpChain of(Filter.Chain chain) {
            return new Http1Chain(chain);
        }

        public static HttpChain of(List<HttpTestFilter> filters, HttpTestHandler handler) {
            return new Http2Chain(filters, handler);
        }

        private static class Http1Chain extends HttpChain {
            final Filter.Chain chain;
            Http1Chain(Filter.Chain chain) {
                this.chain = chain;
            }
            @Override
            public void doFilter(HttpTestExchange exchange) throws IOException {
                try {
                    exchange.doFilter(chain);
                } catch (Throwable t) {
                    System.out.println("WARNING: exception caught in Http1Chain::doFilter " + t);
                    System.err.println("WARNING: exception caught in Http1Chain::doFilter " + t);
                    if (PRINTSTACK && !expectException(exchange)) t.printStackTrace(System.out);
                    throw t;
                }
            }
        }

        private static class Http2Chain extends HttpChain {
            ListIterator<HttpTestFilter> iter;
            HttpTestHandler handler;
            Http2Chain(List<HttpTestFilter> filters, HttpTestHandler handler) {
                this.iter = filters.listIterator();
                this.handler = handler;
            }
            @Override
            public void doFilter(HttpTestExchange exchange) throws IOException {
                try {
                    if (iter.hasNext()) {
                        iter.next().doFilter(exchange, this);
                    } else {
                        handler.handle(exchange);
                    }
                } catch (Throwable t) {
                    System.out.println("WARNING: exception caught in Http2Chain::doFilter " + t);
                    System.err.println("WARNING: exception caught in Http2Chain::doFilter " + t);
                    if (PRINTSTACK && !expectException(exchange)) t.printStackTrace(System.out);
                    throw t;
                }
            }
        }

    }

    /**
     * A version agnostic adapter class for HTTP Server Filters.
     */
    public abstract class HttpTestFilter {

        public abstract String description();

        public abstract void doFilter(HttpTestExchange exchange, HttpChain chain) throws IOException;

        public Filter toFilter() {
            return new Filter() {
                @Override
                public void doFilter(HttpExchange exchange, Chain chain) throws IOException {
                    HttpTestFilter.this.doFilter(HttpTestExchange.of(exchange), HttpChain.of(chain));
                }
                @Override
                public String description() {
                    return HttpTestFilter.this.description();
                }
            };
        }
    }

    /**
     * A version agnostic adapter class for HTTP Server Context.
     */
    public static abstract class HttpTestContext {
        public abstract String getPath();
        public abstract void addFilter(HttpTestFilter filter);
        public abstract Version getVersion();

        // will throw UOE if the server is HTTP/2
        public abstract void setAuthenticator(com.sun.net.httpserver.Authenticator authenticator);
    }

    /**
     * A version agnostic adapter class for HTTP Servers.
     */
    public static abstract class HttpTestServer {
        private static final class ServerLogging {
            private static final Logger logger = Logger.getLogger("com.sun.net.httpserver");
            static void enableLogging() {
                logger.setLevel(Level.FINE);
                Stream.of(Logger.getLogger("").getHandlers())
                        .forEach(h -> h.setLevel(Level.ALL));
            }
        }

        public abstract void start();
        public abstract void stop();
        public abstract HttpTestContext addHandler(HttpTestHandler handler, String root);
        public abstract InetSocketAddress getAddress();
        public abstract Version getVersion();

        public String serverAuthority() {
            return InetAddress.getLoopbackAddress().getHostName() + ":"
                    + getAddress().getPort();
        }

        public static HttpTestServer of(HttpServer server) {
            return new Http1TestServer(server);
        }

        public static HttpTestServer of(Http2TestServer server) {
            return new Http2TestServerImpl(server);
        }

        private static class Http1TestServer extends  HttpTestServer {
            private final HttpServer impl;
            Http1TestServer(HttpServer server) {
                this.impl = server;
            }
            @Override
            public void start() {
                System.out.println("Http1TestServer: start");
                impl.start();
            }
            @Override
            public void stop() {
                System.out.println("Http1TestServer: stop");
                impl.stop(0);
            }
            @Override
            public HttpTestContext addHandler(HttpTestHandler handler, String path) {
                System.out.println("Http1TestServer[" + getAddress()
                        + "]::addHandler " + handler + ", " + path);
                return new Http1TestContext(impl.createContext(path, handler.toHttpHandler()));
            }
            @Override
            public InetSocketAddress getAddress() {
                return new InetSocketAddress(InetAddress.getLoopbackAddress(),
                        impl.getAddress().getPort());
            }
            public Version getVersion() { return Version.HTTP_1_1; }
        }

        private static class Http1TestContext extends HttpTestContext {
            private final HttpContext context;
            Http1TestContext(HttpContext ctxt) {
                this.context = ctxt;
            }
            @Override public String getPath() {
                return context.getPath();
            }
            @Override
            public void addFilter(HttpTestFilter filter) {
                System.out.println("Http1TestContext::addFilter " + filter.description());
                context.getFilters().add(filter.toFilter());
            }
            @Override
            public void setAuthenticator(com.sun.net.httpserver.Authenticator authenticator) {
                context.setAuthenticator(authenticator);
            }
            @Override public Version getVersion() { return Version.HTTP_1_1; }
        }

        private static class Http2TestServerImpl extends  HttpTestServer {
            private final Http2TestServer impl;
            Http2TestServerImpl(Http2TestServer server) {
                this.impl = server;
            }
            @Override
            public void start() {
                System.out.println("Http2TestServerImpl: start");
                impl.start();
            }
            @Override
            public void stop() {
                System.out.println("Http2TestServerImpl: stop");
                impl.stop();
            }
            @Override
            public HttpTestContext addHandler(HttpTestHandler handler, String path) {
                System.out.println("Http2TestServerImpl[" + getAddress()
                                   + "]::addHandler " + handler + ", " + path);
                Http2TestContext context = new Http2TestContext(handler, path);
                impl.addHandler(context.toHttp2Handler(), path);
                return context;
            }
            @Override
            public InetSocketAddress getAddress() {
                return new InetSocketAddress(InetAddress.getLoopbackAddress(),
                        impl.getAddress().getPort());
            }
            public Version getVersion() { return Version.HTTP_2; }
        }

        private static class Http2TestContext
                extends HttpTestContext implements HttpTestHandler {
            private final HttpTestHandler handler;
            private final String path;
            private final List<HttpTestFilter> filters = new CopyOnWriteArrayList<>();
            Http2TestContext(HttpTestHandler hdl, String path) {
                this.handler = hdl;
                this.path = path;
            }
            @Override
            public String getPath() { return path; }
            @Override
            public void addFilter(HttpTestFilter filter) {
                System.out.println("Http2TestContext::addFilter " + filter.description());
                filters.add(filter);
            }
            @Override
            public void handle(HttpTestExchange exchange) throws IOException {
                System.out.println("Http2TestContext::handle " + exchange);
                HttpChain.of(filters, handler).doFilter(exchange);
            }
            @Override
            public void setAuthenticator(com.sun.net.httpserver.Authenticator authenticator) {
                throw new UnsupportedOperationException("Can't set HTTP/1.1 authenticator on HTTP/2 context");
            }
            @Override public Version getVersion() { return Version.HTTP_2; }
        }
    }

    public static void enableServerLogging() {
        System.setProperty("java.util.logging.SimpleFormatter.format",
                "%4$s [%1$tb %1$td, %1$tl:%1$tM:%1$tS.%1$tN] %2$s: %5$s%6$s%n");
        HttpTestServer.ServerLogging.enableLogging();
    }

}