List of usage examples for java.util.prefs Preferences get
public abstract String get(String key, String def);
From source file:com.holycityaudio.SpinCAD.SpinCADFile.java
private void loadRecentPatchFileList() { Preferences p = Preferences.userNodeForPackage(RecentFileList.class); String listOfFiles = p.get("RecentPatchFileList.fileList", null); if (fc == null) { String savedPath = prefs.get("MRUPatchFolder", ""); File MRUPatchFolder = new File(savedPath); fc = new JFileChooser(MRUPatchFolder); recentPatchFileList = new RecentFileList(fc); if (listOfFiles != null) { String[] files = listOfFiles.split(File.pathSeparator); for (String fileRef : files) { File file = new File(fileRef); if (file.exists()) { recentPatchFileList.listModel.add(file); }/*from ww w. j a v a2s.c o m*/ } } fc.setAccessory(recentPatchFileList); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); } }
From source file:com.holycityaudio.SpinCAD.SpinCADFile.java
private void loadRecentBankFileList() { Preferences p = Preferences.userNodeForPackage(RecentFileList.class); String listOfFiles = p.get("RecentBankFileList.fileList", null); if (fc == null) { String savedPath = prefs.get("MRUBankFolder", ""); File MRUBankFolder = new File(savedPath); fc = new JFileChooser(MRUBankFolder); recentBankFileList = new RecentFileList(fc); if (listOfFiles != null) { String[] files = listOfFiles.split(File.pathSeparator); for (String fileRef : files) { File file = new File(fileRef); if (file.exists()) { recentBankFileList.listModel.add(file); }//from w ww .j a v a2 s . com } } fc.setAccessory(recentBankFileList); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); } }
From source file:com.holycityaudio.SpinCAD.SpinCADFile.java
private void loadRecentHexFileList() { Preferences p = Preferences.userNodeForPackage(RecentFileList.class); String listOfFiles = p.get("RecentHexFileList.fileList", null); if (fc == null) { String savedPath = prefs.get("MRUHexFolder", ""); File MRUHexFolder = new File(savedPath); fc = new JFileChooser(MRUHexFolder); recentHexFileList = new RecentFileList(fc); if (listOfFiles != null) { String[] files = listOfFiles.split(File.pathSeparator); for (String fileRef : files) { File file = new File(fileRef); if (file.exists()) { recentHexFileList.listModel.add(file); }/*from w w w.j ava 2 s .com*/ } } fc.setAccessory(recentHexFileList); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); } }
From source file:org.multicore_association.measure.mem.generate.MemCodeGen.java
/** * Check of the entry presense./*from w ww .j a v a2 s .c o m*/ * @param prefs read configuration data * @param section section name * @param entry entry name * @return Flag of presense */ private boolean checkPrefEntry(Preferences prefs, String section, String entry) { boolean ret = false; String buf; Preferences s = null; try { s = prefs.node(section); buf = s.get(entry, null); if (buf != null) { ret = true; } } catch (Exception e) { ret = false; } return ret; }
From source file:com.delcyon.capo.Configuration.java
@SuppressWarnings({ "unchecked", "static-access" }) public Configuration(String... programArgs) throws Exception { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilder = documentBuilderFactory.newDocumentBuilder(); options = new Options(); // the enum this is a little complicated, but it gives us a nice // centralized place to put all of the system parameters // and lets us iterate of the list of options and preferences PREFERENCE[] preferences = PREFERENCE.values(); for (PREFERENCE preference : preferences) { // not the most elegant, but there is no default constructor, but // the has arguments value is always there OptionBuilder optionBuilder = OptionBuilder.hasArg(preference.hasArgument); if (preference.hasArgument == true) { String[] argNames = preference.arguments; for (String argName : argNames) { optionBuilder = optionBuilder.withArgName(argName); }//from w w w . j a v a 2 s . c o m } optionBuilder = optionBuilder.withDescription(preference.getDescription()); optionBuilder = optionBuilder.withLongOpt(preference.getLongOption()); options.addOption(optionBuilder.create(preference.getOption())); preferenceHashMap.put(preference.toString(), preference); } //add dynamic options Set<String> preferenceProvidersSet = CapoApplication.getAnnotationMap() .get(PreferenceProvider.class.getCanonicalName()); if (preferenceProvidersSet != null) { for (String className : preferenceProvidersSet) { Class preferenceClass = Class.forName(className).getAnnotation(PreferenceProvider.class) .preferences(); if (preferenceClass.isEnum()) { Object[] enumObjects = preferenceClass.getEnumConstants(); for (Object enumObject : enumObjects) { Preference preference = (Preference) enumObject; //filter out any preferences that don't belong on this server or client. if (preference.getLocation() != Location.BOTH) { if (CapoApplication.isServer() == true && preference.getLocation() == Location.CLIENT) { continue; } else if (CapoApplication.isServer() == false && preference.getLocation() == Location.SERVER) { continue; } } preferenceHashMap.put(preference.toString(), preference); boolean hasArgument = false; if (preference.getArguments() == null || preference.getArguments().length == 0) { hasArgument = false; } else { hasArgument = true; } OptionBuilder optionBuilder = OptionBuilder.hasArg(hasArgument); if (hasArgument == true) { String[] argNames = preference.getArguments(); for (String argName : argNames) { optionBuilder = optionBuilder.withArgName(argName); } } optionBuilder = optionBuilder.withDescription(preference.getDescription()); optionBuilder = optionBuilder.withLongOpt(preference.getLongOption()); options.addOption(optionBuilder.create(preference.getOption())); } } } } // create parser CommandLineParser commandLineParser = new GnuParser(); this.commandLine = commandLineParser.parse(options, programArgs); Preferences systemPreferences = Preferences .systemNodeForPackage(CapoApplication.getApplication().getClass()); String capoDirString = null; while (true) { capoDirString = systemPreferences.get(PREFERENCE.CAPO_DIR.longOption, null); if (capoDirString == null) { systemPreferences.put(PREFERENCE.CAPO_DIR.longOption, PREFERENCE.CAPO_DIR.defaultValue); capoDirString = PREFERENCE.CAPO_DIR.defaultValue; try { systemPreferences.sync(); } catch (BackingStoreException e) { //e.printStackTrace(); if (systemPreferences.isUserNode() == false) { System.err.println("Problem with System preferences, trying user's"); systemPreferences = Preferences .userNodeForPackage(CapoApplication.getApplication().getClass()); continue; } else //just bail out { throw e; } } } break; } disableAutoSync = hasOption(PREFERENCE.DISABLE_CONFIG_AUTOSYNC); File capoDirFile = new File(capoDirString); if (capoDirFile.exists() == false) { if (disableAutoSync == false) { capoDirFile.mkdirs(); } } File configDir = new File(capoDirFile, PREFERENCE.CONFIG_DIR.defaultValue); if (configDir.exists() == false) { if (disableAutoSync == false) { configDir.mkdirs(); } } if (disableAutoSync == false) { capoConfigFile = new File(configDir, CONFIG_FILENAME); if (capoConfigFile.exists() == false) { Document configDocument = CapoApplication.getDefaultDocument("config.xml"); FileOutputStream configFileOutputStream = new FileOutputStream(capoConfigFile); TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(configDocument), new StreamResult(configFileOutputStream)); configFileOutputStream.close(); } configDocument = documentBuilder.parse(capoConfigFile); } else //going memory only, because of disabled auto sync { configDocument = CapoApplication.getDefaultDocument("config.xml"); } if (configDocument instanceof CDocument) { ((CDocument) configDocument).setSilenceEvents(true); } loadPreferences(); preferenceValueHashMap.put(PREFERENCE.CAPO_DIR.longOption, capoDirString); //print out preferences //this also has the effect of persisting all of the default values if a values doesn't already exist for (PREFERENCE preference : preferences) { if (getValue(preference) != null) { CapoApplication.logger.log(Level.CONFIG, preference.longOption + "='" + getValue(preference) + "'"); } } CapoApplication.logger.setLevel(Level.parse(getValue(PREFERENCE.LOGGING_LEVEL))); }
From source file:org.multicore_association.measure.mem.generate.MemCodeGen.java
/** * Parsing configuration.//from w ww.jav a 2s . c o m * @param prefs read configuration data * @return Flag for success judgements * @throws BackingStoreException */ private boolean parseConfigData(Preferences prefs) throws BackingStoreException { /* check of the section presence */ ArrayList<String> seclist = ConfigData.getSectionNameList(); boolean result = true; for (Iterator<String> i = seclist.iterator(); i.hasNext();) { String name = i.next(); if (!checkPrefSection(prefs, name)) { System.err.println("Error: mandatory section does not exist" + " (" + name + ")"); //$NON-NLS-3$ result = false; } } /* check of the entry presence */ ArrayList<String> mentrylist = ConfigData.getMainEntryNameList(); for (Iterator<String> i = mentrylist.iterator(); i.hasNext();) { String name = i.next(); if (!checkPrefEntry(prefs, ConfigData.SECTION_MAIN, name)) { System.err.println("Error: mandatory entry does not exist" + " (" + name + ")"); //$NON-NLS-3$ result = false; } } /* set configuration data */ confData = new ConfigData(); Preferences sec_main = prefs.node(ConfigData.SECTION_MAIN); confData.setMainInclude(sec_main.get(ConfigData.ENTRY_INCLUDE, "")); confData.setMainGlobalValiable(sec_main.get(ConfigData.ENTRY_GLOBAL_VARIABLE, "")); confData.setMainMacro(sec_main.get(ConfigData.ENTRY_MACRO, "")); return result; }
From source file:com.adito.jdbc.DBUpgrader.java
/** * Check the database schema and perform any upgrades. * /*from w w w . j a va 2 s . c o m*/ * @throws Exception on any error */ public void upgrade() throws Exception { Properties versions = null; if (versionsFile == null) { /* If required, convert from the old preferences node to the new * file (version 0.2.5) */ versionsFile = new File(ContextHolder.getContext().getDBDirectory(), "versions.log"); Preferences p = ContextHolder.getContext().getPreferences().node("dbupgrader"); if (p.nodeExists("currentDataVersion")) { log.warn("Migrating database versions from preferences to properties file in " + ContextHolder.getContext().getDBDirectory().getAbsolutePath() + "."); versions = new Properties(); p = p.node("currentDataVersion"); String[] c = p.keys(); for (int i = 0; i < c.length; i++) { versions.put(c[i], p.get(c[i], "")); } FileOutputStream fos = new FileOutputStream(versionsFile); try { versions.store(fos, "Database versions"); } finally { Util.closeStream(fos); } p.removeNode(); } } // Load the database versions if (versions == null) { versions = new Properties(); if (versionsFile.exists()) { FileInputStream fin = new FileInputStream(versionsFile); try { versions.load(fin); } finally { Util.closeStream(fin); } } } try { String dbCheckName = useDbNameForVersionCheck ? engine.getDatabase() : engine.getAlias(); if ((!engine.isDatabaseExists() || removed.containsKey(engine.getDatabase())) && !removeProcessed.containsKey(dbCheckName)) { versions.remove(dbCheckName); removeProcessed.put(dbCheckName, Boolean.TRUE); if (log.isInfoEnabled()) log.info("Database for " + dbCheckName + " (" + engine.getDatabase() + ") has been removed, assuming this is a re-install."); removed.put(engine.getDatabase(), Boolean.TRUE); } // Check for any SQL scripts to run to bring the databases up to // date VersionInfo.Version currentDataVersion = new VersionInfo.Version( versions.getProperty(dbCheckName, "0.0.0")); if (log.isInfoEnabled()) { log.info("New logical database version for " + engine.getAlias() + " is " + newDbVersion); log.info("Current logical database version for " + engine.getAlias() + " is " + currentDataVersion); // log.info("Upgrade script directory is " + upgradeDir.getAbsolutePath()); } List upgrades = getSortedUpgrades(upgradeDir); File oldLog = new File(upgradeDir, "upgrade.log"); if (!dbDir.exists()) { if (!dbDir.mkdirs()) { throw new Exception("Failed to create database directory " + dbDir.getAbsolutePath()); } } File logFile = new File(dbDir, "upgrade.log"); if (oldLog.exists()) { if (log.isInfoEnabled()) log.info( "Moving upgrade.log to new location (as of version 0.1.5 it resides in the db directory."); if (!oldLog.renameTo(logFile)) { throw new Exception("Failed to move upgrade log file from " + oldLog.getAbsolutePath() + " to " + logFile.getAbsolutePath()); } } HashMap completedUpgrades = new HashMap(); if (!logFile.exists()) { OutputStream out = null; try { out = new FileOutputStream(logFile); PrintWriter writer = new PrintWriter(out, true); writer.println("# This file contains a list of database upgrades"); writer.println("# that have completed correctly."); } finally { if (out != null) { out.flush(); out.close(); } } } else { InputStream in = null; try { in = new FileInputStream(logFile); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { line = line.trim(); if (!line.equals("") && !line.startsWith("#")) { completedUpgrades.put(line, line); } } } finally { if (in != null) { in.close(); } } } OutputStream out = null; try { out = new FileOutputStream(logFile, true); PrintWriter writer = new PrintWriter(out, true); Class.forName("org.hsqldb.jdbcDriver"); // shouldnt be needed, // but // just in // case for (Iterator i = upgrades.iterator(); i.hasNext();) { DBUpgradeOp upgrade = (DBUpgradeOp) i.next(); boolean runBefore = completedUpgrades.containsKey(upgrade.getFile().getName()); if (log.isInfoEnabled()) log.info("Checking if upgrade " + upgrade.getFile() + " [" + upgrade.getVersion() + "] needs to be run. Run before = " + runBefore + ". Current data version = " + currentDataVersion + ", upgrade version = " + upgrade.getVersion()); if ((!runBefore || (currentDataVersion.getMajor() == 0 && currentDataVersion.getMinor() == 0 && currentDataVersion.getBuild() == 0)) && upgrade.getVersion().compareTo(currentDataVersion) >= 0 && upgrade.getVersion().compareTo(newDbVersion) < 0) { if (log.isInfoEnabled()) log.info("Running script " + upgrade.getName() + " [" + upgrade.getVersion() + "] on database " + engine.getDatabase()); // Get a JDBC connection JDBCConnectionImpl conx = engine.aquireConnection(); try { runSQLScript(conx, upgrade.getFile()); completedUpgrades.put(upgrade.getFile().getName(), upgrade.getFile().getName()); writer.println(upgrade.getFile().getName()); } finally { engine.releaseConnection(conx); } } } versions.put(dbCheckName, newDbVersion.toString()); if (log.isInfoEnabled()) log.info("Logical database " + engine.getAlias() + " (" + engine.getDatabase() + ") is now at version " + newDbVersion); } finally { if (out != null) { out.flush(); out.close(); } } } finally { FileOutputStream fos = new FileOutputStream(versionsFile); try { versions.store(fos, "Database versions"); } finally { Util.closeStream(fos); } } }
From source file:org.docx4all.ui.menu.FileMenu.java
private VFSJFileChooser createFileChooser(ResourceMap resourceMap, String callerActionName, JInternalFrame iframe, String filteredFileExtension) { String filePath = null;/*from ww w.j a v a2s . c o m*/ if (EXPORT_AS_SHARED_DOC_ACTION_NAME.equals(callerActionName)) { Preferences prefs = Preferences.userNodeForPackage(getClass()); filePath = prefs.get(Constants.LAST_OPENED_FILE, Constants.EMPTY_STRING); } else { filePath = (String) iframe.getClientProperty(WordMLDocument.FILE_PATH_PROPERTY); } FileObject file = null; FileObject dir = null; try { file = VFSUtils.getFileSystemManager().resolveFile(filePath); dir = file.getParent(); } catch (FileSystemException exc) { ;//ignore } return createFileChooser(resourceMap, dir, filteredFileExtension); }
From source file:edu.umass.cs.msocket.proxy.console.ConsoleModule.java
private History loadHistory() { jline.History jHistory = new jline.History(); try {/*from w w w. j ava 2 s.c om*/ 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; }
From source file:org.rhq.server.control.command.AbstractInstall.java
private void configureAgent(File agentBasedir, CommandLine commandLine) throws Exception { // If the user provided us with an agent config file, we will use it. // Otherwise, we are going to use the out-of-box agent config file. ////from www . j a v a 2 s.co m // Because we want to accept all defaults and consider the agent fully configured, we need to set // rhq.agent.configuration-setup-flag=true // This tells the agent not to ask any setup questions at startup. // We do this whether using a custom config file or the default config file - this is because // we cannot allow the agent to ask the setup questions (rhqctl doesn't support that). // // Note that agent preferences found in the config file can be overridden with // the AGENT_PREFERENCE settings (you can set more than one). try { File agentConfDir = new File(agentBasedir, "conf"); File agentConfigFile = new File(agentConfDir, "agent-configuration.xml"); if (commandLine.hasOption(AGENT_CONFIG_OPTION)) { log.info("Configuring the RHQ agent with custom configuration file: " + commandLine.getOptionValue(AGENT_CONFIG_OPTION)); replaceAgentConfigIfNecessary(commandLine); } else { log.info("Configuring the RHQ agent with default configuration file: " + agentConfigFile); } // we require our agent preference node to be the user node called "default" Preferences preferencesNode = getAgentPreferences(); // read the comments in AgentMain.loadConfigurationFile(String) to know why we do all of this String securityToken = preferencesNode.get(PREF_RHQ_AGENT_SECURITY_TOKEN, null); ByteArrayOutputStream rawConfigFileData = new ByteArrayOutputStream(); StreamUtil.copy(new FileInputStream(agentConfigFile), rawConfigFileData, true); String newConfig = rawConfigFileData.toString().replace("${rhq.agent.preferences-node}", "default"); ByteArrayInputStream newConfigInputStream = new ByteArrayInputStream(newConfig.getBytes()); Preferences.importPreferences(newConfigInputStream); if (securityToken != null) { preferencesNode.put(PREF_RHQ_AGENT_SECURITY_TOKEN, securityToken); } // get the configured server endpoint information and tell the agent so it knows where the server is. Properties serverEndpoint = getAgentServerEndpoint(); String endpointTransport = serverEndpoint.getProperty(PREF_RHQ_AGENT_SERVER_TRANSPORT); String endpointAddress = serverEndpoint.getProperty(PREF_RHQ_AGENT_SERVER_BINDADDRESS); String endpointPort = serverEndpoint.getProperty(PREF_RHQ_AGENT_SERVER_BINDPORT); String endpointParams = serverEndpoint.getProperty(PREF_RHQ_AGENT_SERVER_TRANSPORTPARAMS); if (endpointTransport != null) { preferencesNode.put(PREF_RHQ_AGENT_SERVER_TRANSPORT, endpointTransport); } if (endpointAddress != null) { preferencesNode.put(PREF_RHQ_AGENT_SERVER_BINDADDRESS, endpointAddress); } if (endpointPort != null) { preferencesNode.put(PREF_RHQ_AGENT_SERVER_BINDPORT, endpointPort); } if (endpointParams != null) { preferencesNode.put(PREF_RHQ_AGENT_SERVER_TRANSPORTPARAMS, endpointParams); } // if the user provided any overrides to the agent config, use them. overrideAgentPreferences(commandLine, preferencesNode); // set some prefs that must be a specific value // - do not tell this agent to auto-update itself - this agent must be managed by rhqctl only // - set the config setup flag to true to prohibit the agent from asking setup questions at startup String agentUpdateEnabledPref = PREF_RHQ_AGENT_AUTO_UPDATE_FLAG; preferencesNode.putBoolean(agentUpdateEnabledPref, false); String setupPref = PREF_RHQ_AGENT_CONFIGURATION_SETUP_FLAG; preferencesNode.putBoolean(setupPref, true); try { preferencesNode.flush(); preferencesNode.sync(); } catch (BackingStoreException bse) { log.error("Failed to store agent preferences, for Linux systems we require writable user.home [" + System.getProperty("user.home") + "]. You can also set different location for agent preferences by setting \"-Djava.util.prefs.userRoot=/some/path/\"" + " java system property. You may need to put this property to RHQ_CONTROL_ADDIDIONAL_JAVA_OPTS and RHQ_AGENT_ADDIDIONAL_JAVA_OPTS env variables."); throw bse; } log.info("Finished configuring the agent"); } catch (Exception e) { log.error("An error occurred while configuring the agent: " + e.getMessage()); throw e; } }