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:org.docx4all.ui.menu.FileMenu.java

@Action
public void openFile(ActionEvent actionEvent) {
    Preferences prefs = Preferences.userNodeForPackage(getClass());
    WordMLEditor editor = WordMLEditor.getInstance(WordMLEditor.class);
    ResourceMap rm = editor.getContext().getResourceMap(WordMLEditor.class);

    String lastFileUri = prefs.get(Constants.LAST_OPENED_FILE, Constants.EMPTY_STRING);
    FileObject dir = null;/*ww  w .j  ava 2  s .com*/
    if (lastFileUri.length() > 0) {
        try {
            dir = VFSUtils.getFileSystemManager().resolveFile(lastFileUri).getParent();
        } catch (FileSystemException exc) {
            dir = null;
        }
    }

    VFSJFileChooser chooser = createFileChooser(rm, dir, Constants.DOCX_STRING);

    RETURN_TYPE returnVal = chooser.showOpenDialog((Component) actionEvent.getSource());

    if (returnVal == RETURN_TYPE.APPROVE) {
        FileObject file = getSelectedFile(chooser, Constants.DOCX_STRING);
        if (file != null) {
            lastFileUri = file.getName().getURI();

            prefs.put(Constants.LAST_OPENED_FILE, lastFileUri);
            if (file.getName().getScheme().equals(("file"))) {
                prefs.put(Constants.LAST_OPENED_LOCAL_FILE, lastFileUri);
            }
            PreferenceUtil.flush(prefs);
            log.info("\n\n Opening " + VFSUtils.getFriendlyName(lastFileUri));
            editor.createInternalFrame(file);
        }
    }
}

From source file:verdandi.ui.ProjectViewerPanel.java

private void exportProjects() {
    Preferences prefs = Preferences.userNodeForPackage(getClass());

    File exportDir = new File(prefs.get("export.dir", System.getProperty("user.home")));

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

    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) {
        LOG.debug("User cancelled");
        return;/* w w w .j a v  a  2 s.co m*/
    }

    int[] selectedProjects = projectTable.getSelectedRows();

    if (selectedProjects.length == 0) {
        LOG.debug("NO row selected");
        return;
    }

    List<CostUnit> projectsToExport = new ArrayList<CostUnit>();

    for (int i = 0; i < selectedProjects.length; i++) {
        // int selModel = projectTable.getFilters().convertRowIndexToModel(
        // selectedProjects[i]);
        int selModel = selectedProjects[i];
        CostUnit p = tableModel.getProject(selModel);
        LOG.debug("Adding project to export list: " + p);
        projectsToExport.add(p);
    }

    File exportFile = chooser.getSelectedFile();
    LOG.debug("Exporting projects to " + exportFile.getAbsolutePath());

    ObjectOutputStream listOut = null;
    try {
        listOut = new ObjectOutputStream(new FileOutputStream(exportFile));
        listOut.writeObject(projectsToExport);
    } catch (FileNotFoundException e) {
        LOG.error("", e);
    } catch (IOException e) {
        LOG.error("", e);
    } finally {
        if (listOut != null) {
            try {
                listOut.close();
            } catch (Throwable t) {
                LOG.error("Cannot close stream: ", t);
            }
        }
    }

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

}

From source file:corelyzer.ui.CorelyzerApp.java

public void pingLaunchTracker() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            // load or create unique user ID
            Preferences sysPrefs = Preferences.userNodeForPackage(CorelyzerApp.class);
            String uuid = sysPrefs.get("uuid", null);
            if (uuid == null) {
                uuid = java.util.UUID.randomUUID().toString();
                sysPrefs.put("uuid", uuid);
            }//from  w w  w.j ava 2 s  .  c  o m

            // track launch
            GoogleAnalytics ga = new GoogleAnalytics("UA-88247383-1");
            GoogleAnalyticsResponse response = ga
                    .post(new PageViewHit("http://www.laccore.org", "launch: UUID=" + uuid));
            //            for (NameValuePair kvp : response.getPostedParms()) {
            //               System.out.println("key: " + kvp.getName() + ", value: "+ kvp.getValue());
            //            }
        }
    });
}

From source file:PreferencesTest.java

