Example usage for java.util.prefs Preferences get

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

Introduction

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

Prototype

public abstract String get(String key, String def);

Source Link

Document

Returns the value associated with the specified key in this preference node.

Usage

From source file:main.UIController.java

public Time calculateSunsetForActualLocationAndTime(boolean useCacheSunset) {
    Preferences data = this.getCurrentPreferences();
    TimeZone tz = TimeZone.getTimeZone(data.get(FIELD_TIMEZONE, DEF_TIMEZONE));
    Time time = this.calculateSunsetForActualLocation(new GregorianCalendar(tz), useCacheSunset);
    return time;/* w  ww  . j a  v a 2 s .  co m*/
}

From source file:org.tros.logo.swing.LogoMenuBar.java

/**
 * Set up the export menu.//from ww w . j av a 2s  . c  o m
 *
 * @return
 */
private JMenu setupExportMenu() {
    JMenu exportMenu = new JMenu(Localization.getLocalizedString("ExportMenu"));

    JMenuItem exportGif = new JMenuItem(Localization.getLocalizedString("ExportGIF"));
    JMenuItem exportPng = new JMenuItem(Localization.getLocalizedString("ExportPNG"));
    JMenuItem exportSvg = new JMenuItem(Localization.getLocalizedString("ExportSVG"));

    exportSvg.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            java.util.prefs.Preferences prefs = java.util.prefs.Preferences
                    .userNodeForPackage(LogoMenuBar.class);
            chooser.setCurrentDirectory(new File(prefs.get("export-directory", ".")));

            chooser.setVisible(true);
            int result = chooser.showSaveDialog(parent);

            if (result == JFileChooser.APPROVE_OPTION) {
                String filename = chooser.getSelectedFile().getPath();
                prefs.put("export-directory", chooser.getSelectedFile().getParent());
                if (Drawable.class.isAssignableFrom(canvas.getClass())) {
                    try (FileOutputStream fos = new FileOutputStream(new File(filename))) {
                        generateSVG((Drawable) canvas, fos);
                        fos.flush();
                    } catch (IOException ex) {
                        org.tros.utils.logging.Logging.getLogFactory().getLogger(LogoMenuBar.class).warn(null,
                                ex);
                    }
                }
            }
        }
    });

    exportGif.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            java.util.prefs.Preferences prefs = java.util.prefs.Preferences
                    .userNodeForPackage(LogoMenuBar.class);
            chooser.setCurrentDirectory(new File(prefs.get("export-directory", ".")));

            chooser.setVisible(true);
            int result = chooser.showSaveDialog(parent);

            if (result == JFileChooser.APPROVE_OPTION) {
                final String filename = chooser.getSelectedFile().getPath();
                prefs.put("export-directory", chooser.getSelectedFile().getParent());
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (Drawable.class.isAssignableFrom(canvas.getClass())
                                && BufferedImageProvider.class.isAssignableFrom((canvas.getClass()))) {
                            try {
                                generateGIF(((Drawable) canvas).cloneDrawable(), (BufferedImageProvider) canvas,
                                        filename);
                            } catch (SVGGraphics2DIOException ex) {
                                Logger.getLogger(LogoMenuBar.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IOException ex) {
                                Logger.getLogger(LogoMenuBar.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                });
                t.setDaemon(true);
                t.start();
            }
        }
    });
    exportPng.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            java.util.prefs.Preferences prefs = java.util.prefs.Preferences
                    .userNodeForPackage(LogoMenuBar.class);
            chooser.setCurrentDirectory(new File(prefs.get("export-directory", ".")));

            chooser.setVisible(true);
            int result = chooser.showSaveDialog(parent);

            if (result == JFileChooser.APPROVE_OPTION) {
                String filename = chooser.getSelectedFile().getPath();
                prefs.put("export-directory", chooser.getSelectedFile().getParent());
                // retrieve image
                if (BufferedImageProvider.class.isAssignableFrom(canvas.getClass())) {
                    generatePNG((BufferedImageProvider) canvas, filename);
                }
            }
        }
    });

    exportMenu.add(exportSvg);
    exportMenu.add(exportGif);
    exportMenu.add(exportPng);
    exportMenu.setMnemonic('X');
    exportSvg.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.ALT_MASK));
    exportGif.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.ALT_MASK));
    exportPng.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.ALT_MASK));
    return (exportMenu);
}

