소스 검색

Add a couple of methods to determine how an application was launched.

Change-Id: I20d3a7b908bbeae833ffffe0598b99bde47021c7
Reviewed-on: http://gerrit.dmdirc.com/4073
Reviewed-by: Chris Smith <chris@dmdirc.com>
Automatic-Compile: DMDirc Build Manager
changes/73/4073/3
Greg Holmes 9 년 전
부모
커밋
c0e532e93e
1개의 변경된 파일47개의 추가작업 그리고 0개의 파일을 삭제
  1. 47
    0
      src/com/dmdirc/util/io/FileUtils.java

+ 47
- 0
src/com/dmdirc/util/io/FileUtils.java 파일 보기

@@ -34,6 +34,8 @@ import java.nio.file.Files;
34 34
 import java.nio.file.Path;
35 35
 import java.nio.file.Paths;
36 36
 import java.nio.file.StandardCopyOption;
37
+import java.security.CodeSource;
38
+import java.security.ProtectionDomain;
37 39
 import java.util.HashMap;
38 40
 import java.util.Map;
39 41
 
@@ -46,6 +48,51 @@ public final class FileUtils {
46 48
         // Shouldn't be instansiated.
47 49
     }
48 50
 
51
+    /**
52
+     * Checks whether this application has been run from a jar or not.
53
+     *
54
+     * @param clazz Class used to locate the application
55
+     *
56
+     * @return true if the application was launched from a jar, false otherwise
57
+     *
58
+     * @throws IllegalStateException If the application path cannot be determined for any reason
59
+     */
60
+    public static boolean isRunningFromJar(final Class<?> clazz) throws IllegalStateException {
61
+        return getApplicationPath(clazz).getFileName().endsWith(".jar");
62
+    }
63
+
64
+    /**
65
+     * Returns the base location for the specified class, this is either the a jar or a folder
66
+     * depending on how the application was launched.
67
+     *
68
+     * This can fail for a number of reasons, it is not wholly reliable.
69
+     *
70
+     * @param clazz Class used to locate the application
71
+     *
72
+     * @return A {@link Path} to application location
73
+     *
74
+     * @throws IllegalStateException If the application path cannot be determined for any reason
75
+     */
76
+    public static Path getApplicationPath(final Class<?> clazz) throws IllegalStateException {
77
+        final ProtectionDomain pd;
78
+        try {
79
+            pd = clazz.getProtectionDomain();
80
+        } catch (SecurityException ex) {
81
+            throw new IllegalStateException("Unable to get protection domain", ex);
82
+        }
83
+        final CodeSource cs = pd.getCodeSource();
84
+        if (cs == null) {
85
+            throw new IllegalStateException("Unable to get the code source");
86
+        }
87
+        final URI uri;
88
+        try {
89
+            uri = cs.getLocation().toURI();
90
+        } catch (URISyntaxException ex) {
91
+            throw new IllegalStateException("Unable to convert location to URI", ex);
92
+        }
93
+        return Paths.get(uri);
94
+    }
95
+
49 96
     /**
50 97
      * Recursively copies the resources specified by the given URL to the destination folder.
51 98
      * Existing files will be replaced.

Loading…
취소
저장