in dbus-java/src/main/java/org/freedesktop/dbus/connections/SASL.java [94:146]
private void addCookie(String _context, String _id, long _timestamp, String _cookie) throws IOException {
String homedir = System.getProperty("user.home");
File keydir = new File(homedir + "/.dbus-keyrings/");
File cookiefile = new File(homedir + "/.dbus-keyrings/" + _context);
File lock = new File(homedir + "/.dbus-keyrings/" + _context + ".lock");
File temp = new File(homedir + "/.dbus-keyrings/" + _context + ".temp");
// ensure directory exists
if (!keydir.exists()) {
keydir.mkdirs();
}
// acquire lock
long start = System.currentTimeMillis();
while (!lock.createNewFile() && LOCK_TIMEOUT > (System.currentTimeMillis() - start)) {
;
}
// read old file
List<String> lines = new ArrayList<>();
if (cookiefile.exists()) {
BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(cookiefile)));
String s = null;
while (null != (s = r.readLine())) {
String[] line = s.split(" ");
long time = Long.parseLong(line[1]);
// expire stale cookies
if ((_timestamp - time) < COOKIE_TIMEOUT) {
lines.add(s);
}
}
r.close();
}
// add cookie
lines.add(_id + " " + _timestamp + " " + _cookie);
// write temp file
PrintWriter w = new PrintWriter(new FileOutputStream(temp));
for (String l : lines) {
w.println(l);
}
w.close();
// atomically move to old file
if (!temp.renameTo(cookiefile)) {
cookiefile.delete();
temp.renameTo(cookiefile);
}
// remove lock
lock.delete();
}