Skip to content

Commit dc31b41

Browse files
agorischekCopilot
andauthored
spring-di: condition messages name classpath jars by their file name (#304)
* spring-di: condition messages name classpath jars by their file name A condition message that named a resource in a jar kept the jar's absolute URL (ResourceBundle found bundle URL [jar:file:/…/common.jar!/messages.properties], or a GraphQL schema found in a jar). A Gradle module's jar is built under the revision, so the CLI refused the extraction; a Maven module's sibling, or any dependency, named the user's home directory through ~/.m2. The helper's new ClasspathNames (JDK only) replaces each classpath jar's spellings, as given and resolved, native, with / separators and percent-encoded as the class loader's URLs are, with its file name (URL [jar:common.jar!/messages.properties]); directories are removed as before, now also percent-encoded. A unit test compiles it with the user's JDK and runs it with a directory and a jar whose paths contain spaces. The native fixture's messages.properties moves to a Gradle module, and spring.json is regenerated. Refs #299 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Changelog fragment cites #304 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Changelog fragment: cite #304 in place of the placeholder Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * spring-di: match a classpath entry however a URL encodes it The class loader's resource URLs encode = ; [ ] and non-ASCII characters with lowercase escapes (a%3db%5b1%5d), where File.toURI() and Path.toUri() leave = and ; and write uppercase escapes, so a classpath directory or jar under such a name kept its absolute path. Each spelling now matches with any character percent-encoded, in either case. Refs #299 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * spring-di: say which classpath ClasspathNames reads; public check class Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --------- Co-authored-by: agorischek <6295280+agorischek@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
1 parent 082fbe2 commit dc31b41

15 files changed

Lines changed: 388 additions & 61 deletions

File tree

‎changelog.d/304.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
section: fixes
3+
---
4+
5+
- **`spring-di` names jars on the classpath by their file name** (#304). A condition message that named a resource in a jar (`ResourceBundle found bundle URL [jar:file:/…/common/build/libs/common.jar!/messages.properties]`, or a GraphQL schema Spring Boot found) kept the jar's absolute path. A Gradle module's jar is built under the revision, so its extraction was refused for naming a host directory; a Maven module's sibling, or any dependency, named the user's home directory through `~/.m2`. Jars are now named by their file name (`URL [jar:common.jar!/messages.properties]`), and paths with spaces or other characters a URL encodes are matched as the class loader spells them.

‎packages/cli/tests/native_tools/spring.rs‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,9 @@ fn native_spring_boot_context_through_gradle_and_maven() {
105105
.iter()
106106
.any(|item| { item["id"].as_str().unwrap().starts_with("service:scopedTarget.") })
107107
);
108-
// A condition names a file in a classpath directory relative to it, not where the build put the directory
109-
// (Gradle's class and resource directories are in a scratch directory under the revision).
108+
// A condition names a file on the classpath without where the build put it: a jar by its file name (Gradle builds
109+
// the common module's common.jar in a scratch directory under the revision) and a file in a classpath directory
110+
// relative to it (Maven packages the module's resources with the application's in target/classes).
110111
let bundle = |state: &Value| -> String {
111112
entity(state, "service:messageSource:registration")["data"]["conditions"]
112113
.as_array()
@@ -117,7 +118,10 @@ fn native_spring_boot_context_through_gradle_and_maven() {
117118
.unwrap_or_else(|| panic!("a bundle condition in {state}"))
118119
.to_owned()
119120
};
120-
assert!(bundle(&gradle).ends_with("[messages.properties]"), "{}", bundle(&gradle));
121+
assert_eq!(
122+
bundle(&gradle),
123+
"ResourceBundle found bundle URL [jar:common.jar!/messages.properties]"
124+
);
121125
let portable = |state: &Value, root: &Path| {
122126
let serialized = state.to_string();
123127
for spelling in [root.to_path_buf(), root.canonicalize().unwrap()] {
@@ -185,7 +189,7 @@ fn native_spring_boot_context_through_gradle_and_maven() {
185189
dependencies(&maven, "implementation:ordersService"),
186190
dependencies(&gradle, "implementation:ordersService")
187191
);
188-
assert_eq!(bundle(&maven), bundle(&gradle));
192+
assert_eq!(bundle(&maven), "ResourceBundle found bundle file [messages.properties]");
189193
portable(&maven, &maven_root);
190194

191195
// Add a service, change a lifetime and swap an implementation.

‎packages/extractors/spring-di/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ application output never reaches stdout.
8484
| A scoped proxy and its `scopedTarget.` bean | One registration with the target's scope and `data.proxied: true` |
8585
| Aliases | `data.aliases` on the service; dependencies resolve to the bean's canonical name |
8686
| `@Primary`, `@Fallback`, qualifiers, `@Lazy`, `@DependsOn`, role | `primary`, `fallback`, `qualifiers`, `lazy`, `initializedAfter`, `role` on the registration |
87-
| Conditions that matched | `data.conditions`, from Spring Boot's condition evaluation report; a file in a directory on the application's classpath is named relative to it (`file [messages.properties]`) |
87+
| Conditions that matched | `data.conditions`, from Spring Boot's condition evaluation report; a file in a directory on the application's classpath is named relative to it (`file [messages.properties]`), and a jar on it (a module's, or a dependency's in the Maven or Gradle cache) by its file name (`URL [jar:common.jar!/messages.properties]`) |
8888
| Constructor, `@Bean` method, field and method injection | `dependsOn` from the implementation to each resolved bean's service, with `injection`, `parameter`, `position`, the `requestedType`, `qualifier`, `optional`, `collection` (one edge per element bean) and `lazy` (`ObjectProvider`, `Provider`, `@Lazy`) |
8989

9090
A bean's identity is its name, the bean factory's own key: two beans of one type
Lines changed: 4 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,9 @@
11
package projections.spring;
22

3-
import java.io.File;
4-
import java.io.IOException;
5-
import java.nio.file.Files;
6-
import java.nio.file.Path;
73
import java.util.ArrayList;
8-
import java.util.Comparator;
94
import java.util.List;
105
import java.util.Map;
11-
import java.util.Set;
126
import java.util.TreeMap;
13-
import java.util.TreeSet;
147

158
/** What Spring Boot reports about the application, read reflectively: its auto-configuration packages and condition evaluation. */
169
final class BootReports {
@@ -34,12 +27,11 @@ static List<String> autoConfigurationPackages(Class<?> application, RecordingBea
3427

3528
/**
3629
* Spring Boot's condition evaluation report: why each configuration class and @Bean method was registered.
37-
* A message that names a file in a directory on the classpath (such as the bundle MessageSourceAutoConfiguration
38-
* found) names it relative to that directory, because where the build puts its class and resource directories
39-
* differs between machines and runs.
30+
* A message that names a file on the classpath (such as the bundle MessageSourceAutoConfiguration found) names it
31+
* without where the build or the user's caches put it: see {@link ClasspathNames}.
4032
*/
4133
static Map<String, List<String>> conditions(Class<?> application, RecordingBeanFactory factory) {
42-
List<String> prefixes = directoryPrefixes(classpathDirectories());
34+
ClasspathNames names = ClasspathNames.ofRuntime();
4335
Map<String, List<String>> result = new TreeMap<>();
4436
try {
4537
Class<?> type = Class.forName(CONDITION_REPORT, false, application.getClassLoader());
@@ -51,7 +43,7 @@ static Map<String, List<String>> conditions(Class<?> application, RecordingBeanF
5143
Object outcome = conditionAndOutcome.getClass().getMethod("getOutcome").invoke(conditionAndOutcome);
5244
Object match = outcome.getClass().getMethod("isMatch").invoke(outcome);
5345
Object message = outcome.getClass().getMethod("getMessage").invoke(outcome);
54-
if (Boolean.TRUE.equals(match) && message != null) messages.add(withoutPrefixes(message.toString(), prefixes));
46+
if (Boolean.TRUE.equals(match) && message != null) messages.add(names.apply(message.toString()));
5547
}
5648
if (!messages.isEmpty()) result.put(String.valueOf(entry.getKey()), messages);
5749
}
@@ -60,46 +52,4 @@ static Map<String, List<String>> conditions(Class<?> application, RecordingBeanF
6052
}
6153
return result;
6254
}
63-
64-
/** The directories on the runtime classpath: the application's class and resource directories, and its modules'. */
65-
static List<Path> classpathDirectories() {
66-
List<Path> directories = new ArrayList<>();
67-
for (String entry : System.getProperty("java.class.path", "").split(File.pathSeparator)) {
68-
try {
69-
Path path = Path.of(entry);
70-
if (!entry.isEmpty() && Files.isDirectory(path)) directories.add(path);
71-
} catch (RuntimeException ignored) {
72-
// An entry that is not a path names no directory.
73-
}
74-
}
75-
return directories;
76-
}
77-
78-
/**
79-
* Each directory as a message can spell it, with the separator that follows it: as given and as resolved,
80-
* with native and URL separators. Longest first, so a nested directory is removed whole.
81-
*/
82-
static List<String> directoryPrefixes(List<Path> directories) {
83-
Set<String> prefixes = new TreeSet<>(Comparator.comparingInt(String::length).reversed().thenComparing(Comparator.naturalOrder()));
84-
for (Path directory : directories) {
85-
List<Path> spellings = new ArrayList<>(List.of(directory.toAbsolutePath().normalize()));
86-
try {
87-
spellings.add(directory.toRealPath());
88-
} catch (IOException | RuntimeException ignored) {
89-
// A directory that cannot be resolved is only spelled as given.
90-
}
91-
for (Path spelling : spellings) {
92-
String text = spelling.toString();
93-
prefixes.add(text + File.separator);
94-
prefixes.add(text.replace(File.separatorChar, '/') + "/");
95-
}
96-
}
97-
return List.copyOf(prefixes);
98-
}
99-
100-
static String withoutPrefixes(String message, List<String> prefixes) {
101-
String result = message;
102-
for (String prefix : prefixes) result = result.replace(prefix, "");
103-
return result;
104-
}
10555
}
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
package projections.spring;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
import java.nio.charset.StandardCharsets;
6+
import java.nio.file.Files;
7+
import java.nio.file.Path;
8+
import java.util.ArrayList;
9+
import java.util.Comparator;
10+
import java.util.LinkedHashSet;
11+
import java.util.List;
12+
import java.util.Map;
13+
import java.util.Set;
14+
import java.util.TreeMap;
15+
import java.util.regex.Matcher;
16+
import java.util.regex.Pattern;
17+
18+
/**
19+
* Names the files on the runtime classpath without where the build or the user's caches put them, because that
20+
* differs between machines and runs. A file in a classpath directory is named relative to it
21+
* ({@code file [/repo/target/classes/messages.properties]} is {@code file [messages.properties]}) and a jar by its file
22+
* name ({@code URL [jar:file:/home/me/.m2/repository/…/common.jar!/messages.properties]} is
23+
* {@code URL [jar:common.jar!/messages.properties]}).
24+
*/
25+
final class ClasspathNames {
26+
/** Each way a message can spell a classpath entry, longest first so a nested entry is replaced whole, and its replacement. */
27+
private final List<Map.Entry<Pattern, String>> replacements;
28+
29+
private ClasspathNames(List<Map.Entry<Pattern, String>> replacements) {
30+
this.replacements = replacements;
31+
}
32+
33+
/**
34+
* The entries of {@code java.class.path}: the application's class and resource directories, and the jars or
35+
* directories of its build's other modules (Gradle subprojects, Maven modules) and of its dependencies.
36+
*/
37+
static ClasspathNames ofRuntime() {
38+
List<Path> entries = new ArrayList<>();
39+
for (String entry : System.getProperty("java.class.path", "").split(File.pathSeparator)) {
40+
try {
41+
if (!entry.isEmpty()) entries.add(Path.of(entry));
42+
} catch (RuntimeException ignored) {
43+
// An entry that is not a path names no file.
44+
}
45+
}
46+
return of(entries);
47+
}
48+
49+
/**
50+
* Each directory and file is spelled as given and as resolved, with native and URL separators, and as a URL path
51+
* ({@code /C:/…} on Windows); a jar also inside a {@code jar:file:} URL. A spelling also matches with any of its
52+
* characters percent-encoded, in either case, because encoders differ: the class loader's resource URLs spell
53+
* {@code a=b[1]} as {@code a%3db%5b1%5d}, and {@link File#toURI()} and {@link Path#toUri()} as {@code a=b%5B1%5D}.
54+
*/
55+
static ClasspathNames of(List<Path> entries) {
56+
Map<String, String> replacements = new TreeMap<>(Comparator.comparingInt(String::length).reversed().thenComparing(Comparator.naturalOrder()));
57+
for (Path entry : entries) {
58+
boolean directory = Files.isDirectory(entry);
59+
if (!directory && !Files.isRegularFile(entry)) continue;
60+
String name = directory ? "" : entry.getFileName().toString();
61+
for (Path spelling : spellings(entry)) {
62+
// The filesystem root is a prefix of every path, not where the build put anything.
63+
if (spelling.getParent() == null) continue;
64+
String text = spelling.toString();
65+
String url = urlPath(spelling);
66+
if (directory) {
67+
replacements.put(text + File.separator, "");
68+
replacements.put(text.replace(File.separatorChar, '/') + "/", "");
69+
if (url != null) replacements.put(url.endsWith("/") ? url : url + "/", "");
70+
} else {
71+
replacements.put(text, name);
72+
replacements.put(text.replace(File.separatorChar, '/'), name);
73+
if (url != null) {
74+
replacements.put(url, name);
75+
replacements.put("jar:file:" + url + "!/", "jar:" + name + "!/");
76+
replacements.put("jar:file://" + url + "!/", "jar:" + name + "!/");
77+
}
78+
}
79+
}
80+
}
81+
List<Map.Entry<Pattern, String>> patterns = new ArrayList<>();
82+
for (Map.Entry<String, String> replacement : replacements.entrySet()) {
83+
patterns.add(Map.entry(anyEncoding(replacement.getKey()), Matcher.quoteReplacement(replacement.getValue())));
84+
}
85+
return new ClasspathNames(List.copyOf(patterns));
86+
}
87+
88+
String apply(String message) {
89+
// A message without a separator names no path, and most condition messages name only classes and properties.
90+
if (message.indexOf('/') < 0 && message.indexOf(File.separatorChar) < 0) return message;
91+
String result = message;
92+
for (Map.Entry<Pattern, String> replacement : replacements) {
93+
result = replacement.getKey().matcher(result).replaceAll(replacement.getValue());
94+
}
95+
return result;
96+
}
97+
98+
/** The entry as given (made absolute) and as resolved, which differ through a symbolic link such as macOS's /tmp. */
99+
private static List<Path> spellings(Path entry) {
100+
Set<Path> spellings = new LinkedHashSet<>(List.of(entry.toAbsolutePath().normalize()));
101+
try {
102+
spellings.add(entry.toRealPath());
103+
} catch (IOException | RuntimeException ignored) {
104+
// An entry that cannot be resolved is only spelled as given.
105+
}
106+
return List.copyOf(spellings);
107+
}
108+
109+
/** The path as a {@code file:} URL names it, decoded; it starts with {@code /}, also on Windows. */
110+
private static String urlPath(Path path) {
111+
try {
112+
String url = path.toFile().toURI().getPath();
113+
return url == null || url.isEmpty() || "/".equals(url) ? null : url;
114+
} catch (RuntimeException ignored) {
115+
// A path without a URL spelling is only spelled natively.
116+
return null;
117+
}
118+
}
119+
120+
/** Matches {@code text} with any character but a letter, digit or {@code /} also percent-encoded as UTF-8, in either case. */
121+
static Pattern anyEncoding(String text) {
122+
StringBuilder pattern = new StringBuilder();
123+
text.codePoints().forEach(codePoint -> {
124+
String character = Character.toString(codePoint);
125+
if (codePoint < 0x80 && (Character.isLetterOrDigit(codePoint) || codePoint == '/')) {
126+
pattern.append(character);
127+
return;
128+
}
129+
pattern.append("(?:").append(Pattern.quote(character));
130+
pattern.append('|');
131+
for (byte value : character.getBytes(StandardCharsets.UTF_8)) {
132+
pattern.append('%').append(hexDigit((value >> 4) & 0xF)).append(hexDigit(value & 0xF));
133+
}
134+
pattern.append(')');
135+
});
136+
return Pattern.compile(pattern.toString());
137+
}
138+
139+
private static String hexDigit(int value) {
140+
char digit = Character.forDigit(value, 16);
141+
return Character.isLetter(digit) ? "[" + digit + Character.toUpperCase(digit) + "]" : String.valueOf(digit);
142+
}
143+
}

‎packages/extractors/spring-di/src/lib.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,12 @@ pub const ID: &str = "spring-di";
2121
const SCHEMA: &str = "architecture/v0";
2222

2323
/// The helper's sources, relative to the helper directory.
24-
const SOURCES: [&str; 11] = [
24+
const SOURCES: [&str; 12] = [
2525
"projections/spring/Extractor.java",
2626
"projections/spring/MainClass.java",
2727
"projections/spring/Composition.java",
2828
"projections/spring/BootReports.java",
29+
"projections/spring/ClasspathNames.java",
2930
"projections/spring/Registration.java",
3031
"projections/spring/DefinitionFacts.java",
3132
"projections/spring/Injections.java",

‎packages/extractors/spring-di/src/tests.rs‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,70 @@ fn maven_compiles_and_reports_runtime_dependencies() {
159159
assert_eq!([runs[1][0].as_str(), runs[2][0].as_str()], ["javac", "java"]);
160160
}
161161

162+
/// The helper's ClasspathNames, compiled and run with the user's JDK (no Spring and no build): the class loader's
163+
/// own URLs for a jar and a directory whose paths contain spaces and characters URLs encode, given through a symbolic
164+
/// link where there is one, name neither where it is.
165+
#[test]
166+
fn classpath_files_are_named_without_where_the_build_or_caches_put_them() {
167+
use std::process::Command;
168+
let java_home = std::env::var("JAVA_HOME").ok().filter(|home| !home.is_empty());
169+
let jdk = |tool: &str| jdk_tool(java_home.as_deref(), tool, std::env::consts::EXE_SUFFIX);
170+
let run = |command: &mut Command| {
171+
let output = command
172+
.output()
173+
.unwrap_or_else(|error| panic!("A JDK (17 or newer) is required to check the Spring helper: {error}"));
174+
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
175+
String::from_utf8(output.stdout).unwrap()
176+
};
177+
let root = std::env::temp_dir().join(format!("projections spring-di {}", std::process::id()));
178+
let _ = fs::remove_dir_all(&root);
179+
// Characters the class loader encodes as no other URL does (`%3d`, `%5b`, `%c3%bc`); `;` separates Windows classpaths.
180+
let odd = if cfg!(windows) { "=[1]" } else { "=;[1] ü" };
181+
let (classes, library, output) = (
182+
root.join(format!("build dir{odd}/classes")),
183+
root.join(format!("lib dir{odd}")),
184+
root.join("helper"),
185+
);
186+
for directory in [&classes, &library, &output] {
187+
fs::create_dir_all(directory).unwrap();
188+
}
189+
fs::write(classes.join("messages.properties"), "greeting=Hello\n").unwrap();
190+
run(Command::new(jdk("jar"))
191+
.args(["--create", "--file"])
192+
.arg(library.join("common lib.jar"))
193+
.arg("-C")
194+
.arg(&classes)
195+
.arg("messages.properties"));
196+
#[cfg(unix)]
197+
let library = {
198+
std::os::unix::fs::symlink(&library, root.join("linked lib")).unwrap();
199+
root.join("linked lib")
200+
};
201+
let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
202+
run(Command::new(jdk("javac"))
203+
.args(["--release", RELEASE, "-d"])
204+
.arg(&output)
205+
.arg(manifest.join("helper/projections/spring/ClasspathNames.java"))
206+
.arg(manifest.join("tests/ClasspathNamesCheck.java")));
207+
let classpath = std::env::join_paths([output, classes, library.join("common lib.jar")]).unwrap();
208+
let printed = run(Command::new(jdk("java"))
209+
.arg("-cp")
210+
.arg(classpath)
211+
.arg("projections.spring.ClasspathNamesCheck"));
212+
let _ = fs::remove_dir_all(&root);
213+
assert_eq!(
214+
printed.lines().collect::<Vec<_>>(),
215+
[
216+
"URL [file:messages.properties]",
217+
"file [messages.properties]",
218+
"URL [jar:common lib.jar!/messages.properties]",
219+
"file [messages.properties]",
220+
"URL [jar:common lib.jar!/messages.properties]",
221+
"found common lib.jar",
222+
]
223+
);
224+
}
225+
162226
/// The error a build that fails the way `stdout` and `stderr` say gives.
163227
fn failed_build(build: &'static str, stdout: &'static str, stderr: &'static str) -> String {
164228
let root = Path::new(env!("CARGO_MANIFEST_DIR"))

0 commit comments

Comments
 (0)