From source file:main.UIController.java

public void showDateOfToday(boolean useCacheSunset) {
    Preferences data = this.getCurrentPreferences();
    String city = data.get(FIELD_CITY, DEF_CITY);
    String country = data.get(FIELD_COUNTRY, DEF_COUNTRY);
    TimeZone tz = TimeZone.getTimeZone(data.get(FIELD_TIMEZONE, DEF_TIMEZONE));
    GregorianCalendar gcal = new GregorianCalendar(tz);
    Time time = this.calculateSunsetForActualLocation(gcal, useCacheSunset);
    ImladrisCalendar cal;/*w  ww .j  a  va  2s  . c o  m*/
    String sunsetStr = "";
    String locationInfo = "";
    if (time == null) {
        cal = new ImladrisCalendar(gcal);
    } else {
        cal = new ImladrisCalendar(time, gcal);
        /*check if before sunset*/
        String gtimeStr = gcal.get(GregorianCalendar.HOUR_OF_DAY) + ":" + gcal.get(GregorianCalendar.MINUTE)
                + ":" + gcal.get(GregorianCalendar.SECOND);
        Time gtime = Time.valueOf(gtimeStr);
        if (gtime.before(time)) { // before sunset
            sunsetStr = " - before sunset";
        } else { // after/during sunset
            sunsetStr = " - after sunset";
        }
        String sunsetTimeStr = time.toString();
        sunsetTimeStr = sunsetTimeStr.substring(0, sunsetTimeStr.length() - 3);
        sunsetStr += " " + Lang.punctuation.parenthesis_open + "occurring at " + sunsetTimeStr
                + Lang.punctuation.parenthesis_close;
        locationInfo = this.makeLocationString(city, country);
        if (locationInfo.length() > 0) {
            locationInfo = Lang.punctuation.parenthesis_open + Lang.common.location_label
                    + Lang.punctuation.double_dot + " " + locationInfo + " " + Lang.punctuation.pipe + " "
                    + Lang.common.timezone_label + Lang.punctuation.double_dot + " "
                    + data.get(FIELD_TIMEZONE, DEF_TIMEZONE) + Lang.punctuation.parenthesis_close;
        }
    }
    String gstr = this.gregorianToString(gcal);
    String istr = cal.toString();
    UI ui = this.getUi();
    ui.getTodayGregorian().setText(gstr + sunsetStr);
    ui.getTodayImladris().setText(istr);
    ui.getLocationInfo().setText(locationInfo);
}

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

