X-Git-Url: https://git.pterodactylus.net/?p=jSite.git;a=blobdiff_plain;f=src%2Fmain%2Fjava%2Fde%2Ftodesbaum%2Fjsite%2Fmain%2FJarFileLocator.java;fp=src%2Fmain%2Fjava%2Fde%2Ftodesbaum%2Fjsite%2Fmain%2FJarFileLocator.java;h=da2e766da6200a384cc1c0c8fc284b2e15de1b51;hp=0000000000000000000000000000000000000000;hb=364353eaf23d55c9302d4f736c685d6b9fa59dcb;hpb=fd3bd2c16b6d9d617bb70478c11ac756a726999f diff --git a/src/main/java/de/todesbaum/jsite/main/JarFileLocator.java b/src/main/java/de/todesbaum/jsite/main/JarFileLocator.java new file mode 100644 index 0000000..da2e766 --- /dev/null +++ b/src/main/java/de/todesbaum/jsite/main/JarFileLocator.java @@ -0,0 +1,45 @@ +package de.todesbaum.jsite.main; + +import static java.util.Optional.empty; + +import java.io.File; +import java.io.UnsupportedEncodingException; +import java.net.URL; +import java.net.URLDecoder; +import java.util.Optional; + +/** + * Locates the JAR file used to load jSite in the filesystem. + */ +public interface JarFileLocator { + + Optional locateJarFile(); + + class DefaultJarFileLocator implements JarFileLocator { + + private final ClassLoader classLoader; + + public DefaultJarFileLocator(ClassLoader classLoader) { + this.classLoader = classLoader; + } + + @Override + public Optional locateJarFile() { + URL resourceUrl = classLoader.getResource(Main.class.getName().replace(".", "/") + ".class"); + if (resourceUrl == null) { + return empty(); + } + String resource = resourceUrl.toString(); + if (resource.startsWith("jar:")) { + try { + String jarFileLocation = URLDecoder.decode(resource.substring(9, resource.indexOf(".jar!") + 4), "UTF-8"); + return Optional.of(new File(jarFileLocation)); + } catch (UnsupportedEncodingException e) { + /* location is not available, ignore. */ + } + } + return empty(); + } + } + +}