/
ScanResult.java
1570 lines (1454 loc) · 71.1 KB
/
ScanResult.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
/*
* This file is part of ClassGraph.
*
* Author: Luke Hutchison
*
* Hosted at: https://github.com/classgraph/classgraph
*
* --
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Luke Hutchison
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.classgraph;
import java.io.Closeable;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.ref.WeakReference;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nonapi.io.github.classgraph.classpath.ClasspathFinder;
import nonapi.io.github.classgraph.concurrency.AutoCloseableExecutorService;
import nonapi.io.github.classgraph.fastzipfilereader.NestedJarHandler;
import nonapi.io.github.classgraph.json.JSONDeserializer;
import nonapi.io.github.classgraph.json.JSONSerializer;
import nonapi.io.github.classgraph.scanspec.ScanSpec;
import nonapi.io.github.classgraph.utils.Assert;
import nonapi.io.github.classgraph.utils.CollectionUtils;
import nonapi.io.github.classgraph.utils.FileUtils;
import nonapi.io.github.classgraph.utils.JarUtils;
import nonapi.io.github.classgraph.utils.LogNode;
/**
* The result of a scan. You should assign a ScanResult in a try-with-resources block, or manually close it when you
* have finished with the result of a scan.
*/
public final class ScanResult implements Closeable, AutoCloseable {
/** The order of raw classpath elements. */
private List<String> rawClasspathEltOrderStrs;
/** The order of classpath elements, after inner jars have been extracted to temporary files, etc. */
private List<ClasspathElement> classpathOrder;
/** A list of all files that were found in accepted packages. */
private ResourceList allAcceptedResourcesCached;
/** The number of times {@link #getResourcesWithPath(String)} has been called. */
private final AtomicInteger getResourcesWithPathCallCount = new AtomicInteger();
/**
* The map from path (relative to package root) to a list of {@link Resource} elements with the matching path.
*/
private Map<String, ResourceList> pathToAcceptedResourcesCached;
/** The map from class name to {@link ClassInfo}. */
Map<String, ClassInfo> classNameToClassInfo;
/** The map from package name to {@link PackageInfo}. */
private Map<String, PackageInfo> packageNameToPackageInfo;
/** The map from class name to {@link ClassInfo}. */
private Map<String, ModuleInfo> moduleNameToModuleInfo;
/**
* The file, directory and jarfile resources timestamped during a scan, along with their timestamp at the time
* of the scan. For jarfiles, the timestamp represents the timestamp of all files within the jar. May be null,
* if this ScanResult object is the result of a call to ClassGraph#getUniqueClasspathElementsAsync().
*/
private Map<File, Long> fileToLastModified;
/** If true, this {@link ScanResult} was produced by {@link ScanResult#fromJSON(String)}. */
private boolean isObtainedFromDeserialization;
/** A custom ClassLoader that can load classes found during the scan. */
private ClassGraphClassLoader classGraphClassLoader;
/** The {@link ClasspathFinder}. */
ClasspathFinder classpathFinder;
/** The nested jar handler instance. */
private NestedJarHandler nestedJarHandler;
/** The scan spec. */
ScanSpec scanSpec;
/** If true, this ScanResult has already been closed. */
private final AtomicBoolean closed = new AtomicBoolean(false);
/** The toplevel log. */
private final LogNode topLevelLog;
// -------------------------------------------------------------------------------------------------------------
/** The {@link WeakReference} for this ScanResult. */
private final WeakReference<ScanResult> weakReference;
/**
* The set of WeakReferences to non-closed ScanResult objects. Uses WeakReferences so that garbage collection is
* not blocked. (Bug #233)
*/
private static Set<WeakReference<ScanResult>> nonClosedWeakReferences = Collections
.newSetFromMap(new ConcurrentHashMap<WeakReference<ScanResult>, Boolean>());
/** If true, ScanResult#staticInit() has been run. */
private static final AtomicBoolean initialized = new AtomicBoolean(false);
// -------------------------------------------------------------------------------------------------------------
/** The current serialization format. */
private static final String CURRENT_SERIALIZATION_FORMAT = "10";
/** A class to hold a serialized ScanResult along with the ScanSpec that was used to scan. */
private static class SerializationFormat {
/** The serialization format. */
public String format;
/** The scan spec. */
public ScanSpec scanSpec;
/** The classpath, as a list of URL strings. */
public List<String> classpath;
/** The list of all {@link ClassInfo} objects. */
public List<ClassInfo> classInfo;
/** The list of all {@link PackageInfo} objects. */
public List<PackageInfo> packageInfo;
/** The list of all {@link ModuleInfo} objects. */
public List<ModuleInfo> moduleInfo;
/**
* Constructor.
*/
@SuppressWarnings("unused")
public SerializationFormat() {
// Empty
}
/**
* Constructor.
*
* @param serializationFormatStr
* the serialization format string
* @param scanSpec
* the scan spec
* @param classInfo
* the list of all {@link ClassInfo} objects
* @param packageInfo
* the list of all {@link PackageInfo} objects
* @param moduleInfo
* the list of all {@link ModuleInfo} objects
* @param classpath
* the classpath as a list of URL strings
*/
public SerializationFormat(final String serializationFormatStr, final ScanSpec scanSpec,
final List<ClassInfo> classInfo, final List<PackageInfo> packageInfo,
final List<ModuleInfo> moduleInfo, final List<String> classpath) {
this.format = serializationFormatStr;
this.scanSpec = scanSpec;
this.classpath = classpath;
this.classInfo = classInfo;
this.packageInfo = packageInfo;
this.moduleInfo = moduleInfo;
}
}
// -------------------------------------------------------------------------------------------------------------
// Shutdown hook init code
/**
* Static initialization (warm up classloading), called when the ClassGraph class is initialized.
*/
static void init() {
if (!initialized.getAndSet(true)) {
// Pre-load non-system classes necessary for calling scanResult.close(), so that classes that need
// to be loaded to close resources are already loaded and cached. This was originally for use in
// a shutdown hook (#331), which has now been removed, but it is probably still a good idea to
// ensure that classes needed to unmap DirectByteBuffer instances are available at init.
// We achieve this by mmap'ing a file and then closing it, since the only problematic classes are
// the PriviledgedAction anonymous inner classes used by FileUtils::closeDirectByteBuffer.
FileUtils.closeDirectByteBuffer(ByteBuffer.allocateDirect(32), /* log = */ null);
}
}
// -------------------------------------------------------------------------------------------------------------
// Constructor
/**
* The result of a scan. Make sure you call complete() after calling the constructor.
*
* @param scanSpec
* the scan spec
* @param classpathOrder
* the classpath order
* @param rawClasspathEltOrderStrs
* the raw classpath element order
* @param classpathFinder
* the {@link ClasspathFinder}
* @param classNameToClassInfo
* a map from class name to class info
* @param packageNameToPackageInfo
* a map from package name to package info
* @param moduleNameToModuleInfo
* a map from module name to module info
* @param fileToLastModified
* a map from file to last modified time
* @param nestedJarHandler
* the nested jar handler
* @param topLevelLog
* the toplevel log
*/
ScanResult(final ScanSpec scanSpec, final List<ClasspathElement> classpathOrder,
final List<String> rawClasspathEltOrderStrs, final ClasspathFinder classpathFinder,
final Map<String, ClassInfo> classNameToClassInfo,
final Map<String, PackageInfo> packageNameToPackageInfo,
final Map<String, ModuleInfo> moduleNameToModuleInfo, final Map<File, Long> fileToLastModified,
final NestedJarHandler nestedJarHandler, final LogNode topLevelLog) {
this.scanSpec = scanSpec;
this.rawClasspathEltOrderStrs = rawClasspathEltOrderStrs;
this.classpathOrder = classpathOrder;
this.classpathFinder = classpathFinder;
this.fileToLastModified = fileToLastModified;
this.classNameToClassInfo = classNameToClassInfo;
this.packageNameToPackageInfo = packageNameToPackageInfo;
this.moduleNameToModuleInfo = moduleNameToModuleInfo;
this.nestedJarHandler = nestedJarHandler;
this.topLevelLog = topLevelLog;
if (classNameToClassInfo != null) {
indexResourcesAndClassInfo(topLevelLog);
}
if (classNameToClassInfo != null) {
// Handle @Repeatable annotations
final Set<String> allRepeatableAnnotationNames = new HashSet<>();
for (final ClassInfo classInfo : classNameToClassInfo.values()) {
if (classInfo.isAnnotation() && classInfo.annotationInfo != null) {
final AnnotationInfo repeatableMetaAnnotation = classInfo.annotationInfo
.get("java.lang.annotation.Repeatable");
if (repeatableMetaAnnotation != null) {
final AnnotationParameterValueList vals = repeatableMetaAnnotation.getParameterValues();
if (!vals.isEmpty()) {
final Object val = vals.getValue("value");
if (val instanceof AnnotationClassRef) {
final AnnotationClassRef classRef = (AnnotationClassRef) val;
final String repeatableAnnotationName = classRef.getName();
if (repeatableAnnotationName != null) {
allRepeatableAnnotationNames.add(repeatableAnnotationName);
}
}
}
}
}
}
if (!allRepeatableAnnotationNames.isEmpty()) {
for (final ClassInfo classInfo : classNameToClassInfo.values()) {
classInfo.handleRepeatableAnnotations(allRepeatableAnnotationNames);
}
}
}
// Define a new ClassLoader that can load the classes found during the scan
this.classGraphClassLoader = new ClassGraphClassLoader(this);
// Provide the shutdown hook with a weak reference to this ScanResult
this.weakReference = new WeakReference<>(this);
nonClosedWeakReferences.add(this.weakReference);
}
/**
* Index {@link Resource} and {@link ClassInfo} objects.
*
* @param log
* the log
*/
private void indexResourcesAndClassInfo(final LogNode log) {
// Add backrefs from Info objects back to this ScanResult
final Collection<ClassInfo> allClassInfo = classNameToClassInfo.values();
for (final ClassInfo classInfo : allClassInfo) {
classInfo.setScanResult(this);
}
// If inter-class dependencies are enabled, create placeholder ClassInfo objects for any referenced
// classes that were not scanned
if (scanSpec.enableInterClassDependencies) {
for (final ClassInfo ci : new ArrayList<>(classNameToClassInfo.values())) {
final Set<ClassInfo> refdClassesFiltered = new HashSet<>();
for (final ClassInfo refdClassInfo : ci.findReferencedClassInfo(log)) {
// Don't add self-references, or references to Object
if (refdClassInfo != null && !ci.equals(refdClassInfo)
&& !refdClassInfo.getName().equals("java.lang.Object")
// Only add class to result if it is accepted, or external classes are enabled
&& (!refdClassInfo.isExternalClass() || scanSpec.enableExternalClasses)) {
refdClassInfo.setScanResult(this);
refdClassesFiltered.add(refdClassInfo);
}
}
ci.setReferencedClasses(new ClassInfoList(refdClassesFiltered, /* sortByName = */ true));
}
}
}
// -------------------------------------------------------------------------------------------------------------
// Classpath / module path
/**
* Returns the list of File objects for unique classpath elements (directories or jarfiles), in classloader
* resolution order.
*
* @return The unique classpath elements.
*/
public List<File> getClasspathFiles() {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
final List<File> classpathElementOrderFiles = new ArrayList<>();
for (final ClasspathElement classpathElement : classpathOrder) {
final File file = classpathElement.getFile();
if (file != null) {
classpathElementOrderFiles.add(file);
}
}
return classpathElementOrderFiles;
}
/**
* Returns all unique directories or zip/jarfiles on the classpath, in classloader resolution order, as a
* classpath string, delineated with the standard path separator character.
*
* @return a the unique directories and jarfiles on the classpath, in classpath resolution order, as a path
* string.
*/
public String getClasspath() {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
return JarUtils.pathElementsToPathStr(getClasspathFiles());
}
/**
* Returns an ordered list of unique classpath element and module URIs.
*
* @return The unique classpath element and module URIs.
*/
public List<URI> getClasspathURIs() {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
final List<URI> classpathElementOrderURIs = new ArrayList<>();
for (final ClasspathElement classpathElement : classpathOrder) {
try {
for (final URI uri : classpathElement.getAllURIs()) {
if (uri != null) {
classpathElementOrderURIs.add(uri);
}
}
} catch (final IllegalArgumentException e) {
// Skip null location URIs
}
}
return classpathElementOrderURIs;
}
/**
* Returns an ordered list of unique classpath element and module URLs. Will skip any system modules or modules
* that are part of a jlink'd runtime image, since {@link URL} does not support the {@code jrt:} {@link URI}
* scheme.
*
* @return The unique classpath element and module URLs.
*/
public List<URL> getClasspathURLs() {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
final List<URL> classpathElementOrderURLs = new ArrayList<>();
for (final URI uri : getClasspathURIs()) {
try {
classpathElementOrderURLs.add(uri.toURL());
} catch (final IllegalArgumentException | MalformedURLException e) {
// Skip "jrt:" URIs and malformed URLs
}
}
return classpathElementOrderURLs;
}
/**
* Get {@link ModuleRef} references for all visible modules.
*
* @return {@link ModuleRef} references for all visible modules.
*/
public List<ModuleRef> getModules() {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
final List<ModuleRef> moduleRefs = new ArrayList<>();
for (final ClasspathElement classpathElement : classpathOrder) {
if (classpathElement instanceof ClasspathElementModule) {
moduleRefs.add(((ClasspathElementModule) classpathElement).getModuleRef());
}
}
return moduleRefs;
}
/**
* Get the module path info provided on the commandline with {@code --module-path}, {@code --add-modules},
* {@code --patch-module}, {@code --add-exports}, {@code --add-opens}, and {@code --add-reads}, and also the
* {@code Add-Exports} and {@code Add-Opens} entries from jarfile manifest files encountered during scanning.
*
* <p>
* Note that the returned {@link ModulePathInfo} object does not include classpath entries from the traditional
* classpath or system modules. Use {@link #getModules()} to get all visible modules, including anonymous,
* automatic and system modules.
*
* @return The {@link ModulePathInfo}.
*/
public ModulePathInfo getModulePathInfo() {
return scanSpec.modulePathInfo;
}
// -------------------------------------------------------------------------------------------------------------
// Resources
/**
* Get the list of all resources.
*
* @return A list of all resources (including classfiles and non-classfiles) found in accepted packages.
*/
public ResourceList getAllResources() {
if (allAcceptedResourcesCached == null) {
// Index Resource objects by path
final ResourceList acceptedResourcesList = new ResourceList();
for (final ClasspathElement classpathElt : classpathOrder) {
acceptedResourcesList.addAll(classpathElt.acceptedResources);
}
// Set atomically for thread safety
allAcceptedResourcesCached = acceptedResourcesList;
}
return allAcceptedResourcesCached;
}
/**
* Get a map from resource path to {@link Resource} for all resources (including classfiles and non-classfiles)
* found in accepted packages.
*
* @return The map from resource path to {@link Resource} for all resources (including classfiles and
* non-classfiles) found in accepted packages.
*/
public Map<String, ResourceList> getAllResourcesAsMap() {
if (pathToAcceptedResourcesCached == null) {
final Map<String, ResourceList> pathToAcceptedResourceListMap = new HashMap<>();
for (final Resource res : getAllResources()) {
ResourceList resList = pathToAcceptedResourceListMap.get(res.getPath());
if (resList == null) {
pathToAcceptedResourceListMap.put(res.getPath(), resList = new ResourceList());
}
resList.add(res);
}
// Set atomically for thread safety
pathToAcceptedResourcesCached = pathToAcceptedResourceListMap;
}
return pathToAcceptedResourcesCached;
}
/**
* Get the list of all resources found in accepted packages that have the given path, relative to the package
* root of the classpath element. May match several resources, up to one per classpath element.
*
* @param resourcePath
* A complete resource path, relative to the classpath entry package root.
* @return A list of all resources found in accepted packages that have the given path, relative to the package
* root of the classpath element. May match several resources, up to one per classpath element.
*/
public ResourceList getResourcesWithPath(final String resourcePath) {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
final String path = FileUtils.sanitizeEntryPath(resourcePath, /* removeInitialSlash = */ true,
/* removeFinalSlash = */ true);
if (getResourcesWithPathCallCount.incrementAndGet() > 3) {
// If numerous calls are made, produce and cache a single HashMap for O(1) access time
return getAllResourcesAsMap().get(path);
} else {
// If just a few calls are made, directly search for resource with the requested path
ResourceList matchingResources = null;
for (final ClasspathElement classpathElt : classpathOrder) {
for (final Resource res : classpathElt.acceptedResources) {
if (res.getPath().equals(path)) {
if (matchingResources == null) {
matchingResources = new ResourceList();
}
matchingResources.add(res);
}
}
}
return matchingResources == null ? ResourceList.EMPTY_LIST : matchingResources;
}
}
/**
* Get the list of all resources found in any classpath element, <i>whether in accepted packages or not (as long
* as the resource is not rejected)</i>, that have the given path, relative to the package root of the classpath
* element. May match several resources, up to one per classpath element. Note that this may not return a
* non-accepted resource, particularly when scanning directory classpath elements, because recursive scanning
* terminates once there are no possible accepted resources below a given directory. However, resources in
* ancestral directories of accepted directories can be found using this method.
*
* @param resourcePath
* A complete resource path, relative to the classpath entry package root.
* @return A list of all resources found in any classpath element, <i>whether in accepted packages or not (as
* long as the resource is not rejected)</i>, that have the given path, relative to the package root of
* the classpath element. May match several resources, up to one per classpath element.
*/
public ResourceList getResourcesWithPathIgnoringAccept(final String resourcePath) {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
final String path = FileUtils.sanitizeEntryPath(resourcePath, /* removeInitialSlash = */ true,
/* removeFinalSlash = */ true);
final ResourceList matchingResources = new ResourceList();
for (final ClasspathElement classpathElt : classpathOrder) {
final Resource matchingResource = classpathElt.getResource(path);
if (matchingResource != null) {
matchingResources.add(matchingResource);
}
}
return matchingResources;
}
/**
* Use {@link #getResourcesWithPathIgnoringAccept(String)} instead.
*
* @param resourcePath
* A complete resource path, relative to the classpath entry package root.
* @return A list of all resources found in any classpath element, <i>whether in accepted packages or not (as
* long as the resource is not rejected)</i>, that have the given path, relative to the package root of
* the classpath element. May match several resources, up to one per classpath element.
* @deprecated Use {@link #getResourcesWithPathIgnoringAccept(String)} instead.
*/
@Deprecated
public ResourceList getResourcesWithPathIgnoringWhitelist(final String resourcePath) {
return getResourcesWithPathIgnoringAccept(resourcePath);
}
/**
* Get the list of all resources found in accepted packages that have the requested leafname.
*
* @param leafName
* A resource leaf filename.
* @return A list of all resources found in accepted packages that have the requested leafname.
*/
public ResourceList getResourcesWithLeafName(final String leafName) {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
final ResourceList allAcceptedResources = getAllResources();
if (allAcceptedResources.isEmpty()) {
return ResourceList.EMPTY_LIST;
} else {
final ResourceList filteredResources = new ResourceList();
for (final Resource classpathResource : allAcceptedResources) {
final String relativePath = classpathResource.getPath();
final int lastSlashIdx = relativePath.lastIndexOf('/');
if (relativePath.substring(lastSlashIdx + 1).equals(leafName)) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
/**
* Get the list of all resources found in accepted packages that have the requested filename extension.
*
* @param extension
* A filename extension, e.g. "xml" to match all resources ending in ".xml".
* @return A list of all resources found in accepted packages that have the requested filename extension.
*/
public ResourceList getResourcesWithExtension(final String extension) {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
final ResourceList allAcceptedResources = getAllResources();
if (allAcceptedResources.isEmpty()) {
return ResourceList.EMPTY_LIST;
} else {
String bareExtension = extension;
while (bareExtension.startsWith(".")) {
bareExtension = bareExtension.substring(1);
}
final ResourceList filteredResources = new ResourceList();
for (final Resource classpathResource : allAcceptedResources) {
final String relativePath = classpathResource.getPath();
final int lastSlashIdx = relativePath.lastIndexOf('/');
final int lastDotIdx = relativePath.lastIndexOf('.');
if (lastDotIdx > lastSlashIdx
&& relativePath.substring(lastDotIdx + 1).equalsIgnoreCase(bareExtension)) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
/**
* Get the list of all resources found in accepted packages that have a path matching the requested pattern.
*
* @param pattern
* A pattern to match {@link Resource} paths with.
* @return A list of all resources found in accepted packages that have a path matching the requested pattern.
*/
public ResourceList getResourcesMatchingPattern(final Pattern pattern) {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
final ResourceList allAcceptedResources = getAllResources();
if (allAcceptedResources.isEmpty()) {
return ResourceList.EMPTY_LIST;
} else {
final ResourceList filteredResources = new ResourceList();
for (final Resource classpathResource : allAcceptedResources) {
final String relativePath = classpathResource.getPath();
if (pattern.matcher(relativePath).matches()) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
// -------------------------------------------------------------------------------------------------------------
// Modules
/**
* Get the {@link ModuleInfo} object for the named module, or null if no module of the requested name was found
* during the scan.
*
* @param moduleName
* The module name.
* @return The {@link ModuleInfo} object for the named module, or null if the module was not found.
*/
public ModuleInfo getModuleInfo(final String moduleName) {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()");
}
return moduleNameToModuleInfo.get(moduleName);
}
/**
* Get all modules found during the scan.
*
* @return A list of all modules found during the scan, or the empty list if none.
*/
public ModuleInfoList getModuleInfo() {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()");
}
return new ModuleInfoList(moduleNameToModuleInfo.values());
}
// -------------------------------------------------------------------------------------------------------------
// Packages
/**
* Get the {@link PackageInfo} object for the named package, or null if no package of the requested name was
* found during the scan.
*
* @param packageName
* The package name.
* @return The {@link PackageInfo} object for the named package, or null if the package was not found.
*/
public PackageInfo getPackageInfo(final String packageName) {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()");
}
return packageNameToPackageInfo.get(packageName);
}
/**
* Get all packages found during the scan.
*
* @return A list of all packages found during the scan, or the empty list if none.
*/
public PackageInfoList getPackageInfo() {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()");
}
return new PackageInfoList(packageNameToPackageInfo.values());
}
// -------------------------------------------------------------------------------------------------------------
// Class dependencies
/**
* Get a map from the {@link ClassInfo} object for each accepted class to a list of the classes referenced by
* that class (i.e. returns a map from dependents to dependencies). Note that you need to call
* {@link ClassGraph#enableInterClassDependencies()} before {@link ClassGraph#scan()} for this method to work.
* You should also call {@link ClassGraph#enableExternalClasses()} before {@link ClassGraph#scan()} if you want
* non-accepted classes to appear in the result. See also {@link #getReverseClassDependencyMap()}, which inverts
* the map.
*
* @return A map from a {@link ClassInfo} object for each accepted class to a list of the classes referenced by
* that class (i.e. returns a map from dependents to dependencies). Each map value is the result of
* calling {@link ClassInfo#getClassDependencies()} on the corresponding key.
*/
public Map<ClassInfo, ClassInfoList> getClassDependencyMap() {
final Map<ClassInfo, ClassInfoList> map = new HashMap<>();
for (final ClassInfo ci : getAllClasses()) {
map.put(ci, ci.getClassDependencies());
}
return map;
}
/**
* Get the reverse class dependency map, i.e. a map from the {@link ClassInfo} object for each dependency class
* (accepted or not) to a list of the accepted classes that referenced that class as a dependency (i.e. returns
* a map from dependencies to dependents). Note that you need to call
* {@link ClassGraph#enableInterClassDependencies()} before {@link ClassGraph#scan()} for this method to work.
* You should also call {@link ClassGraph#enableExternalClasses()} before {@link ClassGraph#scan()} if you want
* non-accepted classes to appear in the result. See also {@link #getClassDependencyMap}.
*
* @return A map from a {@link ClassInfo} object for each dependency class (accepted or not) to a list of the
* accepted classes that referenced that class as a dependency (i.e. returns a map from dependencies to
* dependents).
*/
public Map<ClassInfo, ClassInfoList> getReverseClassDependencyMap() {
final Map<ClassInfo, Set<ClassInfo>> revMapSet = new HashMap<>();
for (final ClassInfo ci : getAllClasses()) {
for (final ClassInfo dep : ci.getClassDependencies()) {
Set<ClassInfo> set = revMapSet.get(dep);
if (set == null) {
revMapSet.put(dep, set = new HashSet<ClassInfo>());
}
set.add(ci);
}
}
final Map<ClassInfo, ClassInfoList> revMapList = new HashMap<>();
for (final Entry<ClassInfo, Set<ClassInfo>> ent : revMapSet.entrySet()) {
revMapList.put(ent.getKey(), new ClassInfoList(ent.getValue(), /* sortByName = */ true));
}
return revMapList;
}
// -------------------------------------------------------------------------------------------------------------
// Classes
/**
* Get the {@link ClassInfo} object for the named class, or null if no class of the requested name was found in
* an accepted/non-rejected package during the scan.
*
* @param className
* The class name.
* @return The {@link ClassInfo} object for the named class, or null if the class was not found.
*/
public ClassInfo getClassInfo(final String className) {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()");
}
return classNameToClassInfo.get(className);
}
/**
* Get all classes, interfaces and annotations found during the scan.
*
* @return A list of all accepted classes found during the scan, or the empty list if none.
*/
public ClassInfoList getAllClasses() {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()");
}
return ClassInfo.getAllClasses(classNameToClassInfo.values(), scanSpec);
}
/**
* Get all {@link Enum} classes found during the scan.
*
* @return A list of all {@link Enum} classes found during the scan, or the empty list if none.
*/
public ClassInfoList getAllEnums() {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()");
}
return ClassInfo.getAllEnums(classNameToClassInfo.values(), scanSpec);
}
/**
* Get all {@code record} classes found during the scan (JDK 14+).
*
* @return A list of all {@code record} classes found during the scan, or the empty list if none.
*/
public ClassInfoList getAllRecords() {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()");
}
return ClassInfo.getAllRecords(classNameToClassInfo.values(), scanSpec);
}
/**
* Get a map from class name to {@link ClassInfo} object for all classes, interfaces and annotations found
* during the scan.
*
* @return The map from class name to {@link ClassInfo} object for all classes, interfaces and annotations found
* during the scan.
*/
public Map<String, ClassInfo> getAllClassesAsMap() {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()");
}
return classNameToClassInfo;
}
/**
* Get all standard (non-interface/non-annotation) classes found during the scan.
*
* @return A list of all accepted standard classes found during the scan, or the empty list if none.
*/
public ClassInfoList getAllStandardClasses() {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()");
}
return ClassInfo.getAllStandardClasses(classNameToClassInfo.values(), scanSpec);
}
/**
* Get all subclasses of the superclass.
*
* @param superclass
* The superclass.
* @return A list of subclasses of the superclass, or the empty list if none.
*/
public ClassInfoList getSubclasses(final Class<?> superclass) {
return getSubclasses(superclass.getName());
}
/**
* Get all subclasses of the named superclass.
*
* @param superclassName
* The name of the superclass.
* @return A list of subclasses of the named superclass, or the empty list if none.
*/
public ClassInfoList getSubclasses(final String superclassName) {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()");
}
if (superclassName.equals("java.lang.Object")) {
// Return all standard classes (interfaces don't extend Object)
return getAllStandardClasses();
} else {
final ClassInfo superclass = classNameToClassInfo.get(superclassName);
return superclass == null ? ClassInfoList.EMPTY_LIST : superclass.getSubclasses();
}
}
/**
* Get superclasses of the named subclass.
*
* @param subclassName
* The name of the subclass.
* @return A list of superclasses of the named subclass, or the empty list if none.
*/
public ClassInfoList getSuperclasses(final String subclassName) {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo() before #scan()");
}
final ClassInfo subclass = classNameToClassInfo.get(subclassName);
return subclass == null ? ClassInfoList.EMPTY_LIST : subclass.getSuperclasses();
}
/**
* Get superclasses of the subclass.
*
* @param subclass
* The subclass.
* @return A list of superclasses of the named subclass, or the empty list if none.
*/
public ClassInfoList getSuperclasses(final Class<?> subclass) {
return getSuperclasses(subclass.getName());
}
/**
* Get classes that have a method with an annotation of the named type.
*
* @param methodAnnotation
* the method annotation.
* @return A list of classes with a method that has an annotation of the named type, or the empty list if none.
*/
public ClassInfoList getClassesWithMethodAnnotation(final Class<? extends Annotation> methodAnnotation) {
Assert.isAnnotation(methodAnnotation);
return getClassesWithMethodAnnotation(methodAnnotation.getName());
}
/**
* Get classes that have a method with an annotation of the named type.
*
* @param methodAnnotationName
* the name of the method annotation.
* @return A list of classes with a method that has an annotation of the named type, or the empty list if none.
*/
public ClassInfoList getClassesWithMethodAnnotation(final String methodAnnotationName) {
if (closed.get()) {
throw new IllegalArgumentException("Cannot use a ScanResult after it has been closed");
}
if (!scanSpec.enableClassInfo || !scanSpec.enableMethodInfo || !scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException("Please call ClassGraph#enableClassInfo(), #enableMethodInfo(), "
+ "and #enableAnnotationInfo() before #scan()");
}
final ClassInfo classInfo = classNameToClassInfo.get(methodAnnotationName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithMethodAnnotation();
}
/**
* Get classes that have a method with a parameter that is annotated with an annotation of the named type.
*
* @param methodParameterAnnotation
* the method parameter annotation.
* @return A list of classes that have a method with a parameter annotated with the named annotation type, or
* the empty list if none.
*/
public ClassInfoList getClassesWithMethodParameterAnnotation(
final Class<? extends Annotation> methodParameterAnnotation) {
Assert.isAnnotation(methodParameterAnnotation);
return getClassesWithMethodParameterAnnotation(methodParameterAnnotation.getName());
}
/**
* Get classes that have a method with a parameter that is annotated with an annotation of the named type.
*
* @param methodParameterAnnotationName
* the name of the method parameter annotation.
* @return A list of classes that have a method with a parameter annotated with the named annotation type, or