Skip to content

Commit c78a213

Browse files
committed
Fix PathMatchingResourcePatternResolver manifest classpath discovery
Update `PathMatchingResourcePatternResolver` so that in addition to searching the `java.class.path` system property for classpath enties, it also searches the `MANIFEST.MF` files from within those jars. Prior to this commit, the `addClassPathManifestEntries()` method expected that the JVM had added `Class-Path` manifest entries to the `java.class.path` system property, however, this did not always happen. The updated code now performs a deep search by loading `MANIFEST.MF` files from jars discovered from the system property. To deal with potential performance issue, loaded results are also now cached. The updated code has been tested with Spring Boot 3.3 jars extracted using `java -Djarmode=tools`. See gh-33705
1 parent ec89553 commit c78a213

File tree

3 files changed

+262
-36
lines changed

3 files changed

+262
-36
lines changed

Diff for: spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java

+108-36
Original file line numberDiff line numberDiff line change
@@ -39,16 +39,21 @@
3939
import java.nio.file.Path;
4040
import java.util.Collections;
4141
import java.util.Enumeration;
42+
import java.util.HashSet;
4243
import java.util.LinkedHashSet;
4344
import java.util.Map;
4445
import java.util.NavigableSet;
4546
import java.util.Objects;
4647
import java.util.Set;
48+
import java.util.StringTokenizer;
4749
import java.util.TreeSet;
4850
import java.util.concurrent.ConcurrentHashMap;
4951
import java.util.function.Predicate;
52+
import java.util.jar.Attributes;
53+
import java.util.jar.Attributes.Name;
5054
import java.util.jar.JarEntry;
5155
import java.util.jar.JarFile;
56+
import java.util.jar.Manifest;
5257
import java.util.stream.Collectors;
5358
import java.util.stream.Stream;
5459
import java.util.zip.ZipException;
@@ -230,6 +235,9 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol
230235
private static final Predicate<ResolvedModule> isNotSystemModule =
231236
resolvedModule -> !systemModuleNames.contains(resolvedModule.name());
232237

238+
@Nullable
239+
private static Set<ClassPathManifestEntry> classPathManifestEntriesCache;
240+
233241
@Nullable
234242
private static Method equinoxResolveMethod;
235243

