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

The following examples show how to use java.util.prefs.Preferences#sync() . 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: Java14ConfigStorage.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Stores the given properties on the defined path.
 *
 * @param configPath
 *          the path on where to store the properties.
 * @param config
 *          the properties which should be stored.
 * @throws ConfigStoreException
 *           if an error occurred.
 */
public void store( final String configPath, final Configuration config ) throws ConfigStoreException {
  if ( ConfigFactory.isValidPath( configPath ) == false ) {
    throw new IllegalArgumentException( "The give path is not valid." );
  }

  try {
    final Enumeration keys = config.getConfigProperties();
    final Preferences pref = base.node( configPath );
    pref.clear();
    while ( keys.hasMoreElements() ) {
      final String key = (String) keys.nextElement();
      final String value = config.getConfigProperty( key );
      if ( value != null ) {
        pref.put( key, value );
      }
    }
    pref.sync();
  } catch ( BackingStoreException be ) {
    throw new ConfigStoreException( "Failed to store config" + configPath, be );
  }
}
 
Example 2
Source File: GFMonMgr.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Set the current user preferences for this test run.
 */
private static void setCurrentPreferences()
throws BackingStoreException
{
  String currDir = System.getProperty("user.dir");

  // look up current user preferences, which needs forward slashes
  String modDir = currDir.replace('\\', '/');
  Preferences currentUser =
    Preferences.userRoot().node("GemFire Monitor 2.0").node(modDir);

  // override the log directory, which needs backslashes
  currentUser.put("prefs_dir", currDir + File.separator + GFMON_DIR);

  // make it write them out right away
  currentUser.flush();
  currentUser.sync();
  log().info("Set current preferences: " + preferencesToString(currentUser));
}
 
Example 3
Source File: SizeSaver.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
Preferences getPrefs() {
  Preferences prefsBase = Preferences.userNodeForPackage(getClass());

  String spid  = Activator.getBC().getProperty("org.osgi.provisioning.spid");
  if(spid == null) {
    spid = "default";
  }

  Preferences prefs     = prefsBase.node(NODE_NAME + "/" + spid + "/" + id);
  try {
    prefs.sync(); // Get the latest version of the node.
  } catch (Exception e) {
    errCount++;
    if(errCount < maxErr) {
      Activator.log.warn("Failed to get id=" + id, e);
    }
  }
  return prefs;
}
 
Example 4
Source File: DefaultSwingBundleDisplayer.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get the preferences node to store user settings for this displayer in.
 */
public Preferences getPrefs()
{
  final Preferences prefsBase = Preferences.userNodeForPackage(getClass());

  String spid = Activator.getBC().getProperty("org.osgi.provisioning.spid");
  if (spid == null) {
    spid = "default";
  }

  final String relPath =
    PREFS_NODE_NAME + "/" + spid + "/" + name.replace('/', '_');
  final Preferences prefs = prefsBase.node(relPath);
  try {
    prefs.sync(); // Get the latest version of the node.
  } catch (final Exception e) {
    errCount++;
    if (errCount < maxErr) {
      Activator.log.warn("Failed to get preferences node " + relPath, e);
    }
  }
  return prefs;
}
 
Example 5
Source File: GFMonMgr.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Set the current user preferences for this test run.
 */
private static void setCurrentPreferences()
throws BackingStoreException
{
  String currDir = System.getProperty("user.dir");

  // look up current user preferences, which needs forward slashes
  String modDir = currDir.replace('\\', '/');
  Preferences currentUser =
    Preferences.userRoot().node("GemFire Monitor 2.0").node(modDir);

  // override the log directory, which needs backslashes
  currentUser.put("prefs_dir", currDir + File.separator + GFMON_DIR);

  // make it write them out right away
  currentUser.flush();
  currentUser.sync();
  log().info("Set current preferences: " + preferencesToString(currentUser));
}
 
Example 6
Source File: PreferencesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testWriting() throws Exception {
    {
    Preferences prefs = MimeLookup.getLookup(MimePath.EMPTY).lookup(Preferences.class);
    assertEquals("Wrong value for 'simple-value-setting-A'", "value-A", prefs.get("simple-value-setting-A", null));
    
    prefs.put("simple-value-setting-A", "New-Written-Value");
    assertEquals("Wrong value for 'simple-value-setting-A'", "New-Written-Value", prefs.get("simple-value-setting-A", null));

    prefs.sync();
    }

    {
    // read the settings right from the file
    StorageImpl<String, TypedValue> storage = new StorageImpl<String, TypedValue>(new PreferencesStorage(), null);
    Map<String, TypedValue> map = storage.load(MimePath.EMPTY, null, false);
    assertEquals("Wrong value for 'simple-value-setting-A'", "New-Written-Value", map.get("simple-value-setting-A").getValue());
    }
}
 
