Java Code Examples for java.util.prefs.Preferences#keys()

The following examples show how to use java.util.prefs.Preferences#keys() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProjectSelection.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
private void removeFromPreferences(ProjectInfo selectedItem) {
    Preferences p = Preferences.userNodeForPackage(this.getClass());
    String[] keys;
    try {
        keys = p.keys();
        for (int i = 0; i < keys.length; i++) {
            String key = keys[i];
            String fName = p.get(key, null);
            if (fName.equals(selectedItem.getFolder())) {
                p.remove(key);
                break;
            }
        }
    } catch (BackingStoreException e) {
        return;
    }
}
 
Example 2
Source File: RepositoryRegistry.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String[] getRepoIds(Preferences preferences, String repoId) {
    String[] keys = null;
    try {
        keys = preferences.keys();
    } catch (BackingStoreException ex) {
        BugtrackingManager.LOG.log(Level.SEVERE, null, ex); 
    }
    if (keys == null || keys.length == 0) {
        return new String[0];
    }
    List<String> ret = new ArrayList<String>();
    for (String key : keys) {
        if (key.startsWith(repoId)) {
            ret.add(key.substring(repoId.length()));
        }
    }
    return ret.toArray(new String[ret.size()]);
}
 
Example 3
Source File: AppSettings.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Loads settings previously saved in the Java preferences.
 * 
 * @param preferencesKey The preferencesKey previously used to save the settings.
 * @throws BackingStoreException If an exception occurs with the preferences
 * 
 * @see #save(java.lang.String) 
 */
public void load(String preferencesKey) throws BackingStoreException {
    Preferences prefs = Preferences.userRoot().node(preferencesKey);
    String[] keys = prefs.keys();
    if (keys != null) {
        for (String key : keys) {
            Object defaultValue = defaults.get(key);
            if (defaultValue instanceof Integer) {
                put(key, prefs.getInt(key, (Integer) defaultValue));
            } else if (defaultValue instanceof String) {
                put(key, prefs.get(key, (String) defaultValue));
            } else if (defaultValue instanceof Boolean) {
                put(key, prefs.getBoolean(key, (Boolean) defaultValue));
            }
        }
    }
}
 
Example 4
Source File: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to get an array of Strings from preferences.
 *
 * @param prefs storage
 * @param key key of the String array
 * @return List<String> stored List of String or an empty List if the key was not found (order is preserved)
 */
public static List<String> getStringList(Preferences prefs, String key) {
    List<String> retval = new ArrayList<String>();
    try {
        String[] keys = prefs.keys();
        for (int i = 0; i < keys.length; i++) {
            String k = keys[i];
            if (k != null && k.startsWith(key)) {
                int idx = Integer.parseInt(k.substring(k.lastIndexOf('.') + 1));
                retval.add(idx + "." + prefs.get(k, null));
            }
        }
        List<String> rv = new ArrayList<String>(retval.size());
        rv.addAll(retval);
        for (String s : retval) {
            int pos = s.indexOf('.');
            int index = Integer.parseInt(s.substring(0, pos));
            rv.set(index, s.substring(pos + 1));
        }
        return rv;
    } catch (Exception ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.INFO, null, ex);
        return new ArrayList<String>(0);
    }
}
 
Example 5
Source File: FileToRepoMappingStorage.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Collection<String> getAllFirmlyAssociatedUrls() {
    HashSet<String> associatedUrls = new HashSet<String>(10);
    try {
        Preferences prefs = getPreferences();
        String[] keys = prefs.keys();
        for (String key : keys) {
            if (key.startsWith(REPOSITORY_FOR_FILE_PREFIX)) { // found an association
                String value = prefs.get(key, null);
                if (value != null && value.length() > 0 && value.charAt(0) == '!') { // found a firm association
                    associatedUrls.add(value.substring(1));
                }
            }
        }
    } catch (BackingStoreException ex) {
        LOG.log(Level.INFO, null, ex);
    }
    return associatedUrls;
}
 
