FileSystemPreferences.java revision 28
0N/A/*
1472N/A * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
0N/A * published by the Free Software Foundation. Sun designates this
0N/A * particular file as subject to the "Classpath" exception as provided
0N/A * by Sun in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
1472N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1472N/A *
1472N/A * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
0N/A * CA 95054 USA or visit www.sun.com if you need additional information or
0N/A * have any questions.
0N/A */
0N/A
0N/Apackage java.util.prefs;
0N/Aimport java.util.*;
0N/Aimport java.io.*;
0N/Aimport java.util.logging.Logger;
0N/Aimport java.security.AccessController;
0N/Aimport java.security.PrivilegedAction;
0N/Aimport java.security.PrivilegedExceptionAction;
0N/Aimport java.security.PrivilegedActionException;
0N/A
0N/A
0N/A/**
0N/A * Preferences implementation for Unix. Preferences are stored in the file
0N/A * system, with one directory per preferences node. All of the preferences
0N/A * at each node are stored in a single file. Atomic file system operations
0N/A * (e.g. File.renameTo) are used to ensure integrity. An in-memory cache of
0N/A * the "explored" portion of the tree is maintained for performance, and
0N/A * written back to the disk periodically. File-locking is used to ensure
0N/A * reasonable behavior when multiple VMs are running at the same time.
0N/A * (The file lock is obtained only for sync(), flush() and removeNode().)
0N/A *
0N/A * @author Josh Bloch
0N/A * @see Preferences
0N/A * @since 1.4
642N/A */
642N/Aclass FileSystemPreferences extends AbstractPreferences {
642N/A /**
642N/A * Sync interval in seconds.
0N/A */
0N/A private static final int SYNC_INTERVAL = Math.max(1,
0N/A Integer.parseInt(
0N/A AccessController.doPrivileged(
0N/A new sun.security.action.GetPropertyAction(
0N/A "java.util.prefs.syncInterval", "30"))));
0N/A
0N/A /**
0N/A * Returns logger for error messages. Backing store exceptions are logged at
642N/A * WARNING level.
0N/A */
0N/A private static Logger getLogger() {
0N/A return Logger.getLogger("java.util.prefs");
0N/A }
0N/A
0N/A /**
0N/A * Directory for system preferences.
0N/A */
0N/A private static File systemRootDir;
0N/A
0N/A /*
0N/A * Flag, indicating whether systemRoot directory is writable
0N/A */
0N/A private static boolean isSystemRootWritable;
0N/A
0N/A /**
0N/A * Directory for user preferences.
0N/A */
0N/A private static File userRootDir;
0N/A
0N/A /*
0N/A * Flag, indicating whether userRoot directory is writable
0N/A */
0N/A private static boolean isUserRootWritable;
0N/A
0N/A /**
0N/A * The user root.
0N/A */
0N/A static Preferences userRoot = null;
0N/A
0N/A static synchronized Preferences getUserRoot() {
0N/A if (userRoot == null) {
0N/A setupUserRoot();
0N/A userRoot = new FileSystemPreferences(true);
0N/A }
0N/A return userRoot;
0N/A }
0N/A
0N/A private static void setupUserRoot() {
0N/A AccessController.doPrivileged(new PrivilegedAction<Void>() {
0N/A public Void run() {
0N/A userRootDir =
0N/A new File(System.getProperty("java.util.prefs.userRoot",
0N/A System.getProperty("user.home")), ".java/.userPrefs");
0N/A // Attempt to create root dir if it does not yet exist.
0N/A if (!userRootDir.exists()) {
0N/A if (userRootDir.mkdirs()) {
0N/A try {
0N/A chmod(userRootDir.getCanonicalPath(), USER_RWX);
0N/A } catch (IOException e) {
0N/A getLogger().warning("Could not change permissions" +
0N/A " on userRoot directory. ");
113N/A }
0N/A getLogger().info("Created user preferences directory.");
2062N/A }
2062N/A else
0N/A getLogger().warning("Couldn't create user preferences" +
0N/A " directory. User preferences are unusable.");
0N/A }
0N/A isUserRootWritable = userRootDir.canWrite();
0N/A String USER_NAME = System.getProperty("user.name");
0N/A userLockFile = new File (userRootDir,".user.lock." + USER_NAME);
0N/A userRootModFile = new File (userRootDir,
0N/A ".userRootModFile." + USER_NAME);
0N/A if (!userRootModFile.exists())
0N/A try {
0N/A // create if does not exist.
0N/A userRootModFile.createNewFile();
0N/A // Only user can read/write userRootModFile.
0N/A int result = chmod(userRootModFile.getCanonicalPath(),
0N/A USER_READ_WRITE);
0N/A if (result !=0)
0N/A getLogger().warning("Problem creating userRoot " +
0N/A "mod file. Chmod failed on " +
0N/A userRootModFile.getCanonicalPath() +
0N/A " Unix error code " + result);
642N/A } catch (IOException e) {
642N/A getLogger().warning(e.toString());
642N/A }
0N/A userRootModTime = userRootModFile.lastModified();
0N/A return null;
0N/A }
0N/A });
0N/A }
0N/A
0N/A
0N/A /**
0N/A * The system root.
0N/A */
0N/A static Preferences systemRoot;
0N/A
0N/A static synchronized Preferences getSystemRoot() {
0N/A if (systemRoot == null) {
0N/A setupSystemRoot();
0N/A systemRoot = new FileSystemPreferences(false);
0N/A }
0N/A return systemRoot;
0N/A }
0N/A
0N/A private static void setupSystemRoot() {
642N/A AccessController.doPrivileged(new PrivilegedAction<Void>() {
642N/A public Void run() {
642N/A String systemPrefsDirName =
642N/A System.getProperty("java.util.prefs.systemRoot","/etc/.java");
642N/A systemRootDir =
642N/A new File(systemPrefsDirName, ".systemPrefs");
642N/A // Attempt to create root dir if it does not yet exist.
642N/A if (!systemRootDir.exists()) {
642N/A // system root does not exist in /etc/.java
642N/A // Switching to java.home
642N/A systemRootDir =
0N/A new File(System.getProperty("java.home"),
0N/A ".systemPrefs");
0N/A if (!systemRootDir.exists()) {
0N/A if (systemRootDir.mkdirs()) {
0N/A getLogger().info(
0N/A "Created system preferences directory "
0N/A + "in java.home.");
0N/A try {
0N/A chmod(systemRootDir.getCanonicalPath(),
0N/A USER_RWX_ALL_RX);
0N/A } catch (IOException e) {
0N/A }
0N/A } else {
0N/A getLogger().warning("Could not create "
0N/A + "system preferences directory. System "
0N/A + "preferences are unusable.");
0N/A }
0N/A }
0N/A }
0N/A isSystemRootWritable = systemRootDir.canWrite();
0N/A systemLockFile = new File(systemRootDir, ".system.lock");
0N/A systemRootModFile =
0N/A new File (systemRootDir,".systemRootModFile");
0N/A if (!systemRootModFile.exists() && isSystemRootWritable)
0N/A try {
0N/A // create if does not exist.
0N/A systemRootModFile.createNewFile();
0N/A int result = chmod(systemRootModFile.getCanonicalPath(),
0N/A USER_RW_ALL_READ);
0N/A if (result !=0)
0N/A getLogger().warning("Chmod failed on " +
0N/A systemRootModFile.getCanonicalPath() +
0N/A " Unix error code " + result);
0N/A } catch (IOException e) { getLogger().warning(e.toString());
0N/A }
0N/A systemRootModTime = systemRootModFile.lastModified();
0N/A return null;
0N/A }
0N/A });
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Unix user write/read permission
0N/A */
0N/A private static final int USER_READ_WRITE = 0600;
0N/A
0N/A private static final int USER_RW_ALL_READ = 0644;
0N/A
0N/A
0N/A private static final int USER_RWX_ALL_RX = 0755;
0N/A
0N/A private static final int USER_RWX = 0700;
0N/A
0N/A /**
0N/A * The lock file for the user tree.
0N/A */
0N/A static File userLockFile;
0N/A
0N/A
0N/A
0N/A /**
0N/A * The lock file for the system tree.
0N/A */
0N/A static File systemLockFile;
0N/A
0N/A /**
0N/A * Unix lock handle for userRoot.
0N/A * Zero, if unlocked.
0N/A */
0N/A
0N/A private static int userRootLockHandle = 0;
0N/A
0N/A /**
0N/A * Unix lock handle for systemRoot.
0N/A * Zero, if unlocked.
0N/A */
0N/A
0N/A private static int systemRootLockHandle = 0;
0N/A
0N/A /**
0N/A * The directory representing this preference node. There is no guarantee
0N/A * that this directory exits, as another VM can delete it at any time
0N/A * that it (the other VM) holds the file-lock. While the root node cannot
0N/A * be deleted, it may not yet have been created, or the underlying
0N/A * directory could have been deleted accidentally.
0N/A */
0N/A private final File dir;
0N/A
0N/A /**
0N/A * The file representing this preference node's preferences.
0N/A * The file format is undocumented, and subject to change
0N/A * from release to release, but I'm sure that you can figure
0N/A * it out if you try real hard.
0N/A */
0N/A private final File prefsFile;
0N/A
0N/A /**
0N/A * A temporary file used for saving changes to preferences. As part of
0N/A * the sync operation, changes are first saved into this file, and then
0N/A * atomically renamed to prefsFile. This results in an atomic state
0N/A * change from one valid set of preferences to another. The
0N/A * the file-lock is held for the duration of this transformation.
0N/A */
0N/A private final File tmpFile;
0N/A
0N/A /**
0N/A * File, which keeps track of global modifications of userRoot.
0N/A */
0N/A private static File userRootModFile;
0N/A
0N/A /**
0N/A * Flag, which indicated whether userRoot was modified by another VM
0N/A */
0N/A private static boolean isUserRootModified = false;
0N/A
0N/A /**
0N/A * Keeps track of userRoot modification time. This time is reset to
0N/A * zero after UNIX reboot, and is increased by 1 second each time
0N/A * userRoot is modified.
0N/A */
0N/A private static long userRootModTime;
0N/A
0N/A
0N/A /*
0N/A * File, which keeps track of global modifications of systemRoot
0N/A */
0N/A private static File systemRootModFile;
0N/A /*
0N/A * Flag, which indicates whether systemRoot was modified by another VM
0N/A */
0N/A private static boolean isSystemRootModified = false;
0N/A
0N/A /**
0N/A * Keeps track of systemRoot modification time. This time is reset to
0N/A * zero after system reboot, and is increased by 1 second each time
0N/A * systemRoot is modified.
0N/A */
0N/A private static long systemRootModTime;
0N/A
0N/A /**
642N/A * Locally cached preferences for this node (includes uncommitted
0N/A * changes). This map is initialized with from disk when the first get or
0N/A * put operation occurs on this node. It is synchronized with the
0N/A * corresponding disk file (prefsFile) by the sync operation. The initial
113N/A * value is read *without* acquiring the file-lock.
113N/A */
113N/A private Map<String, String> prefsCache = null;
113N/A
113N/A /**
113N/A * The last modification time of the file backing this node at the time
113N/A * that prefCache was last synchronized (or initially read). This
642N/A * value is set *before* reading the file, so it's conservative; the
113N/A * actual timestamp could be (slightly) higher. A value of zero indicates
113N/A * that we were unable to initialize prefsCache from the disk, or
113N/A * have not yet attempted to do so. (If prefsCache is non-null, it
113N/A * indicates the former; if it's null, the latter.)
113N/A */
113N/A private long lastSyncTime = 0;
113N/A
642N/A /**
642N/A * Unix error code for locked file.
0N/A */
0N/A private static final int EAGAIN = 11;
0N/A
0N/A /**
0N/A * Unix error code for denied access.
0N/A */
0N/A private static final int EACCES = 13;
0N/A
0N/A /* Used to interpret results of native functions */
0N/A private static final int LOCK_HANDLE = 0;
0N/A private static final int ERROR_CODE = 1;
0N/A
0N/A /**
0N/A * A list of all uncommitted preference changes. The elements in this
0N/A * list are of type PrefChange. If this node is concurrently modified on
0N/A * disk by another VM, the two sets of changes are merged when this node
0N/A * is sync'ed by overwriting our prefsCache with the preference map last
0N/A * written out to disk (by the other VM), and then replaying this change
0N/A * log against that map. The resulting map is then written back
0N/A * to the disk.
0N/A */
0N/A final List<Change> changeLog = new ArrayList<Change>();
0N/A
0N/A /**
0N/A * Represents a change to a preference.
0N/A */
0N/A private abstract class Change {
0N/A /**
0N/A * Reapplies the change to prefsCache.
0N/A */
0N/A abstract void replay();
0N/A };
0N/A
2062N/A /**
0N/A * Represents a preference put.
0N/A */
0N/A private class Put extends Change {
0N/A String key, value;
0N/A
2062N/A Put(String key, String value) {
0N/A this.key = key;
0N/A this.value = value;
0N/A }
0N/A
0N/A void replay() {
0N/A prefsCache.put(key, value);
0N/A }
0N/A }
2062N/A
0N/A /**
0N/A * Represents a preference remove.
0N/A */
0N/A private class Remove extends Change {
0N/A String key;
0N/A
0N/A Remove(String key) {
0N/A this.key = key;
2062N/A }
0N/A
0N/A void replay() {
0N/A prefsCache.remove(key);
0N/A }
0N/A }
0N/A
0N/A /**
2062N/A * Represents the creation of this node.
0N/A */
0N/A private class NodeCreate extends Change {
0N/A /**
2062N/A * Performs no action, but the presence of this object in changeLog
0N/A * will force the node and its ancestors to be made permanent at the
0N/A * next sync.
0N/A */
0N/A void replay() {
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * NodeCreate object for this node.
0N/A */
0N/A NodeCreate nodeCreate = null;
0N/A
0N/A /**
0N/A * Replay changeLog against prefsCache.
0N/A */
0N/A private void replayChanges() {
0N/A for (int i = 0, n = changeLog.size(); i<n; i++)
0N/A changeLog.get(i).replay();
0N/A }
0N/A
0N/A private static Timer syncTimer = new Timer(true); // Daemon Thread
0N/A
0N/A static {
0N/A // Add periodic timer task to periodically sync cached prefs
0N/A syncTimer.schedule(new TimerTask() {
0N/A public void run() {
0N/A syncWorld();
0N/A }
0N/A }, SYNC_INTERVAL*1000, SYNC_INTERVAL*1000);
0N/A
0N/A // Add shutdown hook to flush cached prefs on normal termination
0N/A AccessController.doPrivileged(new PrivilegedAction<Void>() {
0N/A public Void run() {
0N/A Runtime.getRuntime().addShutdownHook(new Thread() {
0N/A public void run() {
0N/A syncTimer.cancel();
0N/A syncWorld();
0N/A }
0N/A });
0N/A return null;
0N/A }
0N/A });
}
private static void syncWorld() {
/*
* Synchronization necessary because userRoot and systemRoot are
* lazily initialized.
*/
Preferences userRt;
Preferences systemRt;
synchronized(FileSystemPreferences.class) {
userRt = userRoot;
systemRt = systemRoot;
}
try {
if (userRt != null)
userRt.flush();
} catch(BackingStoreException e) {
getLogger().warning("Couldn't flush user prefs: " + e);
}
try {
if (systemRt != null)
systemRt.flush();
} catch(BackingStoreException e) {
getLogger().warning("Couldn't flush system prefs: " + e);
}
}
private final boolean isUserNode;
/**
* Special constructor for roots (both user and system). This constructor
* will only be called twice, by the static initializer.
*/
private FileSystemPreferences(boolean user) {
super(null, "");
isUserNode = user;
dir = (user ? userRootDir: systemRootDir);
prefsFile = new File(dir, "prefs.xml");
tmpFile = new File(dir, "prefs.tmp");
}
/**
* Construct a new FileSystemPreferences instance with the specified
* parent node and name. This constructor, called from childSpi,
* is used to make every node except for the two //roots.
*/
private FileSystemPreferences(FileSystemPreferences parent, String name) {
super(parent, name);
isUserNode = parent.isUserNode;
dir = new File(parent.dir, dirName(name));
prefsFile = new File(dir, "prefs.xml");
tmpFile = new File(dir, "prefs.tmp");
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
newNode = !dir.exists();
return null;
}
});
if (newNode) {
// These 2 things guarantee node will get wrtten at next flush/sync
prefsCache = new TreeMap<String, String>();
nodeCreate = new NodeCreate();
changeLog.add(nodeCreate);
}
}
public boolean isUserNode() {
return isUserNode;
}
protected void putSpi(String key, String value) {
initCacheIfNecessary();
changeLog.add(new Put(key, value));
prefsCache.put(key, value);
}
protected String getSpi(String key) {
initCacheIfNecessary();
return prefsCache.get(key);
}
protected void removeSpi(String key) {
initCacheIfNecessary();
changeLog.add(new Remove(key));
prefsCache.remove(key);
}
/**
* Initialize prefsCache if it has yet to be initialized. When this method
* returns, prefsCache will be non-null. If the data was successfully
* read from the file, lastSyncTime will be updated. If prefsCache was
* null, but it was impossible to read the file (because it didn't
* exist or for any other reason) prefsCache will be initialized to an
* empty, modifiable Map, and lastSyncTime remain zero.
*/
private void initCacheIfNecessary() {
if (prefsCache != null)
return;
try {
loadCache();
} catch(Exception e) {
// assert lastSyncTime == 0;
prefsCache = new TreeMap<String, String>();
}
}
/**
* Attempt to load prefsCache from the backing store. If the attempt
* succeeds, lastSyncTime will be updated (the new value will typically
* correspond to the data loaded into the map, but it may be less,
* if another VM is updating this node concurrently). If the attempt
* fails, a BackingStoreException is thrown and both prefsCache and
* lastSyncTime are unaffected by the call.
*/
private void loadCache() throws BackingStoreException {
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>() {
public Void run() throws BackingStoreException {
Map<String, String> m = new TreeMap<String, String>();
long newLastSyncTime = 0;
try {
newLastSyncTime = prefsFile.lastModified();
FileInputStream fis = new FileInputStream(prefsFile);
XmlSupport.importMap(fis, m);
fis.close();
} catch(Exception e) {
if (e instanceof InvalidPreferencesFormatException) {
getLogger().warning("Invalid preferences format in "
+ prefsFile.getPath());
prefsFile.renameTo( new File(
prefsFile.getParentFile(),
"IncorrectFormatPrefs.xml"));
m = new TreeMap<String, String>();
} else if (e instanceof FileNotFoundException) {
getLogger().warning("Prefs file removed in background "
+ prefsFile.getPath());
} else {
throw new BackingStoreException(e);
}
}
// Attempt succeeded; update state
prefsCache = m;
lastSyncTime = newLastSyncTime;
return null;
}
});
} catch (PrivilegedActionException e) {
throw (BackingStoreException) e.getException();
}
}
/**
* Attempt to write back prefsCache to the backing store. If the attempt
* succeeds, lastSyncTime will be updated (the new value will correspond
* exactly to the data thust written back, as we hold the file lock, which
* prevents a concurrent write. If the attempt fails, a
* BackingStoreException is thrown and both the backing store (prefsFile)
* and lastSyncTime will be unaffected by this call. This call will
* NEVER leave prefsFile in a corrupt state.
*/
private void writeBackCache() throws BackingStoreException {
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>() {
public Void run() throws BackingStoreException {
try {
if (!dir.exists() && !dir.mkdirs())
throw new BackingStoreException(dir +
" create failed.");
FileOutputStream fos = new FileOutputStream(tmpFile);
XmlSupport.exportMap(fos, prefsCache);
fos.close();
if (!tmpFile.renameTo(prefsFile))
throw new BackingStoreException("Can't rename " +
tmpFile + " to " + prefsFile);
} catch(Exception e) {
if (e instanceof BackingStoreException)
throw (BackingStoreException)e;
throw new BackingStoreException(e);
}
return null;
}
});
} catch (PrivilegedActionException e) {
throw (BackingStoreException) e.getException();
}
}
protected String[] keysSpi() {
initCacheIfNecessary();
return prefsCache.keySet().toArray(new String[prefsCache.size()]);
}
protected String[] childrenNamesSpi() {
return AccessController.doPrivileged(
new PrivilegedAction<String[]>() {
public String[] run() {
List<String> result = new ArrayList<String>();
File[] dirContents = dir.listFiles();
if (dirContents != null) {
for (int i = 0; i < dirContents.length; i++)
if (dirContents[i].isDirectory())
result.add(nodeName(dirContents[i].getName()));
}
return result.toArray(EMPTY_STRING_ARRAY);
}
});
}
private static final String[] EMPTY_STRING_ARRAY = new String[0];
protected AbstractPreferences childSpi(String name) {
return new FileSystemPreferences(this, name);
}
public void removeNode() throws BackingStoreException {
synchronized (isUserNode()? userLockFile: systemLockFile) {
// to remove a node we need an exclusive lock
if (!lockFile(false))
throw(new BackingStoreException("Couldn't get file lock."));
try {
super.removeNode();
} finally {
unlockFile();
}
}
}
/**
* Called with file lock held (in addition to node locks).
*/
protected void removeNodeSpi() throws BackingStoreException {
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>() {
public Void run() throws BackingStoreException {
if (changeLog.contains(nodeCreate)) {
changeLog.remove(nodeCreate);
nodeCreate = null;
return null;
}
if (!dir.exists())
return null;
prefsFile.delete();
tmpFile.delete();
// dir should be empty now. If it's not, empty it
File[] junk = dir.listFiles();
if (junk.length != 0) {
getLogger().warning(
"Found extraneous files when removing node: "
+ Arrays.asList(junk));
for (int i=0; i<junk.length; i++)
junk[i].delete();
}
if (!dir.delete())
throw new BackingStoreException("Couldn't delete dir: "
+ dir);
return null;
}
});
} catch (PrivilegedActionException e) {
throw (BackingStoreException) e.getException();
}
}
public synchronized void sync() throws BackingStoreException {
boolean userNode = isUserNode();
boolean shared;
if (userNode) {
shared = false; /* use exclusive lock for user prefs */
} else {
/* if can write to system root, use exclusive lock.
otherwise use shared lock. */
shared = !isSystemRootWritable;
}
synchronized (isUserNode()? userLockFile:systemLockFile) {
if (!lockFile(shared))
throw(new BackingStoreException("Couldn't get file lock."));
final Long newModTime =
AccessController.doPrivileged(
new PrivilegedAction<Long>() {
public Long run() {
long nmt;
if (isUserNode()) {
nmt = userRootModFile.lastModified();
isUserRootModified = userRootModTime == nmt;
} else {
nmt = systemRootModFile.lastModified();
isSystemRootModified = systemRootModTime == nmt;
}
return new Long(nmt);
}
});
try {
super.sync();
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
if (isUserNode()) {
userRootModTime = newModTime.longValue() + 1000;
userRootModFile.setLastModified(userRootModTime);
} else {
systemRootModTime = newModTime.longValue() + 1000;
systemRootModFile.setLastModified(systemRootModTime);
}
return null;
}
});
} finally {
unlockFile();
}
}
}
protected void syncSpi() throws BackingStoreException {
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>() {
public Void run() throws BackingStoreException {
syncSpiPrivileged();
return null;
}
});
} catch (PrivilegedActionException e) {
throw (BackingStoreException) e.getException();
}
}
private void syncSpiPrivileged() throws BackingStoreException {
if (isRemoved())
throw new IllegalStateException("Node has been removed");
if (prefsCache == null)
return; // We've never been used, don't bother syncing
long lastModifiedTime;
if ((isUserNode() ? isUserRootModified : isSystemRootModified)) {
lastModifiedTime = prefsFile.lastModified();
if (lastModifiedTime != lastSyncTime) {
// Prefs at this node were externally modified; read in node and
// playback any local mods since last sync
loadCache();
replayChanges();
lastSyncTime = lastModifiedTime;
}
} else if (lastSyncTime != 0 && !dir.exists()) {
// This node was removed in the background. Playback any changes
// against a virgin (empty) Map.
prefsCache = new TreeMap<String, String>();
replayChanges();
}
if (!changeLog.isEmpty()) {
writeBackCache(); // Creates directory & file if necessary
/*
* Attempt succeeded; it's barely possible that the call to
* lastModified might fail (i.e., return 0), but this would not
* be a disaster, as lastSyncTime is allowed to lag.
*/
lastModifiedTime = prefsFile.lastModified();
/* If lastSyncTime did not change, or went back
* increment by 1 second. Since we hold the lock
* lastSyncTime always monotonically encreases in the
* atomic sense.
*/
if (lastSyncTime <= lastModifiedTime) {
lastSyncTime = lastModifiedTime + 1000;
prefsFile.setLastModified(lastSyncTime);
}
changeLog.clear();
}
}
public void flush() throws BackingStoreException {
if (isRemoved())
return;
sync();
}
protected void flushSpi() throws BackingStoreException {
// assert false;
}
/**
* Returns true if the specified character is appropriate for use in
* Unix directory names. A character is appropriate if it's a printable
* ASCII character (> 0x1f && < 0x7f) and unequal to slash ('/', 0x2f),
* dot ('.', 0x2e), or underscore ('_', 0x5f).
*/
private static boolean isDirChar(char ch) {
return ch > 0x1f && ch < 0x7f && ch != '/' && ch != '.' && ch != '_';
}
/**
* Returns the directory name corresponding to the specified node name.
* Generally, this is just the node name. If the node name includes
* inappropriate characters (as per isDirChar) it is translated to Base64.
* with the underscore character ('_', 0x5f) prepended.
*/
private static String dirName(String nodeName) {
for (int i=0, n=nodeName.length(); i < n; i++)
if (!isDirChar(nodeName.charAt(i)))
return "_" + Base64.byteArrayToAltBase64(byteArray(nodeName));
return nodeName;
}
/**
* Translate a string into a byte array by translating each character
* into two bytes, high-byte first ("big-endian").
*/
private static byte[] byteArray(String s) {
int len = s.length();
byte[] result = new byte[2*len];
for (int i=0, j=0; i<len; i++) {
char c = s.charAt(i);
result[j++] = (byte) (c>>8);
result[j++] = (byte) c;
}
return result;
}
/**
* Returns the node name corresponding to the specified directory name.
* (Inverts the transformation of dirName(String).
*/
private static String nodeName(String dirName) {
if (dirName.charAt(0) != '_')
return dirName;
byte a[] = Base64.altBase64ToByteArray(dirName.substring(1));
StringBuffer result = new StringBuffer(a.length/2);
for (int i = 0; i < a.length; ) {
int highByte = a[i++] & 0xff;
int lowByte = a[i++] & 0xff;
result.append((char) ((highByte << 8) | lowByte));
}
return result.toString();
}
/**
* Try to acquire the appropriate file lock (user or system). If
* the initial attempt fails, several more attempts are made using
* an exponential backoff strategy. If all attempts fail, this method
* returns false.
* @throws SecurityException if file access denied.
*/
private boolean lockFile(boolean shared) throws SecurityException{
boolean usernode = isUserNode();
int[] result;
int errorCode = 0;
File lockFile = (usernode ? userLockFile : systemLockFile);
long sleepTime = INIT_SLEEP_TIME;
for (int i = 0; i < MAX_ATTEMPTS; i++) {
try {
int perm = (usernode? USER_READ_WRITE: USER_RW_ALL_READ);
result = lockFile0(lockFile.getCanonicalPath(), perm, shared);
errorCode = result[ERROR_CODE];
if (result[LOCK_HANDLE] != 0) {
if (usernode) {
userRootLockHandle = result[LOCK_HANDLE];
} else {
systemRootLockHandle = result[LOCK_HANDLE];
}
return true;
}
} catch(IOException e) {
// // If at first, you don't succeed...
}
try {
Thread.sleep(sleepTime);
} catch(InterruptedException e) {
checkLockFile0ErrorCode(errorCode);
return false;
}
sleepTime *= 2;
}
checkLockFile0ErrorCode(errorCode);
return false;
}
/**
* Checks if unlockFile0() returned an error. Throws a SecurityException,
* if access denied. Logs a warning otherwise.
*/
private void checkLockFile0ErrorCode (int errorCode)
throws SecurityException {
if (errorCode == EACCES)
throw new SecurityException("Could not lock " +
(isUserNode()? "User prefs." : "System prefs.") +
" Lock file access denied.");
if (errorCode != EAGAIN)
getLogger().warning("Could not lock " +
(isUserNode()? "User prefs. " : "System prefs.") +
" Unix error code " + errorCode + ".");
}
/**
* Locks file using UNIX file locking.
* @param fileName Absolute file name of the lock file.
* @return Returns a lock handle, used to unlock the file.
*/
private static native int[]
lockFile0(String fileName, int permission, boolean shared);
/**
* Unlocks file previously locked by lockFile0().
* @param lockHandle Handle to the file lock.
* @return Returns zero if OK, UNIX error code if failure.
*/
private static native int unlockFile0(int lockHandle);
/**
* Changes UNIX file permissions.
*/
private static native int chmod(String fileName, int permission);
/**
* Initial time between lock attempts, in ms. The time is doubled
* after each failing attempt (except the first).
*/
private static int INIT_SLEEP_TIME = 50;
/**
* Maximum number of lock attempts.
*/
private static int MAX_ATTEMPTS = 5;
/**
* Release the the appropriate file lock (user or system).
* @throws SecurityException if file access denied.
*/
private void unlockFile() {
int result;
boolean usernode = isUserNode();
File lockFile = (usernode ? userLockFile : systemLockFile);
int lockHandle = ( usernode ? userRootLockHandle:systemRootLockHandle);
if (lockHandle == 0) {
getLogger().warning("Unlock: zero lockHandle for " +
(usernode ? "user":"system") + " preferences.)");
return;
}
result = unlockFile0(lockHandle);
if (result != 0) {
getLogger().warning("Could not drop file-lock on " +
(isUserNode() ? "user" : "system") + " preferences." +
" Unix error code " + result + ".");
if (result == EACCES)
throw new SecurityException("Could not unlock" +
(isUserNode()? "User prefs." : "System prefs.") +
" Lock file access denied.");
}
if (isUserNode()) {
userRootLockHandle = 0;
} else {
systemRootLockHandle = 0;
}
}
}