Example 7
Source File: AppSettings.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Saves settings into the Java preferences.
 * <p>
 * On the Windows operating system, the preferences are saved in the registry
 * at the following key:<br>
 * <code>HKEY_CURRENT_USER\Software\JavaSoft\Prefs\[preferencesKey]</code>
 *
 * @param preferencesKey The preferences key to save at. Generally the
 * application's unique name.
 *
 * @throws BackingStoreException If an exception occurs with the preferences
 */
public void save(String preferencesKey) throws BackingStoreException {
    Preferences prefs = Preferences.userRoot().node(preferencesKey);

    // Clear any previous settings set before saving, this will
    // purge any other parameters set in older versions of the app, so
    // that they don't leak onto the AppSettings of newer versions.
    prefs.clear();

    for (String key : keySet()) {
        Object val = get(key);
        if (val instanceof Integer) {
            prefs.putInt("I_" + key, (Integer) val);
        } else if (val instanceof Float) {
            prefs.putFloat("F_" + key, (Float) val);
        } else if (val instanceof String) {
            prefs.put("S_" + key, (String) val);
        } else if (val instanceof Boolean) {
            prefs.putBoolean("B_" + key, (Boolean) val);
        }
        // NOTE: Ignore any parameters of unsupported types instead
        // of throwing exception. This is specifically for handling
        // BufferedImage which is used in setIcons(), as you do not
        // want to export such data in the preferences.
    }

    // Ensure the data is properly written into preferences before
    // continuing.
    prefs.sync();
}
 
Example 8
Source File: ProxyPreferencesImplTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 9
Source File: ProxyPreferencesImplTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testSyncTree1() throws BackingStoreException {
    String [] origTree = new String [] {
        "CodeStyle/profile=GLOBAL",
    };
    String [] newTree = new String [] {
        "CodeStyle/text/x-java/tab-size=2",
        "CodeStyle/text/x-java/override-global-settings=true",
        "CodeStyle/text/x-java/expand-tabs=true",
        "CodeStyle/profile=PROJECT",
    };

    Preferences orig = Preferences.userRoot().node(getName());
    write(orig, origTree);
    checkContains(orig, origTree, "Orig");
    checkNotContains(orig, newTree, "Orig");
    
    Preferences test = ProxyPreferencesImpl.getProxyPreferences(this, orig);
    checkEquals("Test should be the same as Orig", orig, test);
    
    write(test, newTree);
    checkContains(test, newTree, "Test");

    test.sync();
    checkContains(orig, origTree, "Orig");
    checkNotContains(orig, newTree, "Orig");
    checkContains(test, origTree, "Test");
    checkNotContains(test, newTree, "Test");
}
 
Example 10
Source File: ProxyPreferencesImplTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testSyncTree1() throws BackingStoreException {
    String [] origTree = new String [] {
        "CodeStyle/profile=GLOBAL",
    };
    String [] newTree = new String [] {
        "CodeStyle/text/x-java/tab-size=2",
        "CodeStyle/text/x-java/override-global-settings=true",
        "CodeStyle/text/x-java/expand-tabs=true",
        "CodeStyle/profile=PROJECT",
    };

    Preferences orig = Preferences.userRoot().node(getName());
    write(orig, origTree);
    checkContains(orig, origTree, "Orig");
    checkNotContains(orig, newTree, "Orig");
    
    Preferences test = ProxyPreferencesImpl.getProxyPreferences(this, orig);
    checkEquals("Test should be the same as Orig", orig, test);
    
    write(test, newTree);
    checkContains(test, newTree, "Test");

    test.sync();
    checkContains(orig, origTree, "Orig");
    checkNotContains(orig, newTree, "Orig");
    checkContains(test, origTree, "Test");
    checkNotContains(test, newTree, "Test");
}
 
Example 11
Source File: ProxyPreferencesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testSimpleSync() throws BackingStoreException {
    Preferences orig = Preferences.userRoot().node(getName());
    assertNull("Original contains value", orig.get("key-1", null));

    Preferences test = ProxyPreferences.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));
}
 
