Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Always use a URL stream handler for path-based resources #368

Merged
merged 2 commits into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
Expand Down Expand Up @@ -51,7 +52,9 @@ public URL url() {
URL url = this.url;
if (url == null) {
try {
url = this.url = path.toUri().toURL();
URI pathUri = path.toUri();
// todo Java 20+: URL.of(pathUri, new ResourceURLStreamHandler(this))
url = this.url = new URL(null, pathUri.toASCIIString(), new ResourceURLStreamHandler(this));
} catch (MalformedURLException e) {
throw new IllegalStateException("Unexpected URL problem", e);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package io.smallrye.common.resource;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assumptions.assumeTrue;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;

import org.junit.jupiter.api.Test;

public final class PathResourceLoaderTests {

@Test
public void testLoading() throws IOException, URISyntaxException {
URL myClass = PathResourceLoaderTests.class.getResource("PathResourceLoaderTests.class");
assumeTrue(myClass != null);
assumeTrue("file".equals(myClass.getProtocol()));
Path testClasses = Path.of(myClass.toURI()).getParent().getParent().getParent().getParent().getParent();
byte[] myClassBytes;
try (InputStream is = myClass.openStream()) {
assumeTrue(is != null);
myClassBytes = is.readAllBytes();
}
try (PathResourceLoader rl = new PathResourceLoader(testClasses)) {
Resource myClassRsrc = rl.findResource("io/smallrye/common/resource/PathResourceLoaderTests.class");
assertNotNull(myClassRsrc);
try (InputStream is = myClassRsrc.openStream()) {
assertArrayEquals(myClassBytes, is.readAllBytes());
}
URL url = myClassRsrc.url();
assertInstanceOf(ResourceURLConnection.class, url.openConnection());
}
}
}