List of usage examples for java.util.prefs Preferences userRoot
public static Preferences userRoot()
From source file:ca.canucksoftware.ipkpackager.IpkPackagerView.java
private File loadFileChooser(boolean dir, FileFilter filter, String text) { File result = null;/*from w ww.ja v a 2 s. co m*/ JFileChooser fc = new JFileChooser(); //Create a file chooser disableNewFolderButton(fc); if (text != null) { fc.setSelectedFile(new File(text)); } if (dir) { fc.setDialogTitle(""); File lastDir = new File( Preferences.userRoot().get("lastDir", fc.getCurrentDirectory().getAbsolutePath())); fc.setCurrentDirectory(lastDir); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (fc.showDialog(null, "Select") == JFileChooser.APPROVE_OPTION) { result = fc.getSelectedFile(); jTextField1.setText(result.getAbsolutePath()); Preferences.userRoot().put("lastDir", result.getParentFile().getAbsolutePath()); } } else { File lastSaved = null; File lastSelected = null; if (filter != null) { fc.setDialogTitle("Save As..."); lastSaved = new File( Preferences.userRoot().get("lastSaved", fc.getCurrentDirectory().getAbsolutePath())); fc.setCurrentDirectory(lastSaved); fc.setFileFilter(filter); } else { fc.setDialogTitle(""); lastSelected = new File( Preferences.userRoot().get("lastSelected", fc.getCurrentDirectory().getAbsolutePath())); fc.setCurrentDirectory(lastSelected); fc.setAcceptAllFileFilterUsed(true); } if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { result = fc.getSelectedFile(); if (lastSaved != null) { Preferences.userRoot().put("lastSaved", result.getParentFile().getAbsolutePath()); } if (lastSelected != null) { Preferences.userRoot().put("lastSelected", result.getParentFile().getAbsolutePath()); } } } return result; }
From source file:org.pdfsam.module.PreferencesUsageDataStore.java
public long getTotalUsage() { Preferences node = Preferences.userRoot().node(USAGE_PATH); return node.getLong(TASKS_EXECUTED_KEY, 0); }
From source file:nl.toolforge.karma.console.KarmaConsole.java
/** * * @param args The working context (0), whether to update (1) and the command * plus his options (3 ...). *//*from w ww . j av a 2 s. c o m*/ public void runConsole(String[] args) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { if (immediate) { String text = FRONTEND_MESSAGES.getString("message.THANK_YOU"); int length = text.length(); writeln("\n"); writeln(FRONTEND_MESSAGES.getString("message.EXIT")); StringBuffer g = new StringBuffer(); g.append("\n\n").append(StringUtils.repeat("*", length)); g.append("\n").append(text).append("\n"); g.append(StringUtils.repeat("*", length)).append("\n"); writeln(g.toString()); } } }); // If the '-w <working-context> option is used, use it. // WorkingContext workingContext; if (args[0] == null || args[0].equals("")) { workingContext = new WorkingContext( Preferences.userRoot().get(WorkingContext.WORKING_CONTEXT_PREFERENCE, WorkingContext.DEFAULT)); } else { workingContext = new WorkingContext(args[0]); } writeln("\n" + " _________________________________\n" + " Welcome to Karma (R1.0 RC1) !!!!!\n" + "\n" + " K A R M A\n" + " . . . . .\n" + " Karma Ain't Remotely Maven or Ant\n" + " _________________________________\n"); String karmaHome = System.getProperty("karma.home"); if (karmaHome == null) { writeln("[ console ] Property 'karma.home' not set; logging will be written to " + System.getProperty("user.home") + File.separator + "logs."); } else { writeln("[ console ] Logging will be written to " + System.getProperty("karma.home") + File.separator + "logs."); } writeln("[ console ] Checking working context configuration for `" + workingContext.getName() + "`."); WorkingContextConfiguration configuration = null; try { configuration = new WorkingContextConfiguration(workingContext); try { configuration.load(); } catch (WorkingContextException e) { } workingContext.configure(configuration); // Check the validity state of the configuration. // ErrorCode error = configuration.check(); ErrorCode error2 = null; ErrorCode error3 = null; if (error != null) { writeln("[ console ] ** Error in working context configuration : " + error.getErrorMessage()); } if (configuration.getManifestStore() == null) { writeln("[ console ] ** Error in working context configuration : Missing configuration for manifest store."); } else { error2 = configuration.getManifestStore().checkConfiguration(); if (error2 != null) { writeln("[ console ] ** Error in working context configuration : " + error2.getErrorMessage()); } } if (configuration.getLocationStore() == null) { writeln("[ console ] ** Error in working context configuration : Missing configuration for location store."); } else { error3 = configuration.getLocationStore().checkConfiguration(); if (error3 != null) { writeln("[ console ] ** Error in working context configuration : " + error3.getErrorMessage()); } } while (error != null || configuration.getManifestStore() == null || error2 != null || configuration.getLocationStore() == null || error3 != null) { // todo hier eerst de foutmelding tonen. // todo offline-mode ? BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String start = ""; try { while (!start.matches("n|y")) { write("[ console ] Working context not initialized properly, start configurator ? [Y|N] (Y) :"); start = (reader.readLine().trim()).toLowerCase(); start = ("".equals(start) ? "y" : start); } } catch (IOException e) { start = "n"; } if ("n".equals(start)) { writeln("[ console ] ** Configuration incomplete. Cannot start Karma."); writeln("[ console ] Check configuration manually."); System.exit(1); } else { Configurator configurator = new Configurator(workingContext, configuration); configurator.checkConfiguration(); // Run checks once more. // error = configuration.check(); if (configuration.getManifestStore() != null) { error2 = configuration.getManifestStore().checkConfiguration(); } if (configuration.getLocationStore() != null) { error3 = configuration.getLocationStore().checkConfiguration(); } } } } catch (RuntimeException r) { writeln("\n"); if (logger.isDebugEnabled()) { r.printStackTrace(); } System.exit(1); } writeln("[ console ] Configuration complete. Loading working context `" + workingContext.getName() + "` ..."); // Right now, we have a valid configuration and continue to load the working context. // workingContext.configure(configuration); writeln("[ console ] Configuration can be manually updated in `" + workingContext.getWorkingContextConfigurationBaseDir() + "`"); writeln("\n[ console ] Starting up console ...\n"); // // commandContext = new CommandContext(workingContext); try { // long start = System.currentTimeMillis(); commandContext.init(new ConsoleCommandResponseHandler(this), new Boolean(args[1]).booleanValue()); // System.out.println("TOTAL STARTUP-TIME: " + (System.currentTimeMillis() - start)); } catch (CommandException e) { logger.warn(e.getMessage()); } try { // Open a reader, which is the actual command line ... // BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String line = null; while (true) { prompt(); if (reader != null || reader.readLine() != null) { line = reader.readLine().trim(); } if ((line == null) || ("".equals(line.trim()))) { prompt(); continue; } if ("[A".equals(line)) { line = lastLine; writeln(line); } else { lastLine = line; } try { commandContext.execute(line); } catch (CommandException e) { // The command context has already sent all required messages. // } } } catch (Throwable e) { writeln("\n"); logger.fatal("Exception caught by KarmaConsole catch-all. ", e); String logfile = System.getProperty("karma.home", System.getProperty("user.home")) + File.separator + "logs" + File.separator + "karma-default.log"; System.out.println("Something went BOOM inside of Karma."); System.out.println("Details: " + (e.getMessage() != null ? e.getMessage() : e.getClass().getName())); System.out.println("See the log file (" + logfile + ") for more information."); System.out.println( "Please report recurring problems to the Karma developers (http://sourceforge.net/tracker/?group_id=98766)."); System.out.println("We apologize for the inconvenience."); System.out.println(); System.exit(1); } }
From source file:org.copperengine.monitoring.client.context.ApplicationContext.java
public ApplicationContext(String contextId) { this.contextId = contextId; mainStackPane = new StackPane(); mainPane = new BorderPane(); mainStackPane.getChildren().add(mainPane); messageProvider = new MessageProvider(ResourceBundle.getBundle("org.copperengine.gui.message")); final Preferences prefs = Preferences.userRoot().node("org.copperengine.coppermonitor"); SettingsModel defaultSettings = new SettingsModel(); AuditralColorMapping newItem = new AuditralColorMapping(); newItem.color.setValue(Color.rgb(255, 128, 128)); newItem.loglevelRegEx.setValue("1"); defaultSettings.auditralColorMappings.add(newItem); byte[] defaultModelbytes; ByteArrayOutputStream os = null; try {//from ww w.j ava 2 s . c om os = new ByteArrayOutputStream(); ObjectOutputStream o = new ObjectOutputStream(os); o.writeObject(defaultSettings); defaultModelbytes = os.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { throw new RuntimeException(e); } } } try { settingsModelSingleton = SettingsModel.from(prefs, defaultModelbytes, contextId); } catch (Exception e) { logger.error("", e); getIssueReporterSingleton() .reportWarning("Can't load settings from (Preferences: " + prefs + ") use defaults instead", e); settingsModelSingleton = defaultSettings; } Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { settingsModelSingleton.saveSettings(prefs, ApplicationContext.this.contextId); } })); }
From source file:de.ingrid.usermanagement.jetspeed.IngridRoleManager.java
/** * @see org.apache.jetspeed.security.RoleManager#addRole(java.lang.String) *///from w w w. j a va2s. com public void addRole(String roleFullPathName) throws SecurityException { ArgUtil.notNull(new Object[] { roleFullPathName }, new String[] { "roleFullPathName" }, "addRole(java.lang.String)"); // Check if role already exists. if (roleExists(roleFullPathName)) { throw new SecurityException(SecurityException.ROLE_ALREADY_EXISTS.create(roleFullPathName)); } RolePrincipal rolePrincipal = new RolePrincipalImpl(roleFullPathName); String fullPath = rolePrincipal.getFullPath(); // Add the preferences. Preferences preferences = Preferences.userRoot().node(fullPath); if (log.isDebugEnabled()) { log.debug("Added role preferences node: " + fullPath); } try { if ((null != preferences) && preferences.absolutePath().equals(fullPath)) { // Add role principal. roleSecurityHandler.setRolePrincipal(rolePrincipal); if (log.isDebugEnabled()) { log.debug("Added role: " + fullPath); } } } catch (SecurityException se) { KeyedMessage msg = SecurityException.UNEXPECTED.create("RoleManager.addRole", "RoleSecurityHandler.setRolePrincipal(" + rolePrincipal.getName() + ")", se.getMessage()); log.error(msg, se); // Remove the preferences node. try { preferences.removeNode(); } catch (BackingStoreException bse) { bse.printStackTrace(); } throw new SecurityException(msg, se); } }
From source file:org.pdfsam.ui.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();/*from ww w . j av a 2 s . c om*/ 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)); }
From source file:gui.DownloadManagerGUI.java
public DownloadManagerGUI(String name) { super(name);/*ww w. java 2s .c o m*/ setLayout(new BorderLayout()); preferences = Preferences.userRoot().node("db"); final PreferencesDTO preferencesDTO = getPreferences(); LookAndFeel.setLaf(preferencesDTO.getPreferencesInterfaceDTO().getLookAndFeelName()); createFileHierarchy(); mainToolbar = new MainToolBar(); categoryPanel = new CategoryPanel( preferencesDTO.getPreferencesSaveDTO().getPreferencesDirectoryCategoryDTOs()); downloadPanel = new DownloadPanel(this, preferencesDTO.getPreferencesSaveDTO().getDatabasePath(), preferencesDTO.getPreferencesConnectionDTO().getConnectionTimeOut(), preferencesDTO.getPreferencesConnectionDTO().getReadTimeOut()); messagePanel = new MessagePanel(this); JTabbedPane mainTabPane = new JTabbedPane(); mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, categoryPanel, mainTabPane); mainSplitPane.setOneTouchExpandable(true); statusPanel = new StatusPanel(); addNewDownloadDialog = new AddNewDownloadDialog(this); mainTabPane.addTab(messagesBundle.getString("downloadManagerGUI.mainTabPane.downloadPanel"), downloadPanel); mainTabPane.addTab(messagesBundle.getString("downloadManagerGUI.mainTabPane.messagePanel"), messagePanel); preferenceDialog = new PreferenceDialog(this, preferencesDTO); aboutDialog = new AboutDialog(this); categoryPanel.setCategoryPanelListener((fileExtensions, downloadCategory) -> downloadPanel .setDownloadsByDownloadPath(fileExtensions, downloadCategory)); // preferenceDialog.setDefaults(preferencesDTO); addNewDownloadDialog.setAddNewDownloadListener(textUrl -> { Objects.requireNonNull(textUrl, "textUrl"); if (textUrl.equals("")) throw new IllegalArgumentException("textUrl is empty"); String downloadName; try { downloadName = ConnectionUtil.getRealFileName(textUrl); } catch (IOException e) { logger.error("Can't get real name of file that you want to download." + textUrl); messageLogger.error("Can't get real name of file that you want to download." + textUrl); downloadName = ConnectionUtil.getFileName(textUrl); } String fileExtension = FilenameUtils.getExtension(downloadName); File downloadPathFile = new File( preferencesDTO.getPreferencesSaveDTO().getPathByFileExtension(fileExtension)); File downloadRangeFile = new File(preferencesDTO.getPreferencesSaveDTO().getTempDirectory()); int maxNum = preferencesDTO.getPreferencesConnectionDTO().getMaxConnectionNumber(); Download download = null; List<Download> downloads = downloadPanel.getDownloadList(); String properDownloadName = getProperNameForDownload(downloadName, downloads, downloadPathFile); // todo must set stretegy pattern switch (ProtocolType.valueOfByDesc(textUrl.getProtocol())) { case HTTP: download = new HttpDownload(downloadPanel.getNextDownloadID(), textUrl, properDownloadName, maxNum, downloadPathFile, downloadRangeFile, ProtocolType.HTTP); break; case FTP: // todo must be created ... break; case HTTPS: download = new HttpsDownload(downloadPanel.getNextDownloadID(), textUrl, properDownloadName, maxNum, downloadPathFile, downloadRangeFile, ProtocolType.HTTPS); break; } downloadPanel.addDownload(download); }); // Add panels to display. add(mainToolbar, BorderLayout.PAGE_START); add(mainSplitPane, BorderLayout.CENTER); add(statusPanel, BorderLayout.PAGE_END); setJMenuBar(initMenuBar()); mainToolbar.setMainToolbarListener(new MainToolbarListener() { @Override public void newDownloadEventOccured() { addNewDownloadDialog.setVisible(true); addNewDownloadDialog.onPaste(); } @Override public void pauseEventOccured() { downloadPanel.actionPause(); mainToolbar.setStateOfButtonsControl(false, false, false, false, false, true); // canceled } @Override public void resumeEventOccured() { downloadPanel.actionResume(); } @Override public void pauseAllEventOccured() { downloadPanel.actionPauseAll(); } @Override public void clearEventOccured() { downloadPanel.actionClear(); } @Override public void clearAllCompletedEventOccured() { downloadPanel.actionClearAllCompleted(); } @Override public void reJoinEventOccured() { downloadPanel.actionReJoinFileParts(); } @Override public void reDownloadEventOccured() { downloadPanel.actionReDownload(); } @Override public void propertiesEventOccured() { downloadPanel.actionProperties(); } @Override public void preferencesEventOccured() { preferenceDialog.setVisible(true); } }); downloadPanel.setDownloadPanelListener(new DownloadPanelListener() { @Override public void stateChangedEventOccured(DownloadStatus downloadState) { updateButtons(downloadState); } @Override public void downloadSelected(Download download) { statusPanel.setStatus(download.getDownloadName()); } }); preferenceDialog.setPreferencesListener(new PreferencesListener() { @Override public void preferencesSet(PreferencesDTO preferenceDTO) { setPreferencesOS(preferenceDTO); } @Override public void preferenceReset() { PreferencesDTO resetPreferencesDTO = getPreferences(); preferenceDialog.setPreferencesDTO(resetPreferencesDTO); categoryPanel.setTreeModel( resetPreferencesDTO.getPreferencesSaveDTO().getPreferencesDirectoryCategoryDTOs()); } @Override public void preferenceDefaults() { PreferencesDTO defaultPreferenceDTO = new PreferencesDTO(); resetAndSetPreferencesDTOFromConf(defaultPreferenceDTO); preferenceDialog.setPreferencesDTO(defaultPreferenceDTO); categoryPanel.setTreeModel( defaultPreferenceDTO.getPreferencesSaveDTO().getPreferencesDirectoryCategoryDTOs()); } }); // Handle window closing events. addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent windowEvent) { int action = JOptionPane.showConfirmDialog(DownloadManagerGUI.this, "Do you realy want to exit the application?", "Confirm Exit", JOptionPane.OK_CANCEL_OPTION); if (action == JOptionPane.OK_OPTION) { logger.info("Window Closing"); downloadPanel.actionPauseAll(); dispose(); System.gc(); } } }); Authenticator.setDefault(new DialogAuthenticator(this)); setIconImage( Utils.createIcon(messagesBundle.getString("downloadManagerGUI.mainFrame.iconPath")).getImage()); setMinimumSize(new Dimension(640, 480)); // Set window size. pack(); setSize(900, 580); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); setVisible(true); }
From source file:com.gnadenheimer.mg3.utils.Utils.java
public Map<String, String> getPersistenceMap() { try {/* ww w .j a v a 2s. c o m*/ String databaseIP; databaseIP = Preferences.userRoot().node("MG").get("DatabaseIP", "127.0.0.1"); Map<String, String> persistenceMap = new HashMap<>(); persistenceMap.put("javax.persistence.jdbc.url", "jdbc:derby://" + databaseIP + ":1527/mgdb;create=true"); persistenceMap.put("javax.persistence.jdbc.user", "mg"); persistenceMap.put("javax.persistence.jdbc.password", "123456"); persistenceMap.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.ClientDriver"); //persistenceMap.put("hibernate.dialect", "org.hibernate.dialect.DerbyTenSevenDialect"); //persistenceMap.put("hibernate.show_sql", "false"); //persistenceMap.put("hibernate.connection.release_mode", "auto"); //persistenceMap.put("current_session_context_class", "thread"); /*persistenceMap.put("hibernate.connection.autoReconnect", "true"); persistenceMap.put("hibernate.c3p0.min_size", "5"); persistenceMap.put("hibernate.c3p0.max_size", "20"); persistenceMap.put("hibernate.c3p0.timeout", "500"); persistenceMap.put("hibernate.c3p0.max_statements", "50"); persistenceMap.put("hibernate.c3p0.idle_test_period", "2000"); persistenceMap.put("hibernate.c3p0.testConnectionOnCheckout", "true"); persistenceMap.put("connection.provider_class", "org.hibernate.connection.C3P0ConnectionProvider");*/ persistenceMap.put("backUpDir", Preferences.userRoot().node("MG").get("Datadir", System.getProperty("user.dir") + File.separator + "javadb") + File.separator + "autoBackUp"); return persistenceMap; } catch (Exception exx) { App.showException(Thread.currentThread().getStackTrace()[1].getMethodName(), exx.getMessage(), exx); LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), exx); return null; } }
From source file:com.gnadenheimer.mg3.controller.admin.AdminConfigController.java
@FXML private void cmdSave(ActionEvent event) { try {/*from ww w . jav a2 s .co m*/ Preferences.userRoot().node("MG").put("DatabaseIP", txtIP.getText()); Preferences.userRoot().node("MG").put("Datadir", txtDataDir.getText()); Preferences.userRoot().node("MG").put("isServer", String.valueOf(rbServidor.isSelected())); Preferences.userRoot().node("MG").put("modoImpresion", cboTransferencias.getSelectionModel().getSelectedItem()); Preferences.userRoot().node("MG").put("formatoFactura", cboFacturasFormato.getSelectionModel().getSelectedItem()); Preferences.userRoot().node("MG").put("cobrarAC", String.valueOf(rbAyCPorMes.isSelected())); Preferences.userRoot().node("MG").putInt("PeriodoFiscal", cboPeriodoFiscal.getSelectionModel().getSelectedItem()); App.periodoFiscal = cboPeriodoFiscal.getSelectionModel().getSelectedItem(); Utils.getInstance().setEntityManagerFactory(); LoginManager.getInstance().showMainView(); } catch (Exception ex) { App.showException(this.getClass().getName(), ex.getMessage(), ex); } }
From source file:edu.umass.cs.msocket.proxy.console.ConsoleModule.java
private History loadHistory() { jline.History jHistory = new jline.History(); try {/*ww w .j av a 2s. co m*/ Preferences prefs = Preferences.userRoot().node(this.getClass().getName()); String[] historyKeys = prefs.keys(); Arrays.sort(historyKeys, 0, historyKeys.length); for (int i = 0; i < historyKeys.length; i++) { String key = historyKeys[i]; String value = prefs.get(key, ""); //$NON-NLS-1$ jHistory.addToHistory(value); } } catch (Exception e) { // unable to load prefs: do nothing } return jHistory; }