in dbus-java/src/main/java/org/freedesktop/dbus/connections/impl/DBusConnection.java [216:286]
public static DBusConnection getConnection(DBusBusType _bustype, boolean _shared, int _timeout) throws DBusException {
switch (_bustype) {
case SYSTEM:
DBusConnection systemConnection = getConnection(() -> {
String bus = System.getenv("DBUS_SYSTEM_BUS_ADDRESS");
if (bus == null) {
bus = DEFAULT_SYSTEM_BUS_ADDRESS;
}
return bus;
}, true, _shared, _timeout);
return systemConnection;
case SESSION:
DBusConnection sessionConnection = getConnection(() -> {
String s = null;
// MacOS support: e.g DBUS_LAUNCHD_SESSION_BUS_SOCKET=/private/tmp/com.apple.launchd.4ojrKe6laI/unix_domain_listener
if (SystemUtil.isMacOs()) {
s = "unix:path=" + System.getenv("DBUS_LAUNCHD_SESSION_BUS_SOCKET");
} else { // all others (linux)
s = System.getenv("DBUS_SESSION_BUS_ADDRESS");
}
if (s == null) {
// address gets stashed in $HOME/.dbus/session-bus/`dbus-uuidgen --get`-`sed 's/:\(.\)\..*/\1/' <<<
// $DISPLAY`
String display = System.getenv("DISPLAY");
if (null == display) {
throw new RuntimeException("Cannot Resolve Session Bus Address");
}
if (!display.startsWith(":") && display.contains(":")) { // display seems to be a remote display
// (e.g. X forward through SSH)
display = display.substring(display.indexOf(':'));
}
try {
String uuid = getDbusMachineId();
String homedir = System.getProperty("user.home");
File addressfile = new File(homedir + "/.dbus/session-bus",
uuid + "-" + display.replaceAll(":([0-9]*)\\..*", "$1"));
if (!addressfile.exists()) {
throw new RuntimeException("Cannot Resolve Session Bus Address");
}
Properties readProperties = FileIoUtil.readProperties(addressfile);
String sessionAddress = readProperties.getProperty("DBUS_SESSION_BUS_ADDRESS");
if (StringUtil.isEmpty(sessionAddress)) {
throw new RuntimeException("Cannot Resolve Session Bus Address");
}
// sometimes (e.g. Ubuntu 18.04) the returned address is wrapped in single quotes ('), we have to remove them
if (sessionAddress.matches("^'[^']+'$")) {
sessionAddress = sessionAddress.replaceFirst("^'([^']+)'$", "$1");
}
return sessionAddress;
} catch (DBusException _ex) {
throw new RuntimeException("Cannot Resolve Session Bus Address", _ex);
}
}
return s;
}, true, _shared, _timeout);
return sessionConnection;
default:
throw new DBusException("Invalid Bus Type: " + _bustype);
}
}