下面列出了怎么用java.util.prefs.BackingStoreException的API类实例代码及写法,或者点击链接到github查看源代码。
private static void addToMenu(JMenu menu, Preferences prefs) throws BackingStoreException {
if (debug)
System.out.println(" addMenu " + prefs.name());
String[] keys = prefs.keys();
for (String key : keys) {
boolean bval = prefs.getBoolean(key, false);
String fullname = prefs.absolutePath() + "/" + key;
menu.add(new DebugMenuItem(fullname, key, bval)); // menu leaf
if (debug)
System.out.println(" leaf= <" + key + "><" + fullname + ">");
}
String[] kidName = prefs.childrenNames();
for (String aKidName : kidName) {
Preferences pkid = prefs.node(aKidName);
JMenu subMenu = new JMenu(pkid.name());
menu.add(subMenu);
addToMenu(subMenu, pkid);
}
}
protected static String sanitizeNameAndUniquifyForId(String name) {
String sanitizedId = name.replaceAll("[^a-zA-Z0-9_.-]+", "_");
Set<String> existing;
try {
existing = new HashSet<String>(Arrays.asList(NODE.childrenNames()));
} catch (BackingStoreException x) {
Exceptions.printStackTrace(x);
return sanitizedId;
}
if (existing.contains(sanitizedId)) {
for (int i = 2; ; i++) {
String candidate = sanitizedId + "_" + i;
if (!existing.contains(candidate)) {
return candidate;
}
}
} else {
return sanitizedId;
}
}
@Override
public Stream<EntityState> entityStates( final ModuleDescriptor module )
{
UsecaseBuilder builder = UsecaseBuilder.buildUsecase( "polygene.entitystore.preferences.visit" );
Usecase visitUsecase = builder.withMetaInfo( CacheOptions.NEVER ).newUsecase();
EntityStoreUnitOfWork uow = newUnitOfWork( module, visitUsecase, SystemTime.now() );
try
{
return Stream.of( root.childrenNames() )
.map( EntityReference::parseEntityReference )
.map( ref -> uow.entityStateOf( module, ref ) )
.onClose( uow::discard );
}
catch( BackingStoreException e )
{
throw new EntityStoreException( e );
}
}
private String findPreferredInputMethodNode(Locale locale) {
if (userRoot == null) {
return null;
}
// create locale node relative path
String nodePath = preferredIMNode + "/" + createLocalePath(locale);
// look for the descriptor
while (!nodePath.equals(preferredIMNode)) {
try {
if (userRoot.nodeExists(nodePath)) {
if (readPreferredInputMethod(nodePath) != null) {
return nodePath;
}
}
} catch (BackingStoreException bse) {
}
// search at parent's node
nodePath = nodePath.substring(0, nodePath.lastIndexOf('/'));
}
return null;
}
protected void disable() {
// See if we can grab the text
String text = console.getInputArea().getText();
if( text.trim().length() > 0 ) {
log.info("Saving for next time:\n" + text);
// Save it for next time
Preferences prefs = Preferences.userNodeForPackage(getClass());
prefs.put(PREF_LAST_SCRIPT, text);
try {
prefs.flush();
} catch( BackingStoreException e ) {
log.warn( "Error saving last script to preferences", e );
}
}
if( frame != null && frame.isDisplayable() ) {
console.exit(null);
}
}
private String findPreferredInputMethodNode(Locale locale) {
if (userRoot == null) {
return null;
}
// create locale node relative path
String nodePath = preferredIMNode + "/" + createLocalePath(locale);
// look for the descriptor
while (!nodePath.equals(preferredIMNode)) {
try {
if (userRoot.nodeExists(nodePath)) {
if (readPreferredInputMethod(nodePath) != null) {
return nodePath;
}
}
} catch (BackingStoreException bse) {
}
// search at parent's node
nodePath = nodePath.substring(0, nodePath.lastIndexOf('/'));
}
return null;
}
/**
Read the list of recently used workspaces from the preferences store.
@param preferences the preferences node
*/
public void read(Preferences preferences) {
recentWorkspaces.clear();
TreeMap<Integer, String> numberToFile = new TreeMap<Integer, String>();
Preferences recentNode = preferences.node(SETTINGS_RECENT_WORKSPACES);
try {
String[] keys = recentNode.keys();
for (int i = 0; i < keys.length; i++) {
String key = keys[i];
String fileName = recentNode.get(key, null);
if (fileName != null) {
numberToFile.put(new Integer(key), fileName);
}
}
recentWorkspaces.addAll(numberToFile.values());
} catch (BackingStoreException ex) {
}
}
/**
* @param wikipedia Wikipedia.
* @param property Property name.
* @param subProperty Sub property name.
* @return Property value.
*/
public Properties getSubProperties(
EnumWikipedia wikipedia, String property, String subProperty) {
Properties values = new Properties();
try {
if ((getPreferences(wikipedia) != null) &&
(getPreferences(wikipedia).nodeExists(property)) &&
(getPreferences(wikipedia).nodeExists(property + "/" + subProperty))) {
Preferences node = getPreferences(wikipedia).node(property + "/" + subProperty);
String[] children = node.keys();
for (String child : children) {
values.setProperty(child, node.get(child, ""));
}
}
} catch (BackingStoreException e) {
//
}
return values;
}
private void checkNotContains(Preferences prefs, String[] tree, String prefsId) throws BackingStoreException {
for(String s : tree) {
int equalIdx = s.lastIndexOf('=');
assertTrue(equalIdx != -1);
String value = s.substring(equalIdx + 1);
String key;
String nodePath;
int slashIdx = s.lastIndexOf('/', equalIdx);
if (slashIdx != -1) {
key = s.substring(slashIdx + 1, equalIdx);
nodePath = s.substring(0, slashIdx);
} else {
key = s.substring(0, equalIdx);
nodePath = "";
}
if (prefs.nodeExists(nodePath)) {
Preferences node = prefs.node(nodePath);
String realValue = node.get(key, null);
if (realValue != null && realValue.equals(value)) {
fail(prefsId + ", '" + nodePath + "' node contains key '" + key + "' = '" + realValue + "'");
}
}
}
}
private void checkEquals(String msg, Preferences expected, Preferences test) throws BackingStoreException {
assertEquals("Won't compare two Preferences with different absolutePath", expected.absolutePath(), test.absolutePath());
// check the keys and their values
for(String key : expected.keys()) {
String expectedValue = expected.get(key, null);
assertNotNull(msg + "; Expected:" + expected.absolutePath() + " has no '" + key + "'", expectedValue);
String value = test.get(key, null);
assertNotNull(msg + "; Test:" + test.absolutePath() + " has no '" + key + "'", value);
assertEquals(msg + "; Test:" + test.absolutePath() + "/" + key + " has wrong value", expectedValue, value);
}
// check the children
for(String child : expected.childrenNames()) {
assertTrue(msg + "; Expected:" + expected.absolutePath() + " has no '" + child + "' subnode", expected.nodeExists(child));
Preferences expectedChild = expected.node(child);
assertTrue(msg + "; Test:" + test.absolutePath() + " has no '" + child + "' subnode", test.nodeExists(child));
Preferences testChild = test.node(child);
checkEquals(msg, expectedChild, testChild);
}
}
private void checkNotContains(Preferences prefs, String[] tree, String prefsId) throws BackingStoreException {
for(String s : tree) {
int equalIdx = s.lastIndexOf('=');
assertTrue(equalIdx != -1);
String value = s.substring(equalIdx + 1);
String key;
String nodePath;
int slashIdx = s.lastIndexOf('/', equalIdx);
if (slashIdx != -1) {
key = s.substring(slashIdx + 1, equalIdx);
nodePath = s.substring(0, slashIdx);
} else {
key = s.substring(0, equalIdx);
nodePath = "";
}
if (prefs.nodeExists(nodePath)) {
Preferences node = prefs.node(nodePath);
String realValue = node.get(key, null);
if (realValue != null && realValue.equals(value)) {
fail(prefsId + ", '" + nodePath + "' node contains key '" + key + "' = '" + realValue + "'");
}
}
}
}
public void run() {
synchronized(lock) {
try {
flushSpi();
} catch (BackingStoreException ex) {
LOG.log(Level.WARNING, null, ex);
}
}
}
@Override
protected void syncSpi() throws BackingStoreException {
if (properties != null) {
try {
putAllProperties(fileStorage.load(), true);
} catch (IOException ex) {
throw new BackingStoreException(ex);
}
}
}
@Override
public void setMapDir(final GameData data, final String mapDir) {
internalSetMapDir(mapDir, data);
this.getMapData().verify(data);
// set the default after internal succeeds, if an error is thrown we don't want to persist it
final String mapName = (String) data.getProperties().get(Constants.MAP_NAME);
final Preferences prefs = getPreferencesForMap(mapName);
prefs.put(MAP_SKIN_PREF, mapDir);
try {
prefs.flush();
} catch (final BackingStoreException e) {
log.log(Level.SEVERE, "Failed to flush preferences: " + prefs.absolutePath(), e);
}
}
@Test
// @Ignore("This doesn't actually assert that the substitute and export features work.")
public void testExport() throws IOException, BackingStoreException, InvalidPreferencesFormatException {
Preferences userRoot = Preferences.userRoot();
Preferences fromNode = userRoot.node("SemperUbi");
assert fromNode instanceof PreferencesExt : "Factory not set = " + userRoot.getClass().getName();
ByteArrayOutputStream os = new ByteArrayOutputStream(10000);
fromNode.exportNode(os);
String xml = new String(os.toByteArray());
xml = substitute(xml, "SemperUbi", "SubUbi");
ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());
Preferences.importPreferences(is);
userRoot.exportSubtree(System.out);
}
/**
* Set the default font size as a preference if its not already defined.
* <p>
* Top Components listen for changes in
* ApplicationPreferenceKeys.OUTPUT2_PREFERENCE and if its not defined then
* the listener will not be registered. This initialise method is called
* when the application starts to make sure a preference is defined.
*/
public static synchronized void initialiseFontPreferenceOnFirstUse() {
final Preferences p = NbPreferences.root();
try {
if (!p.nodeExists(ApplicationPreferenceKeys.OUTPUT2_PREFERENCE)) {
p.node(ApplicationPreferenceKeys.OUTPUT2_PREFERENCE).put(ApplicationPreferenceKeys.OUTPUT2_FONT_SIZE, ApplicationPreferenceKeys.OUTPUT2_FONT_SIZE_DEFAULT);
}
} catch (final BackingStoreException ex) {
Exceptions.printStackTrace(ex);
}
}
protected void removeTopic(TopicMapIF topicmap, TopicIF topic) throws BackingStoreException {
// specs: "If this method is invoked on a node that has been removed with the removeNode() method,
// flushSpi() is invoked on this node, but not on others."
// so, first remove children, then topic itself
logger.debug("Removing topic " + TopicStringifiers.toString(topic));
for (TopicIF child : fetchChildren(topicmap, topic)) {
removeTopic(topicmap, child);
}
topic.remove();
}
public void saveOpenedFiles() {
List<SourceFilePanel> panels = new ArrayList<SourceFilePanel>(tabbedPane.getTabCount());
for (int i = 0; i < tabbedPane.getTabCount(); ++i) {
Component component = tabbedPane.getComponentAt(i);
if (component instanceof SourceFilePanel) {
panels.add((SourceFilePanel) component);
}
}
Preferences prefs = Preferences.userNodeForPackage(MainForm.class);
try {
prefs.clear();
int count = 0;
for (SourceFilePanel panel : panels) {
if (panel.getFileState() != FileState.UNSAVED) {
File file = panel.getFile();
prefs.put("file" + count, file.getAbsolutePath());
CodeParserPlugin plugin = panel.getParserPlugin();
prefs.put("plugin" + count, plugin.getClass().getName());
count++;
}
}
prefs.putInt("count", count);
} catch (BackingStoreException e) {
log.warn("Unable to save opened files.", e);
}
}
public void deleteTaskPreferences (String taskId) {
Preferences prefs = getPreferences();
try {
String taskKey = getTaskKey(taskId);
for (String key : prefs.keys()) {
if (key.startsWith(taskKey)) {
prefs.remove(key);
}
}
} catch (BackingStoreException ex) {
}
}
@Override
protected String[] childrenNamesSpi() throws BackingStoreException {
if (stored != null) {
return stored.childrenNames();
} else {
return new String[0];
}
}
/**
* Returns the preferences with key-value pairs as a string.
*/
private static String preferencesToString(Preferences prefs)
throws BackingStoreException
{
StringBuffer buf = new StringBuffer();
buf.append(prefs);
String[] keys = prefs.keys();
for (int i = 0; i < keys.length; i++) {
buf.append("\n" + keys[i] + "=" + prefs.get(keys[i], null));
}
return buf.toString();
}
private void setNextStartingTipLocation(int loc) {
int num = loc;
if (tipOfTheDay != null && tipOfTheDay.getModel() != null) {
num++;
if (num > tipOfTheDay.getModel().getTipCount() - 1)
num = 0;
}
prefs.putInt(PREF_TIPNUM, num);
try {
prefs.flush();
} catch (BackingStoreException e) {
logger.error("error presisting preferences (show tip of the day)", e);
}
}
public void testSimpleSync() throws BackingStoreException {
Preferences orig = Preferences.userRoot().node(getName());
assertNull("Original contains value", orig.get("key-1", null));
Preferences test = ProxyPreferencesImpl.getProxyPreferences(this, orig);
assertNull("Test should not contains pair", orig.get("key-1", null));
test.put("key-1", "xyz");
assertEquals("Test doesn't contain new pair", "xyz", test.get("key-1", null));
test.sync();
assertNull("Test didn't rollback pair", test.get("key-1", null));
}
private AWTKeyStroke getInputMethodSelectionKeyStroke(Preferences root) {
try {
if (root.nodeExists(inputMethodSelectionKeyPath)) {
Preferences node = root.node(inputMethodSelectionKeyPath);
int keyCode = node.getInt(inputMethodSelectionKeyCodeName, KeyEvent.VK_UNDEFINED);
if (keyCode != KeyEvent.VK_UNDEFINED) {
int modifiers = node.getInt(inputMethodSelectionKeyModifiersName, 0);
return AWTKeyStroke.getAWTKeyStroke(keyCode, modifiers);
}
}
} catch (BackingStoreException bse) {
}
return null;
}
private void setAndFlush(String key,boolean value) {
try {
Preferences pref = MarkOccurencesSettings.getCurrentNode();
pref.putBoolean(key, value);
pref.flush();
} catch (BackingStoreException ex) {
fail("Error while storing settings");
}
}
@Override
protected AbstractPreferences getChild(final String nodeName) throws BackingStoreException {
try {
return ProjectManager.mutex(false, project).readAccess(new ExceptionAction<AbstractPreferences>() {
public AbstractPreferences run() throws BackingStoreException {
return AuxiliaryConfigBasedPreferences.super.getChild(nodeName);
}
});
} catch (MutexException ex) {
throw (BackingStoreException) ex.getException();
}
}
private AWTKeyStroke getInputMethodSelectionKeyStroke(Preferences root) {
try {
if (root.nodeExists(inputMethodSelectionKeyPath)) {
Preferences node = root.node(inputMethodSelectionKeyPath);
int keyCode = node.getInt(inputMethodSelectionKeyCodeName, KeyEvent.VK_UNDEFINED);
if (keyCode != KeyEvent.VK_UNDEFINED) {
int modifiers = node.getInt(inputMethodSelectionKeyModifiersName, 0);
return AWTKeyStroke.getAWTKeyStroke(keyCode, modifiers);
}
}
} catch (BackingStoreException bse) {
}
return null;
}
final void delete() {
synchronized (this) {
if (prefs == null) {
throw new IllegalStateException();
}
try {
prefs.removePreferenceChangeListener(listener);
prefs.removeNode();
} catch (BackingStoreException ex) {
LOGGER.log(Level.WARNING, null, ex);
}
prefs = null;
}
}
@Override
public void sync() throws BackingStoreException {
ArrayList<EventBag<PreferenceChangeListener, PreferenceChangeEvent>> prefEvents = new ArrayList<EventBag<PreferenceChangeListener, PreferenceChangeEvent>>();
ArrayList<EventBag<NodeChangeListener, NodeChangeEvent>> nodeEvents = new ArrayList<EventBag<NodeChangeListener, NodeChangeEvent>>();
synchronized (tree.treeLock()) {
_sync(prefEvents, nodeEvents);
}
fireNodeEvents(nodeEvents);
firePrefEvents(prefEvents);
}
/**
* Clears the preferences.
*
* @return true if successful, false if there was an exception.
*/
public boolean clearPreferences() {
try {
preferences.clear();
} catch (BackingStoreException e) {
return false;
}
return true;
}