Example usage for java.util.prefs Preferences put

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

Introduction

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

Prototype

public abstract void put(String key, String value);

Source Link

Document

Associates the specified value with the specified key in this preference node.

Usage

From source file:verdandi.ui.ProjectViewerPanel.java

private void importProjects() {
    Preferences prefs = Preferences.userNodeForPackage(getClass());
    File importDir = new File(prefs.get("import.dir", System.getProperty("user.home")));

    JFileChooser chooser = new JFileChooser(importDir);
    chooser.setDialogTitle(RB.getString("projectviewer.import.filechooser.title"));
    chooser.setMultiSelectionEnabled(false);

    if (chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION) {
        LOG.debug("User cancelled");
        return;/*  w  ww .j av a  2 s . c om*/
    }

    File importFile = chooser.getSelectedFile();

    prefs.put("import.dir", importFile.getParent());
    try {
        prefs.flush();
    } catch (BackingStoreException e) {
        LOG.error("Cannot write export file preference", e);
    }

    ObjectInputStream projectsIn = null;

    try {
        setCursor(CURSOR_WAIT);
        projectsIn = new ObjectInputStream(new FileInputStream(importFile));

        Object o = projectsIn.readObject();

        if (!(o instanceof Collection)) {
            LOG.error("The file does not contain a valid verdandi project list");
            return;
        }

        Collection<?> importcoll = (Collection<?>) o;
        @SuppressWarnings("unchecked")
        List<CostUnit> projects = (List<CostUnit>) o;
        new ProjectImporter(projects).start();
    } catch (FileNotFoundException e) {
        LOG.error("", e);
    } catch (IOException e) {
        LOG.error("No verdandi project list?", e);
    } catch (ClassNotFoundException e) {
        LOG.error("", e);
    } finally {
        setCursor(CURSOR_DEFAULT);
        if (projectsIn != null) {
            try {
                projectsIn.close();
            } catch (Throwable t) {
                LOG.error("Cannot close stream: ", t);
            }
        }
    }

}

From source file:org.tros.torgo.ControllerBase.java

/**
 * Save the script as a new file.// w  w w .ja  v  a  2 s .c o  m
 */
@Override
public void saveFileAs() {
    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    java.util.prefs.Preferences prefs = java.util.prefs.Preferences.userNodeForPackage(ControllerBase.class);
    chooser.setCurrentDirectory(
            new File(prefs.get(ControllerBase.class.getName() + "-working-directory", ".")));

    int result = chooser.showSaveDialog(window);

    if (result == JFileChooser.APPROVE_OPTION) {
        filename = chooser.getSelectedFile().getPath();
        prefs.put(ControllerBase.class.getName() + "-working-directory", chooser.getSelectedFile().getParent());
        saveFile();
    }
}

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   ww  w . ja  v  a 2s. com*/
        }

        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:abfab3d.param.editor.URIEditor.java

public URIEditor(Parameter param) {
    super(param);

    m_textField = new TextField(EDITOR_SIZE);
    Object val = m_param.getValue();
    String sval = "";
    if (val != null) {
        sval = val.toString();
    }/*from  w  ww .j av a  2 s.c  om*/
    m_textField.setText(sval);
    m_textField.addActionListener(this);

    m_open = new JButton("Open");
    m_open.setToolTipText("Open File");

    panel = new JPanel(new FlowLayout());
    panel.add(m_open);
    panel.add(m_textField);

    String user_dir = System.getProperty("user.dir");

    Preferences prefs = Preferences.userNodeForPackage(URIEditor.class);

    String last_dir = prefs.get(LASTDIR_PROPERTY, null);
    String dir;

    if (last_dir != null)
        dir = last_dir;
    else
        dir = user_dir;

    fc = new JFileChooser(dir);

    m_open.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int returnVal = fc.showDialog(parent, "Open File");
            if (returnVal == JFileChooser.APPROVE_OPTION) {

                File file = fc.getSelectedFile();

                String dir = file.getPath();

                int idx = dir.lastIndexOf(File.separator);

                if (idx > 0) {
                    dir = dir.substring(0, idx);

                    Preferences prefs = Preferences.userNodeForPackage(URIEditor.class);

                    prefs.put(LASTDIR_PROPERTY, dir);
                }

                m_param.setValue(file.getAbsolutePath());
                informParamChangedListeners();
            }

        }
    });
}

From source file:verdandi.ui.action.ImportPluginAction.java

/**
 * Ask the import file from the user//from www. j a  va  2s .c  o  m
 */
private File getFile() {
    File res = null;
    Preferences prefs = Preferences.userNodeForPackage(getClass());
    File importDir = new File(prefs.get(KEY_CWD, System.getProperty("user.home")));

    JFileChooser chooser = new JFileChooser(importDir);
    chooser.setFileFilter(new FileFilter() {

        @Override
        public boolean accept(File f) {
            return f.getName().toLowerCase().endsWith(".jar") || f.isDirectory();
        }

        @Override
        public String getDescription() {
            return RC.getString("pluginimportaction.filechooser.jarfilter.description");
        }
    });

    chooser.setDialogTitle(RC.getString("pluginimportaction.filechooser.title"));
    chooser.setMultiSelectionEnabled(false);

    if (chooser.showOpenDialog(parent) != JFileChooser.APPROVE_OPTION) {
        LOG.debug("User cancelled");
        return null;
    }
    res = chooser.getSelectedFile();

    prefs.put("import.dir", res.getParent());
    try {
        prefs.flush();
    } catch (BackingStoreException e) {
        LOG.error("Cannot write export file preference", e);
    }

    return res;
}