public PreferencesFrame() {
    // get position, size, title from preferences

    Preferences root = Preferences.userRoot();
    final Preferences node = root.node("/com/horstmann/corejava");
    int left = node.getInt("left", 0);
    int top = node.getInt("top", 0);
    int width = node.getInt("width", DEFAULT_WIDTH);
    int height = node.getInt("height", DEFAULT_HEIGHT);
    setBounds(left, top, width, height);

    // if no title given, ask user

    String title = node.get("title", "");
    if (title.equals(""))
        title = JOptionPane.showInputDialog("Please supply a frame title:");
    if (title == null)
        title = "";
    setTitle(title);/*from  w w  w  .j ava2  s . c o m*/

    // set up file chooser that shows XML files

    final JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));

    // accept all files ending with .xml
    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public boolean accept(File f) {
            return f.getName().toLowerCase().endsWith(".xml") || f.isDirectory();
        }

        public String getDescription() {
            return "XML files";
        }
    });

    // set up menus
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    JMenu menu = new JMenu("File");
    menuBar.add(menu);

    JMenuItem exportItem = new JMenuItem("Export preferences");
    menu.add(exportItem);
    exportItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (chooser.showSaveDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION) {
                try {
                    OutputStream out = new FileOutputStream(chooser.getSelectedFile());
                    node.exportSubtree(out);
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    JMenuItem importItem = new JMenuItem("Import preferences");
    menu.add(importItem);
    importItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (chooser.showOpenDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION) {
                try {
                    InputStream in = new FileInputStream(chooser.getSelectedFile());
                    Preferences.importPreferences(in);
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    JMenuItem exitItem = new JMenuItem("Exit");
    menu.add(exitItem);
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            node.putInt("left", getX());
            node.putInt("top", getY());
            node.putInt("width", getWidth());
            node.putInt("height", getHeight());
            node.put("title", getTitle());
            System.exit(0);
        }
    });
}

From source file:org.domainmath.gui.MainFrame.java

public void saveCurrentDir() {
    String s = "";
    ArrayList<String> l = new ArrayList<>();

    for (int i = 0; i < dirComboBox.getItemCount(); i++) {
        // s+=dirComboBox.getItemAt(i).toString()+File.pathSeparator;
        l.add(dirComboBox.getItemAt(i).toString());
    }/*from   ww  w. j a v  a 2s.c  o m*/

    if (l.contains(worksDir.getAbsolutePath())) {
        l.remove(worksDir.getAbsolutePath());
    }

    System.out.println("Directory list:" + l);

    for (String st : l) {
        s += st + File.pathSeparator;
    }
    Preferences pr2 = Preferences.userNodeForPackage(this.getClass());
    if (s != null) {
        pr2.put("DomainMath_CurrentDir", s);
        System.out.println("Saved current directory list:" + s);
    } else {
        pr2.put("DomainMath_CurrentDir", worksDir.getAbsolutePath());

    }

    pr2.put("DomainMath_StartUpDir", worksDir.getAbsolutePath());

}

From source file:org.docx4all.ui.menu.FileMenu.java