Example 12
Source File: ProxyPreferencesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testSyncTree1() throws BackingStoreException {
    String [] origTree = new String [] {
        "CodeStyle/profile=GLOBAL",
    };
    String [] newTree = new String [] {
        "CodeStyle/text/x-java/tab-size=2",
        "CodeStyle/text/x-java/override-global-settings=true",
        "CodeStyle/text/x-java/expand-tabs=true",
        "CodeStyle/profile=PROJECT",
    };

    Preferences orig = Preferences.userRoot().node(getName());
    write(orig, origTree);
    checkContains(orig, origTree, "Orig");
    checkNotContains(orig, newTree, "Orig");
    
    Preferences test = ProxyPreferences.getProxyPreferences(this, orig);
    checkEquals("Test should be the same as Orig", orig, test);
    
    write(test, newTree);
    checkContains(test, newTree, "Test");

    test.sync();
    checkContains(orig, origTree, "Orig");
    checkNotContains(orig, newTree, "Orig");
    checkContains(test, origTree, "Test");
    checkNotContains(test, newTree, "Test");
}
 
Example 13
Source File: HackTranslator.java    From nand2tetris-emu with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Saves the given working dir into the data file.
 */
protected void saveWorkingDir(File file) {
    final Preferences preferences = Preferences.userNodeForPackage(HackTranslator.class);
    preferences.put(DIRECTORY, file.getAbsolutePath());
    try {
        preferences.sync();
    } catch (BackingStoreException ignored) {
    }

    gui.setWorkingDir(file);
}
 