From source file:edu.umass.cs.msocket.proxy.console.ConsoleModule.java

/**
 * Store the current command history/*from   w w  w  . j  a  v a 2s . 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:org.apache.cayenne.pref.CayennePreferenceEditor.java

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

    if (restartRequired) {
        restart();/* ww  w  .ja  va2s .c  o  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.kuali.test.ui.components.panels.FileTestPanel.java

/**
 *
 * @param e//w  ww.j av  a  2s . com
 */
@Override
protected void handleUnprocessedActionEvent(ActionEvent e) {
    if (Constants.FILE_SEARCH_ACTION.equals(e.getActionCommand())) {
        Preferences proot = Preferences.userRoot();
        Preferences node = proot.node(Constants.PREFS_FILES_NODE);

        String lastDir = node.get(Constants.PREFS_LAST_FILE_TEST_DIR, System.getProperty("user.home"));

        JFileChooser chooser = new JFileChooser(lastDir);
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        chooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return (f.isDirectory() && f.exists());
            }

            @Override
            public String getDescription() {
                return "file inquiry directory";
            }
        });

        int returnVal = chooser.showOpenDialog(getMainframe());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File f = chooser.getSelectedFile();
            fileDirectory.setText(f.getPath());
            node.put(Constants.PREFS_LAST_FILE_TEST_DIR, f.getPath());
        }
    } else if (Constants.FILE_EXISTS.equals(e.getActionCommand())) {
        getFileCheckCondition(Constants.FILE_DOES_NOT_EXIST).setSelected(false);
        getFileCheckCondition(Constants.FILE_SIZE_GREATER_THAN_ZERO).setEnabled(true);
        getFileCheckCondition(Constants.FILE_CREATED_TODAY).setEnabled(true);
        getFileCheckCondition(Constants.FILE_CREATED_YESTERDAY).setEnabled(true);
        containingText.setEnabled(true);
    } else if (Constants.FILE_DOES_NOT_EXIST.equals(e.getActionCommand())) {
        getFileCheckCondition(Constants.FILE_EXISTS).setSelected(false);
        getFileCheckCondition(Constants.FILE_SIZE_GREATER_THAN_ZERO).setSelected(false);
        getFileCheckCondition(Constants.FILE_SIZE_GREATER_THAN_ZERO).setEnabled(false);
        getFileCheckCondition(Constants.FILE_CREATED_TODAY).setSelected(false);
        getFileCheckCondition(Constants.FILE_CREATED_TODAY).setEnabled(false);
        getFileCheckCondition(Constants.FILE_CREATED_YESTERDAY).setSelected(false);
        getFileCheckCondition(Constants.FILE_CREATED_YESTERDAY).setEnabled(false);
        containingText.setText("");
        containingText.setEnabled(false);
    } else if (Constants.FILE_CREATED_TODAY.equals(e.getActionCommand())) {
        getFileCheckCondition(Constants.FILE_CREATED_YESTERDAY).setSelected(false);
    } else if (Constants.FILE_CREATED_YESTERDAY.equals(e.getActionCommand())) {
        getFileCheckCondition(Constants.FILE_CREATED_TODAY).setSelected(false);
    }
}

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

/**
 * This will ensure the agent's configuration preferences are populated. If need be, the configuration file is
 * loaded and all overrides are overlaid on top of the preferences. The preferences are also upgraded to ensure they
 * conform to the latest configuration schema version.
 *
 * @return the agent configuration/*from w  w  w  . j  a v a2  s  .co  m*/
 *
 * @throws Exception
 */
private AgentConfiguration prepareConfigurationPreferences() throws Exception {
    Preferences preferences_node = getPreferencesNode();
    AgentConfiguration config = new AgentConfiguration(preferences_node);

    if (config.getAgentConfigurationVersion() == 0) {
        config = loadConfigurationFile();
    }

    // now that the configuration preferences are loaded, we need to override them with any bootstrap override properties
    Properties overrides = getConfigurationOverrides();
    if (overrides != null) {
        for (Map.Entry<Object, Object> entry : overrides.entrySet()) {
            String key = entry.getKey().toString();
            String value = entry.getValue().toString();

            // allow ${var} notation in the values so we can provide variable replacements in the values
            value = StringPropertyReplacer.replaceProperties(value);

            preferences_node.put(key, value);
        }
    }

    // let's make sure our configuration is upgraded to the latest schema
    AgentConfigurationUpgrade.upgradeToLatest(config.getPreferences());

    return config;
}

From source file:com.basho.riak.pbc.RiakClient.java

/**
 * helper method to use a reasonable default client id
 * beware, it caches the client id. If you call it multiple times on the same client
 * you get the *same* id (not good for reusing a client with different ids)
 * /*from   w w w .j a  va  2 s. c o m*/
 * @throws IOException
 */
public void prepareClientID() throws IOException {
    Preferences prefs = Preferences.userNodeForPackage(RiakClient.class);

    String clid = prefs.get("client_id", null);
    if (clid == null) {
        SecureRandom sr;
        try {
            sr = SecureRandom.getInstance("SHA1PRNG");
            // Not totally secure, but doesn't need to be
            // and 100% less prone to 30 second hangs on linux jdk5
            sr.setSeed(UUID.randomUUID().getLeastSignificantBits() + new Date().getTime());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] data = new byte[6];
        sr.nextBytes(data);
        clid = CharsetUtils.asString(Base64.encodeBase64Chunked(data), CharsetUtils.ISO_8859_1);
        prefs.put("client_id", clid);
        try {
            prefs.flush();
        } catch (BackingStoreException e) {
            throw new IOException(e.toString());
        }
    }

    setClientID(clid);
}