File: CustomFileSystemTest.java

package info (click to toggle)
openjdk-21 21.0.8%2B9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 823,976 kB
  • sloc: java: 5,613,338; xml: 1,643,607; cpp: 1,296,296; ansic: 420,291; asm: 404,850; objc: 20,994; sh: 15,271; javascript: 11,245; python: 6,895; makefile: 2,362; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (981 lines) | stat: -rw-r--r-- 38,500 bytes parent folder | download | duplicates (7)
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
/*
 * Copyright (c) 2021, 2022, 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.
 */

/*
 * @test
 * @summary Tests for SimpleFileServer with a root that is not of the default
 *          file system
 * @library /test/lib
 * @build jdk.test.lib.Platform jdk.test.lib.net.URIBuilder
 * @run testng/othervm CustomFileSystemTest
 */

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.AccessMode;
import java.nio.file.CopyOption;
import java.nio.file.DirectoryStream;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.ProviderMismatchException;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.FileAttributeView;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.nio.file.spi.FileSystemProvider;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import com.sun.net.httpserver.SimpleFileServer.OutputLevel;
import jdk.test.lib.Platform;
import jdk.test.lib.net.URIBuilder;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.SkipException;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardOpenOption.CREATE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;

public class CustomFileSystemTest {
    static final InetSocketAddress LOOPBACK_ADDR = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);

    static final boolean ENABLE_LOGGING = true;
    static final Logger LOGGER = Logger.getLogger("com.sun.net.httpserver");

    @BeforeTest
    public void setup() throws Exception {
        if (ENABLE_LOGGING) {
            ConsoleHandler ch = new ConsoleHandler();
            LOGGER.setLevel(Level.ALL);
            ch.setLevel(Level.ALL);
            LOGGER.addHandler(ch);
        }
    }

    @Test
    public void testFileGET() throws Exception {
        var root = createDirectoryInCustomFs("testFileGET");
        var file = Files.writeString(root.resolve("aFile.txt"), "some text", CREATE);
        var lastModified = getLastModified(file);
        var expectedLength = Long.toString(Files.size(file));

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
            var request = HttpRequest.newBuilder(uri(server, "aFile.txt")).build();
            var response = client.send(request, BodyHandlers.ofString());
            assertEquals(response.statusCode(), 200);
            assertEquals(response.body(), "some text");
            assertEquals(response.headers().firstValue("content-type").get(), "text/plain");
            assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
            assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
        } finally {
            server.stop(0);
        }
    }

    @Test
    public void testDirectoryGET() throws Exception {
        var expectedBody = openHTML + """
                <h1>Directory listing for &#x2F;</h1>
                <ul>
                <li><a href="aFile.txt">aFile.txt</a></li>
                </ul>
                """ + closeHTML;
        var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length);
        var root = createDirectoryInCustomFs("testDirectoryGET");
        var file = Files.writeString(root.resolve("aFile.txt"), "some text", CREATE);
        var lastModified = getLastModified(root);

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
            var request = HttpRequest.newBuilder(uri(server, "")).build();
            var response = client.send(request, BodyHandlers.ofString());
            assertEquals(response.statusCode(), 200);
            assertEquals(response.headers().firstValue("content-type").get(), "text/html; charset=UTF-8");
            assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
            assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
            assertEquals(response.body(), expectedBody);
        } finally {
            server.stop(0);
        }
    }

    @Test
    public void testFileHEAD() throws Exception {
        var root = createDirectoryInCustomFs("testFileHEAD");
        var file = Files.writeString(root.resolve("aFile.txt"), "some text", CREATE);
        var lastModified = getLastModified(file);
        var expectedLength = Long.toString(Files.size(file));

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
            var request = HttpRequest.newBuilder(uri(server, "aFile.txt"))
                    .method("HEAD", HttpRequest.BodyPublishers.noBody()).build();
            var response = client.send(request, BodyHandlers.ofString());
            assertEquals(response.statusCode(), 200);
            assertEquals(response.headers().firstValue("content-type").get(), "text/plain");
            assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
            assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
            assertEquals(response.body(), "");
        } finally {
            server.stop(0);
        }
    }

    @Test
    public void testDirectoryHEAD() throws Exception {
        var expectedLength = Integer.toString(
                (openHTML + """
                <h1>Directory listing for &#x2F;</h1>
                <ul>
                <li><a href="aFile.txt">aFile.txt</a></li>
                </ul>
                """ + closeHTML).getBytes(UTF_8).length);
        var root = createDirectoryInCustomFs("testDirectoryHEAD");
        var file = Files.writeString(root.resolve("aFile.txt"), "some text", CREATE);
        var lastModified = getLastModified(root);

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
            var request = HttpRequest.newBuilder(uri(server, ""))
                    .method("HEAD", HttpRequest.BodyPublishers.noBody()).build();
            var response = client.send(request, BodyHandlers.ofString());
            assertEquals(response.statusCode(), 200);
            assertEquals(response.headers().firstValue("content-type").get(), "text/html; charset=UTF-8");
            assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
            assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
            assertEquals(response.body(), "");
        } finally {
            server.stop(0);
        }
    }

    @DataProvider
    public Object[][] indexFiles() {
        var fileContent = openHTML + """
                <h1>This is an index file</h1>
                """ + closeHTML;
        var dirListing = openHTML + """
                <h1>Directory listing for &#x2F;</h1>
                <ul>
                </ul>
                """ + closeHTML;
        return new Object[][] {
                {"1", "index.html", "text/html",                "116", fileContent, true},
                {"2", "index.htm",  "text/html",                "116", fileContent, true},
                {"3", "index.txt",  "text/html; charset=UTF-8", "134", dirListing,  false}
        };
    }

    @Test(dataProvider = "indexFiles")
    public void testDirectoryWithIndexGET(String id,
                                          String filename,
                                          String contentType,
                                          String contentLength,
                                          String expectedBody,
                                          boolean serveIndexFile) throws Exception {
        var root = createDirectoryInCustomFs("testDirectoryWithIndexGET"+id);
        var lastModified = getLastModified(root);
        if (serveIndexFile) {
            var file = Files.writeString(root.resolve(filename), expectedBody, CREATE);
            lastModified = getLastModified(file);
        }

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
            var request = HttpRequest.newBuilder(uri(server, "")).build();
            var response = client.send(request, BodyHandlers.ofString());
            assertEquals(response.statusCode(), 200);
            assertEquals(response.headers().firstValue("content-type").get(), contentType);
            assertEquals(response.headers().firstValue("content-length").get(), contentLength);
            assertEquals(response.headers().firstValue("last-modified").get(), lastModified);
            assertEquals(response.body(), expectedBody);
        } finally {
            server.stop(0);
            if (serveIndexFile) {
                Files.delete(root.resolve(filename));
            }
        }
    }

    @Test
    public void testNotReadableFileGET() throws Exception {
        if (!Platform.isWindows()) {  // not applicable on Windows
            var expectedBody = openHTML + """
                <h1>File not found</h1>
                <p>&#x2F;aFile.txt</p>
                """ + closeHTML;
            var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length);
            var root = createDirectoryInCustomFs("testNotReadableFileGET");
            var file = Files.writeString(root.resolve("aFile.txt"), "some text", CREATE);

            file.toFile().setReadable(false, false);
            assert !Files.isReadable(file);

            var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
            server.start();
            try {
                var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
                var request = HttpRequest.newBuilder(uri(server, "aFile.txt")).build();
                var response = client.send(request, BodyHandlers.ofString());
                assertEquals(response.statusCode(), 404);
                assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
                assertEquals(response.body(), expectedBody);
            } finally {
                server.stop(0);
                file.toFile().setReadable(true, false);
            }
        }
    }

    @Test
    public void testNotReadableSegmentGET() throws Exception {
        if (!Platform.isWindows()) {  // not applicable on Windows
            var expectedBody = openHTML + """
                <h1>File not found</h1>
                <p>&#x2F;dir&#x2F;aFile.txt</p>
                """ + closeHTML;
            var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length);
            var root = createDirectoryInCustomFs("testNotReadableSegmentGET");
            var dir = Files.createDirectory(root.resolve("dir"));
            var file = Files.writeString(dir.resolve("aFile.txt"), "some text", CREATE);

            dir.toFile().setReadable(false, false);
            assert !Files.isReadable(dir);
            assert Files.isReadable(file);

            var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
            server.start();
            try {
                var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
                var request = HttpRequest.newBuilder(uri(server, "dir/aFile.txt")).build();
                var response = client.send(request, BodyHandlers.ofString());
                assertEquals(response.statusCode(), 404);
                assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
                assertEquals(response.body(), expectedBody);
            } finally {
                server.stop(0);
                dir.toFile().setReadable(true, false);
            }
        }
    }

    @Test
    public void testInvalidRequestURIGET() throws Exception {
        var expectedBody = openHTML + """
                <h1>File not found</h1>
                <p>&#x2F;aFile?#.txt</p>
                """ + closeHTML;
        var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length);
        var root = createDirectoryInCustomFs("testInvalidRequestURIGET");

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
            var request = HttpRequest.newBuilder(uri(server, "aFile?#.txt")).build();
            var response = client.send(request, BodyHandlers.ofString());
            assertEquals(response.statusCode(), 404);
            assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
            assertEquals(response.body(), expectedBody);
        } finally {
            server.stop(0);
        }
    }

    @Test
    public void testNotFoundGET() throws Exception {
        var expectedBody = openHTML + """
                <h1>File not found</h1>
                <p>&#x2F;doesNotExist.txt</p>
                """ + closeHTML;
        var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length);
        var root = createDirectoryInCustomFs("testNotFoundGET");

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
            var request = HttpRequest.newBuilder(uri(server, "doesNotExist.txt")).build();
            var response = client.send(request, BodyHandlers.ofString());
            assertEquals(response.statusCode(), 404);
            assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
            assertEquals(response.body(), expectedBody);
        } finally {
            server.stop(0);
        }
    }

    @Test
    public void testNotFoundHEAD() throws Exception {
        var expectedBody = openHTML + """
                <h1>File not found</h1>
                <p>&#x2F;doesNotExist.txt</p>
                """ + closeHTML;
        var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length);
        var root = createDirectoryInCustomFs("testNotFoundHEAD");

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
            var request = HttpRequest.newBuilder(uri(server, "doesNotExist.txt"))
                    .method("HEAD", HttpRequest.BodyPublishers.noBody()).build();
            var response = client.send(request, BodyHandlers.ofString());
            assertEquals(response.statusCode(), 404);
            assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
            assertEquals(response.body(), "");
        } finally {
            server.stop(0);
        }
    }

    @Test
    public void testSymlinkGET() throws Exception {
        var expectedBody = openHTML + """
                <h1>File not found</h1>
                <p>&#x2F;symlink</p>
                """ + closeHTML;
        var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length);
        var root = createDirectoryInCustomFs("testSymlinkGET");
        var symlink = root.resolve("symlink");
        var target = Files.writeString(root.resolve("target.txt"), "some text", CREATE);
        createSymLink(symlink, target);

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
            var request = HttpRequest.newBuilder(uri(server, "symlink")).build();
            var response = client.send(request, BodyHandlers.ofString());
            assertEquals(response.statusCode(), 404);
            assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
            assertEquals(response.body(), expectedBody);
        } finally {
            server.stop(0);
        }
    }

    @Test
    public void testSymlinkSegmentGET() throws Exception {
        var expectedBody = openHTML + """
                <h1>File not found</h1>
                <p>&#x2F;symlink&#x2F;aFile.txt</p>
                """ + closeHTML;
        var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length);
        var root = createDirectoryInCustomFs("testSymlinkSegmentGET");
        var symlink = root.resolve("symlink");
        var target = Files.createDirectory(root.resolve("target"));
        Files.writeString(target.resolve("aFile.txt"), "some text", CREATE);
        createSymLink(symlink, target);

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
            var request = HttpRequest.newBuilder(uri(server, "symlink/aFile.txt")).build();
            var response = client.send(request, BodyHandlers.ofString());
            assertEquals(response.statusCode(), 404);
            assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
            assertEquals(response.body(), expectedBody);
        } finally {
            server.stop(0);
        }
    }

    private void createSymLink(Path symlink, Path target) {
        try {
            Files.createSymbolicLink(symlink, target);
        } catch (UnsupportedOperationException uoe) {
            throw new SkipException("sym link creation not supported", uoe);
        } catch (IOException ioe) {
            throw new SkipException("probably insufficient privileges to create sym links (Windows)", ioe);
        }
    }

    @Test
    public void testHiddenFileGET() throws Exception {
        var root = createDirectoryInCustomFs("testHiddenFileGET");
        var file = createHiddenFile(root);
        var fileName = file.getFileName().toString();
        var expectedBody = openHTML + """
                <h1>File not found</h1>
                <p>&#x2F;""" + fileName +
                """
                </p>
                """ + closeHTML;
        var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length);

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
            var request = HttpRequest.newBuilder(uri(server, fileName)).build();
            var response = client.send(request, BodyHandlers.ofString());
            assertEquals(response.statusCode(), 404);
            assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
            assertEquals(response.body(), expectedBody);
        } finally {
            server.stop(0);
        }
    }

    @Test
    public void testHiddenSegmentGET() throws Exception {
        var root = createDirectoryInCustomFs("testHiddenSegmentGET");
        var file = createFileInHiddenDirectory(root);
        var expectedBody = openHTML + """
                <h1>File not found</h1>
                <p>&#x2F;.hiddenDirectory&#x2F;aFile.txt</p>
                """ + closeHTML;
        var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length);

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
            var request = HttpRequest.newBuilder(uri(server, ".hiddenDirectory/aFile.txt")).build();
            var response = client.send(request, BodyHandlers.ofString());
            assertEquals(response.statusCode(), 404);
            assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
            assertEquals(response.body(), expectedBody);
        } finally {
            server.stop(0);
        }
    }

    private Path createHiddenFile(Path root) throws IOException {
        Path file;
        if (Platform.isWindows()) {
            file = Files.createFile(root.resolve("aFile.txt"));
            Files.setAttribute(file, "dos:hidden", true, LinkOption.NOFOLLOW_LINKS);
        } else {
            file = Files.writeString(root.resolve(".aFile.txt"), "some text", CREATE);
        }
        assertTrue(Files.isHidden(file));
        return file;
    }

    private Path createFileInHiddenDirectory(Path root) throws IOException {
        Path dir;
        Path file;
        if (Platform.isWindows()) {
            dir = Files.createDirectory(root.resolve("hiddenDirectory"));
            Files.setAttribute(dir, "dos:hidden", true, LinkOption.NOFOLLOW_LINKS);
        } else {
            dir = Files.createDirectory(root.resolve(".hiddenDirectory"));
        }
        file = Files.writeString(dir.resolve("aFile.txt"), "some text", CREATE);
        assertTrue(Files.isHidden(dir));
        assertFalse(Files.isHidden(file));
        return file;
    }

    @Test
    public void testMovedPermanently() throws Exception {
        var root = createDirectoryInCustomFs("testMovedPermanently");
        Files.createDirectory(root.resolve("aDirectory"));
        var expectedBody = openHTML + """
                <h1>Directory listing for &#x2F;aDirectory&#x2F;</h1>
                <ul>
                </ul>
                """ + closeHTML;
        var expectedLength = Integer.toString(expectedBody.getBytes(UTF_8).length);

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            {
                var client = HttpClient.newBuilder().proxy(NO_PROXY)
                        .followRedirects(HttpClient.Redirect.NEVER).build();
                var uri = uri(server, "aDirectory");
                var request = HttpRequest.newBuilder(uri).build();
                var response = client.send(request, BodyHandlers.ofString());
                assertEquals(response.statusCode(), 301);
                assertEquals(response.headers().firstValue("content-length").get(), "0");
                assertEquals(response.headers().firstValue("location").get(), "/aDirectory/");

                // tests that query component is preserved during redirect
                var uri2 = uri(server, "aDirectory", "query");
                var req2 = HttpRequest.newBuilder(uri2).build();
                var res2 = client.send(req2, BodyHandlers.ofString());
                assertEquals(res2.statusCode(), 301);
                assertEquals(res2.headers().firstValue("content-length").get(), "0");
                assertEquals(res2.headers().firstValue("location").get(), "/aDirectory/?query");
            }

            {   // tests that redirect to returned relative URI works
                var client = HttpClient.newBuilder().proxy(NO_PROXY)
                        .followRedirects(HttpClient.Redirect.ALWAYS).build();
                var uri = uri(server, "aDirectory");
                var request = HttpRequest.newBuilder(uri).build();
                var response = client.send(request, BodyHandlers.ofString());
                assertEquals(response.statusCode(), 200);
                assertEquals(response.body(), expectedBody);
                assertEquals(response.headers().firstValue("content-type").get(), "text/html; charset=UTF-8");
                assertEquals(response.headers().firstValue("content-length").get(), expectedLength);
            }
        } finally {
            server.stop(0);
        }
    }

    @Test
    public void testXss() throws Exception {
        var root = createDirectoryInCustomFs("testXss");

        var server = SimpleFileServer.createFileServer(LOOPBACK_ADDR, root, OutputLevel.VERBOSE);
        server.start();
        try {
            var client = HttpClient.newBuilder().proxy(NO_PROXY).build();
            var request = HttpRequest.newBuilder(uri(server, "beginDelim%3C%3EEndDelim")).build();
            var response = client.send(request, BodyHandlers.ofString());
            assertEquals(response.statusCode(), 404);
            assertTrue(response.body().contains("beginDelim%3C%3EEndDelim"));
            assertTrue(response.body().contains("File not found"));
        } finally {
            server.stop(0);
        }
    }

    static Path createDirectoryInCustomFs(String name) throws Exception {
        var defaultFs = FileSystems.getDefault();
        var fs = new CustomProvider(defaultFs.provider()).newFileSystem(defaultFs);
        var dir = fs.getPath(name);
        if (Files.notExists(dir)) {
            Files.createDirectory(dir);
        }
        return dir.toAbsolutePath();
    }

    static final String openHTML = """
                <!DOCTYPE html>
                <html>
                <head>
                <meta charset="utf-8"/>
                </head>
                <body>
                """;

    static final String closeHTML = """
                </body>
                </html>
                """;

    static URI uri(HttpServer server, String path) {
        return URIBuilder.newBuilder()
                .host("localhost")
                .port(server.getAddress().getPort())
                .scheme("http")
                .path("/" + path)
                .buildUnchecked();
    }

    static URI uri(HttpServer server, String path, String query) {
        return URIBuilder.newBuilder()
                .host("localhost")
                .port(server.getAddress().getPort())
                .scheme("http")
                .path("/" + path)
                .query(query)
                .buildUnchecked();
    }

    static String getLastModified(Path path) throws IOException {
        return Files.getLastModifiedTime(path).toInstant().atZone(ZoneId.of("GMT"))
                .format(DateTimeFormatter.RFC_1123_DATE_TIME);
    }

    // --- Custom File System ---

    static class CustomProvider extends FileSystemProvider {
        private final ConcurrentHashMap<FileSystem, CustomFileSystem> map =
                new ConcurrentHashMap<>();
        private final FileSystemProvider defaultProvider;

        public CustomProvider(FileSystemProvider provider) {
            defaultProvider = provider;
        }

        @Override
        public String getScheme() {
            return defaultProvider.getScheme();
        }

        public FileSystem newFileSystem(FileSystem fs) {
            return map.computeIfAbsent(fs, (sfs) ->
                    new CustomFileSystem(this, fs));
        }

        @Override
        public FileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException {
            FileSystem fs = defaultProvider.newFileSystem(uri, env);
            return map.computeIfAbsent(fs, (sfs) ->
                    new CustomFileSystem(this, fs)
            );
        }

        @Override
        public FileSystem getFileSystem(URI uri) {
            return map.get(defaultProvider.getFileSystem(uri));
        }

        @Override
        public Path getPath(URI uri) {
            Path p = defaultProvider.getPath(uri);
            return map.get(defaultProvider.getFileSystem(uri)).wrap(p);
        }

        @Override
        public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
            Path p = toCustomPath(path).unwrap();
            return defaultProvider.newByteChannel(p, options, attrs);
        }

        @Override
        public DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) throws IOException {
            throw new RuntimeException("not implemented");
        }

        @Override
        public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException {
            Path p = toCustomPath(dir).unwrap();
            defaultProvider.createDirectory(p, attrs);
        }

        @Override
        public void delete(Path path) throws IOException {
            Path p = toCustomPath(path).unwrap();
            defaultProvider.delete(p);
        }

        @Override
        public void copy(Path source, Path target, CopyOption... options) throws IOException {
            Path sp = toCustomPath(source).unwrap();
            Path tp = toCustomPath(target).unwrap();
            defaultProvider.copy(sp, tp, options);
        }

        @Override
        public void move(Path source, Path target, CopyOption... options)
                throws IOException {
            Path sp = toCustomPath(source).unwrap();
            Path tp = toCustomPath(target).unwrap();
            defaultProvider.move(sp, tp, options);
        }

        @Override
        public boolean isSameFile(Path path, Path path2)
                throws IOException {
            Path p = toCustomPath(path).unwrap();
            Path p2 = toCustomPath(path2).unwrap();
            return defaultProvider.isSameFile(p, p2);
        }

        @Override
        public boolean isHidden(Path path) throws IOException {
            Path p = toCustomPath(path).unwrap();
            return defaultProvider.isHidden(p);
        }

        @Override
        public FileStore getFileStore(Path path) throws IOException {
            Path p = toCustomPath(path).unwrap();
            return defaultProvider.getFileStore(p);
        }

        @Override
        public void checkAccess(Path path, AccessMode... modes) throws IOException {
            Path p = toCustomPath(path).unwrap();
            defaultProvider.checkAccess(p, modes);
        }

        @Override
        public <V extends FileAttributeView> V getFileAttributeView(Path path,
                                                                    Class<V> type,
                                                                    LinkOption... options) {
            Path p = toCustomPath(path).unwrap();
            return defaultProvider.getFileAttributeView(p, type, options);
        }

        @Override
        public <A extends BasicFileAttributes> A readAttributes(Path path,
                                                                Class<A> type,
                                                                LinkOption... options)
                throws IOException {
            Path p = toCustomPath(path).unwrap();
            return defaultProvider.readAttributes(p, type, options);
        }

        @Override
        public Map<String, Object> readAttributes(Path path,
                                                  String attributes,
                                                  LinkOption... options)
                throws IOException {
            Path p = toCustomPath(path).unwrap();
            return defaultProvider.readAttributes(p, attributes, options);
        }

        @Override
        public void setAttribute(Path path, String attribute,
                                 Object value, LinkOption... options)
                throws IOException {
            Path p = toCustomPath(path).unwrap();
            defaultProvider.setAttribute(p, attribute, options);
        }

        // Checks that the given file is a CustomPath
        static CustomPath toCustomPath(Path obj) {
            if (obj == null)
                throw new NullPointerException();
            if (!(obj instanceof CustomPath cp))
                throw new ProviderMismatchException();
            return cp;
        }
    }

    static class CustomFileSystem extends FileSystem {

        private final CustomProvider provider;
        private final FileSystem delegate;

        public CustomFileSystem(CustomProvider provider, FileSystem delegate) {
            this.provider = provider;
            this.delegate = delegate;
        }

        @Override
        public FileSystemProvider provider() {
            return provider;
        }

        @Override
        public void close() throws IOException { delegate.close(); }

        @Override
        public boolean isOpen() {
            return true;
        }

        @Override
        public boolean isReadOnly() {
            return false;
        }

        @Override
        public String getSeparator() { return delegate.getSeparator(); }

        @Override
        public Iterable<Path> getRootDirectories() {
            return null;
        }

        @Override
        public Iterable<FileStore> getFileStores() {
            return null;
        }

        @Override
        public Set<String> supportedFileAttributeViews() {
            return null;
        }

        @Override
        public Path getPath(String first, String... more) {
            return delegate.getPath(first, more);
        }

        @Override
        public PathMatcher getPathMatcher(String syntaxAndPattern) {
            return null;
        }

        @Override
        public UserPrincipalLookupService getUserPrincipalLookupService() {
            return null;
        }

        @Override
        public WatchService newWatchService() throws IOException {
            return null;
        }

        @Override
        public String toString() {
            return delegate.toString();
        }

        Path wrap(Path path) {
            return (path != null) ? new CustomPath(this, path) : null;
        }

        Path unwrap(Path wrapper) {
            if (wrapper == null)
                throw new NullPointerException();
            if (!(wrapper instanceof CustomPath cp))
                throw new ProviderMismatchException();
            return cp.unwrap();
        }
    }

    static class CustomPath implements Path {

        private final CustomFileSystem fs;
        private final Path delegate;

        CustomPath(CustomFileSystem fs, Path delegate) {
            this.fs = fs;
            this.delegate = delegate;
        }

        @Override
        public FileSystem getFileSystem() {
            return fs;
        }

        @Override
        public boolean isAbsolute() {
            return delegate.isAbsolute();
        }

        @Override
        public Path getRoot() {
            return fs.wrap(delegate.getRoot());
        }

        @Override
        public Path getFileName() {
            return null;
        }

        @Override
        public Path getParent() {
            return null;
        }

        @Override
        public int getNameCount() {
            return 0;
        }

        @Override
        public Path getName(int index) {
            return null;
        }

        @Override
        public Path subpath(int beginIndex, int endIndex) {
            return null;
        }

        @Override
        public boolean startsWith(Path other) {
            return delegate.startsWith(other);
        }

        @Override
        public boolean endsWith(Path other) {
            return false;
        }

        @Override
        public Path normalize() {
            return fs.wrap(delegate.normalize());
        }

        @Override
        public Path resolve(Path other) {
            return fs.wrap(delegate.resolve(fs.unwrap(other)));
        }

        @Override
        public Path relativize(Path other) {
            return null;
        }

        @Override
        public URI toUri() {
            return delegate.toUri();
        }

        @Override
        public Path toAbsolutePath() {
            return fs.wrap(delegate.toAbsolutePath());
        }

        @Override
        public Path toRealPath(LinkOption... options) throws IOException {
            return null;
        }

        @Override
        public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers) throws IOException {
            return null;
        }

        @Override
        public int compareTo(Path other) {
            return 0;
        }

        Path unwrap() {
            return delegate;
        }
    }
}