create changelog entry
[debian/openrocket] / core / src / net / sf / openrocket / util / JarUtil.java
1 package net.sf.openrocket.util;
2
3 import java.io.File;
4 import java.net.URI;
5 import java.net.URISyntaxException;
6 import java.net.URL;
7 import java.security.CodeSource;
8
9 import net.sf.openrocket.database.Database;
10
11 public class JarUtil {
12
13         /**
14          * Return the a File object pointing to the JAR file that this class belongs to,
15          * or <code>null</code> if it cannot be found.
16          * 
17          * @return      a File object of the current Java archive, or <code>null</code>
18          */
19         public static File getCurrentJarFile() {
20                 // Find the jar file this class is contained in
21                 
22                 URL jarUrl = null;
23                 CodeSource codeSource;
24                 try {
25                         codeSource = new URL("rsrc:.").openConnection().getClass().getProtectionDomain().getCodeSource();
26                 } catch (Throwable e) {
27                         codeSource = Database.class.getProtectionDomain().getCodeSource();
28                 }
29                 
30                 if (codeSource != null)
31                         jarUrl = codeSource.getLocation();
32                 
33                 if (jarUrl == null) {
34                         return null;
35                 }
36                 
37                 File file = urlToFile(jarUrl);
38                 if (file.isFile())
39                         return file;
40                 return null;
41         }
42         
43         
44
45         public static File urlToFile(URL url) {
46                 URI uri;
47                 try {
48                         uri = url.toURI();
49                 } catch (URISyntaxException e) {
50                         try {
51                                 uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), 
52                                                 url.getPort(), url.getPath(), url.getQuery(), url.getRef());
53                         } catch (URISyntaxException e1) {
54                                 throw new IllegalArgumentException("Broken URL: " + url);
55                         }
56                 }
57                 return new File(uri);
58         }
59         
60         
61 }