Example usage for java.util.prefs Preferences node

List of usage examples for java.util.prefs Preferences node

Introduction

In this page you can find the example usage for java.util.prefs Preferences node.

Prototype

public abstract Preferences node(String pathName);

Source Link

Document

Returns the named preference node in the same tree as this node, creating it and any of its ancestors if they do not already exist.

Usage

From source file:org.apache.cayenne.pref.UpgradeCayennePreference.java

public void upgrade() {
    try {//from   w w  w. ja  v a 2 s. c  om

        if (!Preferences.userRoot().nodeExists(CAYENNE_PREFERENCES_PATH)) {

            File prefsFile = new File(preferencesDirectory(), PREFERENCES_NAME_OLD);
            if (prefsFile.exists()) {
                ExtendedProperties ep = new ExtendedProperties();
                try {
                    ep.load(new FileInputStream(prefsFile));

                    Preferences prefEditor = Preferences.userRoot().node(CAYENNE_PREFERENCES_PATH).node(EDITOR);

                    prefEditor.putBoolean(ModelerPreferences.EDITOR_LOGFILE_ENABLED,
                            ep.getBoolean(EDITOR_LOGFILE_ENABLED_OLD));
                    prefEditor.put(ModelerPreferences.EDITOR_LOGFILE, ep.getString(EDITOR_LOGFILE_OLD));

                    Preferences frefLastProjFiles = prefEditor.node(LAST_PROJ_FILES);

                    Vector arr = ep.getVector(LAST_PROJ_FILES_OLD);

                    while (arr.size() > ModelerPreferences.LAST_PROJ_FILES_SIZE) {
                        arr.remove(arr.size() - 1);
                    }

                    frefLastProjFiles.clear();
                    int size = arr.size();

                    for (int i = 0; i < size; i++) {
                        frefLastProjFiles.put(String.valueOf(i), arr.get(i).toString());
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (BackingStoreException e) {
        // do nothing
    }
}

From source file:org.apache.cayenne.modeler.preferences.UpgradeCayennePreference.java

public void upgrade() {
    try {/* w w  w.  ja  va2  s.c o m*/

        if (!Preferences.userRoot().nodeExists(CAYENNE_PREFERENCES_PATH)) {

            File prefsFile = new File(preferencesDirectory(), PREFERENCES_NAME_OLD);
            if (prefsFile.exists()) {
                ExtendedProperties ep = new ExtendedProperties();
                try {
                    ep.load(new FileInputStream(prefsFile));

                    Preferences prefEditor = Preferences.userRoot().node(CAYENNE_PREFERENCES_PATH).node(EDITOR);

                    prefEditor.putBoolean(ModelerPreferences.EDITOR_LOGFILE_ENABLED,
                            ep.getBoolean(EDITOR_LOGFILE_ENABLED_OLD));
                    prefEditor.put(ModelerPreferences.EDITOR_LOGFILE, ep.getString(EDITOR_LOGFILE_OLD));

                    Preferences frefLastProjFiles = prefEditor.node(LAST_PROJ_FILES);

                    Vector arr = ep.getVector(LAST_PROJ_FILES_OLD);

                    while (arr.size() > ModelerPreferences.LAST_PROJ_FILES_SIZE) {
                        arr.remove(arr.size() - 1);
                    }

                    frefLastProjFiles.clear();
                    int size = arr.size();

                    for (int i = 0; i < size; i++) {
                        frefLastProjFiles.put(String.valueOf(i), arr.get(i).toString());
                    }
                } catch (FileNotFoundException e) {
                    LOGGER.error(e);
                } catch (IOException e) {
                    LOGGER.error(e);
                }
            }
        }
    } catch (BackingStoreException e) {
        // do nothing
    }
}

From source file:org.nuclos.client.genericobject.logbook.LogbookController.java

public LogbookController(MainFrameTab source, int iModuleId, int iGenericObjectId, Preferences prefs) {
    super(source);
    this.iModuleId = iModuleId;
    this.iGenericObjectId = iGenericObjectId;
    this.prefs = prefs.node(PREFS_KEY_LOGBOOK);
}

From source file:de.fhg.igd.mapviewer.server.wms.WMSConfiguration.java

/**
 * Save the configuration/*from   w  ww . j  a v  a 2  s. c  om*/
 * 
 * @param overwrite if old settings/servers with the same name shall be
 *            overridden
 */
public void save(boolean overwrite) {
    Preferences preferences = getPreferences();

    try {
        String name = getName();

        if (!overwrite) {
            int i = 1;
            // find unique name
            while (preferences.nodeExists(name)) {
                name = getName() + "_" + i; //$NON-NLS-1$
                i++;
            }
        }

        Preferences node = preferences.node(name);
        setName(name);

        saveProperties(node);

        node.flush();
    } catch (BackingStoreException e) {
        log.error("Error saving map server preferences", e); //$NON-NLS-1$
    }
}

From source file:org.griphyn.vdl.karajan.monitor.monitors.swing.GraphPanel.java

public void store(Preferences p) {
    p.putInt("enabledCount", enabled.size());
    for (int i = 0; i < enabled.size(); i++) {
        Preferences gp = p.node("series" + i);
        gp.put("key", enabled.get(i));
        Color color = (Color) chart.getPlot().getLegendItems().get(i).getLinePaint();
        gp.putInt("color.r", color.getRed());
        gp.putInt("color.g", color.getGreen());
        gp.putInt("color.b", color.getBlue());
    }//w ww .ja  v  a  2  s  . c  o m
}

From source file:org.rhq.enterprise.server.agent.EmbeddedAgentBootstrapService.java

/**
 * Returns the preferences for this agent. The node returned is where all preferences are to be stored.
 *
 * @return the agent preferences//  ww w .j  ava 2 s.c o m
 */
private Preferences getPreferencesNode() {
    Preferences top_node = Preferences.userRoot().node(AgentConfigurationConstants.PREFERENCE_NODE_PARENT);
    Preferences preferences_node = top_node.node(getPreferencesNodeName());

    return preferences_node;
}

From source file:org.pentaho.reporting.ui.datasources.jdbc.connection.JdbcConnectionDefinitionManager.java

/**
 * package-local visibility for testing purposes
 *///from  w w w .ja  v  a 2 s  .  co m
JdbcConnectionDefinitionManager(final Preferences externalPreferences, final String node) {
    userPreferences = externalPreferences;
    // Load the list of JNDI Sources
    try {
        final String[] childNodeNames = userPreferences.childrenNames();
        for (int i = 0; i < childNodeNames.length; i++) {
            final String name = childNodeNames[i];
            final Preferences p = userPreferences.node(name);
            final String type = p.get("type", null);
            if (type == null) {
                p.removeNode();
            } else if (type.equals("local")) {
                final Properties props = new Properties();
                if (p.nodeExists("properties")) {
                    final Preferences preferences = p.node("properties");
                    final String[] strings = preferences.keys();
                    for (int j = 0; j < strings.length; j++) {
                        final String string = strings[j];
                        final String value = preferences.get(string, null);
                        if (value != null) {
                            props.setProperty(string, value);
                        } else {
                            props.remove(string);
                        }
                    }
                }

                final DriverConnectionDefinition driverConnection = new DriverConnectionDefinition(name,
                        p.get(DRIVER_KEY, null), p.get(URL_KEY, null), p.get(USERNAME_KEY, null),
                        p.get(PASSWORD_KEY, null), p.get(HOSTNAME_KEY, null), p.get(DATABASE_NAME_KEY, null),
                        p.get(DATABASE_TYPE_KEY, null), p.get(PORT_KEY, null), props);

                connectionDefinitions.put(name, driverConnection);
            } else if (type.equals("jndi")) {
                final JndiConnectionDefinition connectionDefinition = new JndiConnectionDefinition(name,
                        p.get(JNDI_LOCATION, null), p.get(DATABASE_TYPE_KEY, null), p.get(USERNAME_KEY, null),
                        p.get(PASSWORD_KEY, null));
                connectionDefinitions.put(name, connectionDefinition);
            } else {
                p.removeNode();
            }
        }
    } catch (BackingStoreException e) {
        // The system preferences system is not working - log this as a message and use defaults
        log.warn("Could not access the user prefererences while loading the "
                + "JNDI connection information - using default JNDI connection entries", e);
    } catch (final Exception e) {
        log.warn("Configuration information was invalid.", e);
    }

    // If the connectionDefinitions is empty, add any default entries
    if (connectionDefinitions.isEmpty() && DATASOURCE_PREFERENCES_NODE.equals(node)) {
        if (userPreferences.getBoolean("sample-data-created", false) == true) {
            // only create the sample connections once, if we work on a totally fresh config.
            return;
        }
        updateSourceList(SAMPLE_DATA_JNDI_SOURCE);
        updateSourceList(SAMPLE_DATA_DRIVER_SOURCE);
        updateSourceList(SAMPLE_DATA_MEMORY_SOURCE);
        updateSourceList(LOCAL_SAMPLE_DATA_DRIVER_SOURCE);
        updateSourceList(MYSQL_SAMPLE_DATA_DRIVER_SOURCE);
        userPreferences.putBoolean("sample-data-created", true);
        try {
            userPreferences.flush();
        } catch (BackingStoreException e) {
            // ignored ..
        }
    }
}

From source file:com.github.fritaly.dualcommander.DualCommander.java

@Override
public void windowClosing(WindowEvent e) {
    try {/*from w  w  w. ja  v  a 2 s  .c o  m*/
        if (logger.isDebugEnabled()) {
            logger.debug("Saving preferences ...");
        }

        // Save the program state
        final Preferences prefs = Preferences.userNodeForPackage(this.getClass());

        this.leftPane.saveState(prefs.node("left.panel"));
        this.rightPane.saveState(prefs.node("right.panel"));
        this.preferences.saveState(prefs.node("user.preferences"));

        prefs.sync();

        if (logger.isInfoEnabled()) {
            logger.info("Saved preferences");
        }
    } catch (BackingStoreException e1) {
        // Not a big deal
    }
}

From source file:com.adito.jdbc.DBUpgrader.java

/**
 * Check the database schema and perform any upgrades.
 * // w ww  .j a  v a  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.pentaho.reporting.ui.datasources.jdbc.connection.JdbcConnectionDefinitionManager.java

/**
 * Adds or updates the source list with the specified source entry. If the entry exists (has the same name), the new
 * entry will replace the old entry. If the enrty does not already exist, the new entry will be added to the list. <br>
 * Since the definition of the ConnectionDefintion ensures that it will be valid, no testing will be performed on the
 * contents of the ConnectionDefintion.//ww w.  jav a 2 s. c  om
 * 
 * @param source
 *          the entry to add/update in the list
 * @throws IllegalArgumentException
 *           indicates the source is <code>null</code>
 */
private boolean updateSourceList(final DriverConnectionDefinition source) throws IllegalArgumentException {
    if (source == null) {
        throw new IllegalArgumentException("The provided source is null");
    }

    // Update the node in the list
    final boolean updateExisting = (connectionDefinitions.put(source.getName(), source) != null);

    // Update the information in the preferences
    try {
        final Preferences node = userPreferences.node(source.getName());
        put(node, TYPE_KEY, "local");
        put(node, DRIVER_KEY, source.getDriverClass());
        put(node, URL_KEY, source.getConnectionString());
        put(node, USERNAME_KEY, source.getUsername());
        put(node, PASSWORD_KEY, source.getPassword());
        put(node, HOSTNAME_KEY, source.getHostName());
        put(node, PORT_KEY, source.getPort());
        put(node, DATABASE_TYPE_KEY, source.getDatabaseType());
        put(node, DATABASE_NAME_KEY, source.getDatabaseName());
        final Preferences preferences = node.node("properties");
        final Properties properties = source.getProperties();
        final Iterator entryIterator = properties.entrySet().iterator();
        while (entryIterator.hasNext()) {
            final Map.Entry entry = (Map.Entry) entryIterator.next();
            put(preferences, String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
        }
        node.flush();
    } catch (BackingStoreException e) {
        log.error("Could not add/update connection entry [" + source.getName() + ']', e);
    }
    return updateExisting;
}