Example 14
Source File: MavenProjectSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static void setSettings(Project project, String key, String value, boolean shared) {
    Preferences preferences = getPreferences(project, shared);
    if (value != null) {
        preferences.put(key, value);
    } else {
        preferences.remove(key);
    }
    try {
        preferences.flush();
        preferences.sync();
    } catch (BackingStoreException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 15
Source File: NbTestCasePreferencesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testNotPersistentPreferences() throws Exception {
    Preferences pref = Preferences.userNodeForPackage(getClass());
    assertNotNull(pref);
    pref.put(getName(), "value");
    assertEquals("value", pref.get(getName(), null));
    pref.sync();
    assertEquals(null, pref.get(getName(), null));
}
 
Example 16
Source File: AlwaysEnabledActionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void checkPreferencesAction(Action a, Preferences prefsNode) throws Exception {
    prefsNode.putBoolean("myKey", true);
    prefsNode.sync();
    class L implements PreferenceChangeListener {
        boolean notified;

        public synchronized void preferenceChange(PreferenceChangeEvent evt) {
            notified = true;
            notifyAll();
        }

        public synchronized void waitFor() throws Exception {
            while (!notified) {
                wait();
            }
            notified = false;
        }
    }
    L listener = new L();

    // Verify value
    assertTrue("Expected true as preference value", prefsNode.getBoolean("myKey", false));

    TestCase.assertTrue("Expected to be instance of Presenter.Menu", a instanceof Presenter.Menu);
    JMenuItem item = ((Presenter.Menu) a).getMenuPresenter();
    TestCase.assertTrue("Expected to be selected", item.isSelected());
    prefsNode.addPreferenceChangeListener(listener);
    prefsNode.putBoolean("myKey", false);
    prefsNode.sync();
    listener.waitFor();
    TestCase.assertFalse("Expected to not be selected", item.isSelected());
    a.actionPerformed(null); // new ActionEvent(null, 0, ""));
    listener.waitFor();
    TestCase.assertTrue("Expected to be selected", item.isSelected());
    prefsNode.putBoolean("myKey", false);
    prefsNode.sync();
    listener.waitFor();
}
 
Example 17
Source File: AuxiliaryConfigBasedPreferencesProviderTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testSync() throws IOException, BackingStoreException {
    lookup.setDelegates(Lookups.fixed(new TestAuxiliaryConfigurationImpl()));
    
    AuxiliaryConfiguration ac = p.getLookup().lookup(AuxiliaryConfiguration.class);
    
    assertNotNull(ac);
            
    AuxiliaryConfigBasedPreferencesProvider toSync = new AuxiliaryConfigBasedPreferencesProvider(p, ac, null, true);
    Preferences pref = toSync.findModule("test");
    
    pref.put("test", "test");
    
    pref.node("subnode1/subnode2").put("somekey", "somevalue");
    pref.flush();
    
    AuxiliaryConfigBasedPreferencesProvider orig = new AuxiliaryConfigBasedPreferencesProvider(p, ac, null, true);
    
    Preferences origNode = orig.findModule("test").node("subnode1/subnode2");
    
    pref.node("subnode1/subnode2").put("somekey", "somevalue2");
    pref.flush();
    
    origNode.sync();
    
    assertEquals("somevalue2", origNode.get("somekey", null));
}
 
Example 18
Source File: TextInputDialog.java    From pumpernickel with MIT License 4 votes vote down vote up
/**
 * Show a QDialog prompting the user for text input. This method reads and
 * writes a value from the Preferences object provided. (If you don't want
 * to use Preferences, use another static method.)
 * 
 * @param frame
 *            the frame that will own the dialog.
 * @param dialogTitle
 *            the title of the dialog.
 * @param boldMessage
 *            the optional bold message for the content pane.
 * @param plainMessage
 *            the optional plain message for the content pane to display
 *            below the bold message.
 * @param textFieldPrompt
 *            the optional text field prompt.
 * @param textFieldToolTip
 *            the optional text field tooltip.
 * @param defaultTextFieldText
 *            the text to show in the text field if the preferences don't
 *            offer any starting text.
 * @param prefs
 *            the preferences to consult.
 * @param preferenceKey
 *            the key to consult in the Preferences argument.
 * @param handler
 *            the optional handler used to control UI elements in the
 *            dialog.
 * @return the String the user entered, or null if the user cancelled the
 *         dialog.
 */
public static String show(Frame frame, String dialogTitle,
		String boldMessage, String plainMessage, String textFieldPrompt,
		String textFieldToolTip, String defaultTextFieldText,
		Preferences prefs, String preferenceKey, StringInputHandler handler) {
	String initialText = prefs.get(preferenceKey, defaultTextFieldText);
	String returnValue = show(frame, dialogTitle, boldMessage,
			plainMessage, textFieldPrompt, textFieldToolTip, initialText,
			handler);

	if (returnValue != null) {
		prefs.put(preferenceKey, returnValue);
	}
	try {
		prefs.sync();
	} catch (BackingStoreException e) {
		e.printStackTrace();
	}
	return returnValue;

}
 
Example 19
Source File: EditPreferences.java    From iBioSim with Apache License 2.0 4 votes vote down vote up
public void preferences() {
	Preferences biosimrc = Preferences.userRoot();
	if (biosimrc.get("biosim.check.undeclared", "").equals("false")) {
		checkUndeclared = false;
	}
	else {
		checkUndeclared = true;
	}
	if (biosimrc.get("biosim.check.units", "").equals("false")) {
		checkUnits = false;
	}
	else {
		checkUnits = true;
	}
	JPanel generalPrefs = generalPreferences(biosimrc);
	JPanel schematicPrefs = schematicPreferences(biosimrc);
	JPanel modelPrefs = modelPreferences(biosimrc);
	JPanel analysisPrefs = analysisPreferences(biosimrc);

	// create tabs
	JTabbedPane prefTabs = new JTabbedPane();
	if (async) prefTabs.addTab("General Preferences", generalPrefs);
	if (async) prefTabs.addTab("Schematic Preferences", schematicPrefs);
	if (async) prefTabs.addTab("Model Preferences", modelPrefs);
	if (async) prefTabs.addTab("Analysis Preferences", analysisPrefs);

	boolean problem;
	int value;
	do {
		problem = false;
		Object[] options = { "Save", "Cancel" };
		value = JOptionPane.showOptionDialog(frame, prefTabs, "Preferences", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null,
				options, options[0]);

		// if user hits "save", store and/or check new data
		if (value == JOptionPane.YES_OPTION) {
			if (async) saveGeneralPreferences(biosimrc);
			if (async) problem = saveSchematicPreferences(biosimrc);
			if (async && !problem) problem = saveModelPreferences(biosimrc);
			if (async && !problem) problem = saveAnalysisPreferences(biosimrc);
			try {
				biosimrc.sync();
			}
			catch (BackingStoreException e) {
				e.printStackTrace();
			}
		}
	} while (value == JOptionPane.YES_OPTION && problem);
}
 
Example 20
Source File: PreferencesBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) throws BackingStoreException {

        Preferences preferences = Preferences.systemRoot().node("/mercyblitz");

        Stream.of(preferences.childrenNames()).forEach(System.out::println);

        preferences.put("name", "小马哥");

        preferences.sync();

        System.out.println(preferences.get("name", ""));



    }