forked from spotbugs/spotbugs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PluginLoader.java
1638 lines (1474 loc) · 66.6 KB
/
PluginLoader.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
/*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2003-2005 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.Attributes;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.WillClose;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.charsets.UTF8;
import edu.umd.cs.findbugs.classfile.IAnalysisEngineRegistrar;
import edu.umd.cs.findbugs.internalAnnotations.DottedClassName;
import edu.umd.cs.findbugs.io.IO;
import edu.umd.cs.findbugs.plan.ByInterfaceDetectorFactorySelector;
import edu.umd.cs.findbugs.plan.DetectorFactorySelector;
import edu.umd.cs.findbugs.plan.DetectorOrderingConstraint;
import edu.umd.cs.findbugs.plan.ReportingDetectorFactorySelector;
import edu.umd.cs.findbugs.plan.SingleDetectorFactorySelector;
import edu.umd.cs.findbugs.plugins.DuplicatePluginIdError;
import edu.umd.cs.findbugs.plugins.DuplicatePluginIdException;
import edu.umd.cs.findbugs.util.ClassName;
import edu.umd.cs.findbugs.util.JavaWebStart;
import edu.umd.cs.findbugs.util.Util;
import edu.umd.cs.findbugs.xml.XMLUtil;
/**
* Loader for a FindBugs plugin. A plugin is a jar file containing two metadata
* files, "findbugs.xml" and "messages.xml". Those files specify
* <ul>
* <li>the bug pattern Detector classes,
* <li>the bug patterns detected (including all text for displaying detected
* instances of those patterns), and
* <li>the "bug codes" which group together related bug instances
* </ul>
*
* <p>
* The PluginLoader creates a Plugin object to store the Detector factories and
* metadata.
* </p>
*
* @author David Hovemeyer
* @see Plugin
* @see PluginException
*/
public class PluginLoader implements AutoCloseable {
private static final String XPATH_PLUGIN_SHORT_DESCRIPTION = "/MessageCollection/Plugin/ShortDescription";
private static final String XPATH_PLUGIN_WEBSITE = "/FindbugsPlugin/@website";
private static final String XPATH_PLUGIN_PROVIDER = "/FindbugsPlugin/@provider";
private static final String XPATH_PLUGIN_PLUGINID = "/FindbugsPlugin/@pluginid";
private static final Logger LOG = LoggerFactory.getLogger(PluginLoader.class);
static boolean lazyInitialization = false;
static LinkedList<PluginLoader> partiallyInitialized = new LinkedList<>();
// Keep a count of how many plugins we've seen without a
// "pluginid" attribute, so we can assign them all unique ids.
private static int nextUnknownId;
// ClassLoader used to load classes and resources
private ClassLoader classLoader;
private final ClassLoader classLoaderForResources;
// The loaded Plugin
private final Plugin plugin;
private final boolean corePlugin;
boolean initialPlugin;
boolean cannotDisable;
private boolean optionalPlugin;
private final URL loadedFrom;
private final String jarName;
private final URI loadedFromUri;
// The classloaders we have created, so we can close then if we want to close the plugin
private List<URLClassLoader> createdClassLoaders = new ArrayList<>();
/** plugin Id for parent plugin */
String parentId;
static HashSet<String> loadedPluginIds = new HashSet<>();
static {
LOG.debug("Debugging plugin loading. SpotBugs version {}", Version.VERSION_STRING);
loadInitialPlugins();
}
/**
* Constructor.
*
* @param url
* the URL of the plugin Jar file
* @throws PluginException
* if the plugin cannot be fully loaded
*/
@Deprecated
public PluginLoader(URL url) throws PluginException {
this(url, toUri(url), null, false, true);
}
/**
* Constructor.
*
* @param url
* the URL of the plugin Jar file
* @param parent
* the parent classloader
* @deprecated Use {@link #PluginLoader(URL,URI,ClassLoader,boolean,boolean)} instead
*/
@Deprecated
public PluginLoader(URL url, ClassLoader parent) throws PluginException {
this(url, toUri(url), parent, false, true);
}
public boolean hasParent() {
return parentId != null && parentId.length() > 0;
}
/**
* Constructor.
*
* @param url
* the URL of the plugin Jar file
* @param uri
* @param parent
* the parent classloader
* @param isInitial
* is this plugin loaded from one of the standard locations for plugins
* @param optional
* is this an optional plugin
*/
private PluginLoader(@Nonnull URL url, URI uri, ClassLoader parent, boolean isInitial, boolean optional) throws PluginException {
URL[] loaderURLs = createClassloaderUrls(url);
classLoaderForResources = buildURLClassLoader(loaderURLs);
loadedFrom = url;
loadedFromUri = uri;
jarName = getJarName(url);
corePlugin = false;
initialPlugin = isInitial;
optionalPlugin = optional;
plugin = init();
if (!hasParent()) {
classLoader = buildURLClassLoader(loaderURLs, parent);
} else {
if (parent != PluginLoader.class.getClassLoader()) {
throw new IllegalArgumentException("Can't specify parentid " + parentId + " and provide a separate class loader");
}
Plugin parentPlugin = Plugin.getByPluginId(parentId);
if (parentPlugin != null) {
parent = parentPlugin.getClassLoader();
classLoader = buildURLClassLoader(loaderURLs, parent);
}
}
if (classLoader == null) {
if (!lazyInitialization) {
throw new IllegalStateException("Can't find parent plugin " + parentId);
}
partiallyInitialized.add(this);
} else {
loadPluginComponents();
Plugin.putPlugin(loadedFromUri, plugin);
}
}
private static void finishLazyInitialization() {
if (!lazyInitialization) {
throw new IllegalStateException("Not in lazy initialization mode");
}
while (!partiallyInitialized.isEmpty()) {
boolean changed = false;
LinkedList<String> unresolved = new LinkedList<>();
Set<String> needed = new TreeSet<>();
for (Iterator<PluginLoader> i = partiallyInitialized.iterator(); i.hasNext();) {
PluginLoader pluginLoader = i.next();
String pluginId = pluginLoader.getPlugin().getPluginId();
assert pluginLoader.hasParent();
String parentid = pluginLoader.parentId;
Plugin parent = Plugin.getByPluginId(parentid);
if (parent != null) {
i.remove();
try {
URL[] loaderURLs = PluginLoader.createClassloaderUrls(pluginLoader.loadedFrom);
pluginLoader.classLoader = pluginLoader.buildURLClassLoader(loaderURLs, parent.getClassLoader());
pluginLoader.loadPluginComponents();
Plugin.putPlugin(pluginLoader.loadedFromUri, pluginLoader.plugin);
} catch (PluginException e) {
throw new RuntimeException("Unable to load plugin " + pluginId, e);
}
changed = true;
} else {
unresolved.add(pluginId);
needed.add(parentid);
}
}
if (!changed) {
String msg = "Unable to load parent plugins " + needed + " in order to load " + unresolved;
System.err.println(msg);
AnalysisContext.logError(msg);
msg = "Available plugins are " + Plugin.getAllPluginIds();
System.err.println(msg);
AnalysisContext.logError(msg);
for (PluginLoader pluginLoader : partiallyInitialized) {
Plugin.removePlugin(pluginLoader.loadedFromUri);
}
partiallyInitialized.clear();
}
}
lazyInitialization = false;
}
/**
* Creates a new {@link URLClassLoader} and adds it to the list of classloaders
* we need to close if we close the corresponding plugin
*
* @param
* urls the URLs from which to load classes and resources
* @return a new {@link URLClassLoader}
*/
private URLClassLoader buildURLClassLoader(URL[] urls) {
URLClassLoader urlClassLoader = new URLClassLoader(urls);
createdClassLoaders.add(urlClassLoader);
return urlClassLoader;
}
/**
* Creates a new {@link URLClassLoader} and adds it to the list of classloaders
* we need to close if we close the corresponding plugin
*
* @param
* urls the URLs from which to load classes and resources
* @param
* parent the parent class loader for delegation
* @return a new {@link URLClassLoader}
*/
private URLClassLoader buildURLClassLoader(URL[] urls, ClassLoader parent) {
URLClassLoader urlClassLoader = new URLClassLoader(urls, parent);
createdClassLoaders.add(urlClassLoader);
return urlClassLoader;
}
/**
* Closes the class loaders created in this {@link PluginLoader}
* @throws IOException if a class loader fails to close, in that case the other classloaders won't be closed
*/
@Override
public void close() throws IOException {
for (URLClassLoader urlClassLoader : createdClassLoaders) {
urlClassLoader.close();
}
}
/**
* Patch for issue 3429143: allow plugins load classes/resources from 3rd
* party jars
*
* @param url
* plugin jar location as url
* @return non empty list with url to be used for loading classes from given
* plugin. If plugin jar contains standard Java manifest file, all
* entries of its "Class-Path" attribute will be translated to the
* jar-relative url's and added to the returned list. If plugin jar
* does not contains a manifest, or manifest does not have
* "Class-Path" attribute, the given argument will be the only entry
* in the array.
* @throws PluginException
*/
private static @Nonnull URL[] createClassloaderUrls(@Nonnull URL url) throws PluginException {
List<URL> urls = new ArrayList<>();
urls.add(url);
Manifest mf = null;
File f = new File(url.getPath());
// default: try with jar/zip/war etc files
if (!f.isDirectory()) {
JarInputStream jis = null;
try {
jis = new JarInputStream(url.openStream());
mf = jis.getManifest();
} catch (IOException ioe) {
throw new PluginException("Failed loading manifest for plugin jar: " + url, ioe);
} finally {
IO.close(jis);
}
} else {
// If this is not a jar/zip/war etc file, can we can load from directory?
// Allow plugins be loaded from "exploded jar" directories (e.g. while debugging
// 3rd party FB plugin projects in Eclipse without packaging them to jars at all)
File manifest = guessManifest(f);
if (manifest != null) {
FileInputStream is = null;
try {
is = new FileInputStream(manifest);
mf = new Manifest(is);
} catch (IOException e) {
throw new PluginException("Failed loading manifest for plugin jar: " + url, e);
} finally {
IO.close(is);
}
}
}
if (mf != null) {
try {
addClassPathFromManifest(url, urls, mf);
} catch (MalformedURLException e) {
throw new PluginException("Failed loading manifest for plugin jar: " + url, e);
}
}
return urls.toArray(new URL[0]);
}
private static void addClassPathFromManifest(@Nonnull URL url, @Nonnull List<URL> urls,
@Nonnull Manifest mf) throws MalformedURLException {
Attributes atts = mf.getMainAttributes();
if (atts == null) {
return;
}
String classPath = atts.getValue(Attributes.Name.CLASS_PATH);
if (classPath != null) {
String jarRoot = url.toString();
jarRoot = jarRoot.substring(0, jarRoot.lastIndexOf('/') + 1);
String[] jars = classPath.split(",");
for (String jar : jars) {
jar = jarRoot + jar.trim();
urls.add(new URL(jar));
}
}
}
/**
* Trying to find the manifest of "exploded plugin" in the current dir, "standard jar" manifest
* location or "standard" Eclipse location (sibling to the current classpath)
*/
@CheckForNull
private static File guessManifest(@Nonnull File parent) {
File file = new File(parent, "MANIFEST.MF");
if (!file.isFile()) {
file = new File(parent, "META-INF/MANIFEST.MF");
}
if (!file.isFile()) {
file = new File(parent, "../META-INF/MANIFEST.MF");
}
if (file.isFile()) {
return file;
}
return null;
}
/**
* Constructor. Loads a plugin using the caller's class loader. This
* constructor should only be used to load the "core" findbugs detectors,
* which are built into findbugs.jar.
* @throws PluginException
*/
@Deprecated
public PluginLoader() throws PluginException {
classLoader = getClass().getClassLoader();
classLoaderForResources = classLoader;
corePlugin = true;
initialPlugin = true;
optionalPlugin = false;
loadedFrom = computeCoreUrl();
try {
loadedFromUri = loadedFrom.toURI();
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Failed to parse uri: " + loadedFrom);
}
jarName = getJarName(loadedFrom);
plugin = init();
loadPluginComponents();
Plugin.putPlugin(null, plugin);
}
/**
* Fake plugin.
*/
@Deprecated
public PluginLoader(boolean fake, URL url) {
classLoader = getClass().getClassLoader();
classLoaderForResources = classLoader;
corePlugin = false;
initialPlugin = true;
optionalPlugin = false;
loadedFrom = url;
try {
loadedFromUri = loadedFrom.toURI();
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Failed to parse uri: " + loadedFrom);
}
jarName = getJarName(loadedFrom);
plugin = null;
}
@Nonnull
private static URL computeCoreUrl() {
URL from;
String findBugsClassFile = ClassName.toSlashedClassName(FindBugs.class) + ".class";
URL me = FindBugs.class.getClassLoader().getResource(findBugsClassFile);
LOG.debug("FindBugs.class loaded from {}", me);
if (me == null) {
throw new IllegalStateException("Failed to load " + findBugsClassFile);
}
try {
String u = me.toString();
if (u.startsWith("jar:") && u.endsWith("!/" + findBugsClassFile)) {
u = u.substring(4, u.indexOf("!/"));
from = new URL(u);
} else if (u.endsWith(findBugsClassFile)) {
u = u.substring(0, u.indexOf(findBugsClassFile));
from = new URL(u);
} else {
throw new IllegalArgumentException("Unknown url shema: " + u);
}
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Failed to parse url: " + me);
}
LOG.debug("Core class files loaded from {}", from);
return from;
}
public URL getURL() {
return loadedFrom;
}
public URI getURI() {
return loadedFromUri;
}
private static URI toUri(URL url) throws PluginException {
try {
return url.toURI();
} catch (URISyntaxException e) {
throw new PluginException("Bad uri: " + url, e);
}
}
private static String getJarName(URL url) {
String location = url.getPath();
int i = location.lastIndexOf('/');
location = location.substring(i + 1);
return location;
}
public ClassLoader getClassLoader() {
if (classLoader == null) {
throw new IllegalStateException("Plugin not completely initialized; classloader not set yet");
}
return classLoader;
}
/**
* Get the Plugin.
*
* @throws PluginException
* if the plugin cannot be fully loaded
*/
public Plugin loadPlugin() throws PluginException {
return getPlugin();
}
public Plugin getPlugin() {
if (plugin == null) {
throw new AssertionError("plugin not already loaded");
}
return plugin;
}
private static URL resourceFromPlugin(URL u, String args) throws MalformedURLException {
String path = u.getPath();
if (path.endsWith(".zip") || path.endsWith(".jar")) {
return new URL("jar:" + u.toString() + "!/" + args);
} else if (path.endsWith("/")) {
return new URL(u.toString() + args);
} else {
return new URL(u.toString() + "/" + args);
}
}
/**
* Get a resource using the URLClassLoader classLoader. We try findResource
* first because (based on experiment) we can trust it to prefer resources
* in the jarfile to resources on the filesystem. Simply calling
* classLoader.getResource() allows the filesystem to override the jarfile,
* which can mess things up if, for example, there is a findbugs.xml or
* messages.xml in the current directory.
*
* @param name
* resource to get
* @return URL for the resource, or null if it could not be found
*/
public URL getResource(String name) {
if (isCorePlugin()) {
URL url = getCoreResource(name);
if (url != null && IO.verifyURL(url)) {
return url;
}
}
if (loadedFrom != null) {
try {
URL url = resourceFromPlugin(loadedFrom, name);
LOG.debug("Trying to load {} from {}", name, url);
if (IO.verifyURL(url)) {
return url;
}
} catch (MalformedURLException e) {
assert true;
}
}
if (classLoaderForResources instanceof URLClassLoader) {
URLClassLoader urlClassLoader = (URLClassLoader) classLoaderForResources;
LOG.debug("Trying to load {} using URLClassLoader.findResource", name);
LOG.debug(" from urls: {}", Arrays.asList(urlClassLoader.getURLs()));
URL url = urlClassLoader.findResource(name);
if (url == null) {
url = urlClassLoader.findResource("/" + name);
}
if (IO.verifyURL(url)) {
return url;
}
}
LOG.debug("Trying to load {} using ClassLoader.getResource", name);
URL url = classLoaderForResources.getResource(name);
if (url == null) {
url = classLoaderForResources.getResource("/" + name);
}
if (IO.verifyURL(url)) {
return url;
}
return null;
}
static @CheckForNull URL getCoreResource(String name) {
URL u = loadFromFindBugsPluginDir(name);
if (u != null) {
return u;
}
u = loadFromFindBugsEtcDir(name);
if (u != null) {
return u;
}
u = resourceFromFindbugsJar(name);
if (u != null) {
return u;
}
u = PluginLoader.class.getResource(name);
if (u != null) {
return u;
}
u = PluginLoader.class.getResource("/" + name);
return u;
}
/**
* Try to load resource from JAR file of Findbugs core plugin.
* @param slashedResourceName Name of resource to load
* @return URL which points resource in jar file, or null if JAR file not found
*/
@CheckForNull
private static URL resourceFromFindbugsJar(String slashedResourceName) {
try {
@Nullable
URL findbugsJar = getFindbugsJar();
if (findbugsJar == null) {
return null;
}
assert findbugsJar.getProtocol().equals("file");
try (ZipFile jarFile = new ZipFile(new File(findbugsJar.toURI()))) {
ZipEntry entry = jarFile.getEntry(slashedResourceName);
if (entry != null) {
return resourceFromPlugin(findbugsJar, slashedResourceName);
}
} catch (ZipException e) {
LOG.warn("Failed to load resourceFromFindbugsJar: {} is not valid zip file.", findbugsJar, e);
} catch (IOException e) {
LOG.warn("Failed to load resourceFromFindbugsJar: IOException was thrown at zip file {} loading.",
findbugsJar, e);
}
} catch (MalformedURLException | URISyntaxException e) {
LOG.warn("Failed to load resourceFromFindbugsJar: Resource name is {}", slashedResourceName, e);
}
return null;
}
/**
* @return URL of findbugs.jar,
* or null if found no jar file which contains FindBugs.class
* @throws MalformedURLException
*/
@CheckForNull
private static URL getFindbugsJar() throws MalformedURLException {
String findBugsClassFile = ClassName.toSlashedClassName(FindBugs.class) + ".class";
URL me = FindBugs.class.getClassLoader().getResource(findBugsClassFile);
if (me == null) {
return null;
}
if (!"jar".equals(me.getProtocol())) {
return null;
}
String u = me.toString();
String jarPath = u.substring(4, u.indexOf("!/"));
return new URL(jarPath);
}
public static @CheckForNull URL loadFromFindBugsEtcDir(String name) {
String findBugsHome = DetectorFactoryCollection.getFindBugsHome();
if (findBugsHome != null) {
File f = new File(new File(new File(findBugsHome), "etc"), name);
if (f.canRead()) {
try {
return f.toURL();
} catch (MalformedURLException e) {
// ignore it
assert true;
}
}
}
return null;
}
public static @CheckForNull URL loadFromFindBugsPluginDir(String name) {
String findBugsHome = DetectorFactoryCollection.getFindBugsHome();
if (findBugsHome != null) {
File f = new File(new File(new File(findBugsHome), "plugin"), name);
if (f.canRead()) {
try {
return f.toURI().toURL();
} catch (MalformedURLException e) {
// ignore it
assert true;
}
}
}
return null;
}
private static <T> Class<? extends T> getClass(ClassLoader loader, @DottedClassName String className, Class<T> type) throws PluginException {
try {
return loader.loadClass(className).asSubclass(type);
} catch (ClassNotFoundException e) {
throw new PluginException("Unable to load " + className, e);
} catch (ClassCastException e) {
throw new PluginException("Cannot cast " + className + " to " + type.getName(), e);
}
}
private Plugin init() throws PluginException {
LOG.debug("Loading plugin from {}", loadedFrom);
// Plugin descriptor (a.k.a, "findbugs.xml"). Defines
// the bug detectors and bug patterns that the plugin provides.
Document pluginDescriptor = getPluginDescriptor();
List<Document> messageCollectionList = getMessageDocuments();
Plugin constructedPlugin = constructMinimalPlugin(pluginDescriptor, messageCollectionList);
// Success!
LOG.debug("Loaded {} from {}", constructedPlugin.getPluginId(), loadedFrom);
return constructedPlugin;
}
private void loadPluginComponents()
throws PluginException {
Document pluginDescriptor = getPluginDescriptor();
List<Document> messageCollectionList = getMessageDocuments();
// Create PluginComponents
try {
List<Node> componentNodeList = XMLUtil.selectNodes(pluginDescriptor, "/FindbugsPlugin/PluginComponent");
for (Node componentNode : componentNodeList) {
@DottedClassName
String componentKindname = componentNode.valueOf("@componentKind");
if (componentKindname == null) {
throw new PluginException("Missing @componentKind for " + plugin.getPluginId()
+ " loaded from " + loadedFrom);
}
@DottedClassName
String componentClassname = componentNode.valueOf("@componentClass");
if (componentClassname == null) {
throw new PluginException("Missing @componentClassname for " + plugin.getPluginId()
+ " loaded from " + loadedFrom);
}
String componentId = componentNode.valueOf("@id");
if (componentId == null) {
throw new PluginException("Missing @id for " + plugin.getPluginId()
+ " loaded from " + loadedFrom);
}
try {
String propertiesLocation = componentNode.valueOf("@properties");
boolean disabled = Boolean.valueOf(componentNode.valueOf("@disabled"));
Node filterMessageNode = findMessageNode(messageCollectionList,
"/MessageCollection/PluginComponent[@id='" + componentId + "']",
"Missing Cloud description for PluginComponent " + componentId);
String description = getChildText(filterMessageNode, "Description").trim();
String details = getChildText(filterMessageNode, "Details").trim();
PropertyBundle properties = new PropertyBundle();
if (propertiesLocation != null && propertiesLocation.length() > 0) {
URL properiesURL = classLoaderForResources.getResource(propertiesLocation);
if (properiesURL == null) {
AnalysisContext.logError("Could not load properties for " + plugin.getPluginId() + " component " + componentId
+ " from " + propertiesLocation);
continue;
}
properties.loadPropertiesFromURL(properiesURL);
}
List<Node> propertyNodes = XMLUtil.selectNodes(componentNode, "Property");
for (Node node : propertyNodes) {
String key = node.valueOf("@key");
String value = node.getText();
properties.setProperty(key, value);
}
Class<?> componentKind = classLoader.loadClass(componentKindname);
loadComponentPlugin(plugin, componentKind, componentClassname, componentId, disabled, description, details,
properties);
} catch (RuntimeException e) {
AnalysisContext.logError("Unable to load ComponentPlugin " + componentId +
" : " + componentClassname + " implementing " + componentKindname, e);
}
}
// Create FindBugsMains
if (!FindBugs.isNoMains()) {
List<Node> findBugsMainList = XMLUtil.selectNodes(pluginDescriptor, "/FindbugsPlugin/FindBugsMain");
for (Node main : findBugsMainList) {
String className = main.valueOf("@class");
if (className == null) {
throw new PluginException("Missing @class for FindBugsMain in plugin" + plugin.getPluginId()
+ " loaded from " + loadedFrom);
}
String cmd = main.valueOf("@cmd");
if (cmd == null) {
throw new PluginException("Missing @cmd for for FindBugsMain in plugin " + plugin.getPluginId()
+ " loaded from " + loadedFrom);
}
String kind = main.valueOf("@kind");
boolean analysis = Boolean.valueOf(main.valueOf("@analysis"));
Element mainMessageNode = (Element) findMessageNode(messageCollectionList,
"/MessageCollection/FindBugsMain[@cmd='" + cmd
// + " and @class='" + className
+ "']/Description",
"Missing FindBugsMain description for cmd " + cmd);
String description = mainMessageNode.getTextTrim();
try {
Class<?> mainClass = classLoader.loadClass(className);
plugin.addFindBugsMain(mainClass, cmd, description, kind, analysis);
} catch (Exception e) {
String msg = "Unable to load FindBugsMain " + cmd +
" : " + className + " in plugin " + plugin.getPluginId()
+ " loaded from " + loadedFrom;
PluginException e2 = new PluginException(msg, e);
AnalysisContext.logError(msg, e2);
}
}
}
List<Node> detectorNodeList = XMLUtil.selectNodes(pluginDescriptor, "/FindbugsPlugin/Detector");
int detectorCount = 0;
for (Node detectorNode : detectorNodeList) {
String className = detectorNode.valueOf("@class");
String speed = detectorNode.valueOf("@speed");
String disabled = detectorNode.valueOf("@disabled");
String reports = detectorNode.valueOf("@reports");
String requireJRE = detectorNode.valueOf("@requirejre");
String hidden = detectorNode.valueOf("@hidden");
if (speed == null || speed.length() == 0) {
speed = "fast";
}
// System.out.println("Found detector: class="+className+", disabled="+disabled);
// Create DetectorFactory for the detector
Class<?> detectorClass = null;
if (!FindBugs.isNoAnalysis()) {
detectorClass = classLoader.loadClass(className);
if (!Detector.class.isAssignableFrom(detectorClass) && !Detector2.class.isAssignableFrom(detectorClass)) {
throw new PluginException("Class " + className + " does not implement Detector or Detector2");
}
}
DetectorFactory factory = new DetectorFactory(plugin, className, detectorClass, !"true".equals(disabled), speed,
reports, requireJRE);
if (Boolean.valueOf(hidden).booleanValue()) {
factory.setHidden(true);
}
factory.setPositionSpecifiedInPluginDescriptor(detectorCount++);
plugin.addDetectorFactory(factory);
// Find Detector node in one of the messages files,
// to get the detail HTML.
Node node = findMessageNode(messageCollectionList, "/MessageCollection/Detector[@class='" + className
+ "']/Details", "Missing Detector description for detector " + className);
Element details = (Element) node;
String detailHTML = details.getText();
StringBuilder buf = new StringBuilder();
buf.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n");
buf.append("<HTML><HEAD><TITLE>Detector Description</TITLE></HEAD><BODY>\n");
buf.append(detailHTML);
buf.append("</BODY></HTML>\n");
factory.setDetailHTML(buf.toString());
}
} catch (ClassNotFoundException e) {
throw new PluginException("Could not instantiate detector class: " + e, e);
}
// Create ordering constraints
Node orderingConstraintsNode = pluginDescriptor.selectSingleNode("/FindbugsPlugin/OrderingConstraints");
if (orderingConstraintsNode != null) {
// Get inter-pass and intra-pass constraints
List<Element> elements = XMLUtil.selectNodes(orderingConstraintsNode, "./SplitPass|./WithinPass");
for (Element constraintElement : elements) {
// Create the selectors which determine which detectors are
// involved in the constraint
DetectorFactorySelector earlierSelector = getConstraintSelector(constraintElement, plugin, "Earlier");
DetectorFactorySelector laterSelector = getConstraintSelector(constraintElement, plugin, "Later");
// Create the constraint
DetectorOrderingConstraint constraint = new DetectorOrderingConstraint(earlierSelector, laterSelector);
// Keep track of which constraints are single-source
constraint.setSingleSource(earlierSelector instanceof SingleDetectorFactorySelector);
// Add the constraint to the plugin
if ("SplitPass".equals(constraintElement.getName())) {
plugin.addInterPassOrderingConstraint(constraint);
} else {
plugin.addIntraPassOrderingConstraint(constraint);
}
}
}
// register global Category descriptions
List<Node> categoryNodeListGlobal = XMLUtil.selectNodes(pluginDescriptor, "/FindbugsPlugin/BugCategory");
for (Node categoryNode : categoryNodeListGlobal) {
String key = categoryNode.valueOf("@category");
if ("".equals(key)) {
throw new PluginException("BugCategory element with missing category attribute");
}
BugCategory bc = plugin.addOrCreateBugCategory(key);
boolean hidden = Boolean.valueOf(categoryNode.valueOf("@hidden"));
if (hidden) {
bc.setHidden(hidden);
}
}
for (Document messageCollection : messageCollectionList) {
List<Node> categoryNodeList = XMLUtil.selectNodes(messageCollection, "/MessageCollection/BugCategory");
LOG.debug("found {} categories in {}", categoryNodeList.size(), plugin.getPluginId());
for (Node categoryNode : categoryNodeList) {
String key = categoryNode.valueOf("@category");
if ("".equals(key)) {
throw new PluginException("BugCategory element with missing category attribute");
}
BugCategory bc = plugin.addOrCreateBugCategory(key);
String shortDesc = getChildText(categoryNode, "Description");
bc.setShortDescription(shortDesc);
try {
String abbrev = getChildText(categoryNode, "Abbreviation");
if (bc.getAbbrev() == null) {
bc.setAbbrev(abbrev);
LOG.debug("category {} abbrev -> {}", key, abbrev);
} else {
LOG.debug("rejected abbrev '{}' for category {}: {}", abbrev, key, bc.getAbbrev());
}
} catch (PluginException pe) {
System.out.println("missing Abbreviation for category " + key + "/" + shortDesc);
// do nothing else -- Abbreviation is required, but handle
// its omission gracefully
}
try {
String details = getChildText(categoryNode, "Details");
if (bc.getDetailText() == null) {
bc.setDetailText(details);
LOG.debug("category {} details -> {}", key, details);
} else {
LOG.debug("rejected details [{}] for category {}: [{}]", details, key, bc.getDetailText());
}
} catch (PluginException pe) {
// do nothing -- LongDescription is optional
}
}
}
// Create BugPatterns
List<Node> bugPatternNodeList = XMLUtil.selectNodes(pluginDescriptor, "/FindbugsPlugin/BugPattern");
for (Node bugPatternNode : bugPatternNodeList) {
String type = bugPatternNode.valueOf("@type");
String abbrev = bugPatternNode.valueOf("@abbrev");
String category = bugPatternNode.valueOf("@category");
boolean experimental = Boolean.parseBoolean(bugPatternNode.valueOf("@experimental"));
// Find the matching element in messages.xml (or translations)
String query = "/MessageCollection/BugPattern[@type='" + type + "']";
Node messageNode = findMessageNode(messageCollectionList, query, "messages.xml missing BugPattern element for type "
+ type);
Node bugsUrlNode = messageNode.getDocument().selectSingleNode("/MessageCollection/Plugin/" + (experimental ? "AllBugsUrl" : "BugsUrl"));
String bugsUrl = bugsUrlNode == null ? null : bugsUrlNode.getText();
String shortDesc = getChildText(messageNode, "ShortDescription");
String longDesc = getChildText(messageNode, "LongDescription");
String detailText = getChildText(messageNode, "Details");
int cweid = 0;
try {
String cweString = bugPatternNode.valueOf("@cweid");
if (cweString.length() > 0) {
cweid = Integer.parseInt(cweString);
}
} catch (RuntimeException e) {