/
WebappClassLoaderBase.java
2576 lines (2181 loc) · 93.8 KB
/
WebappClassLoaderBase.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.loader;
import java.io.File;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.ref.Reference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Policy;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.Manifest;
import org.apache.catalina.Container;
import org.apache.catalina.Globals;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.WebResource;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory;
import org.apache.juli.WebappProperties;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.InstrumentableClassLoader;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.compat.JreCompat;
import org.apache.tomcat.util.res.StringManager;
import org.apache.tomcat.util.security.PermissionCheck;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
/**
* Specialized web application class loader.
* <p>
* This class loader is a full reimplementation of the <code>URLClassLoader</code> from the JDK. It is designed to be
* fully compatible with a normal <code>URLClassLoader</code>, although its internal behavior may be completely
* different.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - By default, this class loader follows the delegation model required by the
* specification. The bootstrap class loader will be queried first, then the local repositories, and only then
* delegation to the parent class loader will occur. This allows the web application to override any shared class except
* the classes from J2SE. Special handling is provided from the JAXP XML parser interfaces, the JNDI interfaces, and the
* classes from the servlet API, which are never loaded from the webapp repositories. The <code>delegate</code> property
* allows an application to modify this behavior to move the parent class loader ahead of the local repositories.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - Due to limitations in Jasper compilation technology, any repository which
* contains classes from the servlet API will be ignored by the class loader.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - The class loader generates source URLs which include the full JAR URL when a
* class is loaded from a JAR file, which allows setting security permission at the class level, even when a class is
* contained inside a JAR.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - Local repositories are searched in the order they are added via the initial
* constructor.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - No check for sealing violations or security is made unless a security manager
* is present.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - As of 8.0, this class loader implements {@link InstrumentableClassLoader},
* permitting web application classes to instrument other classes in the same web application. It does not permit
* instrumentation of system or container classes or classes in other web apps.
*
* @author Remy Maucherat
* @author Craig R. McClanahan
*/
public abstract class WebappClassLoaderBase extends URLClassLoader
implements Lifecycle, InstrumentableClassLoader, WebappProperties, PermissionCheck {
private static final Log log = LogFactory.getLog(WebappClassLoaderBase.class);
/**
* List of ThreadGroup names to ignore when scanning for web application started threads that need to be shut down.
*/
private static final List<String> JVM_THREAD_GROUP_NAMES = new ArrayList<>();
private static final String JVM_THREAD_GROUP_SYSTEM = "system";
private static final String CLASS_FILE_SUFFIX = ".class";
static {
if (!JreCompat.isGraalAvailable()) {
registerAsParallelCapable();
}
JVM_THREAD_GROUP_NAMES.add(JVM_THREAD_GROUP_SYSTEM);
JVM_THREAD_GROUP_NAMES.add("RMI Runtime");
}
protected class PrivilegedFindClassByName implements PrivilegedAction<Class<?>> {
private final String name;
PrivilegedFindClassByName(String name) {
this.name = name;
}
@Override
public Class<?> run() {
return findClassInternal(name);
}
}
protected static final class PrivilegedGetClassLoader implements PrivilegedAction<ClassLoader> {
private final Class<?> clazz;
public PrivilegedGetClassLoader(Class<?> clazz) {
this.clazz = clazz;
}
@Override
public ClassLoader run() {
return clazz.getClassLoader();
}
}
protected final class PrivilegedJavaseGetResource implements PrivilegedAction<URL> {
private final String name;
public PrivilegedJavaseGetResource(String name) {
this.name = name;
}
@Override
public URL run() {
return javaseClassLoader.getResource(name);
}
}
// ------------------------------------------------------- Static Variables
/**
* The string manager for this package.
*/
protected static final StringManager sm = StringManager.getManager(WebappClassLoaderBase.class);
// ----------------------------------------------------------- Constructors
/**
* Construct a new ClassLoader with no defined repositories and no parent ClassLoader.
*/
protected WebappClassLoaderBase() {
super(new URL[0]);
ClassLoader p = getParent();
if (p == null) {
p = getSystemClassLoader();
}
this.parent = p;
ClassLoader j = String.class.getClassLoader();
if (j == null) {
j = getSystemClassLoader();
while (j.getParent() != null) {
j = j.getParent();
}
}
this.javaseClassLoader = j;
securityManager = System.getSecurityManager();
if (securityManager != null) {
refreshPolicy();
}
}
/**
* Construct a new ClassLoader with no defined repositories and the given parent ClassLoader.
* <p>
* Method is used via reflection - see {@link WebappLoader#createClassLoader()}
*
* @param parent Our parent class loader
*/
protected WebappClassLoaderBase(ClassLoader parent) {
super(new URL[0], parent);
ClassLoader p = getParent();
if (p == null) {
p = getSystemClassLoader();
}
this.parent = p;
ClassLoader j = String.class.getClassLoader();
if (j == null) {
j = getSystemClassLoader();
while (j.getParent() != null) {
j = j.getParent();
}
}
this.javaseClassLoader = j;
securityManager = System.getSecurityManager();
if (securityManager != null) {
refreshPolicy();
}
}
// ----------------------------------------------------- Instance Variables
/**
* Associated web resources for this webapp.
*/
protected WebResourceRoot resources = null;
/**
* The cache of ResourceEntry for classes and resources we have loaded, keyed by resource path, not binary name.
* Path is used as the key since resources may be requested by binary name (classes) or path (other resources such
* as property files) and the mapping from binary name to path is unambiguous but the reverse mapping is ambiguous.
*/
protected final Map<String,ResourceEntry> resourceEntries = new ConcurrentHashMap<>();
/**
* Should this class loader delegate to the parent class loader <strong>before</strong> searching its own
* repositories (i.e. the usual Java2 delegation model)? If set to <code>false</code>, this class loader will search
* its own repositories first, and delegate to the parent only if the class or resource is not found locally. Note
* that the default, <code>false</code>, is the behavior called for by the servlet specification.
*/
protected boolean delegate = false;
private final Map<String,Long> jarModificationTimes = new HashMap<>();
/**
* A list of read File Permission's required if this loader is for a web application context.
*/
protected final ArrayList<Permission> permissionList = new ArrayList<>();
/**
* The PermissionCollection for each CodeSource for a web application context.
*/
protected final HashMap<String,PermissionCollection> loaderPC = new HashMap<>();
/**
* Instance of the SecurityManager installed.
*/
protected final SecurityManager securityManager;
/**
* The parent class loader.
*/
protected final ClassLoader parent;
/**
* The bootstrap class loader used to load the JavaSE classes. In some implementations this class loader is always
* <code>null</code> and in those cases {@link ClassLoader#getParent()} will be called recursively on the system
* class loader and the last non-null result used.
*/
private ClassLoader javaseClassLoader;
/**
* Enables the RMI Target memory leak detection to be controlled. This is necessary since the detection can only
* work on Java 9 if some of the modularity checks are disabled.
*/
private boolean clearReferencesRmiTargets = true;
/**
* Should Tomcat attempt to terminate threads that have been started by the web application? Stopping threads is
* performed via the deprecated (for good reason) <code>Thread.stop()</code> method and is likely to result in
* instability. As such, enabling this should be viewed as an option of last resort in a development environment and
* is not recommended in a production environment. If not specified, the default value of <code>false</code> will be
* used.
*/
private boolean clearReferencesStopThreads = false;
/**
* Should Tomcat attempt to terminate any {@link java.util.TimerThread}s that have been started by the web
* application? If not specified, the default value of <code>false</code> will be used.
*/
private boolean clearReferencesStopTimerThreads = false;
/**
* Should Tomcat call {@link org.apache.juli.logging.LogFactory#release(ClassLoader)} when the class loader is
* stopped? If not specified, the default value of <code>true</code> is used. Changing the default setting is likely
* to lead to memory leaks and other issues.
*/
private boolean clearReferencesLogFactoryRelease = true;
/**
* If an HttpClient keep-alive timer thread has been started by this web application and is still running, should
* Tomcat change the context class loader from the current {@link ClassLoader} to {@link ClassLoader#getParent()} to
* prevent a memory leak? Note that the keep-alive timer thread will stop on its own once the keep-alives all expire
* however, on a busy system that might not happen for some time.
*/
private boolean clearReferencesHttpClientKeepAliveThread = true;
/**
* Should Tomcat attempt to clear references to classes loaded by this class loader from the ObjectStreamClass
* caches?
*/
private boolean clearReferencesObjectStreamClassCaches = true;
/**
* Should Tomcat attempt to clear references to classes loaded by this class loader from ThreadLocals?
*/
private boolean clearReferencesThreadLocals = true;
/**
* Should Tomcat skip the memory leak checks when the web application is stopped as part of the process of shutting
* down the JVM?
*/
private boolean skipMemoryLeakChecksOnJvmShutdown = false;
/**
* Holds the class file transformers decorating this class loader. The CopyOnWriteArrayList is thread safe. It is
* expensive on writes, but those should be rare. It is very fast on reads, since synchronization is not actually
* used. Importantly, the ClassLoader will never block iterating over the transformers while loading a class.
*/
private final List<ClassFileTransformer> transformers = new CopyOnWriteArrayList<>();
/**
* Flag that indicates that {@link #addURL(URL)} has been called which creates a requirement to check the super
* class when searching for resources.
*/
private boolean hasExternalRepositories = false;
/**
* Repositories managed by this class rather than the super class.
*/
private List<URL> localRepositories = new ArrayList<>();
private volatile LifecycleState state = LifecycleState.NEW;
// ------------------------------------------------------------- Properties
/**
* Unused. Always returns {@code null}.
*
* @return associated resources.
*
* @deprecated This will be removed in Tomcat 10.1.x onwards
*/
@Deprecated
public WebResourceRoot getResources() {
return null;
}
/**
* Set associated resources.
*
* @param resources the resources from which the classloader will load the classes
*/
public void setResources(WebResourceRoot resources) {
this.resources = resources;
}
/**
* @return the context name for this class loader.
*/
public String getContextName() {
if (resources == null) {
return "Unknown";
} else {
return resources.getContext().getBaseName();
}
}
/**
* Return the "delegate first" flag for this class loader.
*
* @return <code>true</code> if the class lookup will delegate to the parent first. The default in Tomcat is
* <code>false</code>.
*/
public boolean getDelegate() {
return this.delegate;
}
/**
* Set the "delegate first" flag for this class loader. If this flag is true, this class loader delegates to the
* parent class loader <strong>before</strong> searching its own repositories, as in an ordinary (non-servlet) chain
* of Java class loaders. If set to <code>false</code> (the default), this class loader will search its own
* repositories first, and delegate to the parent only if the class or resource is not found locally, as per the
* servlet specification.
*
* @param delegate The new "delegate first" flag
*/
public void setDelegate(boolean delegate) {
this.delegate = delegate;
}
/**
* If there is a Java SecurityManager create a read permission for the target of the given URL as appropriate.
*
* @param url URL for a file or directory on local system
*/
void addPermission(URL url) {
if (url == null) {
return;
}
if (securityManager != null) {
String protocol = url.getProtocol();
if ("file".equalsIgnoreCase(protocol)) {
URI uri;
File f;
String path;
try {
uri = url.toURI();
f = new File(uri);
path = f.getCanonicalPath();
} catch (IOException | URISyntaxException e) {
log.warn(sm.getString("webappClassLoader.addPermissionNoCanonicalFile", url.toExternalForm()));
return;
}
if (f.isFile()) {
// Allow the file to be read
addPermission(new FilePermission(path, "read"));
} else if (f.isDirectory()) {
addPermission(new FilePermission(path, "read"));
addPermission(new FilePermission(path + File.separator + "-", "read"));
} else {
// File does not exist - ignore (shouldn't happen)
}
} else {
// Unsupported URL protocol
log.warn(sm.getString("webappClassLoader.addPermissionNoProtocol", protocol, url.toExternalForm()));
}
}
}
/**
* If there is a Java SecurityManager create a Permission.
*
* @param permission The permission
*/
void addPermission(Permission permission) {
if (securityManager != null && permission != null) {
permissionList.add(permission);
}
}
public boolean getClearReferencesRmiTargets() {
return this.clearReferencesRmiTargets;
}
public void setClearReferencesRmiTargets(boolean clearReferencesRmiTargets) {
this.clearReferencesRmiTargets = clearReferencesRmiTargets;
}
/**
* @return the clearReferencesStopThreads flag for this Context.
*/
public boolean getClearReferencesStopThreads() {
return this.clearReferencesStopThreads;
}
/**
* Set the clearReferencesStopThreads feature for this Context.
*
* @param clearReferencesStopThreads The new flag value
*/
public void setClearReferencesStopThreads(boolean clearReferencesStopThreads) {
this.clearReferencesStopThreads = clearReferencesStopThreads;
}
/**
* @return the clearReferencesStopTimerThreads flag for this Context.
*/
public boolean getClearReferencesStopTimerThreads() {
return this.clearReferencesStopTimerThreads;
}
/**
* Set the clearReferencesStopTimerThreads feature for this Context.
*
* @param clearReferencesStopTimerThreads The new flag value
*/
public void setClearReferencesStopTimerThreads(boolean clearReferencesStopTimerThreads) {
this.clearReferencesStopTimerThreads = clearReferencesStopTimerThreads;
}
/**
* @return the clearReferencesLogFactoryRelease flag for this Context.
*/
public boolean getClearReferencesLogFactoryRelease() {
return this.clearReferencesLogFactoryRelease;
}
/**
* Set the clearReferencesLogFactoryRelease feature for this Context.
*
* @param clearReferencesLogFactoryRelease The new flag value
*/
public void setClearReferencesLogFactoryRelease(boolean clearReferencesLogFactoryRelease) {
this.clearReferencesLogFactoryRelease = clearReferencesLogFactoryRelease;
}
/**
* @return the clearReferencesHttpClientKeepAliveThread flag for this Context.
*/
public boolean getClearReferencesHttpClientKeepAliveThread() {
return this.clearReferencesHttpClientKeepAliveThread;
}
/**
* Set the clearReferencesHttpClientKeepAliveThread feature for this Context.
*
* @param clearReferencesHttpClientKeepAliveThread The new flag value
*/
public void setClearReferencesHttpClientKeepAliveThread(boolean clearReferencesHttpClientKeepAliveThread) {
this.clearReferencesHttpClientKeepAliveThread = clearReferencesHttpClientKeepAliveThread;
}
public boolean getClearReferencesObjectStreamClassCaches() {
return clearReferencesObjectStreamClassCaches;
}
public void setClearReferencesObjectStreamClassCaches(boolean clearReferencesObjectStreamClassCaches) {
this.clearReferencesObjectStreamClassCaches = clearReferencesObjectStreamClassCaches;
}
public boolean getClearReferencesThreadLocals() {
return clearReferencesThreadLocals;
}
public void setClearReferencesThreadLocals(boolean clearReferencesThreadLocals) {
this.clearReferencesThreadLocals = clearReferencesThreadLocals;
}
public boolean getSkipMemoryLeakChecksOnJvmShutdown() {
return skipMemoryLeakChecksOnJvmShutdown;
}
public void setSkipMemoryLeakChecksOnJvmShutdown(boolean skipMemoryLeakChecksOnJvmShutdown) {
this.skipMemoryLeakChecksOnJvmShutdown = skipMemoryLeakChecksOnJvmShutdown;
}
// ------------------------------------------------------- Reloader Methods
@Override
public void addTransformer(ClassFileTransformer transformer) {
if (transformer == null) {
throw new IllegalArgumentException(
sm.getString("webappClassLoader.addTransformer.illegalArgument", getContextName()));
}
if (this.transformers.contains(transformer)) {
// if the same instance of this transformer was already added, bail out
log.warn(sm.getString("webappClassLoader.addTransformer.duplicate", transformer, getContextName()));
return;
}
this.transformers.add(transformer);
log.info(sm.getString("webappClassLoader.addTransformer", transformer, getContextName()));
}
@Override
public void removeTransformer(ClassFileTransformer transformer) {
if (transformer == null) {
return;
}
if (this.transformers.remove(transformer)) {
log.info(sm.getString("webappClassLoader.removeTransformer", transformer, getContextName()));
}
}
protected void copyStateWithoutTransformers(WebappClassLoaderBase base) {
base.resources = this.resources;
base.delegate = this.delegate;
base.state = LifecycleState.NEW;
base.clearReferencesStopThreads = this.clearReferencesStopThreads;
base.clearReferencesStopTimerThreads = this.clearReferencesStopTimerThreads;
base.clearReferencesLogFactoryRelease = this.clearReferencesLogFactoryRelease;
base.clearReferencesHttpClientKeepAliveThread = this.clearReferencesHttpClientKeepAliveThread;
base.jarModificationTimes.putAll(this.jarModificationTimes);
base.permissionList.addAll(this.permissionList);
base.loaderPC.putAll(this.loaderPC);
}
/**
* Have one or more classes or resources been modified so that a reload is appropriate?
*
* @return <code>true</code> if there's been a modification
*/
public boolean modified() {
if (log.isTraceEnabled()) {
log.trace("modified()");
}
for (Entry<String,ResourceEntry> entry : resourceEntries.entrySet()) {
long cachedLastModified = entry.getValue().lastModified;
long lastModified = resources.getClassLoaderResource(entry.getKey()).getLastModified();
if (lastModified != cachedLastModified) {
if (log.isDebugEnabled()) {
log.debug(sm.getString("webappClassLoader.resourceModified", entry.getKey(),
new Date(cachedLastModified), new Date(lastModified)));
}
return true;
}
}
// Check if JARs have been added or removed
WebResource[] jars = resources.listResources("/WEB-INF/lib");
// Filter out non-JAR resources
int jarCount = 0;
for (WebResource jar : jars) {
if (jar.getName().endsWith(".jar") && jar.isFile() && jar.canRead()) {
jarCount++;
Long recordedLastModified = jarModificationTimes.get(jar.getName());
if (recordedLastModified == null) {
// Jar has been added
log.info(sm.getString("webappClassLoader.jarsAdded", resources.getContext().getName()));
return true;
}
if (recordedLastModified.longValue() != jar.getLastModified()) {
// Jar has been changed
log.info(sm.getString("webappClassLoader.jarsModified", resources.getContext().getName()));
return true;
}
}
}
if (jarCount < jarModificationTimes.size()) {
log.info(sm.getString("webappClassLoader.jarsRemoved", resources.getContext().getName()));
return true;
}
// No classes have been modified
return false;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(this.getClass().getSimpleName());
sb.append("\r\n context: ");
sb.append(getContextName());
sb.append("\r\n delegate: ");
sb.append(delegate);
sb.append("\r\n");
if (this.parent != null) {
sb.append("----------> Parent Classloader:\r\n");
sb.append(this.parent.toString());
sb.append("\r\n");
}
if (this.transformers.size() > 0) {
sb.append("----------> Class file transformers:\r\n");
for (ClassFileTransformer transformer : this.transformers) {
sb.append(transformer).append("\r\n");
}
}
return sb.toString();
}
// ---------------------------------------------------- ClassLoader Methods
// Note: exposed for use by tests
protected final Class<?> doDefineClass(String name, byte[] b, int off, int len, ProtectionDomain protectionDomain) {
return super.defineClass(name, b, off, len, protectionDomain);
}
/**
* Find the specified class in our local repositories, if possible. If not found, throw
* <code>ClassNotFoundException</code>.
*
* @param name The binary name of the class to be loaded
*
* @exception ClassNotFoundException if the class was not found
*/
@Override
public Class<?> findClass(String name) throws ClassNotFoundException {
if (log.isTraceEnabled()) {
log.trace(" findClass(" + name + ")");
}
checkStateForClassLoading(name);
// (1) Permission to define this class when using a SecurityManager
if (securityManager != null) {
int i = name.lastIndexOf('.');
if (i >= 0) {
try {
if (log.isTraceEnabled()) {
log.trace(" securityManager.checkPackageDefinition");
}
securityManager.checkPackageDefinition(name.substring(0, i));
} catch (Exception se) {
if (log.isTraceEnabled()) {
log.trace(" -->Exception-->ClassNotFoundException", se);
}
throw new ClassNotFoundException(name, se);
}
}
}
// Ask our superclass to locate this class, if possible
// (throws ClassNotFoundException if it is not found)
Class<?> clazz = null;
try {
if (log.isTraceEnabled()) {
log.trace(" findClassInternal(" + name + ")");
}
try {
if (securityManager != null) {
PrivilegedAction<Class<?>> dp = new PrivilegedFindClassByName(name);
clazz = AccessController.doPrivileged(dp);
} else {
clazz = findClassInternal(name);
}
} catch (AccessControlException ace) {
log.warn(sm.getString("webappClassLoader.securityException", name, ace.getMessage()), ace);
throw new ClassNotFoundException(name, ace);
} catch (RuntimeException e) {
if (log.isTraceEnabled()) {
log.trace(" -->RuntimeException Rethrown", e);
}
throw e;
}
if (clazz == null && hasExternalRepositories) {
try {
clazz = super.findClass(name);
} catch (AccessControlException ace) {
log.warn(sm.getString("webappClassLoader.securityException", name, ace.getMessage()), ace);
throw new ClassNotFoundException(name, ace);
} catch (RuntimeException e) {
if (log.isTraceEnabled()) {
log.trace(" -->RuntimeException Rethrown", e);
}
throw e;
}
}
if (clazz == null) {
if (log.isTraceEnabled()) {
log.trace(" --> Returning ClassNotFoundException");
}
throw new ClassNotFoundException(name);
}
} catch (ClassNotFoundException e) {
if (log.isTraceEnabled()) {
log.trace(" --> Passing on ClassNotFoundException");
}
throw e;
}
// Return the class we have located
if (log.isTraceEnabled()) {
log.trace(" Returning class " + clazz);
}
if (log.isTraceEnabled()) {
ClassLoader cl;
if (Globals.IS_SECURITY_ENABLED) {
cl = AccessController.doPrivileged(new PrivilegedGetClassLoader(clazz));
} else {
cl = clazz.getClassLoader();
}
log.trace(" Loaded by " + cl.toString());
}
return clazz;
}
/**
* Find the specified resource in our local repository, and return a <code>URL</code> referring to it, or
* <code>null</code> if this resource cannot be found.
*
* @param name Name of the resource to be found
*/
@Override
public URL findResource(final String name) {
if (log.isTraceEnabled()) {
log.trace(" findResource(" + name + ")");
}
checkStateForResourceLoading(name);
URL url = null;
String path = nameToPath(name);
WebResource resource = resources.getClassLoaderResource(path);
if (resource.exists()) {
url = resource.getURL();
trackLastModified(path, resource);
}
if (url == null && hasExternalRepositories) {
url = super.findResource(name);
}
if (log.isTraceEnabled()) {
if (url != null) {
log.trace(" --> Returning '" + url.toString() + "'");
} else {
log.trace(" --> Resource not found, returning null");
}
}
return url;
}
private void trackLastModified(String path, WebResource resource) {
if (resourceEntries.containsKey(path)) {
return;
}
ResourceEntry entry = new ResourceEntry();
entry.lastModified = resource.getLastModified();
synchronized (resourceEntries) {
resourceEntries.putIfAbsent(path, entry);
}
}
@Override
public Enumeration<URL> findResources(String name) throws IOException {
if (log.isTraceEnabled()) {
log.trace(" findResources(" + name + ")");
}
checkStateForResourceLoading(name);
LinkedHashSet<URL> result = new LinkedHashSet<>();
String path = nameToPath(name);
WebResource[] webResources = resources.getClassLoaderResources(path);
for (WebResource webResource : webResources) {
if (webResource.exists()) {
result.add(webResource.getURL());
}
}
// Adding the results of a call to the superclass
if (hasExternalRepositories) {
Enumeration<URL> otherResourcePaths = super.findResources(name);
while (otherResourcePaths.hasMoreElements()) {
result.add(otherResourcePaths.nextElement());
}
}
return Collections.enumeration(result);
}
/**
* Find the resource with the given name. A resource is some data (images, audio, text, etc.) that can be accessed
* by class code in a way that is independent of the location of the code. The name of a resource is a "/"-separated
* path name that identifies the resource. If the resource cannot be found, return <code>null</code>.
* <p>
* This method searches according to the following algorithm, returning as soon as it finds the appropriate URL. If
* the resource cannot be found, returns <code>null</code>.
* <ul>
* <li>If the <code>delegate</code> property is set to <code>true</code>, call the <code>getResource()</code> method
* of the parent class loader, if any.</li>
* <li>Call <code>findResource()</code> to find this resource in our locally defined repositories.</li>
* <li>Call the <code>getResource()</code> method of the parent class loader, if any.</li>
* </ul>
*
* @param name Name of the resource to return a URL for
*/
@Override
public URL getResource(String name) {
if (log.isTraceEnabled()) {
log.trace("getResource(" + name + ")");
}
checkStateForResourceLoading(name);
URL url = null;
boolean delegateFirst = delegate || filter(name, false);
// (1) Delegate to parent if requested
if (delegateFirst) {
if (log.isTraceEnabled()) {
log.trace(" Delegating to parent classloader " + parent);
}
url = parent.getResource(name);
if (url != null) {
if (log.isTraceEnabled()) {
log.trace(" --> Returning '" + url.toString() + "'");
}
return url;
}
}
// (2) Search local repositories
url = findResource(name);
if (url != null) {
if (log.isTraceEnabled()) {
log.trace(" --> Returning '" + url.toString() + "'");
}
return url;
}
// (3) Delegate to parent unconditionally if not already attempted
if (!delegateFirst) {
url = parent.getResource(name);
if (url != null) {
if (log.isTraceEnabled()) {
log.trace(" --> Returning '" + url.toString() + "'");
}
return url;
}
}
// (4) Resource was not found