Skip to content

Commit

Permalink
unify URL parsing into base and path
Browse files Browse the repository at this point in the history
We use different approaches in different places to obtain base, path or both from a JAR URI (i.e. the part up to the separator denoting where the JAR resides versus the part after the separator denoting the path within the JAR file). We now unify this to make the connection clearer in code and use simple character splitting instead of Regex.

Signed-off-by: Peter Gafert <peter.gafert@tngtech.com>
  • Loading branch information
codecholeric committed Aug 8, 2023
1 parent 49215f8 commit 3334633
Showing 1 changed file with 19 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -271,8 +271,8 @@ private static URI newJarUri(URI uri) {
@Override
ClassFileSource asClassFileSource(ImportOptions importOptions) {
try {
String[] parts = uri.toString().split("!/", 2);
return new ClassFileSource.FromJar(new URL(parts[0] + "!/"), parts[1], importOptions);
ParsedUri parsedUri = ParsedUri.from(uri);
return new ClassFileSource.FromJar(new URL(parsedUri.base), parsedUri.path, importOptions);
} catch (IOException e) {
throw new LocationException(e);
}
Expand All @@ -298,7 +298,7 @@ private Optional<JarFile> getJarFile() {
// Note: We can't use a composed JAR URL like `jar:file:/path/to/file.jar!/com/example`, because opening the connection
// fails with an exception if the directory entry for this path is missing (which is possible, even if there is
// a class `com.example.SomeClass` in the JAR file).
String baseUri = uri.toString().replaceAll("!/.*", "!/");
String baseUri = ParsedUri.from(uri).base;
JarURLConnection jarUrlConnection = (JarURLConnection) new URL(baseUri).openConnection();
return Optional.of(jarUrlConnection.getJarFile());
} catch (IOException e) {
Expand All @@ -308,7 +308,7 @@ private Optional<JarFile> getJarFile() {

private Collection<NormalizedResourceName> readJarFileContent(JarFile jarFile) {
ImmutableList.Builder<NormalizedResourceName> result = ImmutableList.builder();
String prefix = uri.toString().replaceAll(".*!/", "");
String prefix = ParsedUri.from(uri).path;
result.addAll(readEntries(prefix, jarFile));
return result.build();
}
Expand All @@ -324,6 +324,21 @@ private List<NormalizedResourceName> readEntries(String prefix, JarFile jarFile)
}
return result;
}

private static class ParsedUri {
final String base;
final String path;

private ParsedUri(String base, String path) {
this.base = base;
this.path = path;
}

static ParsedUri from(NormalizedUri uri) {
String[] parts = uri.toString().split("!/", 2);
return new ParsedUri(parts[0] + "!/", parts[1]);
}
}
}

private static class FilePathLocation extends Location {
Expand Down

0 comments on commit 3334633

Please sign in to comment.