private void setupUI() {
    removeAllComponents();/*from  ww  w .  j  a va 2  s.  com*/

    User currentUser = _userDAO.getAssertedCurrentUser();
    Profile profile = _uiPreferences.getSelectedCompany();

    final ImageComponent userImage = new ImageComponent();
    if (getUser().getImage() != null) {
        try {
            final Dimension size = ImageFileUtil.getDimension(getUser().getImage(), true);
            // We are showing a max height of 200px
            if (size != null && size.getHeightMetric().intValue() < MAX_HEIGHT_PROFILE_PIC_VIEW)
                userImage.setSize(size);
            else
                userImage.setHeight(new PixelMetric(MAX_HEIGHT_PROFILE_PIC_VIEW));
        } catch (IOException e) {
            _logger.debug("Unable to get file dimension.", e);
        }
        userImage.setImage(new Image(getUser().getImage()));
    } else
        userImage.setImage(new Image(_appUtil.getDefaultUserImage()));
    userImage.addClassName("image");
    final Container userImageField = of("prop picture", userImage);

    final TextEditor nameField = new TextEditor(LABEL_NAME(),
            NameCellRenderer.getFormattedString(getUser().getPrincipal().getContact().getName()));
    nameField.setEditable(false);
    setFieldVisibility(nameField);
    nameField.addClassName("name");

    Address address = ContactUtil
            .getAddress(getUser().getPrincipal().getContact(), ContactDataCategory.values())
            .orElse(new Address());
    final Container addressContainer = Container.of("prop address", LABEL_ADDRESS(),
            new AddressCellRenderer(address));

    final TextEditor emailField = new TextEditor(LABEL_EMAIL(),
            ContactUtil.getEmailAddress(getUser().getPrincipal().getContact(), ContactDataCategory.values())
                    .map(EmailAddress::getEmail).orElse(""));
    emailField.setEditable(false);
    setFieldVisibility(emailField);
    emailField.addClassName("email");

    final TextEditor phoneField = new TextEditor(LABEL_PHONE(),
            ContactUtil.getPhoneNumber(getUser().getPrincipal().getContact(), ContactDataCategory.values())
                    .map(PhoneNumber::toExternalForm).orElse(""));
    phoneField.setEditable(false);
    setFieldVisibility(phoneField);
    phoneField.addClassName("phone");

    final TextEditor smsPhoneField = new TextEditor(LABEL_SMS_PHONE(),
            Optional.ofNullable(getUser().getSmsPhone()).map(PhoneNumber::toExternalForm).orElse(""));
    smsPhoneField.setEditable(false);
    setFieldVisibility(smsPhoneField);
    smsPhoneField.addClassName("sms-phone");

    final TextEditor timeZoneField = new TextEditor(LABEL_PREFERRED_TIME_ZONE(),
            Optional.ofNullable(getUser().getPrincipal().getContact().getPreferredTimeZone())
                    //            .map(tz -> tz.getDisplayName(false, TimeZone.LONG, getLocaleContext().getLocale()))
                    .map(TimeZone::getID).orElse(""));
    timeZoneField.setEditable(false);
    setFieldVisibility(timeZoneField);
    timeZoneField.addClassName("time-zone");

    final ComboBoxValueEditor<Profile> coachingField = new ComboBoxValueEditor<>(_terms.company(),
            Collections.singletonList(profile), profile);
    coachingField.setEditable(false);
    coachingField.addClassName("coaching");

    final CheckboxValueEditor<LocalizedObjectKey> contactPrefsField = new CheckboxValueEditor<>(
            LABEL_CONTACT_PREFERENCES(), Collections.singleton(LABEL_SEND_NOTIFICATION_TO_PHONESMS()), null);
    contactPrefsField.getLabel().withHTMLElement(HTMLElement.h3);
    contactPrefsField.withHTMLElement(HTMLElement.section);
    contactPrefsField.setEditable(false);
    contactPrefsField.setVisible(Objects.equals(currentUser.getId(), getUser().getId()));
    if (getUser().getPreferredContactMethod() == ContactMethod.PhoneSms)
        contactPrefsField.setValue(Collections.singleton(LABEL_SEND_NOTIFICATION_TO_PHONESMS()));

    List<Link> links = LoginLandingLinks.getAvailableLinks(getUser(), getLocaleContext());
    links = nullFirst(links);
    final ComboBoxValueEditor<Link> loginLangingPage = new ComboBoxValueEditor<>(LABEL_LOGIN_LANDING_PAGE(),
            links, null);
    //This field is available when the current user is the user being viewed
    // AND only to the user who has a particular membership under the company.
    loginLangingPage.setVisible(Objects.equals(currentUser.getId(), getUser().getId())
            && _profileDAO.getMembershipsForUser(getUser(), null, getSession().getTimeZone()).stream()
                    .map(Membership::getMembershipType).filter(membershipType1 -> membershipType1 != null)
                    .anyMatch(membershipType -> membershipType.equals(_mtp.companyAdmin())));
    loginLangingPage.setCellRenderer(new CustomCellRenderer(CommonButtonText.PLEASE_SELECT, input -> {
        Link link = (Link) input;
        return TextSources.createText(link.getAdditionalAttributes().get("label"));
    }));
    final Preferences userPref = Preferences.userRoot().node(User.LOGIN_PREF_NODE);
    final String uri = userPref != null ? userPref.get(User.LOGIN_PREF_NODE_LANDING_PAGE, null) : null;
    for (Link l : links) {
        if (l != null && l.getURIAsString().equals(uri)) {
            loginLangingPage.setValue(l);
            break;
        }
    }

    loginLangingPage.getLabel().withHTMLElement(HTMLElement.h3);
    loginLangingPage.withHTMLElement(HTMLElement.section);
    loginLangingPage.setEditable(false);

    add(userImageField);
    add(nameField);
    add(addressContainer);
    add(emailField);
    add(phoneField);
    if (getUser().getSmsPhone() != null)
        add(smsPhoneField);
    add(timeZoneField);
    if (isAdminMode()) {
        add(coachingField);
    }
    add(contactPrefsField);
    add(loginLangingPage);
}

