Example usage for java.util.prefs Preferences removeNode

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

Introduction

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

Prototype

public abstract void removeNode() throws BackingStoreException;

Source Link

Document

Removes this preference node and all of its descendants, invalidating any preferences contained in the removed nodes.

Usage

From source file:org.pdfsam.module.PreferencesUsageDataStore.java

public void clear() {
    Preferences prefs = Preferences.userRoot().node(USAGE_PATH);
    try {/*from  w w w . j a  v  a2 s . co m*/
        prefs.removeNode();
        prefs.flush();
    } catch (BackingStoreException e) {
        LOG.error("Unable to clear modules usage statistics", e);
    }
}

From source file:de.ingrid.usermanagement.jetspeed.IngridRoleManager.java

/**
 * @see org.apache.jetspeed.security.RoleManager#removeRole(java.lang.String)
 *//* w  ww . j  a  v a2s. co m*/
public void removeRole(String roleFullPathName) throws SecurityException {
    ArgUtil.notNull(new Object[] { roleFullPathName }, new String[] { "roleFullPathName" },
            "removeRole(java.lang.String)");

    // Resolve the role hierarchy.
    Preferences prefs = Preferences.userRoot()
            .node(RolePrincipalImpl.getFullPathFromPrincipalName(roleFullPathName));
    String[] roles = securityMappingHandler.getRoleHierarchyResolver().resolveChildren(prefs);
    for (int i = 0; i < roles.length; i++) {
        try {
            roleSecurityHandler.removeRolePrincipal(
                    new RolePrincipalImpl(RolePrincipalImpl.getPrincipalNameFromFullPath((String) roles[i])));
        } catch (Exception e) {
            KeyedMessage msg = SecurityException.UNEXPECTED.create("RoleManager.removeRole",
                    "RoleSecurityHandler.removeRolePrincipal("
                            + RolePrincipalImpl.getPrincipalNameFromFullPath((String) roles[i]) + ")",
                    e.getMessage());
            log.error(msg, e);
            throw new SecurityException(msg, e);
        }
        // Remove preferences
        Preferences rolePref = Preferences.userRoot().node((String) roles[i]);
        try {
            rolePref.removeNode();
        } catch (BackingStoreException bse) {
            KeyedMessage msg = SecurityException.UNEXPECTED.create("RoleManager.removeRole",
                    "Preferences.removeNode(" + roles[i] + ")", bse.getMessage());
            log.error(msg, bse);
            throw new SecurityException(msg, bse);
        }
    }
}

From source file:de.ingrid.usermanagement.jetspeed.IngridRoleManager.java

/**
 * @see org.apache.jetspeed.security.RoleManager#addRole(java.lang.String)
 *//*from   www  . j ava 2s.c o  m*/
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:com.adito.jdbc.DBUpgrader.java

/**
 * Check the database schema and perform any upgrades.
 * //from   w  w w  .  j ava2  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.apache.cayenne.pref.CayennePreferenceEditor.java

public void save() {
    cayenneProjectPreferences.getDetailObject(DBConnectionInfo.class).save();

    if (restartRequired) {
        restart();/* w  ww.j  a  v a  2  s. co  m*/
    }

    // update boolean preferences
    Iterator it = changedBooleanPreferences.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        Preferences pref = (Preferences) entry.getKey();
        Map<String, Boolean> map = (Map<String, Boolean>) entry.getValue();

        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry en = (Map.Entry) iterator.next();
            String key = (String) en.getKey();
            Boolean value = (Boolean) en.getValue();

            pref.putBoolean(key, value);
        }
    }

    // update string preferences
    Iterator iter = changedPreferences.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        Preferences pref = (Preferences) entry.getKey();
        Map<String, String> map = (Map<String, String>) entry.getValue();

        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry en = (Map.Entry) iterator.next();
            String key = (String) en.getKey();
            String value = (String) en.getValue();

            pref.put(key, value);
        }
    }

    // remove string preferences
    Iterator iterator = removedPreferences.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry entry = (Map.Entry) iterator.next();
        Preferences pref = (Preferences) entry.getKey();
        Map<String, String> map = (Map<String, String>) entry.getValue();

        Iterator itRem = map.entrySet().iterator();
        while (itRem.hasNext()) {
            Map.Entry en = (Map.Entry) itRem.next();
            String key = (String) en.getKey();
            pref.remove(key);
        }
    }

    // remove preferences node
    Iterator<Preferences> iteratorNode = removedNode.iterator();
    while (iteratorNode.hasNext()) {
        Preferences pref = iteratorNode.next();
        try {
            pref.removeNode();
        } catch (BackingStoreException e) {
            logger.warn("Error removing preferences");
        }
    }

    Application.getInstance().initClassLoader();
}

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

public void revert() {

    // remove added preferences node
    Iterator<Preferences> iteratorNode = addedNode.iterator();
    while (iteratorNode.hasNext()) {
        Preferences pref = iteratorNode.next();
        try {// ww  w.java2 s  .co m
            pref.removeNode();
        } catch (BackingStoreException e) {
            // do nothing
        }
    }

    cayenneProjectPreferences.getDetailObject(DBConnectionInfo.class).cancel();
    restartRequired = false;
}

From source file:org.fuin.utils4j.PropertiesFilePreferencesTest.java

/**
 * @testng.test/*from  w  ww  . j a v a  2  s  .c om*/
 */
public final void testChildRemove() throws BackingStoreException {

    final File dir = new File(baseDir, "user");
    final File subDir = new File(dir, "abc");
    final File file = new File(subDir, PropertiesFilePreferences.FILENAME);
    final PropertiesFilePreferences root = new PropertiesFilePreferences(dir);

    final Preferences pref = root.node("abc");
    pref.flush();
    Assert.assertTrue(file.exists());

    pref.removeNode();
    pref.flush();
    Assert.assertFalse(file.exists());

}

From source file:org.pdfsam.ui.PreferencesRecentWorkspacesService.java

@Override
public void clear() {
    Preferences prefs = Preferences.userRoot().node(WORKSPACES_PATH);
    cache.clear();//from  www.j a  va  2 s  . c  o  m
    try {
        prefs.removeNode();
        prefs.flush();
    } catch (BackingStoreException e) {
        LOG.error("Unable to clear recently used workspaces", e);
    }
}

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

/**
 * package-local visibility for testing purposes
 *//*w w w  .  j av  a 2 s. c  o 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:org.pentaho.reporting.ui.datasources.jdbc.connection.JdbcConnectionDefinitionManager.java

/**
 * Removes the specified connection-definition from the list of connections.
 * /* w  w w  . j  a  v  a 2  s .  c  o  m*/
 * @param name
 *          the name of the JNDI source to remove from the list
 */
public void removeSource(final String name) {
    // Make sure the name provided is not null
    if (StringUtils.isEmpty(name)) {
        throw new IllegalArgumentException("The provided name is invalid");
    }

    // If the source is in our list, remove it
    connectionDefinitions.remove(name);

    // Remove the entry from the user preferences
    try {
        final Preferences node = userPreferences.node(name);
        if (node != null) {
            node.removeNode();
            userPreferences.flush();
        }
    } catch (BackingStoreException e) {
        log.error("Could not remove JNDI connection entry [" + name + ']', e);
    }

}