From ddea6f3466e74158ff7119ce1ceaf09bf82b82c1 Mon Sep 17 00:00:00 2001 From: linghengqian Date: Fri, 16 Feb 2024 19:40:08 +0800 Subject: [PATCH] Fixes ClassPathURLLoader cannot find files under GraalVM Native Image --- .../type/classpath/ClassPathURLLoader.java | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/infra/url/type/classpath/src/main/java/org/apache/shardingsphere/infra/url/type/classpath/ClassPathURLLoader.java b/infra/url/type/classpath/src/main/java/org/apache/shardingsphere/infra/url/type/classpath/ClassPathURLLoader.java index 658c9dd8731210..a90894cc9efbff 100644 --- a/infra/url/type/classpath/src/main/java/org/apache/shardingsphere/infra/url/type/classpath/ClassPathURLLoader.java +++ b/infra/url/type/classpath/src/main/java/org/apache/shardingsphere/infra/url/type/classpath/ClassPathURLLoader.java @@ -20,10 +20,15 @@ import lombok.SneakyThrows; import org.apache.shardingsphere.infra.url.ShardingSphereURLLoader; -import java.io.File; import java.io.IOException; +import java.net.URI; import java.net.URISyntaxException; +import java.nio.file.FileSystem; +import java.nio.file.FileSystems; import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; @@ -36,12 +41,18 @@ public final class ClassPathURLLoader implements ShardingSphereURLLoader { @Override @SneakyThrows(IOException.class) public String load(final String configurationSubject, final Map parameters) { - return Files.readAllLines(getResourceFile(configurationSubject).toPath()).stream().collect(Collectors.joining(System.lineSeparator())); + if (null == System.getProperty("org.graalvm.nativeimage.imagecode") || !"runtime".equals(System.getProperty("org.graalvm.nativeimage.imagecode"))) { + return Files.readAllLines(getResourcePath(configurationSubject)).stream().collect(Collectors.joining(System.lineSeparator())); + } else { + try (FileSystem ignored = FileSystems.newFileSystem(URI.create("resource:/"), Collections.emptyMap())) { + return Files.readAllLines(getResourcePath(configurationSubject)).stream().collect(Collectors.joining(System.lineSeparator())); + } + } } @SneakyThrows(URISyntaxException.class) - private File getResourceFile(final String configurationSubject) { - return new File(Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource(configurationSubject)).toURI().getPath()); + private Path getResourcePath(final String configurationSubject) { + return Paths.get(Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource(configurationSubject)).toURI()); } @Override