From source file:main.UIController.java

/************* SETTINGS ****************/

private void fillSettingsForm() {
    UI ui = this.getUi();
    Preferences data = this.getCurrentPreferences();
    /* Country and city */
    String city = data.get(FIELD_CITY, DEF_CITY);
    String country = data.get(FIELD_COUNTRY, DEF_COUNTRY);
    ui.getCity().setText(city);//from w  ww. j av  a 2  s  .  c o m
    ui.getCountry().setText(country);
    /* Lang */
    LangManager langManager = LangManager.getInstance();
    String lang = langManager.getDefinedLang().getShortName();
    JComboBox langsCombo = ui.getLangCombo();
    langsCombo.setSelectedIndex(Arrays.asList(LangManager.getLanguagesShort()).indexOf(lang));
    /* Time Zone */
    String[] tzs = TimeZone.getAvailableIDs();
    Arrays.sort(tzs);
    JList list = ui.getTimeZone();
    list.setListData(tzs);
    String timezone = data.get(FIELD_TIMEZONE, DEF_TIMEZONE);
    list.setSelectedValue(timezone, true);
}

From source file:org.settings4j.connector.PreferencesConnector.java

/**
 * Resolve the given path and key against the given Preferences.
 *
 * @param path the preferences path (placeholder part before '/')
 * @param key the preferences key (placeholder part after '/')
 * @param preferences the Preferences to resolve against
 * @return the value for the placeholder, or <code>null</code> if none found
 *//*from  w  w  w .ja v a 2  s. co  m*/
protected String getPreferenceValue(final String path, final String key, final Preferences preferences) {
    if (path != null) {
        // Do not create the node if it does not exist...
        try {
            if (preferences.nodeExists(path)) {
                return preferences.node(path).get(key, null);
            }
            return null;
        } catch (final BackingStoreException e) {
            throw new RuntimeException("Cannot access specified node path [" + path + "]", e);
        }
    }
    return preferences.get(key, null);
}

From source file:com.wwidesigner.gui.StudyView.java