Example 6
Source File: TaskSchedulingManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void loadTasks() {
    Preferences pref = NbPreferences.forModule(TaskSchedulingManager.class);
    try {
        for (String key : pref.keys()) {
            if (key.startsWith(PREF_SCHEDULED)) {
                String repositoryId = key.substring(PREF_SCHEDULED.length());
                String tasks = pref.get(key, "");
                for (String taskId : tasks.split(SEP)) {
                    if (!taskId.isEmpty()) {
                        getRepositoryTasks(repositoryId).add(taskId);
                    }
                }
            }
        }
    } catch (BackingStoreException ex) {
        Logger.getLogger(TaskSchedulingManager.class.getName()).log(Level.INFO, null, ex);
    }
}
 
Example 7
Source File: ProxyPreferencesImplTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 8
Source File: ApplicationSettings.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private ApplicationSettings() {

		// one-time conversion from old to new preferences location:
		Preferences root = Preferences.userRoot();
		try {
			// if preferences exist under /net/sf/keystore_explorer but not under /org/kse ...
			if (root.nodeExists(PREFS_NODE_OLD) && !root.nodeExists(PREFS_NODE)) {

				// ... then copy settings from old to new subtree
				Preferences prefsOld = root.node(PREFS_NODE_OLD);
				Preferences prefsNew = root.node(PREFS_NODE);

				for (String key : prefsOld.keys()) {
					prefsNew.put(key, prefsOld.get(key, ""));
				}

				prefsNew.flush();
			}
		} catch (BackingStoreException e) {
			// ignore errors here
		}

		load();
	}
 
Example 9
Source File: TopComponentTracker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Load window list from previous session.
 */
void load() {
    Preferences prefs = getPreferences();
    try {
        for( String key : prefs.keys() ) {
            boolean view = prefs.getBoolean( key, false );
            if( view )
                viewIds.add( key );
            else
                editorIds.add( key );
        }
    } catch( BackingStoreException ex ) {
        Logger.getLogger( TopComponentTracker.class.getName() ).log( Level.INFO, null, ex );
    }
}
 
Example 10
Source File: FormattingCustomizerPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void dump(Preferences prefs, String prefsId) throws BackingStoreException {
    for(String key : prefs.keys()) {
        System.out.println(prefsId + ", " + prefs.absolutePath() + "/" + key + "=" + prefs.get(key, null));
    }
    for(String child : prefs.childrenNames()) {
        dump(prefs.node(child), prefsId);
    }
}
 
Example 11
Source File: LocalRepositoryConfig.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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) {
    }
}
 
Example 12
Source File: AppSettings.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Loads settings previously saved in the Java preferences.
 *
 * @param preferencesKey The preferencesKey previously used to save the settings.
 * @throws BackingStoreException If an exception occurs with the preferences
 *
 * @see #save(java.lang.String)
 */
public void load(String preferencesKey) throws BackingStoreException {
    Preferences prefs = Preferences.userRoot().node(preferencesKey);
    String[] keys = prefs.keys();
    if (keys != null) {
        for (String key : keys) {
            if (key.charAt(1) == '_') {
                // Try loading using new method
                switch (key.charAt(0)) {
                    case 'I':
                        put(key.substring(2), prefs.getInt(key, 0));
                        break;
                    case 'F':
                        put(key.substring(2), prefs.getFloat(key, 0f));
                        break;
                    case 'S':
                        put(key.substring(2), prefs.get(key, null));
                        break;
                    case 'B':
                        put(key.substring(2), prefs.getBoolean(key, false));
                        break;
                    default:
                        throw new UnsupportedOperationException("Undefined setting type: " + key.charAt(0));
                }
            } else {
                // Use old method for compatibility with older preferences
                // TODO: Remove when no longer necessary
                Object defaultValue = defaults.get(key);
                if (defaultValue instanceof Integer) {
                    put(key, prefs.getInt(key, (Integer) defaultValue));
                } else if (defaultValue instanceof String) {
                    put(key, prefs.get(key, (String) defaultValue));
                } else if (defaultValue instanceof Boolean) {
                    put(key, prefs.getBoolean(key, (Boolean) defaultValue));
                }
            }
        }
    }
}
 
