From 6b3bcd4fdffcc93761ba90e290bd6ef1a8248542 Mon Sep 17 00:00:00 2001 From: olim7t Date: Tue, 18 Aug 2020 07:54:14 -0700 Subject: [PATCH] Revisit resource loading code The previous version only worked when the CQL script was in a JAR file. The new version also works when it's loaded directly from the filesystem (for example when running the app from the IDE). --- .../java/com/datastax/examples/MapperApp.java | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/datastax/examples/MapperApp.java b/src/main/java/com/datastax/examples/MapperApp.java index efb4f2e..157b61e 100644 --- a/src/main/java/com/datastax/examples/MapperApp.java +++ b/src/main/java/com/datastax/examples/MapperApp.java @@ -29,6 +29,7 @@ import com.datastax.oss.driver.api.core.cql.SimpleStatement; import java.net.URI; +import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; @@ -37,9 +38,9 @@ import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Arrays; +import java.util.Collections; import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; @@ -178,10 +179,17 @@ private static void maybeCreateSchema(CqlSession session) throws Exception { } private static List getStatements(String fileName) throws Exception { - URI uri = Thread.currentThread().getContextClassLoader().getResource(fileName).toURI(); - FileSystems.newFileSystem(uri, Map.of("create", "true")); - Path path = Paths.get(uri); - + URI uri = MapperApp.class.getClassLoader().getResource(fileName).toURI(); + Path path; + if (uri.toString().contains("!")) { + // This happens when the file is in a packaged JAR + String[] parts = uri.toString().split("!"); + assert parts.length == 2; + FileSystem fs = FileSystems.newFileSystem(URI.create(parts[0]), Collections.emptyMap()); + path = fs.getPath(parts[1]); + } else { + path = Paths.get(uri); + } String contents = Files.readString(path); return Arrays.stream(contents.split(";")) .map(String::trim)