Example usage for java.util.prefs Preferences userRoot

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

Introduction

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

Prototype

public static Preferences userRoot() 

Source Link

Document

Returns the root preference node for the calling user.

Usage

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

public JdbcConnectionDefinitionManager(final String node) {
    this(Preferences.userRoot().node(node), node);
}

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

@Test
public void blankIsNotLoaded() throws BackingStoreException {
    Preferences node = Preferences.userRoot().node(WORKSPACES_PATH);
    node.put("1", EMPTY);
    node.flush();/*  w  ww  .  jav a2  s. co m*/
    PreferencesRecentWorkspacesService newVictim = new PreferencesRecentWorkspacesService();
    assertEquals(0, newVictim.getRecentlyUsedWorkspaces().size());
}

From source file:org.kuali.test.ui.base.BaseTable.java

/**
 *
 *///from  w  w w  .  j av a2s  .c  o  m
public void saveTablePreferences() {
    TableConfiguration config = (TableConfiguration) getConfig();
    Preferences proot = Preferences.userRoot();
    Preferences node = proot.node(Constants.PREFS_TABLE_NODE);

    for (int i = 0; i < config.getPropertyNames().length; ++i) {
        String key = getColumnPreferenceKey(i, "width");

        if (StringUtils.isNotBlank(key)) {
            node.putInt(key, getColumnModel().getColumn(i).getPreferredWidth());
        }
    }
}

From source file:com.gnadenheimer.mg.utils.Utils.java

public Map<String, String> getPersistenceMap() {
    try {//from   www  . j  av  a 2  s. co m
        Properties p = System.getProperties();
        p.setProperty("derby.system.home", Preferences.userRoot().node("MG").get("Datadir",
                (new JFileChooser()).getFileSystemView().getDefaultDirectory().toString() + "\\javadb"));
        p.setProperty("derby.drda.host", "0.0.0.0");
        p.setProperty("derby.language.sequence.preallocator", "1");
        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("backUpDir",
                Preferences.userRoot().node("MG").get("Datadir",
                        (new JFileChooser()).getFileSystemView().getDefaultDirectory().toString() + "\\javadb")
                        + "\\autoBackUp");
        persistenceMap.put("anoActivo",
                Preferences.userRoot().node("MG").get("anoActivo", String.valueOf(LocalDate.now().getYear())));
        return persistenceMap;
    } catch (Exception exx) {
        JOptionPane.showMessageDialog(null,
                Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + exx.getMessage());
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), exx);
        return null;
    }
}

From source file:com.example.app.profile.ui.user.MyAccountEdit.java

@SuppressWarnings("Duplicates")
@Override//from www  .j  a v  a2 s  . c  o m
public void init() {
    super.init();

    NavigationAction saveAction = CommonActions.SAVE.navAction();
    saveAction.onCondition(input -> persist(user -> {
        assert user != null : "User should not be null if you are persisting!";
        UserValueEditor editor = getValueEditor();
        User currentUser = _userDAO.getAssertedCurrentUser();
        _sessionHelper.beginTransaction();
        boolean success = false;
        try {
            if (Objects.equals(currentUser.getId(), user.getId())) {
                user.setPreferredContactMethod(editor.commitValuePreferredContactMethod());

                final Link link = editor.commitValueLoginLandingPage();
                if (link != null) {
                    Preferences userPref = Preferences.userRoot().node(User.LOGIN_PREF_NODE);
                    userPref.put(User.LOGIN_PREF_NODE_LANDING_PAGE, link.getURIAsString());
                }
            }

            user = _userDAO.mergeUser(user);
            try {
                EmailAddress emailAddress = ContactUtil
                        .getEmailAddress(user.getPrincipal().getContact(), ContactDataCategory.values())
                        .orElseThrow(() -> new IllegalStateException(
                                "Email Address was null on PrincipalValueEditor.  This should not happen."));

                PasswordCredentials creds = user.getPrincipal().getPasswordCredentials();
                creds.setUsername(emailAddress.getEmail());
                _principalDAO.savePrincipal(user.getPrincipal());

                user = _userDAO.mergeUser(user);

                if (editor.getPictureEditor().getModificationState().isModified()) {
                    _userDAO.saveUserImage(user, editor.getPictureEditor().commitValue());
                }

                success = true;
            } catch (NonUniqueCredentialsException e) {
                _logger.error("Unable to persist changes to the Principal.", e);
                getNotifiable().sendNotification(error(ERROR_MESSAGE_USERNAME_EXISTS_FMT(USER())));
            }
            _sessionHelper.commitTransaction();
        } finally {
            if (!success)
                _sessionHelper.recoverableRollbackTransaction();
        }
        return success;
    }));
    saveAction.configure().toReturnPath(ApplicationFunctions.User.MY_ACCOUNT_VIEW).usingCurrentURLData()
            .withSourceComponent(this);
    saveAction.setTarget(this, "close");

    NavigationAction cancelAction = CommonActions.CANCEL.navAction();
    cancelAction.configure().toReturnPath(ApplicationFunctions.User.MY_ACCOUNT_VIEW).usingCurrentURLData()
            .withSourceComponent(this);
    cancelAction.setTarget(this, "close");

    setPersistenceActions(saveAction, cancelAction);
}