@Override
protected void initializeComponents() {
    // create file tree
    tree = new JTree() {
        @Override/*  w  w  w  .  jav  a  2  s. c  o  m*/
        public String getToolTipText(MouseEvent e) {
            String tip = null;
            TreePath path = tree.getPathForLocation(e.getX(), e.getY());
            if (path != null) {
                if (path.getPathCount() == 3) // it is a leaf
                {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                    if (node instanceof TreeNodeWithToolTips) {
                        tip = ((TreeNodeWithToolTips) node).getToolTip();
                    }
                }
            }
            return tip == null ? getToolTipText() : tip;
        }
    };
    // Show tooltips for the Study view, and let them persist for 8 seconds.
    ToolTipManager.sharedInstance().registerComponent(tree);
    ToolTipManager.sharedInstance().setDismissDelay(8000);
    // If a Study view node doesn't fit in the pane, expand it when hovering
    // over it.
    ExpandedTipUtils.install(tree);
    tree.setRootVisible(false);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    tree.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            TreePath path = tree.getPathForLocation(e.getX(), e.getY());
            if (path != null) {
                if (path.getPathCount() == 3) // it is a leaf
                {
                    DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
                    DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) node.getParent();
                    String category = (String) parentNode.getUserObject();
                    study.setCategorySelection(category, (String) node.getUserObject());
                    if (StudyModel.INSTRUMENT_CATEGORY_ID.equals(category)
                            || StudyModel.TUNING_CATEGORY_ID.equals(category)) {
                        try {
                            study.validHoleCount();
                        } catch (Exception ex) {
                            showException(ex);
                        }
                    }
                }
                updateView();
            }
        }
    });
    JScrollPane scrollPane = new JScrollPane(tree);
    scrollPane.setPreferredSize(new Dimension(225, 100));
    add(scrollPane);

    Preferences myPreferences = getApplication().getPreferences();
    String modelName = myPreferences.get(OptimizationPreferences.STUDY_MODEL_OPT,
            OptimizationPreferences.NAF_STUDY_NAME);
    setStudyModel(modelName);
    study.setPreferences(myPreferences);

    getApplication().getEventManager().subscribe(WIDesigner.FILE_OPENED_EVENT_ID, this);
    getApplication().getEventManager().subscribe(WIDesigner.FILE_CLOSED_EVENT_ID, this);
    getApplication().getEventManager().subscribe(WIDesigner.FILE_SAVED_EVENT_ID, this);
    getApplication().getEventManager().subscribe(WIDesigner.WINDOW_RENAMED_EVENT_ID, this);
}

From source file:org.nuclos.client.common.NuclosCollectController.java

/**
 * @param prefs/*from  ww w .  j av  a  2  s  .c  o  m*/
 * @param parent
 * @return a new <code>NuclosCollectController</code> with the state read from the preferences.
 */
@Deprecated
public static NuclosCollectController<?> createFromPreferences(final Preferences prefs)
        throws PreferencesException {
    final String sEntity = prefs.get(PREFS_KEY_ENTITY, null);
    if (sEntity == null) {
        throw new PreferencesException(SpringLocaleDelegate.getInstance().getMessage(
                "NuclosCollectController.6", "Entit\u00e4t {0} fehlt in den Benutzereinstellungen.", sEntity));
    }

    boolean allowed;
    allowed = SecurityCache.getInstance().isReadAllowedForModule(sEntity, null)
            || SecurityCache.getInstance().isReadAllowedForMasterData(sEntity);

    if (!allowed) {
        throw new PreferencesException(
                SpringLocaleDelegate.getInstance().getMessage("NuclosCollectController.17",
                        "Sie haben kein Recht die Entit\u00e4t ''{0}'' zu verwenden.", sEntity));
    }

    try {
        final NuclosCollectController<?> result = NuclosCollectControllerFactory.getInstance()
                .newCollectController(sEntity, null, ClientParameterProvider.getInstance()
                        .getValue(ParameterProvider.KEY_LAYOUT_CUSTOM_KEY));

        final int iCollectState = result.restoreStateFromPreferences(prefs);

        UIUtils.runCommandLaterForTabbedPane(MainFrame.getPredefinedEntityOpenLocation(sEntity),
                new CommonRunnable() {
                    // This must be done later as reloading the layout in restoreStateFromPreferences is done later also:
                    @Override
                    public void run() throws CommonBusinessException {
                        switch (iCollectState) {
                        case CollectState.OUTERSTATE_SEARCH:
                            result.runSearch(false);
                            break;
                        case CollectState.OUTERSTATE_RESULT:
                            result.runViewAll(false);
                            break;
                        case CollectState.OUTERSTATE_DETAILS:
                            final Collectable clct = result.getCurrentCollectableFromPreferences(prefs);
                            if (clct == null) {
                                result.runNew(false);
                            } else {
                                ((NuclosCollectController) result).runViewSingleCollectable(clct, false);
                            }
                            break;
                        default:
                            throw new PreferencesException(SpringLocaleDelegate.getInstance().getMessage(
                                    "NuclosCollectController.14",
                                    "Ung\u00fcltiger Erfassungsstatus in den Benutzereinstellungen: {0}",
                                    iCollectState));
                        }
                    }
                });

        return result;
    } catch (CommonBusinessException ex) {
        throw new PreferencesException(ex.getMessage(), ex);
    }
}

