Skip to content

Commit

Permalink
Add resource loader method to get base URL
Browse files Browse the repository at this point in the history
This will allow for easier construction of protection domains for class loading, and may be useful in other contexts.
  • Loading branch information
dmlloyd committed Oct 21, 2024
1 parent 7785002 commit 8438233
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ public Resource findResource(final String path) {
}
}

public URL baseUrl() {
return base;
}

public void close() {
try {
jarFile.close();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import java.io.Closeable;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.Path;

Expand Down Expand Up @@ -42,6 +44,15 @@ public Resource findResource(final String path) {
return new PathResource(canon, base.resolve(canon));
}

public URL baseUrl() {
try {
return base.toUri().toURL();
} catch (MalformedURLException e) {
throw new UnsupportedOperationException(
"Base URL is not supported for this loader because the path does not have a valid URL", e);
}
}

public void close() {
Closeable c = this.c;
if (c != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.io.Closeable;
import java.io.IOException;
import java.net.URL;

/**
* A loader which can find resources by their path.
Expand All @@ -22,6 +23,13 @@ public interface ResourceLoader extends Closeable {
*/
Resource findResource(String path) throws IOException;

/**
* {@return the base URL for this loader}
*/
default URL baseUrl() {
throw new UnsupportedOperationException("Base URL is not supported by this resource loader");
}

/**
* Get a child resource loader for the given child path.
* This method always returns a resource loader, even if the path does not exist.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,8 @@ public Resource findResource(final String path) throws IOException {
String canon = ResourceUtils.canonicalizeRelativePath(path);
return new URLResource(canon, new URL(base, canon));
}

public URL baseUrl() {
return base;
}
}

0 comments on commit 8438233

Please sign in to comment.