From source file:org.kuali.test.ui.base.BaseTable.java

private int getColumnWidth(int col) {
    int retval = getConfig().getColumnWidths()[col];
    Preferences proot = Preferences.userRoot();
    Preferences node = proot.node(Constants.PREFS_TABLE_NODE);

    String key = getColumnPreferenceKey(col, "width");

    if (StringUtils.isNotBlank(key)) {
        retval = node.getInt(key, retval);
    }/*  ww w  . j  ava  2  s.  c om*/

    return retval;
}

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

/**
 * @see org.apache.jetspeed.security.RoleManager#removeRole(java.lang.String)
 *///from w  w  w .ja v  a 2s. 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:edu.umass.cs.msocket.proxy.console.ConsoleModule.java

/**
 * Store the current command history/*from  w w w. j a  v a2 s .  c  o m*/
 */
public void storeHistory() {
    List history = console.getHistory().getHistoryList();
    try {
        Preferences prefs = Preferences.userRoot().node(this.getClass().getName());
        prefs.clear();
        int historySize = history.size();
        int start = Math.max(0, historySize - 100);
        // save up to the last 100th history items only
        // witht the stored index starting at 0
        for (int i = start; i < historySize; i++) {
            prefs.put(String.valueOf(i - start), (String) history.get(i + start));
        }
        prefs.flush();
    } catch (Exception e) {
        // unable to store prefs: do nothing
    }
}

From source file:acmi.l2.clientmod.xdat.XdatEditor.java

public static Preferences getPrefs() {
    return Preferences.userRoot().node("xdat_editor");
}

From source file:nl.toolforge.karma.core.cmd.KarmaInitializationCommand.java

/**
 * Initializes a command context./*  w ww . ja  v a  2  s .co m*/
 *
 * @throws CommandException
 */
public void execute() throws CommandException {

    try {

        if (updateStores) {

            try {

                ManifestStore mStore = commandContext.getWorkingContext().getConfiguration().getManifestStore();

                if (!mStore.getLocation().isAvailable()) {
                    commandResponse.addEvent(
                            new MessageEvent(this, new SimpleMessage("Manifest store location unreachable!")));
                } else {
                    commandResponse
                            .addEvent(new MessageEvent(this, new SimpleMessage(("Updating manifests ..."))));
                    mStore.update();
                }

                LocationStore lStore = commandContext.getWorkingContext().getConfiguration().getLocationStore();

                if (!lStore.getLocation().isAvailable()) {
                    commandResponse.addEvent(
                            new MessageEvent(this, new SimpleMessage("Location store location unreachable!")));
                } else {
                    commandResponse
                            .addEvent(new MessageEvent(this, new SimpleMessage(("Updating locations ..."))));
                    lStore.update();
                }

            } catch (VersionControlException e) {
                logger.warn(new ErrorEvent(this, e.getErrorCode(), e.getMessageArguments()));
                commandResponse.addEvent(new ErrorEvent(this, e.getErrorCode(), e.getMessageArguments()));
            } catch (AuthenticationException e) {
                logger.warn(new ErrorEvent(this, e.getErrorCode(), e.getMessageArguments()));
                commandResponse.addEvent(new ErrorEvent(this, e.getErrorCode(), e.getMessageArguments()));
            }
        }

        commandResponse.addEvent(new MessageEvent(this,
                new SimpleMessage(getFrontendMessages().getString("message.LOADING_MANIFEST_FROM_HISTORY"))));

        // Try reloading the last manifest that was used.
        //
        Manifest currentManifest = commandContext.getWorkingContext().getManifestCollector()
                .loadManifestFromHistory();
        if (currentManifest != null) {
            SimpleMessage message = new SimpleMessage(
                    getFrontendMessages().getString("message.MANIFEST_ACTIVATED"),
                    new Object[] { currentManifest });
            commandResponse.addEvent(new MessageEvent(this, message));

            // Register the command context with the listener to allow automaic updates of the manifest.
            //
            commandContext.changeCurrentManifest(currentManifest);
            commandContext.register();
        } else {
            commandResponse.addEvent(new MessageEvent(this,
                    new SimpleMessage(getFrontendMessages().getString("message.NO_MANIFEST_IN_HISTORY"))));
        }

        try {
            Preferences.userRoot().put(WorkingContext.WORKING_CONTEXT_PREFERENCE,
                    commandContext.getWorkingContext().getName());
            Preferences.userRoot().flush();
        } catch (BackingStoreException e) {
            // Too bad ...
        }
    } catch (ManifestException e) {
        throw new CommandException(e, e.getErrorCode(), e.getMessageArguments());
    } catch (LocationException e) {
        throw new CommandException(e, e.getErrorCode(), e.getMessageArguments());
    }
}