From source file:org.apache.cayenne.modeler.Application.java

/**
 * Reinitializes ModelerClassLoader from preferences.
 *//*from ww  w.  j a  v a 2 s .  c om*/
@SuppressWarnings("unchecked")
public void initClassLoader() {
    final FileClassLoadingService classLoader = new FileClassLoadingService();

    // init from preferences...
    Preferences classLoaderPreference = Application.getInstance().getPreferencesNode(ClasspathPreferences.class,
            "");

    Collection details = new ArrayList<>();
    String[] keys = null;
    ArrayList<String> values = new ArrayList<>();

    try {
        keys = classLoaderPreference.keys();
        for (String cpKey : keys) {
            values.add(classLoaderPreference.get(cpKey, ""));
        }
    } catch (BackingStoreException e) {
        // do nothing
    }

    for (int i = 0; i < values.size(); i++) {
        details.add(values.get(i));
    }

    if (details.size() > 0) {

        // transform preference to file...
        Transformer transformer = new Transformer() {

            public Object transform(Object object) {
                String pref = (String) object;
                return new File(pref);
            }
        };

        classLoader.setPathFiles(CollectionUtils.collect(details, transformer));
    }

    this.modelerClassLoader = classLoader;

    // set as EventDispatch thread default class loader
    if (SwingUtilities.isEventDispatchThread()) {
        Thread.currentThread().setContextClassLoader(classLoader.getClassLoader());
    } else {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                Thread.currentThread().setContextClassLoader(classLoader.getClassLoader());
            }
        });
    }
}

From source file:main.UIController.java

public void saveSettings() {
    UI ui = this.getUi();
    Preferences data = this.getCurrentPreferences();
    boolean updateDate = false;
    /* City, country, tz */
    String savedCity = data.get(FIELD_CITY, DEF_CITY);
    String newCity = ui.getCity().getText();
    if (!savedCity.equals(newCity)) {
        data.put(FIELD_CITY, newCity);/*from  www . j a  va 2  s  . c o  m*/
        updateDate = true;
    }
    String savedCountry = data.get(FIELD_COUNTRY, DEF_COUNTRY);
    String newCountry = ui.getCountry().getText();
    if (!savedCountry.equals(newCountry)) {
        data.put(FIELD_COUNTRY, newCountry);
        updateDate = true;
    }
    String savedTimezone = data.get(FIELD_TIMEZONE, DEF_TIMEZONE);
    String newTimezone = (String) ui.getTimeZone().getSelectedValue();
    if (!savedTimezone.equals(newTimezone)) {
        data.put(FIELD_TIMEZONE, newTimezone);
        updateDate = true;
    }
    /* Lang */
    LangManager langManager = LangManager.getInstance();
    String shortLang = LangManager.getLanguagesShort()[Arrays.asList(LangManager.getLanguagesPrintable())
            .indexOf((String) ui.getLangCombo().getSelectedItem())];
    Lang actual = langManager.getDefinedLang();
    if (!actual.getShortName().equals(shortLang)) {
        langManager.defineLang(shortLang);
        data.put(FIELD_LANG, shortLang);
        this.reloadWindowInActualTab();
        updateDate = false;
    }
    /* Update today's date */
    if (updateDate) {
        this.showDateOfToday(false);
    }
}