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:edu.umd.cs.findbugs.gui2.GUISaveState.java

public void save() {
    Preferences p = Preferences.userNodeForPackage(GUISaveState.class);

    p.putInt(TAB_SIZE, tabSize);/*w  w w.j a v  a2 s. c  o m*/

    p.putFloat(FONT_SIZE, fontSize);

    try {
        p.put(STARTERDIRECTORY, starterDirectoryForLoadBugs.getCanonicalPath());
    } catch (IOException e) {
        Debug.println(e);
    }
    int sorterLength = MainFrame.getInstance().getSorter().getColumnCount();
    ArrayList<Sortables> sortables = MainFrame.getInstance().getSorter().getOrder();
    p.putInt(GUISaveState.SORTERTABLELENGTH, sorterLength);

    String[] sorterKeys = GUISaveState.generateSorterKeys(sorterLength);
    for (int x = 0; x < sorterKeys.length; x++) {
        p.put(sorterKeys[x], sortables.get(x).prettyName);
    }

    p.putInt(GUISaveState.PREVCOMMENTSSIZE, previousComments.size());

    for (int x = 0; x < previousComments.size(); x++) {
        String comment = previousComments.get(x);
        p.put(GUISaveState.COMMENTKEYS[x], comment);
    }

    int size = recentFiles.size();
    while (recentFiles.size() > MAXNUMRECENTPROJECTS) {
        recentFiles.remove(0);
    }

    p.putInt(GUISaveState.NUMPROJECTS, Math.min(size, MAXNUMRECENTPROJECTS));
    for (int x = 0; x < Math.min(size, MAXNUMRECENTPROJECTS); x++) {
        File file = recentFiles.get(x);
        p.put(GUISaveState.RECENTPROJECTKEYS[x], file.getAbsolutePath());
    }

    p.putByteArray(DOCKINGLAYOUT, dockingLayout);

    p.put(FRAME_BOUNDS,
            frameBounds.x + "," + frameBounds.y + "," + frameBounds.width + "," + frameBounds.height);
    p.putInt(EXTENDED_WINDOW_STATE, extendedWindowState);

    p.putInt(SPLIT_MAIN, splitMain);
    p.putDouble(SPLIT_SUMMARY_NEW, splitSummary);
    p.putInt(SPLIT_TOP, splitTop);
    p.putInt(SPLIT_TREE_COMMENTS, splitTreeComments);
    p.putInt(PACKAGE_PREFIX_SEGEMENTS, packagePrefixSegments);

    p.put(ENABLED_PLUGINS, StringUtils.join(enabledPlugins, ','));
    p.put(DISABLED_PLUGINS, StringUtils.join(disabledPlugins, ','));
    p.put(CUSTOM_PLUGINS, StringUtils.join(customPlugins, ' '));
}

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);
        updateDate = true;/*from   w  w w .  j ava 2  s.  c  om*/
    }
    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);
    }
}

From source file:com.holycityaudio.SpinCAD.SpinCADFile.java

private void saveRecentBankFileList() {
    StringBuilder sb = new StringBuilder(128);
    if (recentBankFileList != null) {
        int k = recentBankFileList.listModel.getSize() - 1;
        for (int index = 0; index <= k; index++) {
            File file = recentBankFileList.listModel.getElementAt(k - index);
            if (sb.length() > 0) {
                sb.append(File.pathSeparator);
            }/*from ww w . ja va  2 s .c om*/
            sb.append(file.getPath());
        }
        Preferences p = Preferences.userNodeForPackage(RecentFileList.class);
        p.put("RecentBankFileList.fileList", sb.toString());
    }
}

From source file:com.holycityaudio.SpinCAD.SpinCADFile.java

private void saveRecentHexFileList() {
    StringBuilder sb = new StringBuilder(128);
    if (recentHexFileList != null) {
        int k = recentHexFileList.listModel.getSize() - 1;
        for (int index = 0; index <= k; index++) {
            File file = recentHexFileList.listModel.getElementAt(k - index);
            if (sb.length() > 0) {
                sb.append(File.pathSeparator);
            }// w  w  w .j  a va 2 s  . com
            sb.append(file.getPath());
        }
        Preferences p = Preferences.userNodeForPackage(RecentFileList.class);
        p.put("RecentHexFileList.fileList", sb.toString());
    }
}

From source file:com.holycityaudio.SpinCAD.SpinCADFile.java

