/
WebappClassLoader.java
2053 lines (1802 loc) · 74.2 KB
/
WebappClassLoader.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2022, 2023 Contributors to the Eclipse Foundation
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
* Copyright 2004 The Apache Software Foundation
*
* Licensed 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.glassfish.web.loader;
import com.sun.appserv.BytecodePreprocessor;
import com.sun.enterprise.loader.ResourceLocator;
import com.sun.enterprise.security.integration.DDPermissionsLoader;
import com.sun.enterprise.security.integration.PermsHolder;
import com.sun.enterprise.util.io.FileUtils;
import jakarta.annotation.PreDestroy;
import java.beans.Introspector;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.lang.System.Logger;
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.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.AllPermission;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
import java.security.PrivilegedAction;
import java.sql.Driver;
import java.sql.DriverManager;
import java.text.MessageFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Function;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.stream.Collectors;
import javax.naming.Binding;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import org.apache.naming.JndiPermission;
import org.apache.naming.resources.DirContextURLStreamHandler;
import org.apache.naming.resources.JarFileResourcesProvider;
import org.apache.naming.resources.ProxyDirContext;
import org.apache.naming.resources.Resource;
import org.apache.naming.resources.ResourceAttributes;
import org.apache.naming.resources.WebDirContext;
import org.glassfish.api.deployment.InstrumentableClassLoader;
import org.glassfish.common.util.GlassfishUrlClassLoader;
import org.glassfish.web.loader.RepositoryManager.RepositoryResource;
import org.glassfish.web.util.ExceptionUtils;
import org.glassfish.web.util.IntrospectionUtils;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.ERROR;
import static java.lang.System.Logger.Level.INFO;
import static java.lang.System.Logger.Level.TRACE;
import static java.lang.System.Logger.Level.WARNING;
import static org.glassfish.web.loader.LogFacade.UNSUPPORTED_VERSION;
/**
* Specialized web application class loader.
* <p>
* This class loader is a full reimplementation of the
* <code>URLClassLoader</code> from the JDK. It is desinged to be fully
* compatible with a normal <code>URLClassLoader</code>, although its internal
* behavior may be completely different.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - This class loader faithfully follows
* the delegation model recommended in the specification. The system 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 Java SE.
* 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 repository.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - Due to limitations in WaSP
* 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 and/or any subsequent
* calls to <code>addRepository()</code> or <code>addJar()</code>.
* <p>
* <strong>IMPLEMENTATION NOTE</strong> - No check for sealing violations or
* security is made unless a security manager is present.
*
* @author Remy Maucherat
* @author Craig R. McClanahan
* @since 2007/08/17 15:46:27 $
*/
public final class WebappClassLoader extends GlassfishUrlClassLoader
implements Reloader, InstrumentableClassLoader, DDPermissionsLoader, JarFileResourcesProvider {
static {
registerAsParallelCapable();
}
/** First try parent classloader, then own resources. */
public static final boolean DELEGATE_DEFAULT = true;
private static final Logger LOG = LogFacade.getSysLogger(WebappClassLoader.class);
private static final ResourceBundle rb = LogFacade.getLogger().getResourceBundle();
private static final Function<String, String> PACKAGE_TO_PATH = pkg -> pkg.replace('.', '/');
/** The path which will be monitored for added Jar files. */
private static final String WEB_INF_LIB = "/WEB-INF/lib";
/**
* Set of package names which are not allowed to be loaded from a webapp
* class loader without delegating first.
*/
private static final Set<String> DELEGATED_PACKAGES = Set.of(
"jakarta", // Jakarta EE classes
"javax", // Java extensions
"sun", // Sun classes (JRE internals)
"org.xml.sax", // SAX 1 & 2 (JRE, jrt-fs.jar)
"org.w3c.dom", // DOM 1 & 2 (JRE, jrt-fs.jar)
"org.apache.taglibs.standard", // jakarta.servlet.jsp.jstl.jar
"com.sun.faces" // jakarta.faces.jar
);
private static final Set<String> DELEGATED_RESOURCE_PATHS = DELEGATED_PACKAGES.stream()
.map(PACKAGE_TO_PATH).collect(Collectors.toUnmodifiableSet());
/** All permission. */
private static final Permission ALL_PERMISSION = new AllPermission();
/** Instance of the SecurityManager installed. */
private static final SecurityManager SECURITY_MANAGER = System.getSecurityManager();
/**
* Use this variable to invoke the security manager when a resource is
* loaded by this classloader.
*/
private static final boolean PACKAGE_DEFINITION_ENABLED = SECURITY_MANAGER != null
&& Boolean.getBoolean("package.definition");
/** The cache of ResourceEntry for classes and resources we have loaded, keyed by resource name. */
private final ConcurrentHashMap<String, ResourceEntry> resourceEntryCache = new ConcurrentHashMap<>();
/** The list of not found resources. */
private final Set<String> notFoundResources = ConcurrentHashMap.newKeySet();
/** Associated directory context giving access to the resources in this webapp. */
private DirContext jndiResources;
/**
* 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.
*/
private boolean delegate = DELEGATE_DEFAULT;
/** Use anti JAR locking code, which does URL rerouting when accessing resources. */
private boolean antiJARLocking;
private final RepositoryManager repositoryManager = new RepositoryManager();
/**
* JAR files cache manager. When files are not used, they can be automatically closed.
*/
private final JarFileManager jarFiles = new JarFileManager();
/**
* The list of JARs last modified dates, in the order they should be
* searched for locally loaded classes or resources.
*/
private final ConcurrentLinkedQueue<PathTimestamp> pathTimestamps = new ConcurrentLinkedQueue<>();
/**
* The list of JARs in {@link #WEB_INF_LIB}, in the order they should be searched
* for locally loaded classes or resources. This list serves to check if files changed.
*/
private List<String> jarNames = new ArrayList<>();
/**
* A list of read File and Jndi Permission's required if this loader
* is for a web application context.
*/
private final ConcurrentLinkedQueue<Permission> permissionList = new ConcurrentLinkedQueue<>();
/** holder for declared and ee permissions */
private PermsHolder permissionsHolder;
/** Path where resources loaded from JARs will be extracted. */
private File loaderDir;
private String canonicalLoaderDir;
/** The PermissionCollection for each CodeSource for a web application context. */
private final ConcurrentHashMap<String, PermissionCollection> loaderPC = new ConcurrentHashMap<>();
/** The system class loader. */
private final ClassLoader system;
private LifeCycleStatus status = LifeCycleStatus.NEW;
/** Has external repositories. */
private boolean hasExternalRepositories;
/** List of byte code pre-processors per webapp class loader. */
private List<BytecodePreprocessor> byteCodePreprocessors = new ArrayList<>();
/** myfaces-api uses jakarta.faces packages */
private boolean useMyFaces;
/**
* Set of packages that may always be overridden by the application,
* regardless of whether they belong to a protected namespace
* (i.e., a namespace that may never be overridden by any webapp)
*/
private Set<String> overridablePackages = Set.of();
/**
* Should Tomcat attempt to null out any static or final fields from loaded
* classes when a web application is stopped as a work around for apparent
* garbage collection bugs and application coding errors? There have been
* some issues reported with log4j when this option is true. Applications
* without memory leaks using recent JVMs should operate correctly with this
* option set to <code>false</code>. If not specified, the default value of
* <code>false</code> will be used.
*/
private boolean clearReferencesStatic;
/**
* Name of associated context used with logging and JMX to associate with
* the right web application. Particularly useful for the clear references
* messages. Defaults to unknown but if standard Tomcat components are used
* it will be updated during initialisation from the resources.
*/
private String contextName = "unknown";
/** Repositories URLs, used to cache the result of getURLs. */
private List<URL> repositoryURLs;
/**
* Construct a new ClassLoader with the given parent ClassLoader,
* but no defined repositories.
*/
public WebappClassLoader(ClassLoader parent) {
super(new URL[0], parent);
this.system = WebappClassLoader.class.getClassLoader();
if (SECURITY_MANAGER != null) {
refreshPolicy();
}
this.permissionsHolder = new PermsHolder();
}
/**
* Set the "delegate first" flag for this class loader.
*
* @param delegate The new "delegate first" flag
*/
public void setDelegate(boolean delegate) {
checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING);
LOG.log(DEBUG, "setDelegate(delegate={0})", delegate);
this.delegate = delegate;
}
/**
* Sets the given package names that may always be overriden, regardless of whether they belong
* to a protected namespace
*/
public void setOverridablePackages(Set<String> packageNames) {
checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING);
overridablePackages = packageNames;
}
/**
* Set associated resources.
*/
public void setResources(DirContext resources) {
LOG.log(DEBUG, "setResources(resources={0})", resources);
checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING);
this.jndiResources = resources;
final DirContext dirCtx;
if (resources instanceof ProxyDirContext) {
ProxyDirContext proxyRes = (ProxyDirContext) resources;
contextName = proxyRes.getContextName();
dirCtx = proxyRes.getDirContext();
} else {
dirCtx = resources;
}
if (dirCtx instanceof WebDirContext) {
((WebDirContext) dirCtx).setJarFileResourcesProvider(this);
}
}
/**
* Sets the anti JAR locking flag, which does URL rerouting when accessing resources.
*
* @param enable The new "anti JAR locking" flag
*/
public void setAntiJARLocking(boolean enable) {
checkStatus(LifeCycleStatus.NEW);
this.antiJARLocking = enable;
}
/**
* If there is a Java SecurityManager create a read FilePermission
* or JndiPermission for URL.
*
* @param url URL for a file or directory on local system
*/
public void addPermission(URL url) {
checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING);
if (url != null) {
addPermission(url.toString());
}
}
/**
* If there is a Java SecurityManager create a read FilePermission
* or JndiPermission for the file directory path.
*
* @param path file directory path
*/
public void addPermission(final String path) {
checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING);
if (path == null || SECURITY_MANAGER == null) {
return;
}
SECURITY_MANAGER.checkSecurityAccess(DDPermissionsLoader.SET_EE_POLICY);
if (path.startsWith("jndi:") || path.startsWith("jar:jndi:")) {
final String jndiPath = path.endsWith("/") ? path : path + "/";
permissionList.add(new JndiPermission(jndiPath + "*"));
} else {
final String filePath;
if (path.endsWith(File.separator)) {
filePath = path;
} else {
permissionList.add(new FilePermission(path, "read"));
filePath = path + File.separator;
}
permissionList.add(new FilePermission(filePath + "-", "read"));
}
}
/**
* If there is a Java SecurityManager create a Permission.
*
* @param permission permission to add
*/
public void addPermission(Permission permission) {
checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING);
if (SECURITY_MANAGER != null && permission != null) {
SECURITY_MANAGER.checkSecurityAccess(DDPermissionsLoader.SET_EE_POLICY);
permissionList.add(permission);
}
}
@Override
public void addDeclaredPermissions(PermissionCollection declaredPc) throws SecurityException {
checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING);
if (SECURITY_MANAGER != null) {
SECURITY_MANAGER.checkSecurityAccess(DDPermissionsLoader.SET_EE_POLICY);
permissionsHolder.setDeclaredPermissions(declaredPc);
}
}
@Override
public void addEEPermissions(PermissionCollection eePc) throws SecurityException {
checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING);
if (SECURITY_MANAGER != null) {
SECURITY_MANAGER.checkSecurityAccess(DDPermissionsLoader.SET_EE_POLICY);
permissionsHolder.setEEPermissions(eePc);
}
}
/**
* @return the Jar path.
*/
public String getLibJarPath() {
return WEB_INF_LIB;
}
/**
* Change the work directory.
*/
public void setWorkDir(File workDir) {
checkStatus(LifeCycleStatus.NEW);
this.loaderDir = new File(workDir, "loader_" + this.hashCode());
try {
canonicalLoaderDir = this.loaderDir.getCanonicalPath();
if (!canonicalLoaderDir.endsWith(File.separator)) {
canonicalLoaderDir += File.separator;
}
} catch (IOException ioe) {
canonicalLoaderDir = null;
}
}
public void setUseMyFaces(boolean useMyFaces) {
checkStatus(LifeCycleStatus.NEW);
this.useMyFaces = useMyFaces;
}
/**
* Set the clearReferencesStatic feature for this Context.
*
* @param clearReferencesStatic The new flag value
*/
public void setClearReferencesStatic(boolean clearReferencesStatic) {
checkStatus(LifeCycleStatus.NEW);
this.clearReferencesStatic = clearReferencesStatic;
}
/**
* Add a new repository to the set of places this ClassLoader can look for
* classes to be loaded.
*
* @param repository Name of a source of classes to be loaded, such as a directory pathname,
* a JAR file pathname, or a ZIP file pathname
* @throws IllegalArgumentException if the specified repository is invalid or does not exist
*/
@Override
public void addRepository(String repository) {
LOG.log(DEBUG, "addRepository(repository={0})", repository);
checkStatus(LifeCycleStatus.NEW, LifeCycleStatus.RUNNING);
// Ignore any of the standard repositories, as they are set up using
// either addJar or addRepository
if (repository.startsWith(WEB_INF_LIB) || repository.startsWith("/WEB-INF/classes")) {
return;
}
// Add this repository to our underlying class loader
try {
super.addURL(new URL(repository));
hasExternalRepositories = true;
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Invalid repository: " + repository, e);
}
}
/**
* Add a new repository to the set of places this ClassLoader can look for
* classes to be loaded.
*
* @param repository Name of a source of classes to be loaded, such as a
* directory pathname, a JAR file pathname, or a ZIP file pathname
* @param directory
*/
public void addRepository(String repository, File directory) {
LOG.log(DEBUG, "addRepository(repository={0}, file={1})", repository, directory);
checkStatus(LifeCycleStatus.NEW);
repositoryManager.addRepository(repository, directory);
}
public void addJar(String filePath, File file) {
LOG.log(DEBUG, "addJar(filePath={0}, file={1})", filePath, file);
checkStatus(LifeCycleStatus.NEW);
super.addURL(toURL(file));
if (filePath.startsWith(WEB_INF_LIB)) {
String jarName = filePath.substring(WEB_INF_LIB.length());
while (jarName.charAt(0) == '/') {
jarName = jarName.substring(1);
}
jarNames.add(jarName);
}
try {
final long lastModified = getResourceAttributes(filePath).getLastModified();
pathTimestamps.add(new PathTimestamp(filePath, lastModified));
} catch (NamingException e) {
LOG.log(DEBUG, "Could not get resource attributes from JNDI for " + filePath, e);
}
jarFiles.addJarFile(file);
}
/**
* Add a new ClassFileTransformer to this class loader. This transfomer should be called for
* each class loading event.
*
* @param transformer new class file transformer to do byte code enhancement.
*/
@Override
public void addTransformer(final ClassFileTransformer transformer) {
checkStatus(LifeCycleStatus.NEW);
byteCodePreprocessors.add(new WebappBytecodePreprocessor(transformer, this));
}
/**
* Start the class loader.
*/
public void start() {
LOG.log(DEBUG, "start()");
checkStatus(LifeCycleStatus.NEW);
byteCodePreprocessors = Collections.unmodifiableList(byteCodePreprocessors);
jarNames = Collections.unmodifiableList(jarNames);
status = LifeCycleStatus.RUNNING;
}
/**
* Find the specified class in our local repositories, if possible. If
* not found, throw <code>ClassNotFoundException</code>.
*
* @param name Name of the class to be loaded
*
* @throws ClassNotFoundException if the class was not found
*/
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
LOG.log(DEBUG, "findClass(name={0})", name);
checkStatus(LifeCycleStatus.RUNNING);
// (1) Permission to define this class when using a SecurityManager
if (PACKAGE_DEFINITION_ENABLED) {
int i = name.lastIndexOf('.');
if (i >= 0) {
try {
SECURITY_MANAGER.checkPackageDefinition(name.substring(0, i));
} catch (Exception 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 {
try {
ResourceEntry entry = findClassInternal(name);
// Create the code source object
CodeSource codeSource = new CodeSource(entry.codeBase, entry.certificates);
synchronized (getClassLoadingLock(name)) {
if (entry.loadedClass == null) {
// We use a temporary byte[] so that we don't change
// the content of entry in case bytecode preprocessing takes place.
byte[] binaryContent = entry.binaryContent;
if (!byteCodePreprocessors.isEmpty()) {
String classFilePath = toClassFilePath(name);
for (BytecodePreprocessor preprocessor : byteCodePreprocessors) {
binaryContent = preprocessor.preprocess(classFilePath, binaryContent);
}
}
clazz = defineClass(name, binaryContent, 0, binaryContent.length, codeSource);
entry.loadedClass = clazz;
entry.binaryContent = null;
entry.source = null;
entry.codeBase = null;
entry.manifest = null;
entry.certificates = null;
} else {
clazz = entry.loadedClass;
}
}
} catch (ClassNotFoundException cnfe) {
if (!hasExternalRepositories) {
throw cnfe;
}
} catch (UnsupportedClassVersionError ucve) {
throw new UnsupportedClassVersionError(getString(UNSUPPORTED_VERSION, name, getJavaVersion()));
} catch (AccessControlException ace) {
throw new ClassNotFoundException(name, ace);
} catch (RuntimeException | Error e) {
throw e;
} catch (Throwable t) {
throw new RuntimeException(getString(LogFacade.UNABLE_TO_LOAD_CLASS, name, t.toString()), t);
}
if (clazz == null && hasExternalRepositories) {
try {
clazz = super.findClass(name);
} catch (AccessControlException ace) {
throw new ClassNotFoundException(name, ace);
} catch (RuntimeException e) {
throw e;
}
}
if (clazz == null) {
throw new ClassNotFoundException(name);
}
} catch (ClassNotFoundException e) {
// This is because some callers just swallow the CNFE.
LOG.log(TRACE, "Passing on ClassNotFoundException.", e);
throw e;
}
// Return the class we have located
LOG.log(TRACE, "Returning {0}", clazz);
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(String name) {
LOG.log(DEBUG, "findResource(name={0})", name);
checkStatus(LifeCycleStatus.RUNNING);
if (".".equals(name)) {
name = "";
}
ResourceEntry entry = resourceEntryCache.get(name);
if (entry == null) {
entry = findResourceInternal(name, name);
}
URL url = null;
if (entry != null) {
url = entry.source;
}
if (url == null && hasExternalRepositories) {
url = super.findResource(name);
}
LOG.log(TRACE, "Returning {0}", url);
return url;
}
/**
* Return an enumeration of <code>URLs</code> representing all of the
* resources with the given name. If no resources with this name are
* found, return an empty enumeration.
*
* @param name Name of the resources to be found
*
* @throws IOException if an input/output error occurs
*/
@Override
public Enumeration<URL> findResources(String name) throws IOException {
LOG.log(DEBUG, "findResources(name={0})", name);
checkStatus(LifeCycleStatus.RUNNING);
List<URL> foundResources = new ArrayList<>();
List<RepositoryResource> resources = repositoryManager.getResources(name);
for (RepositoryResource resource : resources) {
try {
jndiResources.lookup(resource.name);
foundResources.add(toURL(resource.file));
} catch (NamingException e) {
// ignore, we continue searching
}
}
Enumeration<URL> otherResourcePaths = super.findResources(name);
while (otherResourcePaths.hasMoreElements()) {
foundResources.add(otherResourcePaths.nextElement());
}
return Collections.enumeration(foundResources);
}
/**
* 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) {
LOG.log(DEBUG, "getResource(name={0})", name);
checkStatus(LifeCycleStatus.RUNNING);
// (1) Delegate to parent if requested, or if the requested resource
// belongs to one of the packages that are part of the Jakarta EE platform
if (isDelegateFirstResource(name)) {
URL url = getDelegateClassLoader().getResource(name);
if (url != null) {
LOG.log(TRACE, "Returning {0}", url);
return url;
}
}
// (2) Search local repositories
URL url = findResource(name);
if (url != null) {
if (antiJARLocking) {
// Locating the repository for special handling in the case of a JAR
ResourceEntry entry = resourceEntryCache.get(name);
try {
String repository = entry.codeBase.toString();
if (repository.endsWith(".jar") && !name.endsWith(".class") && !name.endsWith(".jar")) {
// Copy binary content to the work directory if not present
File resourceFile = new File(loaderDir, name);
url = resourceFile.toURI().toURL();
}
} catch (Exception e) {
// Ignore
}
}
LOG.log(TRACE, "Returning {0}", url);
return url;
}
// (3) Delegate to parent unconditionally if not already attempted
if (!delegate) {
url = getDelegateClassLoader().getResource(name);
if (url != null) {
LOG.log(TRACE, "Returning {0}", url);
return url;
}
}
// (4) Resource was not found
LOG.log(TRACE, "Resource not found, returning null");
return null;
}
/**
* Find the resource with the given name, and return an input stream
* that can be used for reading it. The search order is as described
* for <code>getResource()</code>, after checking to see if the resource
* data has been previously cached. If the resource cannot be found,
* return <code>null</code>.
*
* @param name Name of the resource to return an input stream for
*/
@Override
public InputStream getResourceAsStream(String name) {
LOG.log(DEBUG, "getResourceAsStream(name={0})", name);
checkStatus(LifeCycleStatus.RUNNING);
// (0) Check for a cached copy of this resource
InputStream stream = findLoadedResource(name);
if (stream != null) {
return stream;
}
// (1) Delegate to parent if requested, or if the requested resource
// belongs to one of the packages that are part of the Jakarta EE platform
if (isDelegateFirstResource(name)) {
stream = getDelegateClassLoader().getResourceAsStream(name);
if (stream != null) {
return stream;
}
}
// (2) Search local repositories
URL url = findResource(name);
if (url != null) {
stream = findLoadedResource(name);
try {
if (hasExternalRepositories && stream == null) {
stream = url.openStream();
}
} catch (IOException e) {
// Ignore
}
if (stream != null) {
return stream;
}
}
// (3) Delegate to parent unconditionally
if (!delegate) {
stream = getDelegateClassLoader().getResourceAsStream(name);
if (stream != null) {
return stream;
}
}
// (4) Resource was not found
LOG.log(TRACE, "Resource not found, returning null");
return null;
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
checkStatus(LifeCycleStatus.RUNNING);
final ClassLoader loader = getDelegateClassLoader();
final ResourceLocator locator = new ResourceLocator(this, loader, isDelegateFirstResource(name));
return locator.getResources(name);
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
/**
* Load the class with the specified name, searching using the following
* algorithm until it finds and returns the class. If the class cannot
* be found, returns <code>ClassNotFoundException</code>.
* <ul>
* <li>Call <code>findLoadedClass(String)</code> to check if the
* class has already been loaded. If it has, the same
* <code>Class</code> object is returned.</li>
* <li>If the <code>delegate</code> property is set to <code>true</code>,
* call the <code>loadClass()</code> method of the parent class
* loader, if any.</li>
* <li>Call <code>findClass()</code> to find this class in our locally
* defined repositories.</li>
* <li>Call the <code>loadClass()</code> method of our parent
* class loader, if any.</li>
* </ul>
* If the class was found using the above steps, and the
* <code>resolve</code> flag is <code>true</code>, this method will then
* call <code>resolveClass(Class)</code> on the resulting Class object.
*
* @param name Name of the class to be loaded
* @param resolve If <code>true</code> then resolve the class
*
* @throws ClassNotFoundException if the class was not found
*/
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
if (name == null) {
return null;
}
LOG.log(DEBUG, "loadClass(name={0}, resolve={1})", name, resolve);
checkStatus(LifeCycleStatus.RUNNING);
synchronized (getClassLoadingLock(name)) {
// (0) Check our previously loaded local class cache
Class<?> clazz = findLoadedClass0(name);
if (clazz != null) {
return resolveIfRequired(resolve, clazz);
}
// (0.1) Check our previously loaded class cache
clazz = findLoadedClass(name);
if (clazz != null) {
return resolveIfRequired(resolve, clazz);
}
// (0.5) Permission to access this class when using a SecurityManager
if (PACKAGE_DEFINITION_ENABLED) {
int i = name.lastIndexOf('.');
if (i >= 0) {
try {
SECURITY_MANAGER.checkPackageAccess(name.substring(0, i));
} catch (SecurityException se) {
String error = getString(LogFacade.SECURITY_EXCEPTION, name);
LOG.log(INFO, error, se);
throw new ClassNotFoundException(error, se);
}
}
}
final ClassLoader delegateLoader = getDelegateClassLoader();
boolean delegateLoad = isDelegateFirstClass(name);
// (1) Delegate to our parent if requested
if (delegateLoad) {
// Check delegate first
try {
clazz = delegateLoader.loadClass(name);
if (clazz != null) {
return resolveIfRequired(resolve, clazz);
}
} catch (ClassNotFoundException e) {
// Ignore
}
}
// (2) Search local repositories
try {
clazz = findClass(name);
if (clazz != null) {
return resolveIfRequired(resolve, clazz);
}
} catch (ClassNotFoundException e) {
// Ignore
}
// (3) Delegate if class was not found locally
if (!delegateLoad) {
try {
clazz = delegateLoader.loadClass(name);
if (clazz != null) {
return resolveIfRequired(resolve, clazz);
}
} catch (ClassNotFoundException e) {
// Ignore
}
}
}
throw new ClassNotFoundException(name);
}
/**
* Get the Permissions for a CodeSource. If this instance
* of WebappClassLoader is for a web application context,
* add read FilePermission or JndiPermissions for the base
* directory (if unpacked),
* the context URL, and jar file resources.
*
* @param codeSource where the code was loaded from
* @return PermissionCollection for CodeSource
*/
@Override
protected PermissionCollection getPermissions(CodeSource codeSource) {
LOG.log(TRACE, "getPermissions(codeSource={0})", codeSource);
checkStatus(LifeCycleStatus.RUNNING);
String codeUrl = codeSource.getLocation().toString();
PermissionCollection pc = loaderPC.get(codeUrl);
if (pc != null) {
return pc;
}
pc = new Permissions();
PermissionCollection spc = super.getPermissions(codeSource);
Enumeration<Permission> permsa = spc.elements();
while (permsa.hasMoreElements()) {
Permission p = permsa.nextElement();
pc.add(p);
}
for (Permission p : permissionList) {
pc.add(p);
}
//get the declared and EE perms
PermissionCollection pc1 = permissionsHolder.getPermissions(codeSource, null);