17
17
package org .springframework .boot .jarmode .layertools ;
18
18
19
19
import java .io .File ;
20
+ import java .io .IOException ;
21
+ import java .net .JarURLConnection ;
22
+ import java .net .URISyntaxException ;
23
+ import java .net .URL ;
24
+ import java .net .URLConnection ;
20
25
import java .nio .file .Paths ;
26
+ import java .security .CodeSource ;
27
+ import java .security .ProtectionDomain ;
28
+ import java .util .jar .JarFile ;
21
29
22
- import org .springframework .boot .system .ApplicationHome ;
23
30
import org .springframework .util .Assert ;
24
31
25
32
/**
@@ -39,7 +46,7 @@ class Context {
39
46
* Create a new {@link Context} instance.
40
47
*/
41
48
Context () {
42
- this (new ApplicationHome (). getSource (), Paths .get ("." ).toAbsolutePath ().normalize ().toFile ());
49
+ this (getSourceJarFile (), Paths .get ("." ).toAbsolutePath ().normalize ().toFile ());
43
50
}
44
51
45
52
/**
@@ -55,6 +62,39 @@ class Context {
55
62
this .relativeDir = deduceRelativeDir (jarFile .getParentFile (), this .workingDir );
56
63
}
57
64
65
+ private static File getSourceJarFile () {
66
+ try {
67
+ ProtectionDomain domain = Context .class .getProtectionDomain ();
68
+ CodeSource codeSource = (domain != null ) ? domain .getCodeSource () : null ;
69
+ URL location = (codeSource != null ) ? codeSource .getLocation () : null ;
70
+ File source = (location != null ) ? findSource (location ) : null ;
71
+ if (source != null && source .exists ()) {
72
+ return source .getAbsoluteFile ();
73
+ }
74
+ return null ;
75
+ }
76
+ catch (Exception ex ) {
77
+ return null ;
78
+ }
79
+ }
80
+
81
+ private static File findSource (URL location ) throws IOException , URISyntaxException {
82
+ URLConnection connection = location .openConnection ();
83
+ if (connection instanceof JarURLConnection ) {
84
+ return getRootJarFile (((JarURLConnection ) connection ).getJarFile ());
85
+ }
86
+ return new File (location .toURI ());
87
+ }
88
+
89
+ private static File getRootJarFile (JarFile jarFile ) {
90
+ String name = jarFile .getName ();
91
+ int separator = name .indexOf ("!/" );
92
+ if (separator > 0 ) {
93
+ name = name .substring (0 , separator );
94
+ }
95
+ return new File (name );
96
+ }
97
+
58
98
private String deduceRelativeDir (File sourceFolder , File workingDir ) {
59
99
String sourcePath = sourceFolder .getAbsolutePath ();
60
100
String workingPath = workingDir .getAbsolutePath ();
0 commit comments