Example 13
Source File: GFMonMgr.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 14
Source File: AdjustConfigurationPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ModifiedPreferences(ModifiedPreferences parent, String name, Preferences node) {
    this(parent, name); // NOI18N
    try {
        for (java.lang.String key : node.keys()) {
            put(key, node.get(key, null));
        }
        for (String child : node.childrenNames()) {
            subNodes.put(child, new ModifiedPreferences(this, node.name(), node.node(child)));
        }
    }
    catch (BackingStoreException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 15
Source File: HintsPanelLogic.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ModifiedPreferences( Preferences node ) {
    super(null, ""); // NOI18N
    try {                
        for (java.lang.String key : node.keys()) {
            put(key, node.get(key, null));
        }
        modified = false;
    }
    catch (BackingStoreException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 16
Source File: CustomScopeProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private <T> List<T> loadFileList(String basekey, Class<T> type) throws BackingStoreException {
    Preferences pref = NbPreferences.forModule(JavaScopeBuilder.class).node(PREF_SCOPE).node(basekey);
    List<T> toRet = new LinkedList<T>();
    for (String key : pref.keys()) {
        final String url = pref.get(key, null);
        if (url != null && !url.isEmpty()) {
            try {
                final FileObject f = URLMapper.findFileObject(new URL(url));
                if (f != null && f.isValid()) {
                    if (type.isAssignableFrom(FileObject.class)) {
                        toRet.add((T) f);
                    } else {
                        toRet.add((T) new NonRecursiveFolder() {
                            @Override
                            public FileObject getFolder() {
                                return f;
                            }
                        });
                    }
                }
            } catch (MalformedURLException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    return toRet;
}
 
Example 17
Source File: XmlSupport.java    From java-scanner-access-twain with GNU Affero General Public License v3.0 4 votes vote down vote up
private static void putPreferencesInXml(Element elt, Document doc,
           Preferences prefs, boolean subTree) throws BackingStoreException
{
    Preferences[] kidsCopy = null;
    String[] kidNames = null;

    synchronized (((FileSystemPreferences)prefs).getLock()) { 
        if (((FileSystemPreferences)prefs).isRemoved()) { 
            elt.getParentNode().removeChild(elt);
            return;
        }

        String[] keys = prefs.keys();
        Element map = (Element) elt.appendChild(doc.createElement("map"));
        for (int i=0; i<keys.length; i++) {
            Element entry = (Element)
                map.appendChild(doc.createElement("entry"));
            entry.setAttribute("key", keys[i]);

            entry.setAttribute("value", prefs.get(keys[i], null));
        }

        if (subTree) {

            kidNames = prefs.childrenNames();
            kidsCopy = new Preferences[kidNames.length];
            for (int i = 0; i <  kidNames.length; i++)
                kidsCopy[i] = prefs.node(kidNames[i]);
        }

    }

    if (subTree) {
        for (int i=0; i < kidNames.length; i++) {
            Element xmlKid = (Element)
                elt.appendChild(doc.createElement("node"));
            xmlKid.setAttribute("name", kidNames[i]);
            putPreferencesInXml(xmlKid, doc, kidsCopy[i], subTree);
        }
    }
}
 
Example 18
Source File: Configuration.java    From wpcleaner with Apache License 2.0 4 votes vote down vote up
/**
 * Move a child.
 * 
 * @param oldParent Old parent node.
 * @param newParent New parent node.
 * @param childName Child name.
 * @return True if the child has been completely moved.
 * @throws BackingStoreException
 */
private boolean moveChild(
    Preferences oldParent, Preferences newParent, String childName)
    throws BackingStoreException {
  if ((oldParent == null) || (childName == null)) {
    return true;
  }
  if (!oldParent.nodeExists(childName)) {
    return true;
  }
  if (newParent == null) {
    return false;
  }
  Preferences oldChild = oldParent.node(childName);
  Preferences newChild = newParent.node(childName);

  // Move keys
  String[] keyNames = oldChild.keys();
  if (keyNames != null) {
    for (String keyName : keyNames) {
      String value = oldChild.get(keyName, null);
      if (value != null) {
        newChild.put(keyName, value);
      }
      oldChild.remove(keyName);
    }
  }

  // Move children
  String[] childNames2 = oldChild.childrenNames();
  if (childNames2 != null) {
    for (String childName2 : childNames2) {
      moveChild(oldChild, newChild, childName2);
    }
  }

  // Clean up
  boolean ok = false;
  newChild.flush();
  keyNames = oldChild.keys();
  childNames2 = oldChild.childrenNames();
  if (((keyNames == null) || (keyNames.length == 0)) ||
      ((childNames2 == null) || (childNames2.length == 0))) {
    oldChild.removeNode();
    ok = true;
  }
  oldChild.flush();
  return ok;
}
 
Example 19
Source File: FilePreferencesXmlSupport.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Put the preferences in the specified Preferences node into the specified XML
 * element which is assumed to represent a node in the specified XML document
 * which is assumed to conform to PREFS_DTD. If subTree is true, create children
 * of the specified XML node conforming to all of the children of the specified
 * Preferences node and recurse.
 *
 * @throws BackingStoreException
 *             if it is not possible to read the preferences or children out of
 *             the specified preferences node.
 */
private static void putPreferencesInXml(Element elt, Document doc, Preferences prefs, boolean subTree)
        throws BackingStoreException {
    Preferences[] kidsCopy = null;
    String[] kidNames = null;

    // Node is locked to export its contents and get a
    // copy of children, then lock is released,
    // and, if subTree = true, recursive calls are made on children

    // to remove a node we need an exclusive lock

    // to remove a node we need an exclusive lock
    if (!((FileSystemPreferences) prefs).lockFile(false))
        throw (new BackingStoreException("Couldn't get file lock."));
    try {
        // Check if this node was concurrently removed. If yes
        // remove it from XML Document and return.
        if (((FileSystemPreferences) prefs).isRemoved()) {
            elt.getParentNode().removeChild(elt);
            return;
        }
        // Put map in xml element
        String[] keys = prefs.keys();
        Element map = (Element) elt.appendChild(doc.createElement("map"));
        for (int i = 0; i < keys.length; i++) {
            Element entry = (Element) map.appendChild(doc.createElement("entry"));
            entry.setAttribute("key", keys[i]);
            // NEXT STATEMENT THROWS NULL PTR EXC INSTEAD OF ASSERT FAIL
            entry.setAttribute("value", prefs.get(keys[i], null));
        }
        // Recurse if appropriate
        if (subTree) {
            /* Get a copy of kids while lock is held */
            kidNames = prefs.childrenNames();
            kidsCopy = new Preferences[kidNames.length];
            for (int i = 0; i < kidNames.length; i++)
                kidsCopy[i] = prefs.node(kidNames[i]);
        }
    } finally {
        ((FileSystemPreferences) prefs).unlockFile();
    }
    if (subTree) {
        for (int i = 0; i < kidNames.length; i++) {
            Element xmlKid = (Element) elt.appendChild(doc.createElement("node"));
            xmlKid.setAttribute("name", kidNames[i]);
            putPreferencesInXml(xmlKid, doc, kidsCopy[i], subTree);
        }
    }
}
 
Example 20
Source File: QueriesCache.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@NonNull
private Map<URL,T> loadRoots() {
    synchronized(lck) {
       if (cache == null) {
           Map<URL,T> result = new HashMap<URL, T>();
           final Preferences root = NbPreferences.forModule(QueriesCache.class);
           final String folder = clazz.getSimpleName();
           try {
               if (root.nodeExists(folder)) {
                   final Preferences node = root.node(folder);
                   Map<URL,List<URL>> bindings = new HashMap<URL, List<URL>>();
                   for (String key : node.keys()) {
                       final String value = node.get(key, null);
                       if (value != null) {
                           final URL binUrl = getURL(key);
                           List<URL> binding = bindings.get(binUrl);
                           if(binding == null) {
                               binding = new ArrayList<URL>();
                               bindings.put(binUrl,binding);
                           }
                           binding.add(new URL(value));
                       }
                   }
                   for (Map.Entry<URL,List<URL>> e : bindings.entrySet()) {
                       final T instance = clazz.newInstance();
                       instance.update(e.getValue());
                       result.put(e.getKey(), instance);
                   }
               }
           } catch (BackingStoreException bse) {
               Exceptions.printStackTrace(bse);
           } catch (MalformedURLException mue) {
               Exceptions.printStackTrace(mue);
           } catch (InstantiationException ie) {
               Exceptions.printStackTrace(ie);
           } catch (IllegalAccessException iae) {
               Exceptions.printStackTrace(iae);
           }
           cache = result;
       }
       return cache;
    }
}