private void saveRecentPatchFileList() {
    StringBuilder sb = new StringBuilder(128);
    if (recentPatchFileList != null) {
        int k = recentPatchFileList.listModel.getSize() - 1;
        for (int index = 0; index <= k; index++) {
            File file = recentPatchFileList.listModel.getElementAt(k - index);
            if (sb.length() > 0) {
                sb.append(File.pathSeparator);
            }/*from w ww  .  j av  a 2  s .c o m*/
            String fp = file.getPath();
            System.out.println(fp + " Path Length = " + fp.length());
            sb.append(file.getPath());
            System.out.println("RUFL Length = " + sb.length());
        }
        Preferences p = Preferences.userNodeForPackage(RecentFileList.class);
        p.put("RecentPatchFileList.fileList", sb.toString());
    }
}

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

/**
 * Set up the export menu./*from   w w  w .  ja va2 s. 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:org.docx4all.ui.menu.HyperlinkMenu.java

/**
 * Opens a webdav document pointed by vfsWebdavUrl parameter in its own
 * internal frame./*from   ww  w  . jav a2s  .  c om*/
 * 
 * vfsWebdavUrl is a VFS Webdav URL that points to a webdav document.
 * It may or may not contain user credentials information. 
 * For example:
 * <> webdav://dev.plutext.org/alfresco/plutextwebdav/User Homes/someone/AFile.docx
 * <> webdav://dev.plutext.org:80/alfresco/plutextwebdav/User Homes/someone/AFile.docx
 * <> webdav://username:password@dev.plutext.org/alfresco/plutextwebdav/User Homes/someone/AFile.docx
 * 
 * In the event that vfsWebdavUrl does not have user credentials or its user credentials
 * is invalid then this method will cycle through each known user credential found in 
 * VFSJFileChooser Bookmark in order to find an authorised user. If no such user can be 
 * found then an authentication challenge dialog will be displayed and user has three 
 * attempts to authenticate himself. 
 * 
 * @param vfsWebdavUrl a VFS Webdav Url in its friendly format.
 * @param recordAsLastOpenUrl a boolean flag that indicates whether vfsWebdavUrl 
 * should be recorded as the last open url.
 * @param createNewIfNotFound a boolean flag that indicates whether a new webdav
 * document at vfsWebdavUrl should be created if it has not existed.
 * @param newPackage a WordprocessingMLPackage that will become the content of
 * newly created webdav document. This parameter must be supplied when 
 * createNewIfNotFound parameter is true.
 * @param callerActionName an Action name that can be used as a key to get 
 * resource properties in relation to dialog messages.
 * @return FileObject of the opened document
 */
