/
MetaInfConfiguration.java
898 lines (820 loc) · 32 KB
/
MetaInfConfiguration.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
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.webapp;
import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
import org.eclipse.jetty.util.PatternMatcher;
import org.eclipse.jetty.util.resource.EmptyResource;
import org.eclipse.jetty.util.resource.Resource;
import org.eclipse.jetty.util.resource.ResourceCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* MetaInfConfiguration
* <p>
*
* Scan META-INF of jars to find:
* <ul>
* <li>tlds</li>
* <li>web-fragment.xml</li>
* <li>resources</li>
* </ul>
*
* The jars which are scanned are:
* <ol>
* <li>those from the container classpath whose pattern matched the WebInfConfiguration.CONTAINER_JAR_PATTERN</li>
* <li>those from WEB-INF/lib</li>
* </ol>
*/
public class MetaInfConfiguration extends AbstractConfiguration
{
private static final Logger LOG = LoggerFactory.getLogger(MetaInfConfiguration.class);
public static final String USE_CONTAINER_METAINF_CACHE = "org.eclipse.jetty.metainf.useCache";
public static final boolean DEFAULT_USE_CONTAINER_METAINF_CACHE = true;
public static final String CACHED_CONTAINER_TLDS = "org.eclipse.jetty.tlds.cache";
public static final String CACHED_CONTAINER_FRAGMENTS = FragmentConfiguration.FRAGMENT_RESOURCES + ".cache";
public static final String CACHED_CONTAINER_RESOURCES = "org.eclipse.jetty.resources.cache";
public static final String METAINF_TLDS = "org.eclipse.jetty.tlds";
public static final String METAINF_FRAGMENTS = FragmentConfiguration.FRAGMENT_RESOURCES;
public static final String METAINF_RESOURCES = "org.eclipse.jetty.resources";
public static final String CONTAINER_JAR_PATTERN = "org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern";
public static final String WEBINF_JAR_PATTERN = "org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern";
public static final List<String> __allScanTypes = (List<String>)Arrays.asList(METAINF_TLDS, METAINF_RESOURCES, METAINF_FRAGMENTS);
/**
* ContainerPathNameMatcher
*
* Matches names of jars on the container classpath
* against a pattern. If no pattern is specified, no
* jars match.
*/
public class ContainerPathNameMatcher extends PatternMatcher
{
protected final WebAppContext _context;
protected final String _pattern;
public ContainerPathNameMatcher(WebAppContext context, String pattern)
{
if (context == null)
throw new IllegalArgumentException("Context null");
_context = context;
_pattern = pattern;
}
public void match(List<URI> uris) throws Exception
{
if (uris == null)
return;
match(_pattern, uris.toArray(new URI[uris.size()]), false);
}
@Override
public void matched(URI uri) throws Exception
{
_context.getMetaData().addContainerResource(Resource.newResource(uri));
}
}
/**
* WebAppPathNameMatcher
*
* Matches names of jars or dirs on the webapp classpath
* against a pattern. If there is no pattern, all jars or dirs
* will match.
*/
public class WebAppPathNameMatcher extends PatternMatcher
{
protected final WebAppContext _context;
protected final String _pattern;
public WebAppPathNameMatcher(WebAppContext context, String pattern)
{
if (context == null)
throw new IllegalArgumentException("Context null");
_context = context;
_pattern = pattern;
}
public void match(List<URI> uris)
throws Exception
{
match(_pattern, uris.toArray(new URI[uris.size()]), true);
}
@Override
public void matched(URI uri) throws Exception
{
_context.getMetaData().addWebInfResource(Resource.newResource(uri));
}
}
/**
* If set, to a list of URLs, these resources are added to the context
* resource base as a resource collection.
*/
public static final String RESOURCE_DIRS = "org.eclipse.jetty.resources";
public MetaInfConfiguration()
{
addDependencies(WebXmlConfiguration.class);
}
@Override
public void preConfigure(final WebAppContext context) throws Exception
{
//find container jars/modules and select which ones to scan
findAndFilterContainerPaths(context);
//find web-app jars and select which ones to scan
findAndFilterWebAppPaths(context);
//No pattern to appy to classes, just add to metadata
context.getMetaData().setWebInfClassesResources(findClassDirs(context));
scanJars(context);
}
/**
* Find jars and directories that are on the container's classpath
* and apply an optional filter. The filter is a pattern applied to the
* full jar or directory names. If there is no pattern, then no jar
* or dir is considered to match.
*
* Those jars that do match will be later examined for META-INF
* information and annotations.
*
* To find them, examine the classloaders in the hierarchy above the
* webapp classloader that are URLClassLoaders. For jdk-9 we also
* look at the java.class.path, and the jdk.module.path.
*
* @param context the WebAppContext being deployed
*/
public void findAndFilterContainerPaths(final WebAppContext context) throws Exception
{
// Apply an initial name filter to the jars to select which will be eventually
// scanned for META-INF info and annotations. The filter is based on inclusion patterns.
ContainerPathNameMatcher containerPathNameMatcher = new ContainerPathNameMatcher(context, (String)context.getAttribute(CONTAINER_JAR_PATTERN));
List<URI> containerUris = getAllContainerJars(context);
if (LOG.isDebugEnabled())
LOG.debug("Matching container urls {}", containerUris);
containerPathNameMatcher.match(containerUris);
// When running on jvm 9 or above, we we won't be able to look at the application
// classloader to extract urls, so we need to examine the classpath instead.
String classPath = System.getProperty("java.class.path");
if (classPath != null)
{
List<URI> cpUris = new ArrayList<>();
String[] entries = classPath.split(File.pathSeparator);
for (String entry : entries)
{
File f = new File(entry);
cpUris.add(f.toURI());
}
if (LOG.isDebugEnabled())
LOG.debug("Matching java.class.path {}", cpUris);
containerPathNameMatcher.match(cpUris);
}
// We also need to examine the module path.
// TODO need to consider the jdk.module.upgrade.path - how to resolve
// which modules will be actually used. If its possible, it can
// only be attempted in jetty-10 with jdk-9 specific apis.
String modulePath = System.getProperty("jdk.module.path");
if (modulePath != null)
{
List<URI> moduleUris = new ArrayList<>();
String[] entries = modulePath.split(File.pathSeparator);
for (String entry : entries)
{
File file = new File(entry);
if (file.isDirectory())
{
File[] files = file.listFiles();
if (files != null)
{
for (File f : files)
{
moduleUris.add(f.toURI());
}
}
}
else
{
moduleUris.add(file.toURI());
}
}
if (LOG.isDebugEnabled())
LOG.debug("Matching jdk.module.path {}", moduleUris);
containerPathNameMatcher.match(moduleUris);
}
if (LOG.isDebugEnabled())
LOG.debug("Container paths selected:{}", context.getMetaData().getContainerResources());
}
/**
* Finds the jars that are either physically or virtually in
* WEB-INF/lib, and applies an optional filter to their full
* pathnames.
*
* The filter selects which jars will later be examined for META-INF
* information and annotations. If there is no pattern, then
* all jars are considered selected.
*
* @param context the WebAppContext being deployed
*/
public void findAndFilterWebAppPaths(WebAppContext context)
throws Exception
{
//Apply filter to WEB-INF/lib jars
WebAppPathNameMatcher matcher = new WebAppPathNameMatcher(context, (String)context.getAttribute(WEBINF_JAR_PATTERN));
List<Resource> jars = findJars(context);
//Convert to uris for matching
if (jars != null)
{
List<URI> uris = new ArrayList<>();
int i = 0;
for (Resource r : jars)
{
uris.add(r.getURI());
}
matcher.match(uris);
}
}
protected List<URI> getAllContainerJars(final WebAppContext context) throws URISyntaxException
{
List<URI> uris = new ArrayList<>();
if (context.getClassLoader() != null)
{
ClassLoader loader = context.getClassLoader().getParent();
while (loader != null)
{
if (loader instanceof URLClassLoader)
{
URL[] urls = ((URLClassLoader)loader).getURLs();
if (urls != null)
for (URL url : urls)
{
uris.add(new URI(url.toString().replaceAll(" ", "%20")));
}
}
loader = loader.getParent();
}
}
return uris;
}
@Override
public void configure(WebAppContext context) throws Exception
{
// Look for extra resource
@SuppressWarnings("unchecked")
Set<Resource> resources = (Set<Resource>)context.getAttribute(RESOURCE_DIRS);
if (resources != null && !resources.isEmpty())
{
Resource[] collection = new Resource[resources.size() + 1];
int i = 0;
collection[i++] = context.getBaseResource();
for (Resource resource : resources)
{
collection[i++] = resource;
}
context.setBaseResource(new ResourceCollection(collection));
}
}
protected void scanJars(WebAppContext context) throws Exception
{
boolean useContainerCache = DEFAULT_USE_CONTAINER_METAINF_CACHE;
if (context.getServer() != null)
{
Boolean attr = (Boolean)context.getServer().getAttribute(USE_CONTAINER_METAINF_CACHE);
if (attr != null)
useContainerCache = attr.booleanValue();
}
if (LOG.isDebugEnabled())
LOG.debug("{} = {}", USE_CONTAINER_METAINF_CACHE, useContainerCache);
//pre-emptively create empty lists for tlds, fragments and resources as context attributes
//this signals that this class has been called. This differentiates the case where this class
//has been called but finds no META-INF data from the case where this class was never called
if (context.getAttribute(METAINF_TLDS) == null)
context.setAttribute(METAINF_TLDS, new HashSet<URL>());
if (context.getAttribute(METAINF_RESOURCES) == null)
context.setAttribute(METAINF_RESOURCES, new HashSet<Resource>());
if (context.getAttribute(METAINF_FRAGMENTS) == null)
context.setAttribute(METAINF_FRAGMENTS, new HashMap<Resource, Resource>());
//always scan everything from the container's classpath
scanJars(context, context.getMetaData().getContainerResources(), useContainerCache, __allScanTypes);
//only look for fragments if web.xml is not metadata complete, or it version 3.0 or greater
List<String> scanTypes = new ArrayList<>(__allScanTypes);
if (context.getMetaData().isMetaDataComplete() || (context.getServletContext().getEffectiveMajorVersion() < 3) && !context.isConfigurationDiscovered())
scanTypes.remove(METAINF_FRAGMENTS);
scanJars(context, context.getMetaData().getWebInfResources(false), false, scanTypes);
}
/**
* For backwards compatibility. This method will always scan for all types of data.
*
* @param context the context for the scan
* @param jars the jars to scan
* @param useCaches if true, the scanned info is cached
* @throws Exception if unable to scan the jars
*/
public void scanJars(final WebAppContext context, Collection<Resource> jars, boolean useCaches)
throws Exception
{
scanJars(context, jars, useCaches, __allScanTypes);
}
/**
* Look into the jars to discover info in META-INF. If useCaches == true, then we will
* cache the info discovered indexed by the jar in which it was discovered: this speeds
* up subsequent context deployments.
*
* @param context the context for the scan
* @param jars the jars resources to scan
* @param useCaches if true, cache the info discovered
* @param scanTypes the type of things to look for in the jars
* @throws Exception if unable to scan the jars
*/
public void scanJars(final WebAppContext context, Collection<Resource> jars, boolean useCaches, List<String> scanTypes)
throws Exception
{
ConcurrentHashMap<Resource, Resource> metaInfResourceCache = null;
ConcurrentHashMap<Resource, Resource> metaInfFragmentCache = null;
ConcurrentHashMap<Resource, Collection<URL>> metaInfTldCache = null;
if (useCaches)
{
metaInfResourceCache = (ConcurrentHashMap<Resource, Resource>)context.getServer().getAttribute(CACHED_CONTAINER_RESOURCES);
if (metaInfResourceCache == null)
{
metaInfResourceCache = new ConcurrentHashMap<Resource, Resource>();
context.getServer().setAttribute(CACHED_CONTAINER_RESOURCES, metaInfResourceCache);
}
metaInfFragmentCache = (ConcurrentHashMap<Resource, Resource>)context.getServer().getAttribute(CACHED_CONTAINER_FRAGMENTS);
if (metaInfFragmentCache == null)
{
metaInfFragmentCache = new ConcurrentHashMap<Resource, Resource>();
context.getServer().setAttribute(CACHED_CONTAINER_FRAGMENTS, metaInfFragmentCache);
}
metaInfTldCache = (ConcurrentHashMap<Resource, Collection<URL>>)context.getServer().getAttribute(CACHED_CONTAINER_TLDS);
if (metaInfTldCache == null)
{
metaInfTldCache = new ConcurrentHashMap<Resource, Collection<URL>>();
context.getServer().setAttribute(CACHED_CONTAINER_TLDS, metaInfTldCache);
}
}
//Scan jars for META-INF information
if (jars != null)
{
for (Resource r : jars)
{
if (scanTypes.contains(METAINF_RESOURCES))
scanForResources(context, r, metaInfResourceCache);
if (scanTypes.contains(METAINF_FRAGMENTS))
scanForFragment(context, r, metaInfFragmentCache);
if (scanTypes.contains(METAINF_TLDS))
scanForTlds(context, r, metaInfTldCache);
}
}
}
/**
* Scan for META-INF/resources dir in the given jar.
*
* @param context the context for the scan
* @param target the target resource to scan for
* @param cache the resource cache
* @throws Exception if unable to scan for resources
*/
public void scanForResources(WebAppContext context, Resource target, ConcurrentHashMap<Resource, Resource> cache)
throws Exception
{
Resource resourcesDir = null;
if (cache != null && cache.containsKey(target))
{
resourcesDir = cache.get(target);
if (resourcesDir == EmptyResource.INSTANCE)
{
if (LOG.isDebugEnabled())
LOG.debug("{} cached as containing no META-INF/resources", target);
return;
}
else if (LOG.isDebugEnabled())
LOG.debug("{} META-INF/resources found in cache ", target);
}
else
{
//not using caches or not in the cache so check for the resources dir
if (LOG.isDebugEnabled())
LOG.debug("{} META-INF/resources checked", target);
if (target.isDirectory())
{
//TODO think how to handle an unpacked jar file (eg for osgi)
resourcesDir = target.addPath("/META-INF/resources");
}
else
{
//Resource represents a packed jar
URI uri = target.getURI();
resourcesDir = Resource.newResource(uriJarPrefix(uri, "!/META-INF/resources"));
}
if (!resourcesDir.exists() || !resourcesDir.isDirectory())
{
resourcesDir.close();
resourcesDir = EmptyResource.INSTANCE;
}
if (cache != null)
{
Resource old = cache.putIfAbsent(target, resourcesDir);
if (old != null)
resourcesDir = old;
else if (LOG.isDebugEnabled())
LOG.debug("{} META-INF/resources cache updated", target);
}
if (resourcesDir == EmptyResource.INSTANCE)
{
return;
}
}
//add it to the meta inf resources for this context
Set<Resource> dirs = (Set<Resource>)context.getAttribute(METAINF_RESOURCES);
if (dirs == null)
{
dirs = new HashSet<Resource>();
context.setAttribute(METAINF_RESOURCES, dirs);
}
if (LOG.isDebugEnabled())
LOG.debug("{} added to context", resourcesDir);
dirs.add(resourcesDir);
}
/**
* Scan for META-INF/web-fragment.xml file in the given jar.
*
* @param context the context for the scan
* @param jar the jar resource to scan for fragements in
* @param cache the resource cache
* @throws Exception if unable to scan for fragments
*/
public void scanForFragment(WebAppContext context, Resource jar, ConcurrentHashMap<Resource, Resource> cache)
throws Exception
{
Resource webFrag = null;
if (cache != null && cache.containsKey(jar))
{
webFrag = cache.get(jar);
if (webFrag == EmptyResource.INSTANCE)
{
if (LOG.isDebugEnabled())
LOG.debug("{} cached as containing no META-INF/web-fragment.xml", jar);
return;
}
else if (LOG.isDebugEnabled())
LOG.debug("{} META-INF/web-fragment.xml found in cache ", jar);
}
else
{
//not using caches or not in the cache so check for the web-fragment.xml
if (LOG.isDebugEnabled())
LOG.debug("{} META-INF/web-fragment.xml checked", jar);
if (jar.isDirectory())
{
webFrag = Resource.newResource(new File(jar.getFile(), "/META-INF/web-fragment.xml"));
}
else
{
URI uri = jar.getURI();
webFrag = Resource.newResource(uriJarPrefix(uri, "!/META-INF/web-fragment.xml"));
}
if (!webFrag.exists() || webFrag.isDirectory())
{
webFrag.close();
webFrag = EmptyResource.INSTANCE;
}
if (cache != null)
{
//web-fragment.xml doesn't exist: put token in cache to signal we've seen the jar
Resource old = cache.putIfAbsent(jar, webFrag);
if (old != null)
webFrag = old;
else if (LOG.isDebugEnabled())
LOG.debug("{} META-INF/web-fragment.xml cache updated", jar);
}
if (webFrag == EmptyResource.INSTANCE)
return;
}
Map<Resource, Resource> fragments = (Map<Resource, Resource>)context.getAttribute(METAINF_FRAGMENTS);
if (fragments == null)
{
fragments = new HashMap<Resource, Resource>();
context.setAttribute(METAINF_FRAGMENTS, fragments);
}
fragments.put(jar, webFrag);
if (LOG.isDebugEnabled())
LOG.debug("{} added to context", webFrag);
}
/**
* Discover META-INF/*.tld files in the given jar
*
* @param context the context for the scan
* @param jar the jar resources to scan tlds for
* @param cache the resource cache
* @throws Exception if unable to scan for tlds
*/
public void scanForTlds(WebAppContext context, Resource jar, ConcurrentHashMap<Resource, Collection<URL>> cache)
throws Exception
{
Collection<URL> tlds = null;
if (cache != null && cache.containsKey(jar))
{
Collection<URL> tmp = cache.get(jar);
if (tmp.isEmpty())
{
if (LOG.isDebugEnabled())
LOG.debug("{} cached as containing no tlds", jar);
return;
}
else
{
tlds = tmp;
if (LOG.isDebugEnabled())
LOG.debug("{} tlds found in cache ", jar);
}
}
else
{
//not using caches or not in the cache so find all tlds
tlds = new HashSet<URL>();
if (jar.isDirectory())
{
tlds.addAll(getTlds(jar.getFile()));
}
else
{
URI uri = jar.getURI();
tlds.addAll(getTlds(uri));
}
if (cache != null)
{
if (LOG.isDebugEnabled())
LOG.debug("{} tld cache updated", jar);
Collection<URL> old = (Collection<URL>)cache.putIfAbsent(jar, tlds);
if (old != null)
tlds = old;
}
if (tlds.isEmpty())
return;
}
Collection<URL> metaInfTlds = (Collection<URL>)context.getAttribute(METAINF_TLDS);
if (metaInfTlds == null)
{
metaInfTlds = new HashSet<URL>();
context.setAttribute(METAINF_TLDS, metaInfTlds);
}
metaInfTlds.addAll(tlds);
if (LOG.isDebugEnabled())
LOG.debug("tlds added to context");
}
@Override
public void postConfigure(WebAppContext context) throws Exception
{
context.setAttribute(METAINF_RESOURCES, null);
context.setAttribute(METAINF_FRAGMENTS, null);
context.setAttribute(METAINF_TLDS, null);
}
/**
* Find all .tld files in all subdirs of the given dir.
*
* @param dir the directory to scan
* @return the list of tlds found
* @throws IOException if unable to scan the directory
*/
public Collection<URL> getTlds(File dir) throws IOException
{
if (dir == null || !dir.isDirectory())
return Collections.emptySet();
HashSet<URL> tlds = new HashSet<URL>();
File[] files = dir.listFiles();
if (files != null)
{
for (File f : files)
{
if (f.isDirectory())
tlds.addAll(getTlds(f));
else
{
String name = f.getCanonicalPath();
if (name.contains("META-INF") && name.endsWith(".tld"))
tlds.add(f.toURI().toURL());
}
}
}
return tlds;
}
/**
* Find all .tld files in the given jar.
*
* @param uri the uri to jar file
* @return the collection of tlds as url references
* @throws IOException if unable to scan the jar file
*/
public Collection<URL> getTlds(URI uri) throws IOException
{
HashSet<URL> tlds = new HashSet<URL>();
String jarUri = uriJarPrefix(uri, "!/");
URL url = new URL(jarUri);
JarURLConnection jarConn = (JarURLConnection)url.openConnection();
jarConn.setUseCaches(Resource.getDefaultUseCaches());
JarFile jarFile = jarConn.getJarFile();
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements())
{
JarEntry e = entries.nextElement();
String name = e.getName();
if (name.startsWith("META-INF") && name.endsWith(".tld"))
{
tlds.add(new URL(jarUri + name));
}
}
if (!Resource.getDefaultUseCaches())
jarFile.close();
return tlds;
}
protected List<Resource> findClassDirs(WebAppContext context)
throws Exception
{
if (context == null)
return null;
List<Resource> classDirs = new ArrayList<Resource>();
Resource webInfClasses = findWebInfClassesDir(context);
if (webInfClasses != null)
classDirs.add(webInfClasses);
List<Resource> extraClassDirs = findExtraClasspathDirs(context);
if (extraClassDirs != null)
classDirs.addAll(extraClassDirs);
return classDirs;
}
/**
* Look for jars that should be treated as if they are in WEB-INF/lib
*
* @param context the context to find the jars in
* @return the list of jar resources found within context
* @throws Exception if unable to find the jars
*/
protected List<Resource> findJars(WebAppContext context)
throws Exception
{
List<Resource> jarResources = new ArrayList<Resource>();
List<Resource> webInfLibJars = findWebInfLibJars(context);
if (webInfLibJars != null)
jarResources.addAll(webInfLibJars);
List<Resource> extraClasspathJars = findExtraClasspathJars(context);
if (extraClasspathJars != null)
jarResources.addAll(extraClasspathJars);
return jarResources;
}
/**
* Look for jars in <code>WEB-INF/lib</code>
*
* @param context the context to find the lib jars in
* @return the list of jars as {@link Resource}
* @throws Exception if unable to scan for lib jars
*/
protected List<Resource> findWebInfLibJars(WebAppContext context)
throws Exception
{
Resource webInf = context.getWebInf();
if (webInf == null || !webInf.exists())
return null;
List<Resource> jarResources = new ArrayList<Resource>();
Resource webInfLib = webInf.addPath("/lib");
if (webInfLib.exists() && webInfLib.isDirectory())
{
String[] files = webInfLib.list();
if (files != null)
{
Arrays.sort(files);
}
for (int f = 0; files != null && f < files.length; f++)
{
try
{
Resource file = webInfLib.addPath(files[f]);
String fnlc = file.getName().toLowerCase(Locale.ENGLISH);
int dot = fnlc.lastIndexOf('.');
String extension = (dot < 0 ? null : fnlc.substring(dot));
if (extension != null && (extension.equals(".jar") || extension.equals(".zip")))
{
jarResources.add(file);
}
}
catch (Exception ex)
{
LOG.warn("Unable to load WEB-INF file {}", files[f], ex);
}
}
}
return jarResources;
}
/**
* Get jars from WebAppContext.getExtraClasspath as resources
*
* @param context the context to find extra classpath jars in
* @return the list of Resources with the extra classpath, or null if not found
* @throws Exception if unable to resolve the extra classpath jars
*/
protected List<Resource> findExtraClasspathJars(WebAppContext context)
throws Exception
{
if (context == null || context.getExtraClasspath() == null)
return null;
return context.getExtraClasspath()
.stream()
.filter(this::isFileSupported)
.collect(Collectors.toList());
}
/**
* Get <code>WEB-INF/classes</code> dir
*
* @param context the context to look for the <code>WEB-INF/classes</code> directory
* @return the Resource for the <code>WEB-INF/classes</code> directory
* @throws Exception if unable to find the <code>WEB-INF/classes</code> directory
*/
protected Resource findWebInfClassesDir(WebAppContext context)
throws Exception
{
if (context == null)
return null;
Resource webInf = context.getWebInf();
// Find WEB-INF/classes
if (webInf != null && webInf.isDirectory())
{
// Look for classes directory
Resource classes = webInf.addPath("classes/");
if (classes.exists())
return classes;
}
return null;
}
/**
* Get class dirs from WebAppContext.getExtraClasspath as resources
*
* @param context the context to look for extra classpaths in
* @return the list of Resources to the extra classpath
* @throws Exception if unable to resolve the extra classpath resources
*/
protected List<Resource> findExtraClasspathDirs(WebAppContext context)
throws Exception
{
if (context == null || context.getExtraClasspath() == null)
return null;
return context.getExtraClasspath()
.stream()
.filter(Resource::isDirectory)
.collect(Collectors.toList());
}
private String uriJarPrefix(URI uri, String suffix)
{
String uriString = uri.toString();
if (uriString.startsWith("jar:"))
{
return uriString + suffix;
}
else
{
return "jar:" + uriString + suffix;
}
}
private boolean isFileSupported(Resource resource)
{
try
{
if (resource.isDirectory())
return false;
if (resource.getFile() == null)
return false;
}
catch (Throwable t)
{
if (LOG.isDebugEnabled())
LOG.debug("Bad Resource reference: {}", resource, t);
return false;
}
String filenameLowercase = resource.getName().toLowerCase(Locale.ENGLISH);
int dot = filenameLowercase.lastIndexOf('.');
String extension = (dot < 0 ? null : filenameLowercase.substring(dot));
return (extension != null && (extension.equals(".jar") || extension.equals(".zip")));
}
}