Skip to content

Commit 45a7f58

Browse files
committed
Don't trust the JVM to yield the code source path
JAVA-2494
1 parent 19bd544 commit 45a7f58

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

driver-core/src/main/com/mongodb/connection/ClientMetadataHelper.java

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import java.net.URL;
3131
import java.nio.charset.Charset;
3232
import java.security.CodeSource;
33+
import java.security.ProtectionDomain;
3334
import java.util.List;
3435
import java.util.jar.Attributes;
3536
import java.util.jar.Manifest;
@@ -106,11 +107,9 @@ private static boolean nameMatches(final String name, final String... prefixes)
106107

107108
private static String getDriverVersion() {
108109
String driverVersion = "unknown";
109-
110-
try {
111-
CodeSource codeSource = InternalStreamConnectionInitializer.class.getProtectionDomain().getCodeSource();
112-
if (codeSource != null) {
113-
String path = codeSource.getLocation().getPath();
110+
String path = getCodeSourcePath();
111+
if (path != null) {
112+
try {
114113
URL jarUrl = path.endsWith(".jar") ? new URL("jar:file:" + path + "!/") : null;
115114
if (jarUrl != null) {
116115
JarURLConnection jarURLConnection = (JarURLConnection) jarUrl.openConnection();
@@ -120,14 +119,28 @@ private static String getDriverVersion() {
120119
driverVersion = version;
121120
}
122121
}
122+
} catch (IOException e) {
123+
// do nothing
123124
}
124-
} catch (SecurityException e) {
125-
// do nothing
126-
} catch (IOException e) {
127-
// do nothing
128125
}
129126
return driverVersion;
130127
}
128+
129+
private static String getCodeSourcePath() {
130+
String path = null;
131+
ProtectionDomain protectionDomain = InternalStreamConnectionInitializer.class.getProtectionDomain();
132+
if (protectionDomain != null) {
133+
CodeSource codeSource = protectionDomain.getCodeSource();
134+
if (codeSource != null) {
135+
URL location = codeSource.getLocation();
136+
if (location != null) {
137+
path = location.getPath();
138+
}
139+
}
140+
}
141+
return path;
142+
}
143+
131144
static BsonDocument createClientMetadataDocument(final String applicationName) {
132145
return createClientMetadataDocument(applicationName, null);
133146
}

0 commit comments

Comments
 (0)