// Dubbo implementation version, usually is jar version.
private static final String VERSION = getVersion(Version.class, "");
org.apache.dubbo.common.Version#getVersion(java.lang.Class<?>, java.lang.String)
public static String getVersion(Class<?> cls, String defaultVersion) {
try {
// find version info from MANIFEST.MF first
Package pkg = cls.getPackage();
String version = null;
if (pkg != null) {
version = pkg.getImplementationVersion();
if (!StringUtils.isEmpty(version)) {
return version;
}
version = pkg.getSpecificationVersion();
if (!StringUtils.isEmpty(version)) {
return version;
}
}
// guess version fro jar file name if nothing's found from MANIFEST.MF
CodeSource codeSource = cls.getProtectionDomain().getCodeSource();
if (codeSource == null) {
logger.info("No codeSource for class " + cls.getName() + " when getVersion, use default version " + defaultVersion);
return defaultVersion;
}
String file = codeSource.getLocation().getFile();
if (!StringUtils.isEmpty(file) && file.endsWith(".jar")) {
version = getFromFile(file);
}
// return default version if no version info is found
return StringUtils.isEmpty(version) ? defaultVersion : version;
} catch (Throwable e) {
// return default version when any exception is thrown
logger.error("return default version, ignore exception " + e.getMessage(), e);
return defaultVersion;
}
}
/**
* get version from file: path/to/group-module-x.y.z.jar, returns x.y.z
*/
private static String getFromFile(String file) {
// remove suffix ".jar": "path/to/group-module-x.y.z"
file = file.substring(0, file.length() - 4);
// remove path: "group-module-x.y.z"
int i = file.lastIndexOf('/');
if (i >= 0) {
file = file.substring(i + 1);
}
// remove group: "module-x.y.z"
i = file.indexOf("-");
if (i >= 0) {
file = file.substring(i + 1);
}
// remove module: "x.y.z"
while (file.length() > 0 && !Character.isDigit(file.charAt(0))) {
i = file.indexOf("-");
if (i >= 0) {
file = file.substring(i + 1);
} else {
break;
}
}
return file;
}