private RETURN_TYPE saveAsFile(String callerActionName, ActionEvent actionEvent, String fileType) {
    Preferences prefs = Preferences.userNodeForPackage(getClass());
    WordMLEditor editor = WordMLEditor.getInstance(WordMLEditor.class);
    ResourceMap rm = editor.getContext().getResourceMap(getClass());

    JInternalFrame iframe = editor.getCurrentInternalFrame();
    String oldFilePath = (String) iframe.getClientProperty(WordMLDocument.FILE_PATH_PROPERTY);

    VFSJFileChooser chooser = createFileChooser(rm, callerActionName, iframe, fileType);

    RETURN_TYPE returnVal = chooser.showSaveDialog((Component) actionEvent.getSource());
    if (returnVal == RETURN_TYPE.APPROVE) {
        FileObject selectedFile = getSelectedFile(chooser, fileType);

        boolean error = false;
        boolean newlyCreatedFile = false;

        if (selectedFile == null) {

            // Should never happen, whether the file exists or not

        } else {//w  ww .  java 2s .c  o  m

            //Check selectedFile's existence and ask user confirmation when needed.
            try {
                boolean selectedFileExists = selectedFile.exists();
                if (!selectedFileExists) {
                    FileObject parent = selectedFile.getParent();
                    String uri = UriParser.decode(parent.getName().getURI());

                    if (System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") > -1
                            && parent.getName().getScheme().startsWith("file") && !parent.isWriteable()
                            && (uri.indexOf("/Documents") > -1 || uri.indexOf("/My Documents") > -1)) {
                        //TODO: Check whether we still need this workaround.
                        //See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4939819
                        //Re: File.canWrite() returns false for the "My Documents" directory (win)
                        String localpath = org.docx4j.utils.VFSUtils.getLocalFilePath(parent);
                        File f = new File(localpath);
                        f.setWritable(true, true);
                    }

                    selectedFile.createFile();
                    newlyCreatedFile = true;

                } else if (!selectedFile.getName().getURI().equalsIgnoreCase(oldFilePath)) {
                    String title = rm.getString(callerActionName + ".Action.text");
                    String message = VFSUtils.getFriendlyName(selectedFile.getName().getURI()) + "\n"
                            + rm.getString(callerActionName + ".Action.confirmMessage");
                    int answer = editor.showConfirmDialog(title, message, JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE);
                    if (answer != JOptionPane.YES_OPTION) {
                        selectedFile = null;
                    }
                } // if (!selectedFileExists)

            } catch (FileSystemException exc) {
                exc.printStackTrace();//ignore
                log.error("Couldn't create new file or assure file existence. File = "
                        + selectedFile.getName().getURI());
                selectedFile = null;
                error = true;
            }
        }

        //Check whether there has been an error, cancellation by user
        //or may proceed to saving file.
        if (selectedFile != null) {
            //Proceed to saving file
            String selectedPath = selectedFile.getName().getURI();
            if (log.isDebugEnabled()) {
                log.debug("saveAsFile(): selectedFile = " + VFSUtils.getFriendlyName(selectedPath));
            }

            prefs.put(Constants.LAST_OPENED_FILE, selectedPath);
            if (selectedFile.getName().getScheme().equals("file")) {
                prefs.put(Constants.LAST_OPENED_LOCAL_FILE, selectedPath);
            }
            PreferenceUtil.flush(prefs);

            boolean success = false;
            if (EXPORT_AS_NON_SHARED_DOC_ACTION_NAME.equals(callerActionName)) {
                log.info("saveAsFile(): Exporting as non shared document to "
                        + VFSUtils.getFriendlyName(selectedPath));
                success = export(iframe, selectedPath, callerActionName);
                if (success) {
                    prefs.put(Constants.LAST_OPENED_FILE, selectedPath);
                    if (selectedPath.startsWith("file:")) {
                        prefs.put(Constants.LAST_OPENED_LOCAL_FILE, selectedPath);
                    }
                    PreferenceUtil.flush(prefs);
                    log.info("saveAsFile(): Opening " + VFSUtils.getFriendlyName(selectedPath));
                    editor.createInternalFrame(selectedFile);
                }
            } else {
                success = save(iframe, selectedPath, callerActionName);
                if (success) {
                    if (Constants.DOCX_STRING.equals(fileType) || Constants.FLAT_OPC_STRING.equals(fileType)) {
                        //If saving as .docx then update the document dirty flag 
                        //of toolbar states as well as internal frame title.
                        editor.getToolbarStates().setDocumentDirty(iframe, false);
                        editor.getToolbarStates().setLocalEditsEnabled(iframe, false);
                        FileObject file = null;
                        try {
                            file = VFSUtils.getFileSystemManager().resolveFile(oldFilePath);
                            editor.updateInternalFrame(file, selectedFile);
                        } catch (FileSystemException exc) {
                            ;//ignore
                        }
                    } else {
                        //Because document dirty flag is not cleared
                        //and internal frame title is not changed,
                        //we present a success message.
                        String title = rm.getString(callerActionName + ".Action.text");
                        String message = VFSUtils.getFriendlyName(selectedPath) + "\n"
                                + rm.getString(callerActionName + ".Action.successMessage");
                        editor.showMessageDialog(title, message, JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            }

            if (!success && newlyCreatedFile) {
                try {
                    selectedFile.delete();
                } catch (FileSystemException exc) {
                    log.error("saveAsFile(): Saving failure and cannot remove the newly created file = "
                            + selectedPath);
                    exc.printStackTrace();
                }
            }
        } else if (error) {
            log.error("saveAsFile(): selectedFile = NULL");
            String title = rm.getString(callerActionName + ".Action.text");
            String message = rm.getString(callerActionName + ".Action.errorMessage");
            editor.showMessageDialog(title, message, JOptionPane.ERROR_MESSAGE);
        }

    } //if (returnVal == JFileChooser.APPROVE_OPTION)

    return returnVal;
}

From source file:de.innovationgate.wgpublisher.WGACore.java

private void setLastCharacterEncoding(String characterEncoding) {
    Preferences prefs = Preferences.userNodeForPackage(this.getClass());
    prefs.put("LastCharacterEncoding", characterEncoding);
    prefs.putLong("CharacterEncodingModified", System.currentTimeMillis());
}

From source file:de.innovationgate.wgpublisher.WGACore.java

private void setLastDesignEncoding(String dbkey, String encoding) {
    try {/*w w  w . j a  v  a2  s .c o m*/
        Preferences prefs = Preferences.userNodeForPackage(this.getClass());
        prefs.put(createPrefKeyDesignEncoding(dbkey), encoding);
        prefs.putLong(createPrefKeyDesignEncodingLastModified(dbkey), System.currentTimeMillis());
    } catch (Exception e) {
        log.error("Unable to set lastDesignEncoding preferences.", e);
    }
}