Here are the examples of the java api class java.util.prefs.Preferences taken from open source projects.
1. PreferencesRecentWorkspacesServiceTest#isSorted()
Project: pdfsam
File: PreferencesRecentWorkspacesServiceTest.java
File: PreferencesRecentWorkspacesServiceTest.java
@Test public void isSorted() throws BackingStoreException { Preferences node = Preferences.userRoot().node(WORKSPACES_PATH); node.put("2", "second"); node.put("3", "third"); node.put("1", "first"); node.flush(); PreferencesRecentWorkspacesService newVictim = new PreferencesRecentWorkspacesService(); List<String> workspaces = newVictim.getRecentlyUsedWorkspaces(); assertEquals(3, workspaces.size()); assertEquals("third", workspaces.get(0)); assertEquals("second", workspaces.get(1)); assertEquals("first", workspaces.get(2)); }
2. ReportWizardPanel1#storeSettings()
Project: autopsy
File: ReportWizardPanel1.java
File: ReportWizardPanel1.java
@Override public void storeSettings(WizardDescriptor wiz) { TableReportModule module = getComponent().getTableModule(); GeneralReportModule general = getComponent().getGeneralModule(); //NON-NLS wiz.putProperty("tableModule", module); //NON-NLS wiz.putProperty("generalModule", general); //NON-NLS wiz.putProperty("fileModule", getComponent().getFileModule()); // Store preferences that WizardIterator will use to determine what // panels need to be shown Preferences prefs = NbPreferences.forModule(ReportWizardPanel1.class); //NON-NLS prefs.putBoolean("tableModule", module != null); //NON-NLS prefs.putBoolean("generalModule", general != null); }
3. Feedback#used()
Project: Raccoon
File: Feedback.java
File: Feedback.java
/** * Call this when the user performs a "use" action. * * @param center * a component to center the feedback dialog upon (or null). */ public static void used(JFrame center) { Preferences prefs = Preferences.userNodeForPackage(Feedback.class); if (prefs.getBoolean(KEY_DONE, false)) { return; } long count = prefs.getLong(KEY_COUNT, 0) + 1; prefs.putLong(KEY_COUNT, count); long first = prefs.getLong(KEY_FIRST, 0); if (first == 0) { first = System.currentTimeMillis(); prefs.putLong(KEY_FIRST, first); } try { prefs.flush(); } catch (BackingStoreException e) { e.printStackTrace(); } if (count >= USES) { if (System.currentTimeMillis() >= first + (DAYS * 24 * 60 * 60 * 1000)) { showDialog(center); } } }
4. SerialConsoleTopComponent#componentOpened()
Project: Universal-G-Code-Sender
File: SerialConsoleTopComponent.java
File: SerialConsoleTopComponent.java
// End of variables declaration//GEN-END:variables @Override public void componentOpened() { backend = CentralLookup.getDefault().lookup(BackendAPI.class); settings = CentralLookup.getDefault().lookup(Settings.class); commandTextArea.init(backend); verboseMenuItem.setSelected(settings.isVerboseOutputEnabled()); backend.addControllerListener(this); this.consoleTextArea.addMouseListener(this); final Preferences pref = NbPreferences.forModule(ConsolePanel.class); // Listen for prefernce changes. pref.addPreferenceChangeListener(new PreferenceChangeListener() { public void preferenceChange(PreferenceChangeEvent evt) { if (evt.getKey().equals("verboseCheckbox")) { verboseMenuItem.setSelected(pref.getBoolean("verboseCheckbox", false)); } } }); }
5. RecentFiles#writeHistoryToPref()
Project: pdfbox
File: RecentFiles.java
File: RecentFiles.java
private void writeHistoryToPref(Queue<String> filePaths) { if (filePaths.size() == 0) { return; } Preferences node = pref.node(KEY); node.putInt(HISTORY_LENGTH, filePaths.size()); int fileCount = 1; for (String path : filePaths) { String[] pieces = breakString(path); node.putInt(String.format(PIECES_LENGTH_KEY, fileCount), pieces.length); for (int i = 0; i < pieces.length; i++) { node.put(String.format(PATH_KEY, fileCount, i), pieces[i]); } fileCount++; } }
6. CredentialManagerUI#selectImportExportFile()
Project: incubator-taverna-workbench
File: CredentialManagerUI.java
File: CredentialManagerUI.java
/** * Lets the user select a file to export to or import from a key pair or a * certificate. */ private File selectImportExportFile(String title, String[] filter, String description, String approveButtonText, String prefString) { Preferences prefs = Preferences.userNodeForPackage(CredentialManagerUI.class); String keyPairDir = prefs.get(prefString, System.getProperty("user.home")); JFileChooser fileChooser = new JFileChooser(); fileChooser.addChoosableFileFilter(new CryptoFileFilter(filter, description)); fileChooser.setDialogTitle(title); fileChooser.setMultiSelectionEnabled(false); fileChooser.setCurrentDirectory(new File(keyPairDir)); if (fileChooser.showDialog(this, approveButtonText) != APPROVE_OPTION) return null; File selectedFile = fileChooser.getSelectedFile(); prefs.put(prefString, fileChooser.getCurrentDirectory().toString()); return selectedFile; }
7. JavaSEPort#addSkinName()
Project: CodenameOne
File: JavaSEPort.java
File: JavaSEPort.java
private void addSkinName(String f) { Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class); String skinNames = pref.get("skins", DEFAULT_SKINS); if (skinNames != null) { if (!skinNames.contains(f)) { skinNames += ";" + f; } } else { skinNames = f; } pref.put("skins", skinNames); }
8. SSHProxySwitcher#isRunningAsAdmin()
Project: SSH-Proxy-Switcher
File: SSHProxySwitcher.java
File: SSHProxySwitcher.java
private boolean isRunningAsAdmin() { Preferences prefs = Preferences.systemRoot(); PrintStream systemErr = System.err; synchronized (System.err) { System.setErr(new PrintStream(new OutputStream() { @Override public void write(int i) throws IOException { } })); try { // SecurityException on Windows prefs.put("SSHProxySwitcher_AdminChecker", "Success"); prefs.remove("SSHProxySwitcher_AdminChecker"); // BackingStoreException on Linux prefs.flush(); return true; } catch (Exception e) { return false; } finally { System.setErr(systemErr); } } }
9. SpaceracerSettings#load()
Project: spaceracer3d
File: SpaceracerSettings.java
File: SpaceracerSettings.java
public void load(final String preferencesKey) throws BackingStoreException { final Preferences prefs = Preferences.userRoot().node(preferencesKey); final String[] keys = prefs.keys(); if (keys != null) { for (final String key : keys) { final Object defaultValue = defaults.get(key); if (defaultValue instanceof Integer) { jmeAppSettings.put(key, prefs.getInt(key, (Integer) defaultValue)); } else if (defaultValue instanceof String) { jmeAppSettings.put(key, prefs.get(key, (String) defaultValue)); } else if (defaultValue instanceof Boolean) { jmeAppSettings.put(key, prefs.getBoolean(key, (Boolean) defaultValue)); } } } }
10. Util#getPreference()
Project: sling
File: Util.java
File: Util.java
static int[] getPreference(final String name, final int[] defaultValues) { Preferences prefs = getPreferences(); try { prefs.sync(); String value = prefs.get(name, null); if (value != null) { String[] values = value.split(","); int[] result = new int[values.length]; for (int i = 0; i < values.length; i++) { result[i] = Integer.parseInt(values[i]); } return result; } } catch (BackingStoreException ioe) { } catch (NumberFormatException nfe) { } return defaultValues; }
11. PreferencesRecentWorkspacesService#populateCache()
Project: pdfsam
File: PreferencesRecentWorkspacesService.java
File: PreferencesRecentWorkspacesService.java
private void populateCache() { Preferences prefs = Preferences.userRoot().node(WORKSPACES_PATH); try { Arrays.stream(prefs.keys()).sorted().forEach( k -> { String currentValue = prefs.get(k, EMPTY); if (isNotBlank(currentValue)) { cache.put(currentValue, k); } }); } catch (BackingStoreException e) { LOG.error("Error retrieving recently used workspaces", e); } }
12. PreferencesRecentWorkspacesService#flush()
Project: pdfsam
File: PreferencesRecentWorkspacesService.java
File: PreferencesRecentWorkspacesService.java
@PreDestroy public void flush() { Preferences prefs = Preferences.userRoot().node(WORKSPACES_PATH); LOG.trace("Flushing recently used workspaces"); try { prefs.clear(); for (Entry<String, String> entry : cache.entrySet()) { prefs.put(entry.getValue(), entry.getKey()); } prefs.flush(); } catch (BackingStoreException e) { LOG.error("Error storing recently used workspace", e); } }
13. DefaultStageService#getLatestStatus()
Project: pdfsam
File: DefaultStageService.java
File: DefaultStageService.java
public StageStatus getLatestStatus() { Preferences node = Preferences.userRoot().node(STAGE_PATH); try { String statusString = node.get(STAGE_STATUS_KEY, ""); if (isNotBlank(statusString)) { return JSON.std.beanFrom(StageStatus.class, statusString); } } catch (IOException e) { LOG.error("Unable to get latest stage status", e); } return StageStatus.NULL; }
14. PreferencesUsageDataStore#getUsages()
Project: pdfsam
File: PreferencesUsageDataStore.java
File: PreferencesUsageDataStore.java
public List<ModuleUsage> getUsages() { Preferences prefs = Preferences.userRoot().node(USAGE_PATH); List<ModuleUsage> retList = new ArrayList<>(); try { List<String> jsons = Arrays.stream(prefs.childrenNames()).parallel().map( name -> prefs.node(name)).map( node -> node.get(MODULE_USAGE_KEY, "")).filter( json -> isNotBlank(json)).collect(toList()); for (String json : jsons) { retList.add(JSON.std.beanFrom(ModuleUsage.class, json)); } } catch (BackingStoreExceptionIOException | e) { LOG.error("Unable to get modules usage statistics", e); } return retList; }
15. PreferencesUsageDataStore#incrementUsageFor()
Project: pdfsam
File: PreferencesUsageDataStore.java
File: PreferencesUsageDataStore.java
public void incrementUsageFor(String moduleId) { Preferences node = Preferences.userRoot().node(USAGE_PATH).node(moduleId); String json = node.get(MODULE_USAGE_KEY, ""); try { if (isNotBlank(json)) { node.put(MODULE_USAGE_KEY, JSON.std.asString(JSON.std.beanFrom(ModuleUsage.class, json).inc())); } else { node.put(MODULE_USAGE_KEY, JSON.std.asString(ModuleUsage.fistUsage(moduleId))); } LOG.trace("Usage incremented for module {}", moduleId); } catch (IOException e) { LOG.error("Unable to increment modules usage statistics", e); } finally { incrementTotalUsage(); } }
16. RecentFiles#readHistoryFromPref()
Project: pdfbox
File: RecentFiles.java
File: RecentFiles.java
private Queue<String> readHistoryFromPref() { Preferences node = pref.node(KEY); int historyLength = node.getInt(HISTORY_LENGTH, 0); if (historyLength == 0) { return null; } Queue<String> history = new ArrayDeque<String>(); for (int i = 1; i <= historyLength; i++) { int totalPieces = node.getInt(String.format(PIECES_LENGTH_KEY, i), 0); StringBuilder stringBuilder = new StringBuilder(); for (int j = 0; j < totalPieces; j++) { String piece = node.get(String.format(PATH_KEY, i, j), ""); stringBuilder.append(piece); } history.add(stringBuilder.toString()); } return history; }
17. DiffPanel#getPreferences()
Project: OWASP-WebScarab
File: DiffPanel.java
File: DiffPanel.java
private void getPreferences() { Preferences prefs = Preferences.userNodeForPackage(getClass()); if (changedColor == null) { int colorSpec = prefs.getInt("changed", Color.YELLOW.getRGB()); changedColor = new Color(colorSpec); } if (addedColor == null) { int colorSpec = prefs.getInt("added", Color.GREEN.getRGB()); addedColor = new Color(colorSpec); } if (deletedColor == null) { int colorSpec = prefs.getInt("deleted", Color.PINK.getRGB()); deletedColor = new Color(colorSpec); } }
18. PreferencesHelperTest#testMachineConfigurationNames()
Project: Makelangelo
File: PreferencesHelperTest.java
File: PreferencesHelperTest.java
@Test public void testMachineConfigurationNames() throws BackingStoreException { final String thisMethodsName = Thread.currentThread().getStackTrace()[CLIENT_CODE_STACK_INDEX].getMethodName(); Log.message("start: " + PreferencesHelperTest.class.getName() + "#" + thisMethodsName); final Preferences machinesPreferenceNode = PreferencesHelper.getPreferenceNode(PreferencesHelper.MakelangeloPreferenceKey.MACHINES); Log.message("node name: " + machinesPreferenceNode.name()); final String[] childrenPreferenceNodeNames = machinesPreferenceNode.childrenNames(); for (String childNodeName : childrenPreferenceNodeNames) { Log.message("child node name: " + childNodeName); final boolean isMachineNameAnInteger = UnitTestHelper.isInteger(childNodeName); Assert.assertTrue(isMachineNameAnInteger); //Machine configurations numbered -1 and below should not exist. final boolean isMachineNameLessThanZero = Integer.parseInt(childNodeName) < 0; Assert.assertFalse(isMachineNameLessThanZero); } Log.message("end: " + thisMethodsName); }
19. MarginallyCleverPreferencesHelper#main()
Project: Makelangelo
File: MarginallyCleverPreferencesHelper.java
File: MarginallyCleverPreferencesHelper.java
/** * @param args command line arguments. */ @SuppressWarnings("deprecation") public static void main(String[] args) throws BackingStoreException { final Preferences machinesPreferenceNode = PreferencesHelper.getPreferenceNode(PreferencesHelper.MakelangeloPreferenceKey.MACHINES); Log.message("node name: " + machinesPreferenceNode.name()); final boolean wereThereCommandLineArguments = args.length > 0; if (wereThereCommandLineArguments) { final boolean wasSaveFileFlagFound = wasSearchKeyFoundInArray(SAVE_FILE_FLAG, args); if (wasSaveFileFlagFound) { final File preferencesFile = MarginallyCleverPreferencesFileFactory.getXmlPreferencesFile(); try (final OutputStream fileOutputStream = new FileOutputStream(preferencesFile)) { PreferencesHelper.getPreferenceNode(PreferencesHelper.MakelangeloPreferenceKey.LEGACY_MAKELANGELO_ROOT).exportSubtree(fileOutputStream); } catch (IOException e) { Log.error(e.getMessage()); } } final boolean wasPurgeFlagFound = wasSearchKeyFoundInArray(PURGE_FLAG, args); if (wasPurgeFlagFound) { final String[] childrenPreferenceNodeNames = machinesPreferenceNode.childrenNames(); purgeMachineNamesThatAreLessThanZero(machinesPreferenceNode, childrenPreferenceNodeNames); } } }
20. JabRefPreferences#putKeyPattern()
Project: jabref
File: JabRefPreferences.java
File: JabRefPreferences.java
/** * Adds the given key pattern to the preferences * * @param pattern the pattern to store */ public void putKeyPattern(GlobalLabelPattern pattern) { keyPattern = pattern; // Store overridden definitions to Preferences. Preferences pre = Preferences.userNodeForPackage(GlobalLabelPattern.class); try { // We remove all old entries. pre.clear(); } catch (BackingStoreException ex) { LOGGER.info("BackingStoreException in JabRefPreferences.putKeyPattern", ex); } Set<String> allKeys = pattern.getAllKeys(); for (String key : allKeys) { if (!pattern.isDefaultValue(key)) { // no default value // the first entry in the array is the full pattern // see net.sf.jabref.logic.labelPattern.LabelPatternUtil.split(String) pre.put(key, pattern.getValue(key).get(0)); } } }
21. JabRefPreferences#getKeyPattern()
Project: jabref
File: JabRefPreferences.java
File: JabRefPreferences.java
public GlobalLabelPattern getKeyPattern() { keyPattern = new GlobalLabelPattern(); Preferences pre = Preferences.userNodeForPackage(GlobalLabelPattern.class); try { String[] keys = pre.keys(); if (keys.length > 0) { for (String key : keys) { keyPattern.addLabelPattern(key, pre.get(key, null)); } } } catch (BackingStoreException ex) { LOGGER.info("BackingStoreException in JabRefPreferences.getKeyPattern", ex); } return keyPattern; }
22. DirectoryManager#getIgvDirectoryOverride()
Project: igv
File: DirectoryManager.java
File: DirectoryManager.java
private static File getIgvDirectoryOverride() { Preferences userPrefs = null; File override = null; try { // See if an override location has been specified. This is stored with the Java Preferences API userPrefs = Preferences.userNodeForPackage(Globals.class); String userDir = userPrefs.get(IGV_DIR_USERPREF, null); if (userDir != null) { override = new File(userDir); if (!override.exists()) { override = null; userPrefs.remove(IGV_DIR_USERPREF); } } } catch (Exception e) { userPrefs.remove(IGV_DIR_USERPREF); override = null; log.error("Error creating user directory", e); } return override; }
23. FavouriteConnections#exportToFile()
Project: exist
File: FavouriteConnections.java
File: FavouriteConnections.java
public static void exportToFile(final File f) throws IOException, BackingStoreException { final Preferences prefs = Preferences.userNodeForPackage(FavouriteConnections.class); OutputStream os = null; try { os = new FileOutputStream(f); prefs.exportSubtree(os); } finally { if (os != null) { try { os.close(); } catch (final IOException ioe) { ioe.printStackTrace(); } } } }
24. FavouriteConnections#importFromFile()
Project: exist
File: FavouriteConnections.java
File: FavouriteConnections.java
public static void importFromFile(final File f) throws IOException, InvalidPreferencesFormatException { final Preferences prefs = Preferences.userNodeForPackage(FavouriteConnections.class); InputStream is = null; try { is = new FileInputStream(f); prefs.importPreferences(is); } finally { if (is != null) { try { is.close(); } catch (final IOException ioe) { ioe.printStackTrace(); } } } }
25. TestMonitorRunningInstance#makeMockExhibitor()
Project: exhibitor
File: TestMonitorRunningInstance.java
File: TestMonitorRunningInstance.java
private Exhibitor makeMockExhibitor(InstanceConfig config, String us) { Preferences preferences = Mockito.mock(Preferences.class); ControlPanelValues controlPanelValues = new ControlPanelValues(preferences) { @Override public boolean isSet(ControlPanelTypes type) throws Exception { return true; } }; ConfigManager configManager = Mockito.mock(ConfigManager.class); Mockito.when(configManager.getConfig()).thenReturn(config); Exhibitor mockExhibitor = Mockito.mock(Exhibitor.class, Mockito.RETURNS_MOCKS); Mockito.when(mockExhibitor.getConfigManager()).thenReturn(configManager); Mockito.when(mockExhibitor.getThisJVMHostname()).thenReturn(us); Mockito.when(mockExhibitor.getControlPanelValues()).thenReturn(controlPanelValues); return mockExhibitor; }
26. SVNHistory#handleFetchingLatestRepositoryRevision()
Project: code_swarm
File: SVNHistory.java
File: SVNHistory.java
/** * looks up the cache. Stops proceeding if a cached version for this * repository was found. * @param pRevision the latest repository revision. * @return false if a cached version was found, true if the history shall * be fetched from repository. */ public boolean handleFetchingLatestRepositoryRevision(Long pRevision) { long revision = pRevision.longValue(); Preferences p = Preferences.userNodeForPackage(SVNHistory.class); long l = p.getLong(Integer.toString(this.url.hashCode()), -1l); if (l == revision) { LOGGER.log(Level.FINE, "skip fetching {0} (latest revision is {1}) for {2}", new Object[] { String.valueOf(l), revision, this.url }); return false; } else { LOGGER.log(Level.FINE, "proceed fetching (latest revision is {0} , cached revision is {1} for repository {2}", new Object[] { String.valueOf(pRevision), String.valueOf(l), this.url }); Preferences.userNodeForPackage(SVNHistory.class).putLong(Integer.toString(this.url.hashCode()), revision); try { Preferences.userNodeForPackage(SVNHistory.class).flush(); } catch (BackingStoreException ex) { LOGGER.log(Level.SEVERE, null, ex); } } LOGGER.log(Level.FINE, "fetching until revision {0}", new Object[] { revision }); return true; }
27. StubLocationManager#getStatus()
Project: CodenameOne
File: StubLocationManager.java
File: StubLocationManager.java
@Override public int getStatus() { Preferences p = Preferences.userNodeForPackage(com.codename1.ui.Component.class); if (JavaSEPort.locSimulation != null) { int s = JavaSEPort.locSimulation.getState(); setStatus(s); p.putInt("lastGoodLocationStat", s); return s; } else { return p.getInt("lastGoodLocationStat", super.getStatus()); } }
28. JavaSEPort#registerPush()
Project: CodenameOne
File: JavaSEPort.java
File: JavaSEPort.java
@Override public void registerPush(Hashtable meta, boolean noFallback) { Preferences p = Preferences.userNodeForPackage(com.codename1.ui.Component.class); String user = p.get("user", null); Display d = Display.getInstance(); if (user == null) { JPanel pnl = new JPanel(); JTextField tf = new JTextField(20); pnl.add(new JLabel("E-Mail For Push")); pnl.add(tf); JOptionPane.showMessageDialog(canvas, pnl, "Email For Push", JOptionPane.PLAIN_MESSAGE); user = tf.getText(); p.put("user", user); } d.setProperty("built_by_user", user); String mainClass = System.getProperty("MainClass"); if (mainClass != null) { mainClass = mainClass.substring(0, mainClass.lastIndexOf('.')); d.setProperty("package_name", mainClass); } super.registerPush(meta, noFallback); }
29. UserPreferences#track()
Project: CodenameOne
File: UserPreferences.java
File: UserPreferences.java
public static void track(JSplitPane split) { Preferences prefs = node().node("JSplitPane"); // restore the previous location int dividerLocation = prefs.getInt(split.getName() + ".dividerLocation", -1); if (dividerLocation >= 0) { split.setDividerLocation(dividerLocation); } // track changes split.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, splitPaneListener); }
30. UserPreferences#track()
Project: CodenameOne
File: UserPreferences.java
File: UserPreferences.java
/** * Restores the window size, position and state if possible. Tracks the window * size, position and state. * * @param window */ public static void track(Window window) { Preferences prefs = node().node("Windows"); String bounds = prefs.get(window.getName() + ".bounds", null); if (bounds != null) { Rectangle rect = (Rectangle) ConverterRegistry.instance().convert(Rectangle.class, bounds); window.setBounds(rect); } window.addComponentListener(windowDimension); }
31. UserPreferences#track()
Project: CodenameOne
File: UserPreferences.java
File: UserPreferences.java
public static void track(final JRadioButton button) { final Preferences prefs = node().node("Buttons"); boolean selected = prefs.getBoolean(button.getName() + ".selected", button.isSelected()); ((DefaultButtonModel) button.getModel()).getGroup().setSelected(button.getModel(), // .setSelected(selected); selected); button.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { prefs.putBoolean(button.getName() + ".selected", button.isSelected()); } }); }
32. Launcher#main()
Project: ceylon-compiler
File: Launcher.java
File: Launcher.java
public static void main(String... args) { JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); JFileChooser fileChooser; Preferences prefs = Preferences.userNodeForPackage(Launcher.class); if (args.length > 0) fileChooser = new JFileChooser(args[0]); else { String fileName = prefs.get("recent.file", null); fileChooser = new JFileChooser(); if (fileName != null) { fileChooser = new JFileChooser(); fileChooser.setSelectedFile(new File(fileName)); } } if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { String fileName = fileChooser.getSelectedFile().getPath(); prefs.put("recent.file", fileName); javac.run(System.in, null, null, "-d", "/tmp", fileName); } }
33. ThumbelinaFrame#initState()
Project: bboss
File: ThumbelinaFrame.java
File: ThumbelinaFrame.java
/** * Initialize the user preferences. * Reads from the existing user preferences, * or initializes values from the bean directly if they don't exist. * Sets the state of the view checkboxes to match. */ public void initState() { Preferences prefs; prefs = Preferences.userNodeForPackage(getClass()); if (-1 == prefs.getInt(MRULENGTH, -1)) for (int i = 0; i < DEFAULTMRULIST.length; i++) updateMRU(DEFAULTMRULIST[i]); getThumbelina().setStatusBarVisible(prefs.getBoolean(STATUSBARSTATE, getThumbelina().getStatusBarVisible())); mStatusVisible.setSelected(getThumbelina().getStatusBarVisible()); getThumbelina().setHistoryListVisible(prefs.getBoolean(HISTORYLISTSTATE, getThumbelina().getHistoryListVisible())); mHistoryVisible.setSelected(getThumbelina().getHistoryListVisible()); getThumbelina().setSequencerActive(prefs.getBoolean(SEQUENCERACTIVE, getThumbelina().getSequencerActive())); getThumbelina().setBackgroundThreadActive(prefs.getBoolean(BACKGROUNDTHREADACTIVE, getThumbelina().getBackgroundThreadActive())); getThumbelina().setSpeed(prefs.getInt(DISPLAYSPEED, getThumbelina().getSpeed())); }
34. StorageRuntimeProvider#resetStorage()
Project: actor-platform
File: StorageRuntimeProvider.java
File: StorageRuntimeProvider.java
@Override public void resetStorage() { //Clear preferences Preferences pref = this.preferences.getPref(); try { //Only remove this context preferences for (String key : pref.keys()) { pref.remove(context + "_" + key); } } catch (BackingStoreException e) { logger.error("Error in clearing preferences for context: " + context, e); } //TODO clear records in sqlites for this context }
35. MakelangeloRobotSettings#saveConfigToLocal()
Project: Makelangelo
File: MakelangeloRobotSettings.java
File: MakelangeloRobotSettings.java
protected void saveConfigToLocal() { final Preferences uniqueMachinePreferencesNode = topLevelMachinesPreferenceNode.node(Long.toString(robotUID)); uniqueMachinePreferencesNode.put("limit_top", Double.toString(limitTop)); uniqueMachinePreferencesNode.put("limit_bottom", Double.toString(limitBottom)); uniqueMachinePreferencesNode.put("limit_right", Double.toString(limitRight)); uniqueMachinePreferencesNode.put("limit_left", Double.toString(limitLeft)); uniqueMachinePreferencesNode.put("m1invert", Boolean.toString(isLeftMotorInverted)); uniqueMachinePreferencesNode.put("m2invert", Boolean.toString(isRightMotorInverted)); uniqueMachinePreferencesNode.put("bobbin_left_diameter", Double.toString(pulleyDiameterLeft)); uniqueMachinePreferencesNode.put("bobbin_right_diameter", Double.toString(pulleyDiameterRight)); uniqueMachinePreferencesNode.put("feed_rate", Double.toString(maxFeedRate)); uniqueMachinePreferencesNode.put("acceleration", Double.toString(maxAcceleration)); uniqueMachinePreferencesNode.put("startingPosIndex", Integer.toString(startingPositionIndex)); uniqueMachinePreferencesNode.putDouble("paper_left", paperLeft); uniqueMachinePreferencesNode.putDouble("paper_right", paperRight); uniqueMachinePreferencesNode.putDouble("paper_top", paperTop); uniqueMachinePreferencesNode.putDouble("paper_bottom", paperBottom); // save each tool's settings for (DrawingTool tool : tools) { tool.saveConfig(uniqueMachinePreferencesNode); } uniqueMachinePreferencesNode.put("paper_margin", Double.toString(paperMargin)); uniqueMachinePreferencesNode.put("reverseForGlass", Boolean.toString(reverseForGlass)); uniqueMachinePreferencesNode.put("current_tool", Integer.toString(getCurrentToolNumber())); uniqueMachinePreferencesNode.put("isRegistered", Boolean.toString(isRegistered)); }
36. ThumbelinaFrame#saveState()
Project: bboss
File: ThumbelinaFrame.java
File: ThumbelinaFrame.java
/** * Saves the current settings in the user preferences. * By default this writes to the thumbelina subdirectory under * .java in the users home directory. */ public void saveState() { Preferences prefs; prefs = Preferences.userNodeForPackage(getClass()); // don't save size unless we're in normal state if (NORMAL == getExtendedState()) prefs.put(FRAMESIZE, toString(getBounds())); prefs.putBoolean(STATUSBARSTATE, getThumbelina().getStatusBarVisible()); prefs.putBoolean(HISTORYLISTSTATE, getThumbelina().getHistoryListVisible()); prefs.putBoolean(SEQUENCERACTIVE, getThumbelina().getSequencerActive()); prefs.putBoolean(BACKGROUNDTHREADACTIVE, getThumbelina().getBackgroundThreadActive()); prefs.putInt(DISPLAYSPEED, getThumbelina().getSpeed()); try { prefs.flush(); } catch (BackingStoreException bse) { bse.printStackTrace(); } }
37. PreferencesRecentWorkspacesServiceTest#blankIsNotLoaded()
Project: pdfsam
File: PreferencesRecentWorkspacesServiceTest.java
File: PreferencesRecentWorkspacesServiceTest.java
@Test public void blankIsNotLoaded() throws BackingStoreException { Preferences node = Preferences.userRoot().node(WORKSPACES_PATH); node.put("1", EMPTY); node.flush(); PreferencesRecentWorkspacesService newVictim = new PreferencesRecentWorkspacesService(); assertEquals(0, newVictim.getRecentlyUsedWorkspaces().size()); }
38. CheckUserPrefLater#main()
Project: openjdk
File: CheckUserPrefLater.java
File: CheckUserPrefLater.java
public static void main(String[] args) throws Exception { Preferences prefs = Preferences.userNodeForPackage(CheckUserPrefFirst.class); String result = prefs.get("Check", null); if ((result == null) || !(result.equals("Success"))) throw new RuntimeException("User pref not stored!"); prefs.remove("Check"); prefs.flush(); }
39. CheckUserPrefFirst#main()
Project: openjdk
File: CheckUserPrefFirst.java
File: CheckUserPrefFirst.java
public static void main(String[] args) throws Exception { Preferences prefs = Preferences.userNodeForPackage(CheckUserPrefFirst.class); prefs.put("Check", "Success"); prefs.flush(); }
40. AppSettings#save()
Project: jmonkeyengine
File: AppSettings.java
File: AppSettings.java
/** * 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(); }
41. PickMIDlet#okButtonActionPerformed()
Project: CodenameOne
File: PickMIDlet.java
File: PickMIDlet.java
//GEN-LAST:event_pickJarFileActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) { //GEN-FIRST:event_okButtonActionPerformed SwingUtilities.windowForComponent(this).dispose(); Preferences pref = Preferences.userNodeForPackage(ResourceEditorView.class); pref.put("jar", jarFile.getText()); pref.put("midlet", (String) midletPicker.getSelectedItem()); }
42. PickMIDlet#resetSettings()
Project: CodenameOne
File: PickMIDlet.java
File: PickMIDlet.java
public static void resetSettings() { Preferences pref = Preferences.userNodeForPackage(ResourceEditorView.class); pref.remove("jar"); pref.remove("midlet"); }
43. ThumbelinaFrame#updateMRU()
Project: bboss
File: ThumbelinaFrame.java
File: ThumbelinaFrame.java
/** * Updates the user preferences based on the most recently used list. * @param url The URL that is to be placed at the top of the MRU list. */ public void updateMRU(String url) { Preferences prefs; int count; ArrayList list; String string; int max; if (url.startsWith("http://")) url = url.substring(7); prefs = Preferences.userNodeForPackage(getClass()); count = prefs.getInt(MRULENGTH, -1); list = new ArrayList(); for (int i = 0; i < count; i++) { string = prefs.get(MRUPREFIX + i, ""); if (!"".equals(string) && !url.equalsIgnoreCase(string)) list.add(string); } list.add(0, url); max = prefs.getInt(MRUMAX, -1); if (-1 == max) max = 8; while (list.size() > max) list.remove(max); prefs.putInt(MRULENGTH, list.size()); prefs.putInt(MRUMAX, max); for (int i = 0; i < list.size(); i++) prefs.put(MRUPREFIX + i, (String) list.get(i)); try { prefs.flush(); } catch (BackingStoreException bse) { bse.printStackTrace(); } }
44. CvalCheckerTest#cachedPreferences()
Project: vaadin
File: CvalCheckerTest.java
File: CvalCheckerTest.java
static String cachedPreferences(String productName) { // ~/Library/Preferences/com.apple.java.util.prefs.plist // .java/.userPrefs/com/google/gwt/dev/shell/prefs.xml // HKEY_CURRENT_USER\SOFTWARE\JavaSoft\Prefs Preferences p = Preferences.userNodeForPackage(CvalInfo.class); return p.get(productName, null); }
45. CvalChecker#deleteCache()
Project: vaadin
File: CvalChecker.java
File: CvalChecker.java
/* * used in tests */ static void deleteCache(String productName) { Preferences p = Preferences.userNodeForPackage(CvalInfo.class); p.remove(productName); }
46. WinUtils#start()
Project: UniversalMediaServer
File: WinUtils.java
File: WinUtils.java
private void start() { final Preferences userRoot = Preferences.userRoot(); final Preferences systemRoot = Preferences.systemRoot(); final Class<? extends Preferences> clz = userRoot.getClass(); try { if (clz.getName().endsWith("WindowsPreferences")) { final Method openKey = clz.getDeclaredMethod("WindowsRegOpenKey", int.class, byte[].class, int.class); openKey.setAccessible(true); final Method closeKey = clz.getDeclaredMethod("WindowsRegCloseKey", int.class); closeKey.setAccessible(true); final Method winRegQueryValue = clz.getDeclaredMethod("WindowsRegQueryValueEx", int.class, byte[].class); winRegQueryValue.setAccessible(true); byte[] valb; String key; // Check if VLC is installed key = "SOFTWARE\\VideoLAN\\VLC"; int handles[] = (int[]) openKey.invoke(systemRoot, -2147483646, toCstr(key), KEY_READ); if (!(handles.length == 2 && handles[0] != 0 && handles[1] == 0)) { key = "SOFTWARE\\Wow6432Node\\VideoLAN\\VLC"; handles = (int[]) openKey.invoke(systemRoot, -2147483646, toCstr(key), KEY_READ); } if (handles.length == 2 && handles[0] != 0 && handles[1] == 0) { valb = (byte[]) winRegQueryValue.invoke(systemRoot, handles[0], toCstr("")); vlcp = (valb != null ? new String(valb).trim() : null); valb = (byte[]) winRegQueryValue.invoke(systemRoot, handles[0], toCstr("Version")); vlcv = (valb != null ? new String(valb).trim() : null); closeKey.invoke(systemRoot, handles[0]); } // Check if AviSynth is installed key = "SOFTWARE\\AviSynth"; handles = (int[]) openKey.invoke(systemRoot, -2147483646, toCstr(key), KEY_READ); if (!(handles.length == 2 && handles[0] != 0 && handles[1] == 0)) { key = "SOFTWARE\\Wow6432Node\\AviSynth"; handles = (int[]) openKey.invoke(systemRoot, -2147483646, toCstr(key), KEY_READ); } if (handles.length == 2 && handles[0] != 0 && handles[1] == 0) { avis = true; valb = (byte[]) winRegQueryValue.invoke(systemRoot, handles[0], toCstr("plugindir2_5")); avsPluginsDir = (valb != null ? new String(valb).trim() : null); closeKey.invoke(systemRoot, handles[0]); } // Check if K-Lite Codec Pack is installed key = "SOFTWARE\\Wow6432Node\\KLCodecPack"; handles = (int[]) openKey.invoke(systemRoot, -2147483646, toCstr(key), KEY_READ); if (!(handles.length == 2 && handles[0] != 0 && handles[1] == 0)) { key = "SOFTWARE\\KLCodecPack"; handles = (int[]) openKey.invoke(systemRoot, -2147483646, toCstr(key), KEY_READ); } if (handles.length == 2 && handles[0] != 0 && handles[1] == 0) { valb = (byte[]) winRegQueryValue.invoke(systemRoot, handles[0], toCstr("installdir")); kLiteFiltersDir = (valb != null ? new String(valb).trim() : null); closeKey.invoke(systemRoot, handles[0]); } // Check if Kerio is installed key = "SOFTWARE\\Kerio"; handles = (int[]) openKey.invoke(systemRoot, -2147483646, toCstr(key), KEY_READ); if (handles.length == 2 && handles[0] != 0 && handles[1] == 0) { kerio = true; } } } catch (NoSuchMethodExceptionSecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | e) { LOGGER.debug("Caught exception", e); } }
47. Visualizer2TopComponent#makeWindow()
Project: Universal-G-Code-Sender
File: Visualizer2TopComponent.java
File: Visualizer2TopComponent.java
private GLJPanel makeWindow(final GLCapabilities caps) { final GLJPanel p = new GLJPanel(caps); renderer = new GcodeRenderer(); animator = new FPSAnimator(p, 15); RendererInputHandler rih = new RendererInputHandler(renderer, animator); Preferences pref = NbPreferences.forModule(VisualizerOptionsPanel.class); pref.addPreferenceChangeListener(rih); if (backend.getProcessedGcodeFile() != null) { rih.setProcessedGcodeFile(backend.getProcessedGcodeFile().getAbsolutePath()); } else if (backend.getGcodeFile() != null) { rih.setGcodeFile(backend.getGcodeFile().getAbsolutePath()); } // Install listeners... EventBus eb = Lookup.getDefault().lookup(HighlightEventBus.class); if (eb != null) { eb.register(rih); } backend.addControllerListener(rih); backend.addUGSEventListener(rih); // shutdown hook... //frame.addWindowListener(rih); // key listener... p.addKeyListener(rih); // mouse wheel... p.addMouseWheelListener(rih); // mouse motion... p.addMouseMotionListener(rih); // mouse... p.addMouseListener(rih); p.addGLEventListener((GLEventListener) renderer); return p; }
48. WinUtils#start()
Project: ps3mediaserver
File: WinUtils.java
File: WinUtils.java
private void start() { final Preferences userRoot = Preferences.userRoot(); final Preferences systemRoot = Preferences.systemRoot(); final Class<? extends Preferences> clz = userRoot.getClass(); try { if (clz.getName().endsWith("WindowsPreferences")) { final Method openKey = clz.getDeclaredMethod("WindowsRegOpenKey", int.class, byte[].class, int.class); openKey.setAccessible(true); final Method closeKey = clz.getDeclaredMethod("WindowsRegCloseKey", int.class); closeKey.setAccessible(true); final Method winRegQueryValue = clz.getDeclaredMethod("WindowsRegQueryValueEx", int.class, byte[].class); winRegQueryValue.setAccessible(true); byte[] valb; String key; // Check if VLC is installed key = "SOFTWARE\\VideoLAN\\VLC"; int handles[] = (int[]) openKey.invoke(systemRoot, -2147483646, toCstr(key), KEY_READ); if (!(handles.length == 2 && handles[0] != 0 && handles[1] == 0)) { key = "SOFTWARE\\Wow6432Node\\VideoLAN\\VLC"; handles = (int[]) openKey.invoke(systemRoot, -2147483646, toCstr(key), KEY_READ); } if (handles.length == 2 && handles[0] != 0 && handles[1] == 0) { valb = (byte[]) winRegQueryValue.invoke(systemRoot, handles[0], toCstr("")); vlcp = (valb != null ? new String(valb).trim() : null); valb = (byte[]) winRegQueryValue.invoke(systemRoot, handles[0], toCstr("Version")); vlcv = (valb != null ? new String(valb).trim() : null); closeKey.invoke(systemRoot, handles[0]); } // Check if AviSynth is installed key = "SOFTWARE\\AviSynth"; handles = (int[]) openKey.invoke(systemRoot, -2147483646, toCstr(key), KEY_READ); if (!(handles.length == 2 && handles[0] != 0 && handles[1] == 0)) { key = "SOFTWARE\\Wow6432Node\\AviSynth"; handles = (int[]) openKey.invoke(systemRoot, -2147483646, toCstr(key), KEY_READ); } if (handles.length == 2 && handles[0] != 0 && handles[1] == 0) { avis = true; valb = (byte[]) winRegQueryValue.invoke(systemRoot, handles[0], toCstr("plugindir2_5")); avsPluginsDir = (valb != null ? new String(valb).trim() : null); closeKey.invoke(systemRoot, handles[0]); } // Check if Kerio is installed key = "SOFTWARE\\Kerio"; handles = (int[]) openKey.invoke(systemRoot, -2147483646, toCstr(key), KEY_READ); if (handles.length == 2 && handles[0] != 0 && handles[1] == 0) { kerio = true; } } } catch (Exception e) { logger.debug("Caught exception", e); } }
49. AbstractStepMeta#saveAsPreferences()
Project: pentaho-kettle
File: AbstractStepMeta.java
File: AbstractStepMeta.java
/** * Saves properties to preferences. * * @throws BackingStoreException * ... */ public void saveAsPreferences() throws BackingStoreException { final Preferences node = Preferences.userNodeForPackage(this.getClass()); this.getProperties().walk(new SaveToPreferences(node)); node.flush(); }
50. PreferencesUsageDataStore#getTotalUsage()
Project: pdfsam
File: PreferencesUsageDataStore.java
File: PreferencesUsageDataStore.java
public long getTotalUsage() { Preferences node = Preferences.userRoot().node(USAGE_PATH); return node.getLong(TASKS_EXECUTED_KEY, 0); }
51. PreferencesUsageDataStore#incrementTotalUsage()
Project: pdfsam
File: PreferencesUsageDataStore.java
File: PreferencesUsageDataStore.java
private void incrementTotalUsage() { Preferences node = Preferences.userRoot().node(USAGE_PATH); node.putLong(TASKS_EXECUTED_KEY, node.getLong(TASKS_EXECUTED_KEY, 0) + 1); }
52. CodePointZeroPrefsTest#main()
Project: openjdk
File: CodePointZeroPrefsTest.java
File: CodePointZeroPrefsTest.java
public static void main(String[] args) throws Exception { int failures = 0; Preferences node = Preferences.userRoot().node("com/acme/testing"); // legal key and value try { node.put("a", "1"); } catch (IllegalArgumentException iae) { System.err.println("Unexpected IllegalArgumentException for legal put() key"); failures++; } // illegal key only try { node.put("ab", "1"); System.err.println("IllegalArgumentException not thrown for illegal put() key"); failures++; } catch (IllegalArgumentException iae) { } // illegal value only try { node.put("ab", "23"); System.err.println("IllegalArgumentException not thrown for illegal put() value"); failures++; } catch (IllegalArgumentException iae) { } // illegal key and value try { node.put("ab", "23"); System.err.println("IllegalArgumentException not thrown for illegal put() entry"); failures++; } catch (IllegalArgumentException iae) { } // illegal key only try { String theDefault = "default"; String value = node.get("ab", theDefault); System.err.println("IllegalArgumentException not thrown for illegal get() key"); failures++; } catch (IllegalArgumentException iae) { } // illegal key only try { node.remove("ab"); System.err.println("IllegalArgumentException not thrown for illegal remove() key"); failures++; } catch (IllegalArgumentException iae) { } node.removeNode(); if (failures != 0) { throw new RuntimeException("CodePointZeroPrefsTest failed with " + failures + " errors!"); } }
53. PermanentInstallationID#calculateInstallationId()
Project: intellij-community
File: PermanentInstallationID.java
File: PermanentInstallationID.java
private static String calculateInstallationId() { final Preferences oldPrefs = Preferences.userRoot(); // compatibility with previous versions final String oldValue = oldPrefs.get(OLD_USER_ON_MACHINE_ID_KEY, null); final Preferences prefs = Preferences.userRoot().node("jetbrains"); String installationId = prefs.get(INSTALLATION_ID_KEY, null); if (installationId == null || installationId.isEmpty()) { installationId = oldValue != null && !oldValue.isEmpty() ? oldValue : UUID.randomUUID().toString(); prefs.put(INSTALLATION_ID_KEY, installationId); } // for Windows attempt to use PermanentUserId, so that DotNet products and IDEA would use the same ID. if (SystemInfo.isWindows) { final String appdata = System.getenv("APPDATA"); if (appdata != null) { final File dir = new File(appdata, "JetBrains"); if (dir.exists() || dir.mkdirs()) { final File permanentIdFile = new File(dir, "PermanentUserId"); try { String fromFile = ""; if (permanentIdFile.exists()) { fromFile = loadFromFile(permanentIdFile).trim(); } if (!fromFile.isEmpty()) { if (!fromFile.equals(installationId)) { installationId = fromFile; prefs.put(INSTALLATION_ID_KEY, installationId); } } else { writeToFile(permanentIdFile, installationId); } } catch (IOException ignored) { } } } } // make sure values in older location and in the new location are the same if (!installationId.equals(oldValue)) { oldPrefs.put(OLD_USER_ON_MACHINE_ID_KEY, installationId); } return installationId; }
54. LoadInputsFromXML#actionPerformed()
Project: incubator-taverna-workbench
File: LoadInputsFromXML.java
File: LoadInputsFromXML.java
@Override public void actionPerformed(ActionEvent e) { Preferences prefs = Preferences.userNodeForPackage(getClass()); String curDir = prefs.get(INPUT_DATA_DIR_PROPERTY, System.getProperty("user.home")); JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Select file to load input values from"); chooser.resetChoosableFileFilters(); chooser.setFileFilter(new ExtensionFileFilter(new String[] { "xml" })); chooser.setCurrentDirectory(new File(curDir)); if (chooser.showOpenDialog(null) != APPROVE_OPTION) return; prefs.put(INPUT_DATA_DIR_PROPERTY, chooser.getCurrentDirectory().toString()); try { File file = chooser.getSelectedFile(); InputStreamReader stream; stream = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")); Document inputDoc = new SAXBuilder(false).build(stream); Map<String, DataThing> inputMap = DataThingXMLFactory.parseDataDocument(inputDoc); for (String portName : inputMap.keySet()) { RegistrationPanel panel = inputPanelMap.get(portName); Object o = inputMap.get(portName).getDataObject(); if (o != null) { int objectDepth = getObjectDepth(o); if ((panel != null) && (objectDepth <= panel.getDepth())) panel.setValue(o, objectDepth); } } } catch (Exception ex) { } }
55. FavouriteConnections#load()
Project: exist
File: FavouriteConnections.java
File: FavouriteConnections.java
public static List<FavouriteConnection> load() { final Preferences prefs = Preferences.userNodeForPackage(FavouriteConnections.class); final Preferences favouritesNode = prefs.node(FAVOURITES_NODE); // Get all favourites String favouriteNodeNames[] = new String[0]; try { favouriteNodeNames = favouritesNode.childrenNames(); } catch (final BackingStoreException ex) { ex.printStackTrace(); } // Copy for each connection data into Favourite array final List<FavouriteConnection> favourites = new ArrayList<FavouriteConnection>(); for (final String favouriteNodeName : favouriteNodeNames) { final Preferences node = favouritesNode.node(favouriteNodeName); final FavouriteConnection favourite; if ((!"".equals(node.get(FavouriteConnection.URI, ""))) && (!"".equals(node.get(FavouriteConnection.CONFIGURATION, "")))) { if (node.get(FavouriteConnection.URI, "").equals(XmldbURI.EMBEDDED_SERVER_URI.toString())) { //embedded favourite = getEmbeddedFavourite(favouriteNodeName, node); } else { //remote favourite = getRemoteFavourite(favouriteNodeName, node); } } else { if ("".equals(node.get(FavouriteConnection.URI, ""))) { //embedded favourite = getEmbeddedFavourite(favouriteNodeName, node); } else { //remote favourite = getRemoteFavourite(favouriteNodeName, node); } } favourites.add(favourite); } Collections.sort(favourites); return favourites; }
56. FavouriteConnections#store()
Project: exist
File: FavouriteConnections.java
File: FavouriteConnections.java
public static void store(final List<FavouriteConnection> favourites) { final Preferences prefs = Preferences.userNodeForPackage(FavouriteConnections.class); // Clear connection node Preferences favouritesNode = prefs.node(FAVOURITES_NODE); try { favouritesNode.removeNode(); } catch (final BackingStoreException ex) { ex.printStackTrace(); } // Recreate connection node favouritesNode = prefs.node(FAVOURITES_NODE); // Write all favourites for (final FavouriteConnection favourite : favourites) { if (favourites != null) { // Create node final Preferences favouriteNode = favouritesNode.node(favourite.getName()); // Fill node favouriteNode.put(FavouriteConnection.USERNAME, favourite.getUsername()); //do NOT store passwords in plain-text in users preferences //favouriteNode.put(FavouriteConnection.PASSWORD, favourite.getPassword()); favouriteNode.put(FavouriteConnection.PASSWORD, ""); //TODO hash passwords before storing - need to implement server-side login with hashes favouriteNode.put(FavouriteConnection.URI, favourite.getUri()); favouriteNode.put(FavouriteConnection.CONFIGURATION, favourite.getConfiguration()); favouriteNode.put(FavouriteConnection.SSL, Boolean.valueOf(favourite.isSsl()).toString().toUpperCase()); } } }
57. JavaSEPort#downloadSkin()
Project: CodenameOne
File: JavaSEPort.java
File: JavaSEPort.java
private File downloadSkin(File skinDir, String url, String version, JLabel label) throws IOException { String fileName = url.substring(url.lastIndexOf("/")); File skin = new File(skinDir.getAbsolutePath() + "/" + fileName); HttpURLConnection.setFollowRedirects(true); URL u = new URL(url); FileOutputStream os = new FileOutputStream(skin); URLConnection uc = u.openConnection(); InputStream is = uc.getInputStream(); int length = uc.getContentLength(); byte[] buffer = new byte[65536]; int size = is.read(buffer); int offset = 0; int percent = 0; String msg = label.getText(); if (length > 0) { System.out.println("Downloading " + length + " bytes"); } while (size > -1) { offset += size; if (length > 0) { float f = ((float) offset) / ((float) length) * 100; if (percent != ((int) f)) { percent = (int) f; label.setText(msg + " " + percent + "%"); label.repaint(); } } else { if (percent < offset / 102400) { percent = offset / 102400; System.out.println("Downloaded " + percent + "00Kb"); } } os.write(buffer, 0, size); size = is.read(buffer); } is.close(); os.close(); //store the skin version Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class); pref.put(fileName, version); return skin; }
58. JavaSEPort#init()
Project: CodenameOne
File: JavaSEPort.java
File: JavaSEPort.java
/** * @inheritDoc */ public void init(Object m) { inInit = true; // this is essential for push and other things to work in the simulator Preferences p = Preferences.userNodeForPackage(com.codename1.ui.Component.class); String user = p.get("user", null); if (user != null) { Display d = Display.getInstance(); d.setProperty("built_by_user", user); String mainClass = System.getProperty("MainClass"); if (mainClass != null) { mainClass = mainClass.substring(0, mainClass.lastIndexOf('.')); d.setProperty("package_name", mainClass); } } try { Class.forName("javafx.embed.swing.JFXPanel"); Platform.setImplicitExit(false); fxExists = true; } catch (Throwable ex) { } String hide = System.getProperty("hideMenu", "false"); if (hide != null && hide.equals("true")) { showMenu = false; } URLConnection.setDefaultAllowUserInteraction(true); HttpURLConnection.setFollowRedirects(false); Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class); if (!blockMonitors && pref.getBoolean("NetworkMonitor", false)) { showNetworkMonitor(); } if (!blockMonitors && pref.getBoolean("PerformanceMonitor", false)) { showPerformanceMonitor(); } if (defaultInitTarget != null && m == null) { m = defaultInitTarget; } if (canvas.getParent() != null) { canvas.getParent().remove(canvas); } if (m != null && m instanceof java.awt.Container) { java.awt.Container cnt = (java.awt.Container) m; if (cnt.getLayout() instanceof java.awt.BorderLayout) { cnt.add(java.awt.BorderLayout.CENTER, canvas); } else { cnt.add(canvas); } } else { window = new JFrame(); java.awt.Image large = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/application64.png")); java.awt.Image small = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/application48.png")); try { // setIconImages is only available in JDK 1.6 window.setIconImages(Arrays.asList(new java.awt.Image[] { large, small })); } catch (Throwable err) { window.setIconImage(small); } window.addWindowListener(new WindowListener() { public void windowOpened(WindowEvent e) { } public void windowClosing(WindowEvent e) { Display.getInstance().exitApplication(); } public void windowClosed(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } }); window.setLocationByPlatform(true); window.setLayout(new java.awt.BorderLayout()); hSelector = new JScrollBar(Scrollbar.HORIZONTAL); vSelector = new JScrollBar(Scrollbar.VERTICAL); hSelector.addAdjustmentListener(canvas); vSelector.addAdjustmentListener(canvas); android6PermissionsFlag = pref.getBoolean("Android6Permissions", false); scrollableSkin = pref.getBoolean("Scrollable", true); if (scrollableSkin) { window.add(java.awt.BorderLayout.SOUTH, hSelector); window.add(java.awt.BorderLayout.EAST, vSelector); } window.add(java.awt.BorderLayout.CENTER, canvas); String reset = System.getProperty("resetSkins"); if (reset != null && reset.equals("true")) { System.setProperty("resetSkins", ""); pref = Preferences.userNodeForPackage(JavaSEPort.class); pref.put("skins", DEFAULT_SKINS); } if (hasSkins()) { String f = System.getProperty("skin"); if (f != null) { loadSkinFile(f, window); } else { String d = System.getProperty("dskin"); f = pref.get("skin", d); loadSkinFile(f, window); } } else { Resources.setRuntimeMultiImageEnabled(true); window.setUndecorated(true); window.setExtendedState(JFrame.MAXIMIZED_BOTH); } window.pack(); if (getSkin() != null && !scrollableSkin) { float w1 = ((float) canvas.getWidth()) / ((float) getSkin().getWidth()); float h1 = ((float) canvas.getHeight()) / ((float) getSkin().getHeight()); zoomLevel = Math.min(h1, w1); } portrait = pref.getBoolean("Portrait", true); if (!portrait && getSkin() != null) { canvas.setForcedSize(new java.awt.Dimension(getSkin().getWidth(), getSkin().getHeight())); window.setSize(new java.awt.Dimension(getSkin().getWidth(), getSkin().getHeight())); } window.setVisible(true); } if (useNativeInput) { Display.getInstance().setDefaultVirtualKeyboard(null); } float factor = ((float) getDisplayHeight()) / 480.0f; if (factor > 0 && autoAdjustFontSize && getSkin() != null) { // set a reasonable default font size setFontSize((int) (15.0f * factor), (int) (11.0f * factor), (int) (19.0f * factor)); } if (m instanceof Runnable) { Display.getInstance().callSerially((Runnable) m); } inInit = false; }
59. JavaSEPort#disablePerformanceMonitor()
Project: CodenameOne
File: JavaSEPort.java
File: JavaSEPort.java
static void disablePerformanceMonitor() { perfMonitor = null; Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class); pref.putBoolean("PerformanceMonitor", false); }
60. JavaSEPort#disableNetworkMonitor()
Project: CodenameOne
File: JavaSEPort.java
File: JavaSEPort.java
static void disableNetworkMonitor() { netMonitor = null; Preferences pref = Preferences.userNodeForPackage(JavaSEPort.class); pref.putBoolean("NetworkMonitor", false); }
61. Application#applyPreferences()
Project: nodebox
File: Application.java
File: Application.java
/** * Load the preferences and make them available to the Application object. */ private void applyPreferences() { Preferences preferences = Preferences.userNodeForPackage(Application.class); ENABLE_DEVICE_SUPPORT = Boolean.valueOf(preferences.get(Application.PREFERENCE_ENABLE_DEVICE_SUPPORT, "false")); }
62. DrupalDevelPreferences#getDrupalPath()
Project: NBDrupalDevel
File: DrupalDevelPreferences.java
File: DrupalDevelPreferences.java
/** * Retrieve the library path for a given project or the global default if the library * path is not set in the project properties window. * * @param phpModule The phpModule to perform the lookup on * @return A string containing the absolute path to the library files. */ public static String getDrupalPath(Project phpModule) { Preferences preferences = getPreferences(phpModule); String drupalVersion = preferences.get(DRUPAL_PATH, ""); return drupalVersion; }
63. DrupalDevelPreferences#getLibraryPath()
Project: NBDrupalDevel
File: DrupalDevelPreferences.java
File: DrupalDevelPreferences.java
public static String getLibraryPath(Project phpModule, Boolean includeDefault) { Preferences preferences = getPreferences(phpModule); String drupalVersion = preferences.get(DRUPAL_LIBRARY_PATH, ""); if (includeDefault && (drupalVersion.isEmpty() || drupalVersion.equals(""))) { drupalVersion = getDefaultLibraryPath(); } return drupalVersion; }
64. DrupalDevelPreferences#getDrupalVersion()
Project: NBDrupalDevel
File: DrupalDevelPreferences.java
File: DrupalDevelPreferences.java
/** * Retrieves the Drupal version for a specific module. If the version is not found * then the global default version is returned * * @param phpModule the phpModule to retrieve the version for * @return a string containing the Drupal version */ public static String getDrupalVersion(Project phpModule) { Preferences preferences = getPreferences(phpModule); String drupalVersion = preferences.get(DRUPAL_VERSION, ""); if (drupalVersion.equals("") || drupalVersion.equals("Default")) { drupalVersion = getDefaultDrupalVersion(); } return drupalVersion; }
65. MarginallyCleverPreferences#recursiveGetParent()
Project: Makelangelo
File: MarginallyCleverPreferences.java
File: MarginallyCleverPreferences.java
private Preferences recursiveGetParent(Preferences node) { Preferences parent = node.parent(); if (parent == null) { node = parent; } else { recursiveGetParent(parent); } return node; }
66. MarginallyCleverPreferences#storeNodeInFile()
Project: Makelangelo
File: MarginallyCleverPreferences.java
File: MarginallyCleverPreferences.java
private void storeNodeInFile(File file) throws IOException, BackingStoreException { final Preferences parent = recursiveGetParent(this.parent() != null ? this.parent() : this); try (final OutputStream fileOutputStream = new FileOutputStream(file)) { parent.exportNode(fileOutputStream); } }
67. MakelangeloRobotSettings#loadConfigFromLocal()
Project: Makelangelo
File: MakelangeloRobotSettings.java
File: MakelangeloRobotSettings.java
protected void loadConfigFromLocal() { final Preferences uniqueMachinePreferencesNode = topLevelMachinesPreferenceNode.node(Long.toString(robotUID)); limitTop = Double.valueOf(uniqueMachinePreferencesNode.get("limit_top", Double.toString(limitTop))); limitBottom = Double.valueOf(uniqueMachinePreferencesNode.get("limit_bottom", Double.toString(limitBottom))); limitLeft = Double.valueOf(uniqueMachinePreferencesNode.get("limit_left", Double.toString(limitLeft))); limitRight = Double.valueOf(uniqueMachinePreferencesNode.get("limit_right", Double.toString(limitRight))); paperLeft = Double.parseDouble(uniqueMachinePreferencesNode.get("paper_left", Double.toString(paperLeft))); paperRight = Double.parseDouble(uniqueMachinePreferencesNode.get("paper_right", Double.toString(paperRight))); paperTop = Double.parseDouble(uniqueMachinePreferencesNode.get("paper_top", Double.toString(paperTop))); paperBottom = Double.parseDouble(uniqueMachinePreferencesNode.get("paper_bottom", Double.toString(paperBottom))); isLeftMotorInverted = Boolean.parseBoolean(uniqueMachinePreferencesNode.get("m1invert", Boolean.toString(isLeftMotorInverted))); isRightMotorInverted = Boolean.parseBoolean(uniqueMachinePreferencesNode.get("m2invert", Boolean.toString(isRightMotorInverted))); pulleyDiameterLeft = Double.valueOf(uniqueMachinePreferencesNode.get("bobbin_left_diameter", Double.toString(pulleyDiameterLeft))); pulleyDiameterRight = Double.valueOf(uniqueMachinePreferencesNode.get("bobbin_right_diameter", Double.toString(pulleyDiameterRight))); maxFeedRate = Double.valueOf(uniqueMachinePreferencesNode.get("feed_rate", Double.toString(maxFeedRate))); maxAcceleration = Double.valueOf(uniqueMachinePreferencesNode.get("acceleration", Double.toString(maxAcceleration))); startingPositionIndex = Integer.valueOf(uniqueMachinePreferencesNode.get("startingPosIndex", Integer.toString(startingPositionIndex))); // load each tool's settings for (DrawingTool tool : tools) { tool.loadConfig(uniqueMachinePreferencesNode); } paperMargin = Double.valueOf(uniqueMachinePreferencesNode.get("paper_margin", Double.toString(paperMargin))); reverseForGlass = Boolean.parseBoolean(uniqueMachinePreferencesNode.get("reverseForGlass", Boolean.toString(reverseForGlass))); setCurrentToolNumber(Integer.valueOf(uniqueMachinePreferencesNode.get("current_tool", Integer.toString(getCurrentToolNumber())))); setRegistered(Boolean.parseBoolean(uniqueMachinePreferencesNode.get("isRegistered", Boolean.toString(isRegistered)))); }
68. Makelangelo#adjustGraphics()
Project: Makelangelo
File: Makelangelo.java
File: Makelangelo.java
/** * Adjust graphics preferences */ protected void adjustGraphics() { final Preferences graphics_prefs = PreferencesHelper.getPreferenceNode(PreferencesHelper.MakelangeloPreferenceKey.GRAPHICS); final JPanel panel = new JPanel(new GridBagLayout()); //final JCheckBox allow_metrics = new JCheckBox(String.valueOf("I want to add the distance drawn to the // total")); //allow_metrics.setSelected(allowMetrics); final JCheckBox show_pen_up = new JCheckBox(Translator.get("MenuGraphicsPenUp")); final JCheckBox antialias_on = new JCheckBox(Translator.get("MenuGraphicsAntialias")); final JCheckBox speed_over_quality = new JCheckBox(Translator.get("MenuGraphicsSpeedVSQuality")); final JCheckBox draw_all_while_running = new JCheckBox(Translator.get("MenuGraphicsDrawWhileRunning")); show_pen_up.setSelected(graphics_prefs.getBoolean("show pen up", false)); antialias_on.setSelected(graphics_prefs.getBoolean("antialias", true)); speed_over_quality.setSelected(graphics_prefs.getBoolean("speed over quality", true)); draw_all_while_running.setSelected(graphics_prefs.getBoolean("Draw all while running", true)); GridBagConstraints c = new GridBagConstraints(); //c.gridwidth=4; c.gridx=0; c.gridy=0; driver.add(allow_metrics,c); int y = 0; c.anchor = GridBagConstraints.WEST; c.gridwidth = 1; c.gridx = 1; c.gridy = y; panel.add(show_pen_up, c); y++; c.anchor = GridBagConstraints.WEST; c.gridwidth = 1; c.gridx = 1; c.gridy = y; panel.add(draw_all_while_running, c); y++; c.anchor = GridBagConstraints.WEST; c.gridwidth = 1; c.gridx = 1; c.gridy = y; panel.add(antialias_on, c); y++; c.anchor = GridBagConstraints.WEST; c.gridwidth = 1; c.gridx = 1; c.gridy = y; panel.add(speed_over_quality, c); y++; int result = JOptionPane.showConfirmDialog(this.mainFrame, panel, Translator.get("MenuGraphicsTitle"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { //allowMetrics = allow_metrics.isSelected(); graphics_prefs.putBoolean("show pen up", show_pen_up.isSelected()); graphics_prefs.putBoolean("antialias", antialias_on.isSelected()); graphics_prefs.putBoolean("speed over quality", speed_over_quality.isSelected()); graphics_prefs.putBoolean("Draw all while running", draw_all_while_running.isSelected()); robot.setShowPenUp(show_pen_up.isSelected()); } }
69. AppSettings#load()
Project: jmonkeyengine
File: AppSettings.java
File: AppSettings.java
/** * 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, (Integer) 0)); break; case 'F': put(key.substring(2), prefs.getFloat(key, (Float) 0f)); break; case 'S': put(key.substring(2), prefs.get(key, (String) null)); break; case 'B': put(key.substring(2), prefs.getBoolean(key, (Boolean) 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 neccessary 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)); } } } } }
70. Prefs#migrate()
Project: intellij-community
File: Prefs.java
File: Prefs.java
private static <T> void migrate(String key, T def, Getter<T> getter, Setter<T> setter) { // rewrite from old location into the new one final Preferences prefs = Preferences.userRoot(); final T val = getter.get(prefs, key, def); if (!Comparing.equal(val, def)) { setter.set(getPreferences(key), getNodeKey(key), val); prefs.remove(key); } }
71. Prefs#getPreferences()
Project: intellij-community
File: Prefs.java
File: Prefs.java
private static Preferences getPreferences(String key) { Preferences prefs = Preferences.userRoot(); final int dotIndex = key.lastIndexOf('.'); if (dotIndex > 0) { final StringTokenizer tokenizer = new StringTokenizer(key.substring(0, dotIndex), ".", false); while (tokenizer.hasMoreElements()) { prefs = prefs.node(tokenizer.nextElement().toLowerCase(Locale.US)); } } return prefs; }
72. SaveDescriptionAction#saveStringToFile()
Project: incubator-taverna-workbench-common-activities
File: SaveDescriptionAction.java
File: SaveDescriptionAction.java
public static boolean saveStringToFile(Component parent, String dialogTitle, String extension, ToolDescription description) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle(dialogTitle); fileChooser.resetChoosableFileFilters(); fileChooser.setAcceptAllFileFilterUsed(true); fileChooser.setFileFilter(new ExtensionFileFilter(new String[] { extension })); Preferences prefs = Preferences.userNodeForPackage(FileTools.class); String curDir = prefs.get("currentDir", System.getProperty("user.home")); fileChooser.setCurrentDirectory(new File(curDir)); boolean tryAgain = true; while (tryAgain) { tryAgain = false; int returnVal = fileChooser.showSaveDialog(parent); if (returnVal == JFileChooser.APPROVE_OPTION) { prefs.put("currentDir", fileChooser.getCurrentDirectory().toString()); File file = fileChooser.getSelectedFile(); if (!file.getName().contains(".")) { String newName = file.getName() + extension; file = new File(file.getParentFile(), newName); } // TODO: Open in separate thread to avoid hanging UI try { List<ToolDescription> currentDescriptions; if (file.exists()) { currentDescriptions = ToolDescriptionParser.readDescriptionsFromStream(new FileInputStream(file)); } else { currentDescriptions = new ArrayList<ToolDescription>(); } Element overallElement = new Element("usecases"); for (ToolDescription ud : currentDescriptions) { if (!ud.getUsecaseid().equals(description.getUsecaseid())) { overallElement.addContent(ud.writeToXMLElement()); } } overallElement.addContent(description.writeToXMLElement()); BufferedWriter out = new BufferedWriter(new FileWriter(file)); out.write(outputter.outputString(overallElement)); out.close(); logger.info("Saved content by overwriting " + file); return true; } catch (IOException ex) { logger.warn("Could not save content to " + file, ex); JOptionPane.showMessageDialog(parent, "Could not save to " + file + ": \n\n" + ex.getMessage(), "Warning", JOptionPane.WARNING_MESSAGE); return false; } } } return false; }
73. FileTools#readStringFromFile()
Project: incubator-taverna-workbench
File: FileTools.java
File: FileTools.java
public static String readStringFromFile(Component parent, String dialogTitle, String extension) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle(dialogTitle); fileChooser.resetChoosableFileFilters(); fileChooser.setAcceptAllFileFilterUsed(true); fileChooser.setFileFilter(new ExtensionFileFilter(new String[] { extension })); Preferences prefs = Preferences.userNodeForPackage(FileTools.class); String curDir = prefs.get("currentDir", System.getProperty("user.home")); fileChooser.setCurrentDirectory(new File(curDir)); if (fileChooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); try { return FileUtils.readFileToString(selectedFile, StandardCharsets.UTF_8.name()); } catch (IOException ioe) { JOptionPane.showMessageDialog(parent, "Can not read file '" + selectedFile.getName() + "'", "Can not read file", JOptionPane.ERROR_MESSAGE); } } return null; }
74. FileTools#saveStringToFile()
Project: incubator-taverna-workbench
File: FileTools.java
File: FileTools.java
public static boolean saveStringToFile(Component parent, String dialogTitle, String extension, String content) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle(dialogTitle); fileChooser.resetChoosableFileFilters(); fileChooser.setAcceptAllFileFilterUsed(true); fileChooser.setFileFilter(new ExtensionFileFilter(new String[] { extension })); Preferences prefs = Preferences.userNodeForPackage(FileTools.class); String curDir = prefs.get("currentDir", System.getProperty("user.home")); fileChooser.setCurrentDirectory(new File(curDir)); boolean tryAgain = true; while (tryAgain) { tryAgain = false; int returnVal = fileChooser.showSaveDialog(parent); if (returnVal == JFileChooser.APPROVE_OPTION) { prefs.put("currentDir", fileChooser.getCurrentDirectory().toString()); File file = fileChooser.getSelectedFile(); if (!file.getName().contains(".")) { String newName = file.getName() + extension; file = new File(file.getParentFile(), newName); } // TODO: Open in separate thread to avoid hanging UI try { if (file.exists()) { logger.info("File already exists: " + file); String msg = "Are you sure you want to overwrite existing file " + file + "?"; int ret = JOptionPane.showConfirmDialog(parent, msg, "File already exists", JOptionPane.YES_NO_CANCEL_OPTION); if (ret == JOptionPane.YES_OPTION) { } else if (ret == JOptionPane.NO_OPTION) { tryAgain = true; continue; } else { logger.info("Aborted overwrite of " + file); return false; } } FileUtils.writeStringToFile(file, content, StandardCharsets.UTF_8.name()); logger.info("Saved content by overwriting " + file); return true; } catch (IOException ex) { logger.warn("Could not save content to " + file, ex); JOptionPane.showMessageDialog(parent, "Could not save to " + file + ": \n\n" + ex.getMessage(), "Warning", JOptionPane.WARNING_MESSAGE); return false; } } } return false; }
75. SaveAllResultsSPI#actionPerformed()
Project: incubator-taverna-workbench
File: SaveAllResultsSPI.java
File: SaveAllResultsSPI.java
/** * Shows a standard save dialog and dumps the entire result * set to the specified XML file. */ @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(false); JFileChooser fc = new JFileChooser(); Preferences prefs = Preferences.userNodeForPackage(getClass()); String curDir = prefs.get("currentDir", getProperty("user.home")); fc.resetChoosableFileFilters(); if (getFilter() != null) fc.setFileFilter(new ExtensionFileFilter(new String[] { getFilter() })); fc.setCurrentDirectory(new File(curDir)); fc.setFileSelectionMode(getFileSelectionMode()); while (true) { if (fc.showSaveDialog(null) != APPROVE_OPTION) return; prefs.put("currentDir", fc.getCurrentDirectory().toString()); File file = fc.getSelectedFile(); /* * If the user did not use the extension for the file, append it to * the file name now */ if (getFilter() != null && !file.getName().toLowerCase().endsWith("." + getFilter())) { String newFileName = file.getName() + "." + getFilter(); file = new File(file.getParentFile(), newFileName); } final File finalFile = file; if (// File already exists file.exists()) // Ask the user if they want to overwrite the file if (showConfirmDialog(null, file.getAbsolutePath() + " already exists. Do you want to overwrite it?", "File already exists", YES_NO_OPTION) != YES_OPTION) continue; // File doesn't exist, or user has OK'd overwriting it // Do this in separate thread to avoid hanging UI new Thread("SaveAllResults: Saving results to " + finalFile) { @Override public void run() { saveDataToFile(finalFile); } }.start(); return; } }
76. SaveInputsAsXML#actionPerformed()
Project: incubator-taverna-workbench
File: SaveInputsAsXML.java
File: SaveInputsAsXML.java
/** * Shows a standard save dialog and dumps the entire input set to the * specified XML file. */ @Override public void actionPerformed(ActionEvent e) { Preferences prefs = Preferences.userNodeForPackage(getClass()); String curDir = prefs.get(INPUT_DATA_DIR_PROPERTY, getProperty("user.home")); JFileChooser fc = new JFileChooser(); fc.setDialogTitle("Select file to save input values to"); fc.resetChoosableFileFilters(); fc.setFileFilter(new ExtensionFileFilter(new String[] { "xml" })); fc.setCurrentDirectory(new File(curDir)); fc.setFileSelectionMode(FILES_ONLY); File file; do { if (fc.showSaveDialog(null) != APPROVE_OPTION) return; prefs.put(INPUT_DATA_DIR_PROPERTY, fc.getCurrentDirectory().toString()); file = fc.getSelectedFile(); /* * If the user did not use the .xml extension for the file - append * it to the file name now */ if (!file.getName().toLowerCase().endsWith(".xml")) file = new File(file.getParentFile(), file.getName() + ".xml"); // If the file exists, ask the user if they want to overwrite the file } while (file.exists() && showConfirmDialog(null, file.getAbsolutePath() + " already exists. Do you want to overwrite it?", "File already exists", YES_NO_OPTION) != YES_OPTION); doSave(file); }
77. SaveGraphImageSubMenu#saveDialogue()
Project: incubator-taverna-workbench
File: SaveGraphImageSubMenu.java
File: SaveGraphImageSubMenu.java
/** * Pop up a save dialogue relating to the given workflow. This method can be * used, for example, for saving the workflow diagram as .png, and will use * the existing workflow title as a base for suggesting a filename. * * @param parentComponent * Parent component for dialogue window * @param model * Workflow to save * @param extension * Extension for filename, such as "jpg" * @param windowTitle * Title for dialogue box, such as "Save workflow diagram" * @return File instance for the selected abstract filename, or null if the * dialogue was cancelled. */ private File saveDialogue(Component parentComponent, Workflow workflow, String extension, String windowTitle) { JFileChooser fc = new JFileChooser(); Preferences prefs = Preferences.userNodeForPackage(SaveGraphImageSubMenu.class); String curDir = prefs.get("currentDir", System.getProperty("user.home")); String suggestedFileName = ""; // Get the source the workflow was loaded from - can be File, URL, or InputStream Object source = fileManager.getDataflowSource(workflow.getParent()); if (source instanceof File) { suggestedFileName = ((File) source).getName(); // remove the file extension suggestedFileName = suggestedFileName.substring(0, suggestedFileName.lastIndexOf(".")); } else if (source instanceof URL) { suggestedFileName = ((URL) source).getPath(); // remove the file extension suggestedFileName = suggestedFileName.substring(0, suggestedFileName.lastIndexOf(".")); } else { // We cannot suggest the file name if workflow was read from an InputStream } fc.setDialogTitle(windowTitle); fc.resetChoosableFileFilters(); fc.setFileFilter(new ExtensionFileFilter(new String[] { extension })); if (suggestedFileName.isEmpty()) // No file suggestion, just the directory fc.setCurrentDirectory(new File(curDir)); else // Suggest a filename from the workflow file name fc.setSelectedFile(new File(curDir, suggestedFileName + "." + extension)); while (true) { if (fc.showSaveDialog(parentComponent) != APPROVE_OPTION) { logger.info("GraphViewComponent: Aborting diagram export to " + suggestedFileName); return null; } File file = fixExtension(fc.getSelectedFile(), extension); logger.debug("GraphViewComponent: Selected " + file + " as export target"); prefs.put("currentDir", fc.getCurrentDirectory().toString()); // If file doesn't exist, we may write it! (Well, probably...) if (!file.exists()) return file; // Ask the user if they want to overwrite the file String msg = file.getAbsolutePath() + " already exists. Do you want to overwrite it?"; if (showConfirmDialog(null, msg, "File already exists", YES_NO_OPTION) == JOptionPane.YES_OPTION) return file; } }
78. SaveWorkflowAsAction#saveDataflow()
Project: incubator-taverna-workbench
File: SaveWorkflowAsAction.java
File: SaveWorkflowAsAction.java
public boolean saveDataflow(Component parentComponent, WorkflowBundle workflowBundle) { fileManager.setCurrentDataflow(workflowBundle); JFileChooser fileChooser = new JFileChooser(); Preferences prefs = Preferences.userNodeForPackage(getClass()); String curDir = prefs.get(PREF_CURRENT_DIR, System.getProperty("user.home")); fileChooser.setDialogTitle(SAVE_WORKFLOW_AS); fileChooser.resetChoosableFileFilters(); fileChooser.setAcceptAllFileFilterUsed(false); List<FileFilter> fileFilters = fileManager.getSaveFileFilters(File.class); if (fileFilters.isEmpty()) { logger.warn("No file types found for saving workflow " + workflowBundle); showMessageDialog(parentComponent, "No file types found for saving workflow.", "Error", ERROR_MESSAGE); return false; } for (FileFilter fileFilter : fileFilters) fileChooser.addChoosableFileFilter(fileFilter); fileChooser.setFileFilter(fileFilters.get(0)); fileChooser.setCurrentDirectory(new File(curDir)); File possibleName = new File(determineFileName(workflowBundle)); boolean tryAgain = true; while (tryAgain) { tryAgain = false; fileChooser.setSelectedFile(possibleName); int returnVal = fileChooser.showSaveDialog(parentComponent); if (returnVal == APPROVE_OPTION) { prefs.put(PREF_CURRENT_DIR, fileChooser.getCurrentDirectory().toString()); File file = fileChooser.getSelectedFile(); FileTypeFileFilter fileFilter = (FileTypeFileFilter) fileChooser.getFileFilter(); FileType fileType = fileFilter.getFileType(); String extension = "." + fileType.getExtension(); if (!file.getName().toLowerCase().endsWith(extension)) { String newName = file.getName() + extension; file = new File(file.getParentFile(), newName); } // TODO: Open in separate thread to avoid hanging UI try { try { fileManager.saveDataflow(workflowBundle, fileType, file, true); logger.info("Saved workflow " + workflowBundle + " to " + file); return true; } catch (OverwriteException ex) { logger.info("File already exists: " + file); String msg = "Are you sure you want to overwrite existing file " + file + "?"; int ret = showConfirmDialog(parentComponent, msg, "File already exists", YES_NO_CANCEL_OPTION); if (ret == YES_OPTION) { fileManager.saveDataflow(workflowBundle, fileType, file, false); logger.info("Saved workflow " + workflowBundle + " by overwriting " + file); return true; } else if (ret == NO_OPTION) { tryAgain = true; continue; } else { logger.info("Aborted overwrite of " + file); return false; } } } catch (SaveException ex) { logger.warn("Could not save workflow to " + file, ex); showMessageDialog(parentComponent, "Could not save workflow to " + file + ": \n\n" + ex.getMessage(), "Warning", WARNING_MESSAGE); return false; } } } return false; }
79. OpenWorkflowAction#openWorkflows()
Project: incubator-taverna-workbench
File: OpenWorkflowAction.java
File: OpenWorkflowAction.java
/** * Pop up an Open-dialogue to select one or more workflow files to open. * * @param parentComponent * The UI parent component to use for pop up dialogues * @param openCallback * An {@link OpenCallback} to be called during the file opening. * The callback will be invoked for each file that has been * opened, as file opening happens in a separate thread that * might execute after the return of this method. * @return <code>false</code> if no files were selected or the dialogue was * cancelled, or <code>true</code> if the process of opening one or * more files has been started. */ public boolean openWorkflows(final Component parentComponent, OpenCallback openCallback) { JFileChooser fileChooser = new JFileChooser(); Preferences prefs = userNodeForPackage(getClass()); String curDir = prefs.get("currentDir", System.getProperty("user.home")); fileChooser.setDialogTitle(OPEN_WORKFLOW); fileChooser.resetChoosableFileFilters(); fileChooser.setAcceptAllFileFilterUsed(false); List<FileFilter> fileFilters = fileManager.getOpenFileFilters(); if (fileFilters.isEmpty()) { logger.warn("No file types found for opening workflow"); showMessageDialog(parentComponent, "No file types found for opening workflow.", "Error", ERROR_MESSAGE); return false; } for (FileFilter fileFilter : fileFilters) fileChooser.addChoosableFileFilter(fileFilter); fileChooser.setFileFilter(fileFilters.get(0)); fileChooser.setCurrentDirectory(new File(curDir)); fileChooser.setMultiSelectionEnabled(true); int returnVal = fileChooser.showOpenDialog(parentComponent); if (returnVal == APPROVE_OPTION) { prefs.put("currentDir", fileChooser.getCurrentDirectory().toString()); final File[] selectedFiles = fileChooser.getSelectedFiles(); if (selectedFiles.length == 0) { logger.warn("No files selected"); return false; } FileFilter fileFilter = fileChooser.getFileFilter(); FileType fileType; if (fileFilter instanceof FileTypeFileFilter) fileType = ((FileTypeFileFilter) fileChooser.getFileFilter()).getFileType(); else // Unknown filetype, try all of them fileType = null; new FileOpenerThread(parentComponent, selectedFiles, fileType, openCallback).start(); return true; } return false; }
80. OpenSourceWorkflowAction#openWorkflows()
Project: incubator-taverna-workbench
File: OpenSourceWorkflowAction.java
File: OpenSourceWorkflowAction.java
/** * Pop up an Open-dialogue to select one or more workflow files to open. * * @param parentComponent * The UI parent component to use for pop up dialogues * @param openCallback * An {@link OpenCallback} to be called during the file opening. * The callback will be invoked for each file that has been * opened, as file opening happens in a separate thread that * might execute after the return of this method. * @return <code>false</code> if no files were selected or the dialogue was * cancelled, or <code>true</code> if the process of opening one or * more files has been started. */ public boolean openWorkflows(final Component parentComponent) { JFileChooser fileChooser = new JFileChooser(); Preferences prefs = Preferences.userNodeForPackage(getClass()); String curDir = prefs.get("currentDir", System.getProperty("user.home")); fileChooser.setDialogTitle(OPEN_WORKFLOW); fileChooser.resetChoosableFileFilters(); fileChooser.setAcceptAllFileFilterUsed(false); List<FileFilter> fileFilters = fileManager.getOpenFileFilters(); if (fileFilters.isEmpty()) { logger.warn("No file types found for opening workflow"); JOptionPane.showMessageDialog(parentComponent, "No file types found for opening workflow.", "Error", JOptionPane.ERROR_MESSAGE); return false; } for (FileFilter fileFilter : fileFilters) { fileChooser.addChoosableFileFilter(fileFilter); } fileChooser.setFileFilter(fileFilters.get(0)); fileChooser.setCurrentDirectory(new File(curDir)); fileChooser.setMultiSelectionEnabled(true); int returnVal = fileChooser.showOpenDialog(parentComponent); if (returnVal == JFileChooser.APPROVE_OPTION) { prefs.put("currentDir", fileChooser.getCurrentDirectory().toString()); final File[] selectedFiles = fileChooser.getSelectedFiles(); if (selectedFiles.length == 0) { logger.warn("No files selected"); return false; } new FileOpenerThread(parentComponent, selectedFiles).start(); return true; } return false; }
81. ExportServiceDescriptionsAction#actionPerformed()
Project: incubator-taverna-workbench
File: ExportServiceDescriptionsAction.java
File: ExportServiceDescriptionsAction.java
@Override public void actionPerformed(ActionEvent e) { JComponent parentComponent = null; if (e.getSource() instanceof JComponent) parentComponent = (JComponent) e.getSource(); if (INHIBIT) { showMessageDialog(parentComponent, "Operation not currently working correctly", "Not Implemented", ERROR_MESSAGE); return; } JFileChooser fileChooser = new JFileChooser(); Preferences prefs = Preferences.userNodeForPackage(getClass()); String curDir = prefs.get(SERVICE_EXPORT_DIR_PROPERTY, System.getProperty("user.home")); fileChooser.setDialogTitle("Select file to export services to"); fileChooser.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(EXTENSION); } @Override public String getDescription() { return ".xml files"; } }); fileChooser.setCurrentDirectory(new File(curDir)); boolean tryAgain = true; while (tryAgain) { tryAgain = false; int returnVal = fileChooser.showSaveDialog(parentComponent); if (returnVal == APPROVE_OPTION) { prefs.put(SERVICE_EXPORT_DIR_PROPERTY, fileChooser.getCurrentDirectory().toString()); File file = fileChooser.getSelectedFile(); if (!file.getName().toLowerCase().endsWith(EXTENSION)) { String newName = file.getName() + EXTENSION; file = new File(file.getParentFile(), newName); } try { if (file.exists()) { String msg = "Are you sure you want to overwrite existing file " + file + "?"; int ret = showConfirmDialog(parentComponent, msg, "File already exists", YES_NO_CANCEL_OPTION); if (ret == NO_OPTION) { tryAgain = true; continue; } else if (ret != YES_OPTION) { logger.info("Service descriptions export: aborted overwrite of " + file.getAbsolutePath()); break; } } exportServiceDescriptions(file); break; } catch (Exception ex) { logger.error("Service descriptions export: failed to export services to " + file.getAbsolutePath(), ex); showMessageDialog(parentComponent, "Failed to export services to " + file.getAbsolutePath(), "Error", ERROR_MESSAGE); break; } } } if (parentComponent instanceof JButton) // lose the focus from the button after performing the action parentComponent.requestFocusInWindow(); }
82. Executor#setProxySettings()
Project: CodenameOne
File: Executor.java
File: Executor.java
private static void setProxySettings() { Preferences proxyPref = Preferences.userNodeForPackage(Component.class); int proxySel = proxyPref.getInt("proxySel", 2); String proxySelHttp = proxyPref.get("proxySel-http", ""); String proxySelPort = proxyPref.get("proxySel-port", ""); switch(proxySel) { case 1: System.getProperties().remove("java.net.useSystemProxies"); System.getProperties().remove("http.proxyHost"); System.getProperties().remove("http.proxyPort"); System.getProperties().remove("https.proxyHost"); System.getProperties().remove("https.proxyPort"); break; case 2: System.setProperty("java.net.useSystemProxies", "true"); System.getProperties().remove("http.proxyHost"); System.getProperties().remove("http.proxyPort"); System.getProperties().remove("https.proxyHost"); System.getProperties().remove("https.proxyPort"); break; case 3: System.setProperty("http.proxyHost", proxySelHttp); System.setProperty("http.proxyPort", proxySelPort); System.setProperty("https.proxyHost", proxySelHttp); System.setProperty("https.proxyPort", proxySelPort); break; } }
83. ResourceEditorView#initNativeTheme()
Project: CodenameOne
File: ResourceEditorView.java
File: ResourceEditorView.java
private void initNativeTheme() { Preferences p = Preferences.userNodeForPackage(getClass()); String t = p.get("nativeCN1Theme", "/iPhoneTheme.res"); boolean local = p.getBoolean("nativeCN1Local", true); setNativeTheme(t, local); if (local) { if (t.equals("/iPhoneTheme.res")) { iosNativeTheme.setSelected(true); return; } if (t.equals("/iOS7Theme.res")) { ios7NativeTheme.setSelected(true); return; } if (t.equals("/androidTheme.res")) { android2NativeTheme.setSelected(true); return; } if (t.equals("/blackberry_theme.res")) { blackberryNativeTheme.setSelected(true); return; } if (t.equals("/winTheme.res")) { winNativeTheme.setSelected(true); return; } } else { customNativeTheme.setSelected(true); } }
84. PickMIDlet#startMIDlet()
Project: CodenameOne
File: PickMIDlet.java
File: PickMIDlet.java
public static void startMIDlet(Hashtable themeHash) { Accessor.setTheme(themeHash); Preferences pref = Preferences.userNodeForPackage(ResourceEditorView.class); String jar = pref.get("jar", null); String midlet = pref.get("midlet", null); if (jar != null && midlet != null) { File jarFile = new File(jar); if (jarFile.exists()) { try { URLClassLoader cl = URLClassLoader.newInstance(new URL[] { jarFile.toURI().toURL() }, PickMIDlet.class.getClassLoader()); StringTokenizer tokenizer = new StringTokenizer((String) midlet, " ,"); String s = tokenizer.nextToken(); while (tokenizer.hasMoreTokens()) { s = tokenizer.nextToken(); } Class cls = cl.loadClass(s); JavaSEPortWithSVGSupport.setClassLoader(cls); EditableResources.setResourcesClassLoader(cls); Accessor.setTheme(themeHash); Object app = cls.newInstance(); JarFile zip = new JarFile(jarFile); Attributes m = zip.getManifest().getMainAttributes(); cls.getDeclaredMethod("init", new Class[] { Object.class }).invoke(app, new Object[] { null }); cls.getDeclaredMethod("start", new Class[0]).invoke(app, new Object[0]); // there might be an ongoing transition and the form.show() method is serial Display.getInstance().callSerially(new Runnable() { public void run() { if (Display.getInstance().getCurrent() != null) { Display.getInstance().getCurrent().refreshTheme(); return; } else { new Thread() { public void run() { try { sleep(100); } catch (InterruptedException ex) { ex.printStackTrace(); } Display.getInstance().callSerially(this); } }.start(); } } }); return; } catch (Exception ex) { ex.printStackTrace(); } } } JavaSEPortWithSVGSupport.setClassLoader(PickMIDlet.class); LiveDemo l = new LiveDemo(); l.init(null); l.start(); Accessor.setTheme(themeHash); Form current = Display.getInstance().getCurrent(); if (current != null) { current.refreshTheme(); } }
85. ThumbelinaFrame#googlesearch()
Project: bboss
File: ThumbelinaFrame.java
File: ThumbelinaFrame.java
/** * Query google via user specified keywords and queue results. * Asks the user for keywords, and then submits them as input to the * usual google form: * <pre> * <form action="/search" name=f> * <span id=hf></span> * <table cellspacing=0 cellpadding=0> * <tr valign=middle> * <td width=75> </td> * <td align=center> * <input maxLength=256 size=55 name=q value=""> * <input type=hidden name=ie value="UTF-8"> * <input type=hidden name=oe value="UTF-8"> * <input name=hl type=hidden value=en><br> * <input type=submit value="Google Search" name=btnG> * <input type=submit value="I'm Feeling Lucky" name=btnI> * </td> * <td valign=top nowrap><font size=-2> * • <a href=/advanced_search?hl=en>Advanced Search</a> * <br> • <a href=/preferences?hl=en>Preferences</a> * <br> • <a href=/language_tools?hl=en>Language Tools</a> * </font> * </td> * </tr> * <tr> * <td colspan=3 align=center><font size=-1> * Search: <input id=all type=radio name=meta value="" checked> * <label for=all> the web</label> * <input id=cty type=radio name=meta value="cr=countryCA" > * <label for=cty>pages from Canada</label> * </font> * </td> * </tr> * </table> * </form> * </pre> * Creates a query of the form: * <pre> * http://www.google.ca/search?hl=en&ie=UTF-8&oe=UTF-8&q=thumbs&btnG=Google+Search&meta= * </pre> */ public void googlesearch() { Preferences prefs; String query; String terms; StringBuffer buffer; HttpURLConnection connection; URL url; Lexer lexer; URL[][] results; prefs = Preferences.userNodeForPackage(getClass()); query = prefs.get(GOOGLEQUERY, DEFAULTGOOGLEQUERY); try { query = (String) JOptionPane.showInputDialog(this, "Enter the search term:", "Search Google", JOptionPane.PLAIN_MESSAGE, null, null, query); if (null != query) { // replace spaces with + terms = query.replace(' ', '+'); buffer = new StringBuffer(1024); buffer.append("http://www.google.ca/search?"); buffer.append("q="); buffer.append(terms); buffer.append("&ie=UTF-8"); buffer.append("&oe=UTF-8"); buffer.append("&hl=en"); buffer.append("&btnG=Google+Search"); buffer.append("&meta="); url = new URL(buffer.toString()); connection = (HttpURLConnection) url.openConnection(); if (USE_MOZILLA_HEADERS) { // These are the Mozilla header fields: //Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1 //Accept-Language: en-us, en;q=0.50 //Connection: keep-alive //Host: grc.com //Referer: https://grc.com/x/ne.dll?bh0bkyd2 //User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) Gecko/20030225 //Content-Length: 27 //Content-Type: application/x-www-form-urlencoded //Accept-Encoding: gzip, deflate, compress;q=0.9 //Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66 //Keep-Alive: 300 connection.setRequestProperty("Referer", "http://www.google.ca"); connection.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1"); connection.setRequestProperty("Accept-Language", "en-us, en;q=0.50"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) Gecko/20030225"); connection.setRequestProperty("Accept-Charset", "ISO-8859-1, utf-8;q=0.66, *;q=0.66"); } else { // These are the IE header fields: //Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */* //Accept-Language: en-ca //Connection: Keep-Alive //Host: grc.com //User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; trieste; .NET CLR 1.1.4322; .NET CLR 1.0.3705) //Content-Length: 32 //Content-Type: application/x-www-form-urlencoded //Accept-Encoding: gzip, deflate //Cache-Control: no-cache connection.setRequestProperty("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); connection.setRequestProperty("Accept-Language", "en-ca"); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; trieste; .NET CLR 1.1.4322; .NET CLR 1.0.3705)"); } connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); lexer = new Lexer(connection); results = getThumbelina().extractImageLinks(lexer, url); // add 'em getThumbelina().reset(); // remove google links, not just append (results[1]); for (int i = 0; i < results[1].length; i++) { String found = results[1][i].toExternalForm(); if (-1 == found.indexOf("google")) getThumbelina().append(results[1][i]); } prefs.put(GOOGLEQUERY, query); try { prefs.flush(); } catch (BackingStoreException bse) { bse.printStackTrace(); } } } catch (Exception e) { System.out.println(e.getMessage()); } }
86. ThumbelinaFrame#updateMenu()
Project: bboss
File: ThumbelinaFrame.java
File: ThumbelinaFrame.java
/** * Adjusts the menu, by inserting the current MRU list. * Removes the old MRU (Most Recently Used) items and inserts new * ones betweeen the two separators. */ public void updateMenu() { Preferences prefs; int start; int end; Component component; JMenuItem item; int count; String string; prefs = Preferences.userNodeForPackage(getClass()); start = -1; end = -1; for (int i = 0; i < mURL.getItemCount(); i++) { component = mURL.getMenuComponent(i); if (component == mSeparator1) start = i + 1; else if (component == mSeparator2) end = i; } if ((-1 != start) && (-1 != end)) { for (int i = start; i < end; i++) mURL.remove(start); count = prefs.getInt(MRULENGTH, 0); for (int i = 0; i < count; i++) { string = prefs.get(MRUPREFIX + i, ""); if (!"".equals(string)) { item = new JMenuItem(); item.setActionCommand(string); if (string.length() > 40) string = string.substring(0, 38) + "..."; item.setText(string); item.addActionListener(this); mURL.add(item, start++); } } } }
87. ThumbelinaFrame#restoreSize()
Project: bboss
File: ThumbelinaFrame.java
File: ThumbelinaFrame.java
/** * Restores the window size based on stored preferences. * If no preferences exist, it calls <code>initSize()</code>. */ public void restoreSize() { Preferences prefs; String size; Rectangle rectangle; prefs = Preferences.userNodeForPackage(getClass()); size = prefs.get(FRAMESIZE, ""); if ("".equals(size)) initSize(); else try { rectangle = fromString(size); if (rational(rectangle)) setBounds(rectangle.x, rectangle.y, rectangle.width, rectangle.height); else initSize(); } catch (IllegalArgumentException iae) { initSize(); } }
88. TreeViewer#showInDialog()
Project: antlr4
File: TreeViewer.java
File: TreeViewer.java
protected static JDialog showInDialog(final TreeViewer viewer) { final JDialog dialog = new JDialog(); dialog.setTitle("Parse Tree Inspector"); final Preferences prefs = Preferences.userNodeForPackage(TreeViewer.class); // Make new content panes final Container mainPane = new JPanel(new BorderLayout(5, 5)); final Container contentPane = new JPanel(new BorderLayout(0, 0)); contentPane.setBackground(Color.white); // Wrap viewer in scroll pane JScrollPane scrollPane = new JScrollPane(viewer); // Make the scrollpane (containing the viewer) the center component contentPane.add(scrollPane, BorderLayout.CENTER); JPanel wrapper = new JPanel(new FlowLayout()); // Add button to bottom JPanel bottomPanel = new JPanel(new BorderLayout(0, 0)); contentPane.add(bottomPanel, BorderLayout.SOUTH); JButton ok = new JButton("OK"); ok.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING)); } }); wrapper.add(ok); // Add an export-to-png button right of the "OK" button JButton png = new JButton("Export as PNG"); png.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { generatePNGFile(viewer, dialog); } }); wrapper.add(png); bottomPanel.add(wrapper, BorderLayout.SOUTH); // Add scale slider double lastKnownViewerScale = prefs.getDouble(DIALOG_VIEWER_SCALE_PREFS_KEY, viewer.getScale()); viewer.setScale(lastKnownViewerScale); int sliderValue = (int) ((lastKnownViewerScale - 1.0) * 1000); final JSlider scaleSlider = new JSlider(JSlider.HORIZONTAL, -999, 1000, sliderValue); scaleSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { int v = scaleSlider.getValue(); viewer.setScale(v / 1000.0 + 1.0); } }); bottomPanel.add(scaleSlider, BorderLayout.CENTER); // Add a JTree representing the parser tree of the input. JPanel treePanel = new JPanel(new BorderLayout(5, 5)); // An "empty" icon that will be used for the JTree's nodes. Icon empty = new EmptyIcon(); UIManager.put("Tree.closedIcon", empty); UIManager.put("Tree.openIcon", empty); UIManager.put("Tree.leafIcon", empty); Tree parseTreeRoot = viewer.getTree().getRoot(); TreeNodeWrapper nodeRoot = new TreeNodeWrapper(parseTreeRoot, viewer); fillTree(nodeRoot, parseTreeRoot, viewer); final JTree tree = new JTree(nodeRoot); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { JTree selectedTree = (JTree) e.getSource(); TreePath path = selectedTree.getSelectionPath(); if (path != null) { TreeNodeWrapper treeNode = (TreeNodeWrapper) path.getLastPathComponent(); // Set the clicked AST. viewer.setTree((Tree) treeNode.getUserObject()); } } }); treePanel.add(new JScrollPane(tree)); // Create the pane for both the JTree and the AST final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treePanel, contentPane); mainPane.add(splitPane, BorderLayout.CENTER); dialog.setContentPane(mainPane); // make viz WindowListener exitListener = new WindowAdapter() { public void windowClosing(WindowEvent e) { prefs.putInt(DIALOG_WIDTH_PREFS_KEY, (int) dialog.getSize().getWidth()); prefs.putInt(DIALOG_HEIGHT_PREFS_KEY, (int) dialog.getSize().getHeight()); prefs.putDouble(DIALOG_X_PREFS_KEY, dialog.getLocationOnScreen().getX()); prefs.putDouble(DIALOG_Y_PREFS_KEY, dialog.getLocationOnScreen().getY()); prefs.putInt(DIALOG_DIVIDER_LOC_PREFS_KEY, splitPane.getDividerLocation()); prefs.putDouble(DIALOG_VIEWER_SCALE_PREFS_KEY, viewer.getScale()); dialog.setVisible(false); dialog.dispose(); } }; dialog.addWindowListener(exitListener); dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); int width = prefs.getInt(DIALOG_WIDTH_PREFS_KEY, 600); int height = prefs.getInt(DIALOG_HEIGHT_PREFS_KEY, 500); dialog.setPreferredSize(new Dimension(width, height)); dialog.pack(); // After pack(): set the divider at 1/3 (200/600) of the frame. int dividerLocation = prefs.getInt(DIALOG_DIVIDER_LOC_PREFS_KEY, 200); splitPane.setDividerLocation(dividerLocation); if (prefs.getDouble(DIALOG_X_PREFS_KEY, -1) != -1) { dialog.setLocation((int) prefs.getDouble(DIALOG_X_PREFS_KEY, 100), (int) prefs.getDouble(DIALOG_Y_PREFS_KEY, 100)); } else { dialog.setLocationRelativeTo(null); } dialog.setVisible(true); return dialog; }
89. Main#start()
Project: viskell
File: Main.java
File: Main.java
@Override public void start(Stage stage) throws Exception { primaryStage = stage; Font.loadFont(this.getClass().getResourceAsStream("/ui/fonts/titillium.otf"), 20); GhciSession ghci = new GhciSession(); ghci.startAsync(); ToplevelPane toplevelPane = new ToplevelPane(ghci); MainOverlay overlay = new MainOverlay(toplevelPane); Scene scene = new Scene(overlay); Preferences prefs = Preferences.userNodeForPackage(Main.class); String backGroundImage = prefs.get("background", "/ui/grid.png"); toplevelPane.setStyle("-fx-background-image: url('" + backGroundImage + "');"); String theme = prefs.get("theme", "/ui/colours.css"); scene.getStylesheets().addAll("/ui/layout.css", theme); stage.setWidth(1024); stage.setHeight(768); stage.setOnCloseRequest( event -> System.exit(0)); stage.setScene(scene); stage.show(); toplevelPane.requestFocus(); // Check if GHCI is available try { ghci.awaitRunning(); // trigger loading of libraries and test QuickCheck ListenableFuture<String> test = ghci.pullRaw("sample' (arbitrary :: Gen Int)"); Futures.addCallback(test, new FutureCallback<String>() { public void onSuccess(String result) { // all ok } public void onFailure(Throwable error) { error.printStackTrace(); String msg = "It seems like QuickCheck is not working, thus the Arbitry block can not be used."; if (error instanceof HaskellException) { Platform.runLater(() -> new Alert(Alert.AlertType.WARNING, msg).showAndWait()); } } }); } catch (RuntimeException e) { String msg = "It seems the Glasgow Haskell Compiler, GHC, is not " + "available. Executing programs will not be enabled. We " + "strongly recommend you install GHC, for example by " + "installing the Haskell Platform (haskell.org/platform)." + "Or it might be that the QuickCheck is not installed."; new Alert(Alert.AlertType.WARNING, msg).showAndWait(); e.printStackTrace(); } }
90. GhciSession#pickBackend()
Project: viskell
File: GhciSession.java
File: GhciSession.java
/** @return the Backend in the preferences, or GHCi otherwise. */ public static Backend pickBackend() { Preferences prefs = Preferences.userNodeForPackage(Main.class); String name = prefs.get("ghci", Backend.GHCi.name()); return Backend.valueOf(name); }
91. CvalChecker#getCachedLicenseInfo()
Project: vaadin
File: CvalChecker.java
File: CvalChecker.java
private CvalInfo getCachedLicenseInfo(String productName) { Preferences p = Preferences.userNodeForPackage(CvalInfo.class); String json = p.get(productName, ""); if (!json.isEmpty()) { CvalInfo info = parseJson(json); if (info != null) { return info; } } return null; }
92. PackageSelectorGUI#selectPackageFile()
Project: uima-uimaj
File: PackageSelectorGUI.java
File: PackageSelectorGUI.java
/** * Opens dialog window to select desired PEAR package file for a given component. * * @param componentId * The given component ID. * @return Selected PEAR package file for the given component, or <code>null</code>, if the * selection cancelled. */ public synchronized File selectPackageFile(String componentId) { // get last package file path Preferences userPrefs = Preferences.userNodeForPackage(getClass()); String lastFilePath = (userPrefs != null) ? userPrefs.get(LAST_PACKAGE_FILE_KEY, "") : ""; File lastFile = lastFilePath.length() > 0 ? new File(lastFilePath) : null; File lastDir = lastFile != null ? lastFile.getParentFile() : new File("."); // create JFileChooser JFileChooser fileChooser = new JFileChooser(); fileChooser.addChoosableFileFilter(new PackageFileFilter()); fileChooser.setCurrentDirectory(lastDir); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setDialogTitle("Select " + componentId + " PEAR file"); // show information dialog String message = "Select the PEAR file of the\n" + "\n" + componentId + "\n" + "\ncomponent using the following file dialog."; JOptionPane.showMessageDialog(_dialogFrame, message); // open dialog window File selectedFile = null; int result = fileChooser.showDialog(_dialogFrame, "Select"); if (result == JFileChooser.APPROVE_OPTION) { // set 'selected file' selectedFile = fileChooser.getSelectedFile(); if (selectedFile != null) { // set 'last file' in user prefs userPrefs.put(LAST_PACKAGE_FILE_KEY, selectedFile.getAbsolutePath()); } } return selectedFile; }
93. PackageSelectorGUI#selectPackageDirectory()
Project: uima-uimaj
File: PackageSelectorGUI.java
File: PackageSelectorGUI.java
/** * Opens dialog window to select root directory of desired installed component package. * * @param componentId * The given component ID. * @return Selected package root directory or <code>null</code>, if the selection cancelled. */ public synchronized File selectPackageDirectory(String componentId) { // get last package dir path Preferences userPrefs = Preferences.userNodeForPackage(getClass()); String lastDirPath = (userPrefs != null) ? userPrefs.get(LAST_PACKAGE_DIR_KEY, "./") : "./"; File lastDir = new File(lastDirPath); // create JFileChooser JFileChooser fileChooser = new JFileChooser(); fileChooser.addChoosableFileFilter(new PackageDirFilter()); fileChooser.setCurrentDirectory(lastDir); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setDialogTitle("Select " + componentId + " root directory"); // show information dialog String message = "Select the root directory of installed\n" + "\n" + componentId + "\n" + "\ncomponent using the following file dialog,\n" + "or press 'Cancel' in the file dialog, if this\n" + "component is not installed in your file system."; JOptionPane.showMessageDialog(_dialogFrame, message); // open dialog window File selectedDir = null; int result = fileChooser.showDialog(_dialogFrame, "Select"); if (result == JFileChooser.APPROVE_OPTION) { // set 'selected dir' selectedDir = fileChooser.getSelectedFile(); if (selectedDir != null) { // set 'last dir' in user prefs lastDir = selectedDir.getParentFile(); userPrefs.put(LAST_PACKAGE_DIR_KEY, lastDir.getAbsolutePath()); } } return selectedDir; }
94. Util#getPreference()
Project: sling
File: Util.java
File: Util.java
static int getPreference(final String name, final int defaultValue) { Preferences prefs = getPreferences(); try { prefs.sync(); return prefs.getInt(name, defaultValue); } catch (BackingStoreException ioe) { } return defaultValue; }
95. Util#setPreference()
Project: sling
File: Util.java
File: Util.java
static void setPreference(final String name, final Object value, final boolean flush) { Preferences prefs = getPreferences(); try { prefs.sync(); if (value instanceof Long) { prefs.putLong(name, (Long) value); } else if (value instanceof Integer) { prefs.putInt(name, (Integer) value); } else if (value instanceof int[]) { String string = null; for (int val : (int[]) value) { if (string == null) { string = String.valueOf(val); } else { string += "," + val; } } prefs.put(name, string); } else if (value != null) { prefs.put(name, value.toString()); } if (flush) { prefs.flush(); } } catch (BackingStoreException ioe) { } }
96. Feedback#showDialog()
Project: Raccoon
File: Feedback.java
File: Feedback.java
private static void showDialog(JFrame center) { Preferences prefs = Preferences.userNodeForPackage(Feedback.class); Object[] options = { Messages.getString("Feedback.yes"), Messages.getString("Feedback.later"), Messages.getString("Feedback.no") }; String title = Messages.getString("Feedback.title"); String message = Messages.getString("Feedback.message"); int n = JOptionPane.showOptionDialog(center, message, title, JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); switch(n) { case 0: { prefs.putBoolean(KEY_DONE, true); BrowseUtil.openUrl(URL); break; } case 1: { prefs.putLong(KEY_COUNT, 0); break; } case 2: { prefs.putBoolean(KEY_DONE, true); break; } } try { prefs.flush(); } catch (BackingStoreException e) { e.printStackTrace(); } }
97. AbstractStepMeta#readFromPreferences()
Project: pentaho-kettle
File: AbstractStepMeta.java
File: AbstractStepMeta.java
/** * Read properties from preferences. */ public void readFromPreferences() { final Preferences node = Preferences.userNodeForPackage(this.getClass()); this.getProperties().walk(new ReadFromPreferences(node)); }
98. PreferencesRecentWorkspacesService#clear()
Project: pdfsam
File: PreferencesRecentWorkspacesService.java
File: PreferencesRecentWorkspacesService.java
@Override public void clear() { Preferences prefs = Preferences.userRoot().node(WORKSPACES_PATH); cache.clear(); try { prefs.removeNode(); prefs.flush(); } catch (BackingStoreException e) { LOG.error("Unable to clear recently used workspaces", e); } }
99. DefaultStageService#clear()
Project: pdfsam
File: DefaultStageService.java
File: DefaultStageService.java
public void clear() { Preferences prefs = Preferences.userRoot().node(STAGE_PATH); try { prefs.removeNode(); prefs.flush(); } catch (BackingStoreException e) { LOG.error("Unable to clear stage status", e); } }
100. DefaultStageService#save()
Project: pdfsam
File: DefaultStageService.java
File: DefaultStageService.java
public void save(StageStatus status) { Preferences node = Preferences.userRoot().node(STAGE_PATH); try { node.put(STAGE_STATUS_KEY, JSON.std.asString(status)); LOG.trace("Stage status saved {}", status); } catch (IOException e) { LOG.error("Unable to increment modules usage statistics", e); } }