-
Notifications
You must be signed in to change notification settings - Fork 6
Basic usage
When using this library all communication between your application and the systemd daemon is done via D-Bus. Thus at first a connection to either the system or the user (session) daemon is required. Both can be achieved via the 'Systemd' class.
The following code establishes a connection to the system daemon and disconnects at the end. An exception of type 'DBusException' is thrown in case the connection can't be established.
import de.thjom.java.systemd.Systemd;
import org.freedesktop.dbus.exceptions.DBusException;
Systemd systemd = new Systemd();
try {
systemd.connect();
}
catch (DBusException e) {
// ...
}
systemd.disconnect();Calling the constructor method with the DBusConnection.SYSTEM argument does the same:
import de.thjom.java.systemd.Systemd;
import org.freedesktop.dbus.DBusConnection;
import org.freedesktop.dbus.exceptions.DBusException;
Systemd systemd = new Systemd(DBusConnection.SYSTEM);
try {
systemd.connect();
}
catch (DBusException e) {
// ...
}
systemd.disconnect();Likewise it is possible to establish a connection to the user (session) daemon:
import de.thjom.java.systemd.Systemd;
import org.freedesktop.dbus.DBusConnection;
import org.freedesktop.dbus.exceptions.DBusException;
Systemd systemd = new Systemd(DBusConnection.SESSION);
try {
systemd.connect();
}
catch (DBusException e) {
// ...
}
systemd.disconnect();The 'Systemd' class implements the 'AutoClosable' interface hence it allows the try-with-resource pattern like shown below which omits the explicit call to disconnect from the bus.
Connection to system daemon:
import de.thjom.java.systemd.Systemd;
import org.freedesktop.dbus.exceptions.DBusException;
try (Systemd systemd = Systemd.createAndConnect()) {
// ...
}
catch (DBusException e) {
// ...
}Connection to user (session) daemon:
import de.thjom.java.systemd.Systemd;
import org.freedesktop.dbus.DBusConnection;
import org.freedesktop.dbus.exceptions.DBusException;
try (Systemd systemd = Systemd.createAndConnect(DBusConnection.SESSION)) {
// ...
}
catch (DBusException e) {
// ...
}