@@ -522,25 +530,30 @@ protected void addAllClassLoaderJarRoots(@Nullable ClassLoader classLoader, Set<
522530
* @since 4.3
523531
*/
524532
protected void addClassPathManifestEntries(Set<Resource> result) {
533+
Set<ClassPathManifestEntry> entries = classPathManifestEntriesCache;
534+
if (entries == null) {
535+
entries = getClassPathManifestEntries();
536+
classPathManifestEntriesCache = entries;
537+
}
538+
for (ClassPathManifestEntry entry : entries) {
539+
if (!result.contains(entry.resource()) &&
540+
(entry.alternative() != null && !result.contains(entry.alternative()))) {
541+
result.add(entry.resource());
542+
}
543+
}
544+
}
545+
546+
private Set<ClassPathManifestEntry> getClassPathManifestEntries() {
547+
Set<ClassPathManifestEntry> manifestEntries = new HashSet<>();
548+
Set<File> seen = new HashSet<>();
525549
try {
526-
String javaClassPathProperty = System.getProperty("java.class.path");
527-
for (String path : StringUtils.delimitedListToStringArray(javaClassPathProperty, File.pathSeparator)) {
550+
String paths = System.getProperty("java.class.path");
551+
for (String path : StringUtils.delimitedListToStringArray(paths, File.pathSeparator)) {
528552
try {
529-
String filePath = new File(path).getAbsolutePath();
530-
int prefixIndex = filePath.indexOf(':');
531-
if (prefixIndex == 1) {
532-
// Possibly a drive prefix on Windows (for example, "c:"), so we prepend a slash
533-
// and convert the drive letter to uppercase for consistent duplicate detection.
534-
filePath = "/" + StringUtils.capitalize(filePath);
535-
}
536-
// Since '#' can appear in directories/filenames, java.net.URL should not treat it as a fragment
537-
filePath = StringUtils.replace(filePath, "#", "%23");
538-
// Build URL that points to the root of the jar file
539-
UrlResource jarResource = new UrlResource(ResourceUtils.JAR_URL_PREFIX +
540-
ResourceUtils.FILE_URL_PREFIX + filePath + ResourceUtils.JAR_URL_SEPARATOR);
541-
// Potentially overlapping with URLClassLoader.getURLs() result in addAllClassLoaderJarRoots().
542-
if (!result.contains(jarResource) && !hasDuplicate(filePath, result) && jarResource.exists()) {
543-
result.add(jarResource);
553+
File jar = new File(path).getAbsoluteFile();
554+
if (jar.isFile() && seen.add(jar)) {
555+
manifestEntries.add(ClassPathManifestEntry.of(jar));
556+
manifestEntries.addAll(getClassPathManifestEntriesFromJar(jar));
544557
}
545558
}
546559
catch (MalformedURLException ex) {
@@ -550,34 +563,46 @@ protected void addClassPathManifestEntries(Set<Resource> result) {
550563
}
551564
}
552565
}
566+
return Collections.unmodifiableSet(manifestEntries);
553567
}
554568
catch (Exception ex) {
555569
if (logger.isDebugEnabled()) {
556570
logger.debug("Failed to evaluate 'java.class.path' manifest entries: " + ex);
557571
}
572+
return Collections.emptySet();
558573
}
559574
}
560575

561-
/**
562-
* Check whether the given file path has a duplicate but differently structured entry
563-
* in the existing result, i.e. with or without a leading slash.
564-
* @param filePath the file path (with or without a leading slash)
565-
* @param result the current result
566-
* @return {@code true} if there is a duplicate (i.e. to ignore the given file path),
567-
* {@code false} to proceed with adding a corresponding resource to the current result
568-
*/
569-
private boolean hasDuplicate(String filePath, Set<Resource> result) {
570-
if (result.isEmpty()) {
571-
return false;
572-
}
573-
String duplicatePath = (filePath.startsWith("/") ? filePath.substring(1) : "/" + filePath);
574-
try {
575-
return result.contains(new UrlResource(ResourceUtils.JAR_URL_PREFIX + ResourceUtils.FILE_URL_PREFIX +
576-
duplicatePath + ResourceUtils.JAR_URL_SEPARATOR));
576+
private Set<ClassPathManifestEntry> getClassPathManifestEntriesFromJar(File jar) throws IOException {
577+
URL base = jar.toURI().toURL();
578+
File parent = jar.getAbsoluteFile().getParentFile();
579+
try (JarFile jarFile = new JarFile(jar)) {
580+
Manifest manifest = jarFile.getManifest();
581+
Attributes attributes = (manifest != null) ? manifest.getMainAttributes() : null;
582+
String classPath = (attributes != null) ? attributes.getValue(Name.CLASS_PATH) : null;
583+
Set<ClassPathManifestEntry> manifestEntries = new HashSet<>();
584+
if (StringUtils.hasLength(classPath)) {
585+
StringTokenizer tokenizer = new StringTokenizer(classPath);
586+
while (tokenizer.hasMoreTokens()) {
587+
String path = tokenizer.nextToken();
588+
System.out.println("Hello "+path);
589+
if (path.indexOf(':') >= 0 && !"file".equalsIgnoreCase(new URL(base, path).getProtocol())) {
590+
// See jdk.internal.loader.URLClassPath.JarLoader.tryResolveFile(URL, String)
591+
continue;
592+
}
593+
File candidate = new File(parent, path);
594+
if (candidate.isFile() && candidate.getCanonicalPath().contains(parent.getCanonicalPath())) {
595+
manifestEntries.add(ClassPathManifestEntry.of(candidate));
596+
}
597+
}
598+
}
599+
return Collections.unmodifiableSet(manifestEntries);
577600
}
578-
catch (MalformedURLException ex) {
579-
// Ignore: just for testing against duplicate.
580-
return false;
601+
catch (Exception ex) {
602+
if (logger.isDebugEnabled()) {
603+
logger.debug("Failed to load manifest entries from jar file '" + jar + "': " + ex);
604+
}
605+
return Collections.emptySet();
581606
}
582607
}
583608

@@ -1170,4 +1195,51 @@ public String toString() {
11701195
}
11711196
}
11721197

1198+
1199+
/**
1200+
* A single {@code Class-Path} manifest entry.
1201+
*/
1202+
private record ClassPathManifestEntry(Resource resource, @Nullable Resource alternative) {
1203+
1204+
private static final String JARFILE_URL_PREFIX = ResourceUtils.JAR_URL_PREFIX + ResourceUtils.FILE_URL_PREFIX;
1205+
1206+
static ClassPathManifestEntry of(File file) throws MalformedURLException {
1207+
String path = fixPath(file.getAbsolutePath());
1208+
Resource resource = asJarFileResource(path);
1209+
Resource alternative = createAlternative(path);
1210+
return new ClassPathManifestEntry(resource, alternative);
1211+
}
1212+
1213+
private static String fixPath(String path) {
1214+
int prefixIndex = path.indexOf(':');
1215+
if (prefixIndex == 1) {
1216+
// Possibly a drive prefix on Windows (for example, "c:"), so we prepend a slash
1217+
// and convert the drive letter to uppercase for consistent duplicate detection.
1218+
path = "/" + StringUtils.capitalize(path);
1219+
}
1220+
// Since '#' can appear in directories/filenames, java.net.URL should not treat it as a fragment
1221+
return StringUtils.replace(path, "#", "%23");
1222+
}
1223+
1224+
/**
1225+
* Return a alternative form of the resource, i.e. with or without a leading slash.
1226+
* @param path the file path (with or without a leading slash)
1227+
* @return the alternative form or {@code null}
1228+
*/
1229+
@Nullable
1230+
private static Resource createAlternative(String path) {
1231+
try {
1232+
String alternativePath = path.startsWith("/") ? path.substring(1) : "/" + path;
1233+
return asJarFileResource(alternativePath);
1234+
}
1235+
catch (MalformedURLException ex) {
1236+
return null;
1237+
}
1238+
}
1239+
1240+
private static Resource asJarFileResource(String path)
1241+
throws MalformedURLException {
1242+
return new UrlResource(JARFILE_URL_PREFIX + path + ResourceUtils.JAR_URL_SEPARATOR);
1243+
}
1244+
}
11731245
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
* Copyright 2002-2024 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.core.io.support;
18+
19+
import java.io.IOException;
20+
import java.util.List;
21+
22+
/**
23+
* Class packaged into a temporary jar to test
24+
* {@link PathMatchingResourcePatternResolver} detection of classpath manifest
25+
* entries.
26+
*
27+
* @author Phillip Webb
28+
*/
29+
public class ClassPathManifestEntriesTestApplication {
30+
31+
public static void main(String[] args) throws IOException {
32+
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
33+
System.out.println("!!!!" + List.of(resolver.getResources("classpath*:/**/*.txt")));
34+
}
35+
36+
}

Diff for: spring-core/src/test/java/org/springframework/core/io/support/PathMatchingResourcePatternResolverTests.java

+118
Original file line numberDiff line numberDiff line change
@@ -16,23 +16,44 @@
1616

1717
package org.springframework.core.io.support;
1818

19+
import java.io.File;
1920
import java.io.FileNotFoundException;
21+
import java.io.FileOutputStream;
2022
import java.io.IOException;
23+
import java.io.InputStream;
2124
import java.io.UncheckedIOException;
25+
import java.net.JarURLConnection;
26+
import java.net.URISyntaxException;
2227
import java.net.URL;
2328
import java.net.URLClassLoader;
29+
import java.net.URLConnection;
30+
import java.nio.charset.StandardCharsets;
31+
import java.nio.file.Files;
2432
import java.nio.file.Path;
2533
import java.nio.file.Paths;
2634
import java.util.Arrays;
35+
import java.util.Enumeration;
2736
import java.util.List;
37+
import java.util.jar.Attributes;
38+
import java.util.jar.Attributes.Name;
39+
import java.util.jar.JarEntry;
40+
import java.util.jar.JarFile;
41+
import java.util.jar.JarOutputStream;
42+
import java.util.jar.Manifest;
2843
import java.util.stream.Collectors;
44+
import java.util.zip.ZipEntry;
2945

46+
import org.apache.commons.logging.LogFactory;
3047
import org.junit.jupiter.api.Nested;
3148
import org.junit.jupiter.api.Test;
49+
import org.junit.jupiter.api.io.TempDir;
3250

3351
import org.springframework.core.io.DefaultResourceLoader;
3452
import org.springframework.core.io.FileSystemResource;
3553
import org.springframework.core.io.Resource;
54+
import org.springframework.util.ClassUtils;
55+
import org.springframework.util.FileSystemUtils;
56+
import org.springframework.util.StreamUtils;
3657
import org.springframework.util.StringUtils;
3758

3859
import static org.assertj.core.api.Assertions.assertThat;
@@ -278,6 +299,103 @@ void rootPatternRetrievalInJarFiles() throws IOException {
278299
}
279300
}
280301

302+
@Nested
303+
class ClassPathManifestEntries {
304+
305+
@TempDir
306+
Path temp;
307+
308+
@Test
309+
void javaDashJarFindsClassPathManifestEntries() throws Exception {
310+
Path lib = this.temp.resolve("lib");
311+
Files.createDirectories(lib);
312+
writeAssetJar(lib.resolve("asset.jar"));
313+
writeApplicationJar(this.temp.resolve("app.jar"));
314+
String java = ProcessHandle.current().info().command().get();
315+
Process process = new ProcessBuilder(java, "-jar", "app.jar")
316+
.directory(this.temp.toFile())
317+
.start();
318+
assertThat(process.waitFor()).isZero();
319+
String result = StreamUtils.copyToString(process.getInputStream(), StandardCharsets.UTF_8);
320+
assertThat(result.replace("\\", "/")).contains("!!!!").contains("/lib/asset.jar!/assets/file.txt");
321+
}
322+
323+
private void writeAssetJar(Path path) throws Exception {
324+
try (JarOutputStream jar = new JarOutputStream(new FileOutputStream(path.toFile()))) {
325+
jar.putNextEntry(new ZipEntry("assets/"));
326+
jar.closeEntry();
327+
jar.putNextEntry(new ZipEntry("assets/file.txt"));
328+
StreamUtils.copy("test", StandardCharsets.UTF_8, jar);
329+
jar.closeEntry();
330+
}
331+
}
332+
333+
private void writeApplicationJar(Path path) throws Exception {
334+
Manifest manifest = new Manifest();
335+
Attributes mainAttributes = manifest.getMainAttributes();
336+
mainAttributes.put(Name.CLASS_PATH, buildSpringClassPath() + "lib/asset.jar");
337+
mainAttributes.put(Name.MAIN_CLASS, ClassPathManifestEntriesTestApplication.class.getName());
338+
mainAttributes.put(Name.MANIFEST_VERSION, "1.0");
339+
try (JarOutputStream jar = new JarOutputStream(new FileOutputStream(path.toFile()), manifest)) {
340+
String appClassResource = ClassUtils.convertClassNameToResourcePath(
341+
ClassPathManifestEntriesTestApplication.class.getName())
342+
+ ClassUtils.CLASS_FILE_SUFFIX;
343+
String folder = "";
344+
for (String name : appClassResource.split("/")) {
345+
if (!name.endsWith(ClassUtils.CLASS_FILE_SUFFIX)) {
346+
folder += name + "/";
347+
jar.putNextEntry(new ZipEntry(folder));
348+
jar.closeEntry();
349+
}
350+
else {
351+
jar.putNextEntry(new ZipEntry(folder + name));
352+
try (InputStream in = getClass().getResourceAsStream(name)) {
353+
in.transferTo(jar);
354+
}
355+
jar.closeEntry();
356+
}
357+
}
358+
}
359+
}
360+
361+
private String buildSpringClassPath() throws Exception {
362+
return copyClasses(PathMatchingResourcePatternResolver.class, "spring-core")
363+
+ copyClasses(LogFactory.class, "commons-logging");
364+
}
365+
366+
private String copyClasses(Class<?> sourceClass, String destinationName)
367+
throws URISyntaxException, IOException {
368+
Path destination = this.temp.resolve(destinationName);
369+
String resourcePath = ClassUtils.convertClassNameToResourcePath(sourceClass.getName())
370+
+ ClassUtils.CLASS_FILE_SUFFIX;
371+
URL resource = getClass().getClassLoader().getResource(resourcePath);
372+
URL url = new URL(resource.toString().replace(resourcePath, ""));
373+
URLConnection connection = url.openConnection();
374+
if (connection instanceof JarURLConnection jarUrlConnection) {
375+
try (JarFile jarFile = jarUrlConnection.getJarFile()) {
376+
Enumeration<JarEntry> entries = jarFile.entries();
377+
while (entries.hasMoreElements()) {
378+
JarEntry entry = entries.nextElement();
379+
if (!entry.isDirectory()) {
380+
Path entryPath = destination.resolve(entry.getName());
381+
try (InputStream in = jarFile.getInputStream(entry)) {
382+
Files.createDirectories(entryPath.getParent());
383+
Files.copy(in, destination.resolve(entry.getName()));
384+
}
385+
}
386+
}
387+
}
388+
}
389+
else {
390+
File source = new File(url.toURI());
391+
Files.createDirectories(destination);
392+
FileSystemUtils.copyRecursively(source, destination.toFile());
393+
}
394+
return destinationName + "/ ";
395+
}
396+
397+
}
398+
281399

282400
private void assertFilenames(String pattern, String... filenames) {
283401
assertFilenames(pattern, false, filenames);

0 commit comments

Comments
 (0)