Fix bug when JAR file is stored in path with non-US-ASCII characters
[jSite.git] / src / main / java / de / todesbaum / jsite / main / JarFileLocator.java
1 package de.todesbaum.jsite.main;
2
3 import static java.util.Optional.empty;
4
5 import java.io.File;
6 import java.io.UnsupportedEncodingException;
7 import java.net.URL;
8 import java.net.URLDecoder;
9 import java.util.Optional;
10
11 /**
12  * Locates the JAR file used to load jSite in the filesystem.
13  */
14 public interface JarFileLocator {
15
16         Optional<File> locateJarFile();
17
18         class DefaultJarFileLocator implements JarFileLocator {
19
20                 private final ClassLoader classLoader;
21
22                 public DefaultJarFileLocator(ClassLoader classLoader) {
23                         this.classLoader = classLoader;
24                 }
25
26                 @Override
27                 public Optional<File> locateJarFile() {
28                         URL resourceUrl = classLoader.getResource(Main.class.getName().replace(".", "/") + ".class");
29                         if (resourceUrl == null) {
30                                 return empty();
31                         }
32                         String resource = resourceUrl.toString();
33                         if (resource.startsWith("jar:")) {
34                                 try {
35                                         String jarFileLocation = URLDecoder.decode(resource.substring(9, resource.indexOf(".jar!") + 4), "UTF-8");
36                                         return Optional.of(new File(jarFileLocation));
37                                 } catch (UnsupportedEncodingException e) {
38                                         /* location is not available, ignore. */
39                                 }
40                         }
41                         return empty();
42                 }
43         }
44
45 }