-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
JavacFileManager.java
1339 lines (1181 loc) · 48.9 KB
/
JavacFileManager.java
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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2005, 2021, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package com.sun.tools.javac.file;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.module.Configuration;
import java.lang.module.ModuleFinder;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.ProviderNotFoundException;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.spi.FileSystemProvider;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.lang.model.SourceVersion;
import javax.tools.FileObject;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import com.sun.tools.javac.file.RelativePath.RelativeDirectory;
import com.sun.tools.javac.file.RelativePath.RelativeFile;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.resources.CompilerProperties.Errors;
import com.sun.tools.javac.util.Assert;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Context.Factory;
import com.sun.tools.javac.util.DefinedBy;
import com.sun.tools.javac.util.DefinedBy.Api;
import com.sun.tools.javac.util.List;
import com.sun.tools.javac.util.ListBuffer;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.file.FileVisitOption.FOLLOW_LINKS;
import static javax.tools.StandardLocation.*;
/**
* This class provides access to the source, class and other files
* used by the compiler and related tools.
*
* <p><b>This is NOT part of any supported API.
* If you write code that depends on this, you do so at your own risk.
* This code and its internal interfaces are subject to change or
* deletion without notice.</b>
*/
public class JavacFileManager extends BaseFileManager implements StandardJavaFileManager {
public static char[] toArray(CharBuffer buffer) {
if (buffer.hasArray())
return buffer.compact().flip().array();
else
return buffer.toString().toCharArray();
}
private FSInfo fsInfo;
private static final Set<JavaFileObject.Kind> SOURCE_OR_CLASS =
Set.of(JavaFileObject.Kind.SOURCE, JavaFileObject.Kind.CLASS);
protected boolean symbolFileEnabled;
private PathFactory pathFactory = Paths::get;
protected enum SortFiles implements Comparator<Path> {
FORWARD {
@Override
public int compare(Path f1, Path f2) {
return f1.getFileName().compareTo(f2.getFileName());
}
},
REVERSE {
@Override
public int compare(Path f1, Path f2) {
return f2.getFileName().compareTo(f1.getFileName());
}
}
}
protected SortFiles sortFiles;
/**
* We use a two-layered map instead of a map with a complex key because we don't want to reindex
* the values for every Location+RelativeDirectory pair. Once the PathsAndContainers are needed
* for a single Location, we should know all valid RelativeDirectory mappings. Because the
* indexing is costly for very large classpaths, this can result in a significant savings.
*/
private Map<Location, Map<RelativeDirectory, java.util.List<PathAndContainer>>>
pathsAndContainersByLocationAndRelativeDirectory = new HashMap<>();
/** Containers that have no indexing by {@link RelativeDirectory}, keyed by {@link Location}. */
private Map<Location, java.util.List<PathAndContainer>> nonIndexingContainersByLocation =
new HashMap<>();
/**
* Register a Context.Factory to create a JavacFileManager.
*/
public static void preRegister(Context context) {
context.put(JavaFileManager.class,
(Factory<JavaFileManager>)c -> new JavacFileManager(c, true, null));
}
/**
* Create a JavacFileManager using a given context, optionally registering
* it as the JavaFileManager for that context.
*/
public JavacFileManager(Context context, boolean register, Charset charset) {
super(charset);
if (register)
context.put(JavaFileManager.class, this);
setContext(context);
}
/**
* Set the context for JavacFileManager.
*/
@Override
public void setContext(Context context) {
super.setContext(context);
fsInfo = FSInfo.instance(context);
symbolFileEnabled = !options.isSet("ignore.symbol.file");
String sf = options.get("sortFiles");
if (sf != null) {
sortFiles = (sf.equals("reverse") ? SortFiles.REVERSE : SortFiles.FORWARD);
}
}
@Override @DefinedBy(DefinedBy.Api.COMPILER)
public void setPathFactory(PathFactory f) {
pathFactory = Objects.requireNonNull(f);
locations.setPathFactory(f);
}
private Path getPath(String first, String... more) {
return pathFactory.getPath(first, more);
}
/**
* Set whether or not to use ct.sym as an alternate to rt.jar.
*/
public void setSymbolFileEnabled(boolean b) {
symbolFileEnabled = b;
}
public boolean isSymbolFileEnabled() {
return symbolFileEnabled;
}
// used by tests
public JavaFileObject getJavaFileObject(String name) {
return getJavaFileObjects(name).iterator().next();
}
// used by tests
public JavaFileObject getJavaFileObject(Path file) {
return getJavaFileObjects(file).iterator().next();
}
public JavaFileObject getFileForOutput(String classname,
JavaFileObject.Kind kind,
JavaFileObject sibling)
throws IOException
{
return getJavaFileForOutput(CLASS_OUTPUT, classname, kind, sibling);
}
@Override @DefinedBy(Api.COMPILER)
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(Iterable<String> names) {
ListBuffer<Path> paths = new ListBuffer<>();
for (String name : names)
paths.append(getPath(nullCheck(name)));
return getJavaFileObjectsFromPaths(paths.toList());
}
@Override @DefinedBy(Api.COMPILER)
public Iterable<? extends JavaFileObject> getJavaFileObjects(String... names) {
return getJavaFileObjectsFromStrings(Arrays.asList(nullCheck(names)));
}
private static boolean isValidName(String name) {
// Arguably, isValidName should reject keywords (such as in SourceVersion.isName() ),
// but the set of keywords depends on the source level, and we don't want
// impls of JavaFileManager to have to be dependent on the source level.
// Therefore we simply check that the argument is a sequence of identifiers
// separated by ".".
for (String s : name.split("\\.", -1)) {
if (!SourceVersion.isIdentifier(s))
return false;
}
return true;
}
private static void validateClassName(String className) {
if (!isValidName(className))
throw new IllegalArgumentException("Invalid class name: " + className);
}
private static void validatePackageName(String packageName) {
if (packageName.length() > 0 && !isValidName(packageName))
throw new IllegalArgumentException("Invalid packageName name: " + packageName);
}
public static void testName(String name,
boolean isValidPackageName,
boolean isValidClassName)
{
try {
validatePackageName(name);
if (!isValidPackageName)
throw new AssertionError("Invalid package name accepted: " + name);
printAscii("Valid package name: \"%s\"", name);
} catch (IllegalArgumentException e) {
if (isValidPackageName)
throw new AssertionError("Valid package name rejected: " + name);
printAscii("Invalid package name: \"%s\"", name);
}
try {
validateClassName(name);
if (!isValidClassName)
throw new AssertionError("Invalid class name accepted: " + name);
printAscii("Valid class name: \"%s\"", name);
} catch (IllegalArgumentException e) {
if (isValidClassName)
throw new AssertionError("Valid class name rejected: " + name);
printAscii("Invalid class name: \"%s\"", name);
}
}
private static void printAscii(String format, Object... args) {
String message = new String(
String.format(null, format, args).getBytes(US_ASCII), US_ASCII);
System.out.println(message);
}
private final Map<Path, Container> containers = new HashMap<>();
synchronized Container getContainer(Path path) throws IOException {
Container fs = containers.get(path);
if (fs != null) {
return fs;
}
if (fsInfo.isFile(path) && path.equals(Locations.thisSystemModules)) {
containers.put(path, fs = new JRTImageContainer());
return fs;
}
Path realPath = fsInfo.getCanonicalFile(path);
fs = containers.get(realPath);
if (fs != null) {
containers.put(path, fs);
return fs;
}
BasicFileAttributes attr = null;
try {
attr = Files.readAttributes(realPath, BasicFileAttributes.class);
} catch (IOException ex) {
//non-existing
fs = MISSING_CONTAINER;
}
if (attr != null) {
if (attr.isDirectory()) {
fs = new DirectoryContainer(realPath);
} else {
try {
fs = new ArchiveContainer(path);
} catch (ProviderNotFoundException | SecurityException ex) {
throw new IOException(ex);
}
}
}
containers.put(realPath, fs);
containers.put(path, fs);
return fs;
}
private interface Container {
/**
* Insert all files in subdirectory subdirectory of container which
* match fileKinds into resultList
*/
public abstract void list(Path userPath,
RelativeDirectory subdirectory,
Set<JavaFileObject.Kind> fileKinds,
boolean recurse,
ListBuffer<JavaFileObject> resultList) throws IOException;
public abstract JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException;
public abstract void close() throws IOException;
public abstract boolean maintainsDirectoryIndex();
/**
* The directories this container indexes if {@link #maintainsDirectoryIndex()}, otherwise
* an empty iterable.
*/
public abstract Iterable<RelativeDirectory> indexedDirectories();
}
private static final Container MISSING_CONTAINER = new Container() {
@Override
public void list(Path userPath,
RelativeDirectory subdirectory,
Set<JavaFileObject.Kind> fileKinds,
boolean recurse,
ListBuffer<JavaFileObject> resultList) throws IOException {
}
@Override
public JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException {
return null;
}
@Override
public void close() throws IOException {}
@Override
public boolean maintainsDirectoryIndex() {
return false;
}
@Override
public Iterable<RelativeDirectory> indexedDirectories() {
return List.nil();
}
};
private final class JRTImageContainer implements Container {
/**
* Insert all files in a subdirectory of the platform image
* which match fileKinds into resultList.
*/
@Override
public void list(Path userPath,
RelativeDirectory subdirectory,
Set<JavaFileObject.Kind> fileKinds,
boolean recurse,
ListBuffer<JavaFileObject> resultList) throws IOException {
try {
JRTIndex.Entry e = getJRTIndex().getEntry(subdirectory);
if (symbolFileEnabled && e.ctSym.hidden)
return;
for (Path file: e.files.values()) {
if (fileKinds.contains(getKind(file))) {
JavaFileObject fe
= PathFileObject.forJRTPath(JavacFileManager.this, file);
resultList.append(fe);
}
}
if (recurse) {
for (RelativeDirectory rd: e.subdirs) {
list(userPath, rd, fileKinds, recurse, resultList);
}
}
} catch (IOException ex) {
ex.printStackTrace(System.err);
log.error(Errors.ErrorReadingFile(userPath, getMessage(ex)));
}
}
@Override
public JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException {
JRTIndex.Entry e = getJRTIndex().getEntry(name.dirname());
if (symbolFileEnabled && e.ctSym.hidden)
return null;
Path p = e.files.get(name.basename());
if (p != null) {
return PathFileObject.forJRTPath(JavacFileManager.this, p);
} else {
return null;
}
}
@Override
public void close() throws IOException {
}
@Override
public boolean maintainsDirectoryIndex() {
return false;
}
@Override
public Iterable<RelativeDirectory> indexedDirectories() {
return List.nil();
}
}
private synchronized JRTIndex getJRTIndex() {
if (jrtIndex == null)
jrtIndex = JRTIndex.getSharedInstance();
return jrtIndex;
}
private JRTIndex jrtIndex;
private final class DirectoryContainer implements Container {
private final Path directory;
public DirectoryContainer(Path directory) {
this.directory = directory;
}
/**
* Insert all files in subdirectory subdirectory of directory userPath
* which match fileKinds into resultList
*/
@Override
public void list(Path userPath,
RelativeDirectory subdirectory,
Set<JavaFileObject.Kind> fileKinds,
boolean recurse,
ListBuffer<JavaFileObject> resultList) throws IOException {
Path d;
try {
d = subdirectory.resolveAgainst(userPath);
} catch (InvalidPathException ignore) {
return ;
}
if (!Files.exists(d)) {
return;
}
if (!caseMapCheck(d, subdirectory)) {
return;
}
java.util.List<Path> files;
try (Stream<Path> s = Files.list(d)) {
files = (sortFiles == null ? s : s.sorted(sortFiles)).toList();
} catch (IOException ignore) {
return;
}
for (Path f: files) {
String fname = f.getFileName().toString();
if (fname.endsWith("/"))
fname = fname.substring(0, fname.length() - 1);
if (Files.isDirectory(f)) {
if (recurse && SourceVersion.isIdentifier(fname)) {
list(userPath,
new RelativeDirectory(subdirectory, fname),
fileKinds,
recurse,
resultList);
}
} else {
if (isValidFile(fname, fileKinds)) {
try {
RelativeFile file = new RelativeFile(subdirectory, fname);
JavaFileObject fe = PathFileObject.forDirectoryPath(JavacFileManager.this,
file.resolveAgainst(directory), userPath, file);
resultList.append(fe);
} catch (InvalidPathException e) {
throw new IOException("error accessing directory " + directory + e);
}
}
}
}
}
@Override
public JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException {
try {
Path f = name.resolveAgainst(userPath);
if (Files.exists(f))
return PathFileObject.forSimplePath(JavacFileManager.this,
fsInfo.getCanonicalFile(f), f);
} catch (InvalidPathException ignore) {
}
return null;
}
@Override
public void close() throws IOException {
}
@Override
public boolean maintainsDirectoryIndex() {
return false;
}
@Override
public Iterable<RelativeDirectory> indexedDirectories() {
return List.nil();
}
}
private static final Set<FileVisitOption> NO_FILE_VISIT_OPTIONS = Set.of();
private static final Set<FileVisitOption> FOLLOW_LINKS_OPTIONS = Set.of(FOLLOW_LINKS);
private final class ArchiveContainer implements Container {
private final Path archivePath;
private final FileSystem fileSystem;
private final Map<RelativeDirectory, Path> packages;
public ArchiveContainer(Path archivePath) throws IOException, ProviderNotFoundException, SecurityException {
this.archivePath = archivePath;
if (multiReleaseValue != null && archivePath.toString().endsWith(".jar")) {
Map<String,String> env = Collections.singletonMap("multi-release", multiReleaseValue);
FileSystemProvider jarFSProvider = fsInfo.getJarFSProvider();
Assert.checkNonNull(jarFSProvider, "should have been caught before!");
this.fileSystem = jarFSProvider.newFileSystem(archivePath, env);
} else {
this.fileSystem = FileSystems.newFileSystem(archivePath, (ClassLoader)null);
}
packages = new HashMap<>();
for (Path root : fileSystem.getRootDirectories()) {
Files.walkFileTree(root, NO_FILE_VISIT_OPTIONS, Integer.MAX_VALUE,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (isValid(dir.getFileName())) {
packages.put(new RelativeDirectory(root.relativize(dir).toString()), dir);
return FileVisitResult.CONTINUE;
} else {
return FileVisitResult.SKIP_SUBTREE;
}
}
});
}
}
/**
* Insert all files in subdirectory subdirectory of this archive
* which match fileKinds into resultList
*/
@Override
public void list(Path userPath,
RelativeDirectory subdirectory,
Set<JavaFileObject.Kind> fileKinds,
boolean recurse,
ListBuffer<JavaFileObject> resultList) throws IOException {
Path resolvedSubdirectory = packages.get(subdirectory);
if (resolvedSubdirectory == null)
return ;
int maxDepth = (recurse ? Integer.MAX_VALUE : 1);
Files.walkFileTree(resolvedSubdirectory, FOLLOW_LINKS_OPTIONS, maxDepth,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (isValid(dir.getFileName())) {
return FileVisitResult.CONTINUE;
} else {
return FileVisitResult.SKIP_SUBTREE;
}
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (attrs.isRegularFile() && fileKinds.contains(getKind(file.getFileName().toString()))) {
JavaFileObject fe = PathFileObject.forJarPath(
JavacFileManager.this, file, archivePath);
resultList.append(fe);
}
return FileVisitResult.CONTINUE;
}
});
}
private boolean isValid(Path fileName) {
if (fileName == null) {
return true;
} else {
String name = fileName.toString();
if (name.endsWith("/")) {
name = name.substring(0, name.length() - 1);
}
return SourceVersion.isIdentifier(name);
}
}
@Override
public JavaFileObject getFileObject(Path userPath, RelativeFile name) throws IOException {
RelativeDirectory root = name.dirname();
Path packagepath = packages.get(root);
if (packagepath != null) {
Path relpath = packagepath.resolve(name.basename());
if (Files.exists(relpath)) {
return PathFileObject.forJarPath(JavacFileManager.this, relpath, userPath);
}
}
return null;
}
@Override
public void close() throws IOException {
fileSystem.close();
}
@Override
public boolean maintainsDirectoryIndex() {
return true;
}
@Override
public Iterable<RelativeDirectory> indexedDirectories() {
return packages.keySet();
}
}
/**
* container is a directory, a zip file, or a non-existent path.
*/
private boolean isValidFile(String s, Set<JavaFileObject.Kind> fileKinds) {
JavaFileObject.Kind kind = getKind(s);
return fileKinds.contains(kind);
}
private static final boolean fileSystemIsCaseSensitive =
File.separatorChar == '/';
/** Hack to make Windows case sensitive. Test whether given path
* ends in a string of characters with the same case as given name.
* Ignore file separators in both path and name.
*/
private boolean caseMapCheck(Path f, RelativePath name) {
if (fileSystemIsCaseSensitive) return true;
// Note that toRealPath() returns the case-sensitive
// spelled file name.
String path;
char sep;
try {
path = f.toRealPath(LinkOption.NOFOLLOW_LINKS).toString();
sep = f.getFileSystem().getSeparator().charAt(0);
} catch (IOException ex) {
return false;
}
char[] pcs = path.toCharArray();
char[] ncs = name.path.toCharArray();
int i = pcs.length - 1;
int j = ncs.length - 1;
while (i >= 0 && j >= 0) {
while (i >= 0 && pcs[i] == sep) i--;
while (j >= 0 && ncs[j] == '/') j--;
if (i >= 0 && j >= 0) {
if (pcs[i] != ncs[j]) return false;
i--;
j--;
}
}
return j < 0;
}
/** Flush any output resources.
*/
@Override @DefinedBy(Api.COMPILER)
public void flush() {
contentCache.clear();
pathsAndContainersByLocationAndRelativeDirectory.clear();
nonIndexingContainersByLocation.clear();
}
/**
* Close the JavaFileManager, releasing resources.
*/
@Override @DefinedBy(Api.COMPILER)
public void close() throws IOException {
if (deferredCloseTimeout > 0) {
deferredClose();
return;
}
locations.close();
for (Container container: containers.values()) {
container.close();
}
containers.clear();
pathsAndContainersByLocationAndRelativeDirectory.clear();
nonIndexingContainersByLocation.clear();
contentCache.clear();
}
@Override @DefinedBy(Api.COMPILER)
public ClassLoader getClassLoader(Location location) {
checkNotModuleOrientedLocation(location);
Iterable<? extends File> path = getLocation(location);
if (path == null)
return null;
ListBuffer<URL> lb = new ListBuffer<>();
for (File f: path) {
try {
lb.append(f.toURI().toURL());
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
}
return getClassLoader(lb.toArray(new URL[lb.size()]));
}
@Override @DefinedBy(Api.COMPILER)
public Iterable<JavaFileObject> list(Location location,
String packageName,
Set<JavaFileObject.Kind> kinds,
boolean recurse)
throws IOException
{
checkNotModuleOrientedLocation(location);
// validatePackageName(packageName);
nullCheck(packageName);
nullCheck(kinds);
RelativeDirectory subdirectory = RelativeDirectory.forPackage(packageName);
ListBuffer<JavaFileObject> results = new ListBuffer<>();
for (PathAndContainer pathAndContainer : pathsAndContainers(location, subdirectory)) {
Path directory = pathAndContainer.path;
Container container = pathAndContainer.container;
container.list(directory, subdirectory, kinds, recurse, results);
}
return results.toList();
}
@Override @DefinedBy(Api.COMPILER)
public String inferBinaryName(Location location, JavaFileObject file) {
checkNotModuleOrientedLocation(location);
Objects.requireNonNull(file);
// Need to match the path semantics of list(location, ...)
Iterable<? extends Path> path = getLocationAsPaths(location);
if (path == null) {
return null;
}
if (file instanceof PathFileObject pathFileObject) {
return pathFileObject.inferBinaryName(path);
} else
throw new IllegalArgumentException(file.getClass().getName());
}
@Override @DefinedBy(Api.COMPILER)
public boolean isSameFile(FileObject a, FileObject b) {
nullCheck(a);
nullCheck(b);
if (a instanceof PathFileObject pathFileObjectA && b instanceof PathFileObject pathFileObjectB)
return pathFileObjectA.isSameFile(pathFileObjectB);
return a.equals(b);
}
@Override @DefinedBy(Api.COMPILER)
public boolean hasLocation(Location location) {
nullCheck(location);
return locations.hasLocation(location);
}
protected boolean hasExplicitLocation(Location location) {
nullCheck(location);
return locations.hasExplicitLocation(location);
}
@Override @DefinedBy(Api.COMPILER)
public JavaFileObject getJavaFileForInput(Location location,
String className,
JavaFileObject.Kind kind)
throws IOException
{
checkNotModuleOrientedLocation(location);
// validateClassName(className);
nullCheck(className);
nullCheck(kind);
if (!SOURCE_OR_CLASS.contains(kind))
throw new IllegalArgumentException("Invalid kind: " + kind);
return getFileForInput(location, RelativeFile.forClass(className, kind));
}
@Override @DefinedBy(Api.COMPILER)
public FileObject getFileForInput(Location location,
String packageName,
String relativeName)
throws IOException
{
checkNotModuleOrientedLocation(location);
// validatePackageName(packageName);
nullCheck(packageName);
if (!isRelativeUri(relativeName))
throw new IllegalArgumentException("Invalid relative name: " + relativeName);
RelativeFile name = packageName.length() == 0
? new RelativeFile(relativeName)
: new RelativeFile(RelativeDirectory.forPackage(packageName), relativeName);
return getFileForInput(location, name);
}
private JavaFileObject getFileForInput(Location location, RelativeFile name) throws IOException {
Iterable<? extends Path> path = getLocationAsPaths(location);
if (path == null)
return null;
for (Path file: path) {
JavaFileObject fo = getContainer(file).getFileObject(file, name);
if (fo != null) {
return fo;
}
}
return null;
}
@Override @DefinedBy(Api.COMPILER)
public JavaFileObject getJavaFileForOutput(Location location,
String className,
JavaFileObject.Kind kind,
FileObject sibling)
throws IOException
{
checkOutputLocation(location);
// validateClassName(className);
nullCheck(className);
nullCheck(kind);
if (!SOURCE_OR_CLASS.contains(kind))
throw new IllegalArgumentException("Invalid kind: " + kind);
return getFileForOutput(location, RelativeFile.forClass(className, kind), sibling);
}
@Override @DefinedBy(Api.COMPILER)
public FileObject getFileForOutput(Location location,
String packageName,
String relativeName,
FileObject sibling)
throws IOException
{
checkOutputLocation(location);
// validatePackageName(packageName);
nullCheck(packageName);
if (!isRelativeUri(relativeName))
throw new IllegalArgumentException("Invalid relative name: " + relativeName);
RelativeFile name = packageName.length() == 0
? new RelativeFile(relativeName)
: new RelativeFile(RelativeDirectory.forPackage(packageName), relativeName);
return getFileForOutput(location, name, sibling);
}
private JavaFileObject getFileForOutput(Location location,
RelativeFile fileName,
FileObject sibling)
throws IOException
{
Path dir;
if (location == CLASS_OUTPUT) {
if (getClassOutDir() != null) {
dir = getClassOutDir();
} else {
String baseName = fileName.basename();
if (sibling != null && sibling instanceof PathFileObject pathFileObject) {
return pathFileObject.getSibling(baseName);
} else {
Path p = getPath(baseName);
Path real = fsInfo.getCanonicalFile(p);
return PathFileObject.forSimplePath(this, real, p);
}
}
} else if (location == SOURCE_OUTPUT) {
dir = (getSourceOutDir() != null ? getSourceOutDir() : getClassOutDir());
} else {
Iterable<? extends Path> path = locations.getLocation(location);
dir = null;
for (Path f: path) {
dir = f;
break;
}
}
try {
if (dir == null) {
dir = getPath(System.getProperty("user.dir"));
}
Path path = fileName.resolveAgainst(fsInfo.getCanonicalFile(dir));
return PathFileObject.forDirectoryPath(this, path, dir, fileName);
} catch (InvalidPathException e) {
throw new IOException("bad filename " + fileName, e);
}
}
@Override @DefinedBy(Api.COMPILER)
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(
Iterable<? extends File> files)
{
ArrayList<PathFileObject> result;
if (files instanceof Collection<?> collection)
result = new ArrayList<>(collection.size());
else
result = new ArrayList<>();
for (File f: files) {
Objects.requireNonNull(f);
Path p = f.toPath();
result.add(PathFileObject.forSimplePath(this,
fsInfo.getCanonicalFile(p), p));
}
return result;
}
@Override @DefinedBy(Api.COMPILER)
public Iterable<? extends JavaFileObject> getJavaFileObjectsFromPaths(Collection<? extends Path> paths) {
ArrayList<PathFileObject> result;
if (paths != null) {
result = new ArrayList<>(paths.size());
for (Path p: paths)
result.add(PathFileObject.forSimplePath(this,
fsInfo.getCanonicalFile(p), p));
} else {
result = new ArrayList<>();
}
return result;
}
@Override @DefinedBy(Api.COMPILER)
public Iterable<? extends JavaFileObject> getJavaFileObjects(File... files) {
return getJavaFileObjectsFromFiles(Arrays.asList(nullCheck(files)));
}
@Override @DefinedBy(Api.COMPILER)
public Iterable<? extends JavaFileObject> getJavaFileObjects(Path... paths) {
return getJavaFileObjectsFromPaths(Arrays.asList(nullCheck(paths)));
}
@Override @DefinedBy(Api.COMPILER)
public void setLocation(Location location,
Iterable<? extends File> searchpath)
throws IOException
{
nullCheck(location);
locations.setLocation(location, asPaths(searchpath));
clearCachesForLocation(location);
}
@Override @DefinedBy(Api.COMPILER)
public void setLocationFromPaths(Location location,
Collection<? extends Path> searchpath)
throws IOException
{
nullCheck(location);
locations.setLocation(location, nullCheck(searchpath));
clearCachesForLocation(location);
}
@Override @DefinedBy(Api.COMPILER)
public Iterable<? extends File> getLocation(Location location) {