cdc.util.prefs.FilePreferencesFactory Maven / Gradle / Ivy
package cdc.util.prefs;
import java.io.File;
import java.util.prefs.Preferences;
import java.util.prefs.PreferencesFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* PreferencesFactory implementation that stores the preferences in a user-defined file.
*
* To use it, set the system property {@code java.util.prefs.PreferencesFactory} to
* {@code cdc.util.prefs.FilePreferencesFactory}.
*/
public class FilePreferencesFactory implements PreferencesFactory {
private static final Logger LOGGER = LogManager.getLogger(FilePreferencesFactory.class);
private static File preferencesFile;
private Preferences rootPreferences = null;
public FilePreferencesFactory() {
LOGGER.trace("()");
}
@Override
public Preferences systemRoot() {
return userRoot();
}
@Override
public Preferences userRoot() {
if (rootPreferences == null) {
LOGGER.trace("Instantiating root preferences");
rootPreferences = new FilePreferences(null, "");
}
return rootPreferences;
}
public static File getPreferencesFile() {
if (preferencesFile == null) {
final String filename = System.getProperty("user.home") + File.separator + ".fileprefs";
preferencesFile = new File(filename).getAbsoluteFile();
LOGGER.trace("Preferences file is " + preferencesFile);
}
return preferencesFile;
}
}