public FileObject openWebdavDocument(String vfsWebdavUrl, boolean recordAsLastOpenUrl,
        boolean createNewIfNotFound, WordprocessingMLPackage newPackage, String callerActionName) {

    if (!vfsWebdavUrl.startsWith("webdav://")) {
        throw new IllegalArgumentException("Not a webdav uri");
    }

    if (createNewIfNotFound && newPackage == null) {
        throw new IllegalArgumentException("Invalid newPackage parameter");
    }

    final WordMLEditor editor = WordMLEditor.getInstance(WordMLEditor.class);
    final ResourceMap rm = editor.getContext().getResourceMap(getClass());

    VFSURIParser uriParser = new VFSURIParser(vfsWebdavUrl, false);
    if (uriParser.getUsername() != null && uriParser.getUsername().length() > 0
            && uriParser.getPassword() != null && uriParser.getPassword().length() > 0) {
        //vfsWebdavUrl has user credentials.
        try {
            FileObject fo = VFSUtils.getFileSystemManager().resolveFile(vfsWebdavUrl);
            if (fo.exists()) {
                if (recordAsLastOpenUrl) {
                    Preferences prefs = Preferences.userNodeForPackage(FileMenu.class);
                    String lastFileUri = fo.getName().getURI();
                    prefs.put(Constants.LAST_OPENED_FILE, lastFileUri);
                    PreferenceUtil.flush(prefs);
                }

                log.info("\n\n Opening " + fo.getName().getURI());
                editor.createInternalFrame(fo);
                return fo;
            }
        } catch (FileSystemException exc) {
            ;
        }
    }

    String temp = rm.getString(Constants.VFSJFILECHOOSER_DEFAULT_WEBDAV_FOLDER_BOOKMARK_NAME);
    if (temp == null || temp.length() == 0) {
        temp = "Default Webdav Folder";
    } else {
        temp = temp.trim();
    }

    List<String> userCredentials = org.docx4all.vfs.VFSUtil.collectUserCredentialsFromBookmark(uriParser, temp);

    StringBuilder sb = new StringBuilder();
    sb.append(uriParser.getHostname());
    if (uriParser.getPortnumber() != null && uriParser.getPortnumber().length() > 0) {
        sb.append(":");
        sb.append(uriParser.getPortnumber());
    }
    sb.append(uriParser.getPath());
    temp = sb.toString();//hostname[:port] and path
    vfsWebdavUrl = "webdav://" + temp;

    //Try each known userCredential to resolve a FileObject
    FileObject theFile = null;
    for (String uc : userCredentials) {
        sb.delete(0, sb.length());
        sb.append("webdav://");
        sb.append(uc);
        sb.append("@");
        sb.append(temp);
        try {
            theFile = VFSUtils.getFileSystemManager().resolveFile(sb.toString());
            if (theFile.exists()) {
                break;
            } else {
                theFile = null;
            }
        } catch (FileSystemException exc) {
            theFile = null;
        }
    }

    if (theFile != null) {
        //theFile exists
        if (recordAsLastOpenUrl) {
            Preferences prefs = Preferences.userNodeForPackage(FileMenu.class);
            String lastFileUri = theFile.getName().getURI();
            prefs.put(Constants.LAST_OPENED_FILE, lastFileUri);
            PreferenceUtil.flush(prefs);
        }

        log.info("\n\n Opening " + theFile.getName().getURI());
        editor.createInternalFrame(theFile);

    } else {
        //Cannot get theFile yet.
        //Get user to authenticate himself.
        String title = rm.getString(callerActionName + ".Action.text");
        String errMsg = null;
        Preferences prefs = Preferences.userNodeForPackage(FileMenu.class);
        try {
            theFile = AuthenticationUtil.userAuthenticationChallenge(editor, vfsWebdavUrl, title);
            if (theFile == null) {
                //user may have cancelled the authentication challenge
                //or unsuccessfully authenticated himself.
                //Because AuthenticationUtil.userAuthenticationChallenge()
                //has displayed authentication failure message, we do
                //not need to do anything here.
            } else if (theFile.exists()) {
                String lastFileUri = theFile.getName().getURI();
                if (recordAsLastOpenUrl) {
                    prefs.put(Constants.LAST_OPENED_FILE, lastFileUri);
                }

                //Record lastFileUri in bookmark.
                //Use file name as bookmark entry title.
                int idx = lastFileUri.lastIndexOf("/");
                org.docx4all.vfs.VFSUtil.addBookmarkEntry(lastFileUri.substring(idx + 1),
                        new VFSURIParser(lastFileUri, false));

                log.info("\n\n Opening " + lastFileUri);
                editor.createInternalFrame(theFile);

            } else if (createNewIfNotFound) {
                boolean success = createInFileSystem(theFile, newPackage);
                if (success) {
                    String lastFileUri = theFile.getName().getURI();
                    if (recordAsLastOpenUrl) {
                        prefs.put(Constants.LAST_OPENED_FILE, lastFileUri);
                    }

                    //Record lastFileUri in bookmark.
                    //Use file name as bookmark entry title.
                    int idx = lastFileUri.lastIndexOf("/");
                    org.docx4all.vfs.VFSUtil.addBookmarkEntry(lastFileUri.substring(idx + 1),
                            new VFSURIParser(lastFileUri, false));

                    log.info("\n\n Opening " + lastFileUri);
                    editor.createInternalFrame(theFile);

                } else {
                    theFile = null;
                    errMsg = rm.getString(callerActionName + ".file.io.error.message", vfsWebdavUrl);
                }
            } else {
                theFile = null;
                errMsg = rm.getString(callerActionName + ".file.not.found.message", vfsWebdavUrl);
            }
        } catch (FileSystemException exc) {
            exc.printStackTrace();
            theFile = null;
            errMsg = rm.getString(callerActionName + ".file.io.error.message", vfsWebdavUrl);
        } finally {
            PreferenceUtil.flush(prefs);
        }

        if (errMsg != null) {
            theFile = null;
            editor.showMessageDialog(title, errMsg, JOptionPane.ERROR_MESSAGE);
        }
    }

    return theFile;
}

From source file:com.trifork.riak.RiakClient.java

/**
 * helper method to use a reasonable default client id
 * //from   w  ww  . ja v  a  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");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] data = new byte[6];
        sr.nextBytes(data);
        clid = Base64Coder.encodeLines(data);
        prefs.put("client_id", clid);
        try {
            prefs.flush();
        } catch (BackingStoreException e) {
            throw new IOException(e);
        }
    }

    setClientID(clid);
}

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

/**
 * Open a file./*  ww w  . jav a2  s . c  om*/
 */
@Override
public void openFile() {
    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", ".")));

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

From source file:nu.nethome.home.impl.HomeServer.java

/**
 * @param fileName the fileName to set//  w  ww  .  ja v a  2s  . c o m
 */
public void setFileName(String fileName) {
    if (activated && !fileName.equals(this.fileName)) {
        // Kind of ugly. If the user changes the save file name, we also save this as a system property
        // so we can find the name (file) again when the server is started.
        Preferences prefs = Preferences.userNodeForPackage(HomeManager.class);
        prefs.put("SaveFileName", fileName);
    }
    this.fileName = fileName;
}