Example usage for java.util.prefs Preferences userNodeForPackage

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

Introduction

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

Prototype

public static Preferences userNodeForPackage(Class<?> c) 

Source Link

Document

Returns the preference node from the calling user's preference tree that is associated (by convention) with the specified class's package.

Usage

From source file:org.cryptomator.ui.util.SingleInstanceManager.java

/**
 * Creates a server socket on a free port and saves the port in
 * {@link Preferences#userNodeForPackage(Class)} for {@link Main} under the
 * given applicationKey.//ww w.  j a  va 2s  .  c o  m
 * 
 * @param applicationKey
 *            key used to save the port and identify upon connection.
 * @param exec
 *            the task which is submitted is interruptable.
 * @return
 * @throws IOException
 */
public static LocalInstance startLocalInstance(String applicationKey, ExecutorService exec) throws IOException {
    final ServerSocketChannel channel = ServerSocketChannel.open();
    channel.configureBlocking(false);
    channel.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0));

    final int port = ((InetSocketAddress) channel.getLocalAddress()).getPort();
    Preferences.userNodeForPackage(Main.class).putInt(applicationKey, port);
    LOG.info("InstanceManager bound to port {}", port);

    Selector selector = Selector.open();
    channel.register(selector, SelectionKey.OP_ACCEPT);

    LocalInstance instance = new LocalInstance(applicationKey, channel, selector);

    exec.submit(() -> {
        try {
            instance.port = ((InetSocketAddress) channel.getLocalAddress()).getPort();
        } catch (IOException e) {

        }
        instance.selectionLoop();
    });

    return instance;
}

From source file:de.ailis.oneinstance.OneInstance.java

/**
 * Remembers an active port number in the preferences.
 * // w w w  . java  2s .  c  o m
 * @param mainClass
 *            The main class of the application.
 * @param port
 *            The port number.
 */
private void setActivePort(Class<?> mainClass, int port) {
    Preferences prefs = Preferences.userNodeForPackage(mainClass);
    prefs.putInt(PORT_KEY, port);
    try {
        prefs.flush();
    } catch (BackingStoreException e) {
        LOG.error(e.toString(), e);
    }

}

From source file:net.chaosserver.timelord.swingui.Timelord.java

/**
 * Gets back the point location where the frame was last saved.
 *
 * @return location where the frame was last saved
 *//*from   w w  w .j a va2  s . c o m*/
protected Point loadLastFrameLocation() {
    Preferences preferences = Preferences.userNodeForPackage(this.getClass());

    Point windowLocation = new Point();
    windowLocation.setLocation(preferences.getDouble(FRAME_X_LOCATION, 0),
            preferences.getDouble(FRAME_Y_LOCATION, 0));

    return windowLocation;
}

From source file:net.straylightlabs.tivolibre.DecoderApp.java

private Preferences getPrefs() {
    return Preferences.userNodeForPackage(DecoderApp.class);
}

From source file:net.chaosserver.timelord.swingui.Timelord.java

/**
 * Returns the dimension of the last saved framesize.
 *
 * @return last saved frame size in preferences
 *///from   w  ww. ja va  2  s .c o  m
protected Dimension loadLastFrameSize() {
    Preferences preferences = Preferences.userNodeForPackage(this.getClass());

    Dimension windowSize = new Dimension();
    windowSize.setSize(preferences.getDouble(FRAME_WIDTH, DEFAULT_FRAME_WIDTH),
            preferences.getDouble(FRAME_HEIGHT, DEFAULT_FRAME_HEIGHT));

    return windowSize;
}

From source file:au.org.ala.delta.intkey.ui.UIUtils.java

public static List<Pair<String, String>> getPreviouslyUsedFiles() {
    List<Pair<String, String>> retList = new ArrayList<Pair<String, String>>();

    Preferences prefs = Preferences.userNodeForPackage(Intkey.class);
    if (prefs != null) {
        try {// w  w w  .ja  va  2  s  . co  m
            String mru = prefs.get(MRU_FILES_PREF_KEY, "");
            if (!StringUtils.isEmpty(mru)) {
                String[] mruFiles = mru.split(MRU_FILES_SEPARATOR);
                for (String mruFile : mruFiles) {
                    String[] mruFileItems = mruFile.split(MRU_ITEM_SEPARATOR);
                    retList.add(new Pair<String, String>(mruFileItems[0], mruFileItems[1]));
                }
            }
        } catch (Exception e) {
            // An error occurred. Clear the most recently used files list and return an empty list.

            prefs.remove(MRU_FILES_PREF_KEY);
            try {
                prefs.sync();
            } catch (BackingStoreException bse) {
                throw new RuntimeException(bse);
            }
            return Collections.EMPTY_LIST;
        }
    }

    return retList;
}

From source file:com.mirth.connect.client.ui.SettingsPanelMap.java

private void initComponents() {
    setBackground(Color.WHITE);/*from  w  ww. j  a  v a2 s.c om*/
    setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
    setLayout(new MigLayout("insets 12, fill"));

    configurationMapTable = new MirthTable();
    configurationMapTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    configurationMapTable.getTableHeader().setReorderingAllowed(false);
    configurationMapTable.setSortable(false);
    configurationMapTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    configurationMapTable
            .setModel(new RefreshTableModel(new String[][] {}, new String[] { "Key", "Value", "Comment" }));
    TableCellEditor cellEditor = new TextFieldCellEditor() {

        @Override
        protected boolean valueChanged(String value) {
            PlatformUI.MIRTH_FRAME.setSaveEnabled(true);
            return true;
        }

    };
    configurationMapTable.getColumnExt("Key").setCellEditor(cellEditor);
    configurationMapTable.getColumnExt("Value").setCellEditor(cellEditor);
    configurationMapTable.getColumnExt("Comment").setCellEditor(cellEditor);
    configurationMapTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent evt) {
            int selectedRow;
            if (configurationMapTable.isEditing()) {
                selectedRow = configurationMapTable.getEditingRow();
            } else {
                selectedRow = configurationMapTable.getSelectedRow();
            }
            removeButton.setEnabled(selectedRow != -1);
        }
    });

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        configurationMapTable.setHighlighters(HighlighterFactory
                .createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR, UIConstants.BACKGROUND_COLOR));
    }

    configurationMapScrollPane = new JScrollPane();
    configurationMapScrollPane.setViewportView(configurationMapTable);

    addButton = new MirthButton("Add");
    addButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            ((RefreshTableModel) configurationMapTable.getModel()).addRow(new String[] { "", "" });

            if (configurationMapTable.getRowCount() == 1) {
                configurationMapTable.setRowSelectionInterval(0, 0);
            }

            PlatformUI.MIRTH_FRAME.setSaveEnabled(true);
        }

    });
    removeButton = new MirthButton("Remove");
    removeButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (configurationMapTable.getSelectedModelIndex() != -1 && !configurationMapTable.isEditing()) {
                Integer selectedModelIndex = configurationMapTable.getSelectedModelIndex();

                RefreshTableModel model = (RefreshTableModel) configurationMapTable.getModel();

                int newViewIndex = configurationMapTable.convertRowIndexToView(selectedModelIndex);
                if (newViewIndex == (model.getRowCount() - 1)) {
                    newViewIndex--;
                }

                // must set lastModelRow to -1 so that when setting the new
                // row selection below the old data won't try to be saved.
                model.removeRow(selectedModelIndex);

                if (model.getRowCount() != 0) {
                    configurationMapTable.setRowSelectionInterval(newViewIndex, newViewIndex);
                }

                PlatformUI.MIRTH_FRAME.setSaveEnabled(true);
            }
        }

    });

    configurationMapPanel = new JPanel();
    configurationMapPanel.setBackground(Color.WHITE);
    configurationMapPanel.setLayout(new MigLayout("fill, flowy, insets 0", "[grow][]", "grow"));
    configurationMapPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
            javax.swing.BorderFactory.createMatteBorder(1, 0, 0, 0, new java.awt.Color(204, 204, 204)),
            "Configuration Map", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
            javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11))); // NOI18N
    configurationMapPanel.add(configurationMapScrollPane, "grow, wrap");
    configurationMapPanel.add(addButton, "growx, aligny top, split");
    configurationMapPanel.add(removeButton, "growx, aligny top");

    add(configurationMapPanel, "grow, height 100px:100%:100%, wrap");
}

From source file:com.mirth.connect.client.ui.codetemplate.CodeTemplateLibrariesPanel.java

private void initComponents(Channel channel) {
    setBackground(UIConstants.BACKGROUND_COLOR);

    selectAllLabel = new JLabel("<html><u>Select All</u></html>");
    selectAllLabel.setForeground(Color.BLUE);
    selectAllLabel.addMouseListener(new MouseAdapter() {
        @Override//from   w w  w  .  ja  va  2s.  com
        public void mouseReleased(MouseEvent evt) {
            for (Enumeration<? extends MutableTreeTableNode> libraryNodes = ((MutableTreeTableNode) libraryTreeTable
                    .getTreeTableModel().getRoot()).children(); libraryNodes.hasMoreElements();) {
                MutableTreeTableNode libraryNode = libraryNodes.nextElement();
                Triple<String, String, Boolean> triple = (Triple<String, String, Boolean>) libraryNode
                        .getUserObject();
                libraryTreeTable.getTreeTableModel().setValueAt(
                        new MutableTriple<String, String, Boolean>(triple.getLeft(), triple.getMiddle(), true),
                        libraryNode, libraryTreeTable.getHierarchicalColumn());
            }
            libraryTreeTable.updateUI();
        }
    });

    selectSeparatorLabel = new JLabel("|");

    deselectAllLabel = new JLabel("<html><u>Deselect All</u></html>");
    deselectAllLabel.setForeground(Color.BLUE);
    deselectAllLabel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent evt) {
            for (Enumeration<? extends MutableTreeTableNode> libraryNodes = ((MutableTreeTableNode) libraryTreeTable
                    .getTreeTableModel().getRoot()).children(); libraryNodes.hasMoreElements();) {
                MutableTreeTableNode libraryNode = libraryNodes.nextElement();
                Triple<String, String, Boolean> triple = (Triple<String, String, Boolean>) libraryNode
                        .getUserObject();
                libraryTreeTable.getTreeTableModel().setValueAt(
                        new MutableTriple<String, String, Boolean>(triple.getLeft(), triple.getMiddle(), false),
                        libraryNode, libraryTreeTable.getHierarchicalColumn());
            }
            libraryTreeTable.updateUI();
        }
    });

    expandAllLabel = new JLabel("<html><u>Expand All</u></html>");
    expandAllLabel.setForeground(Color.BLUE);
    expandAllLabel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent evt) {
            libraryTreeTable.expandAll();
        }
    });

    expandSeparatorLabel = new JLabel("|");

    collapseAllLabel = new JLabel("<html><u>Collapse All</u></html>");
    collapseAllLabel.setForeground(Color.BLUE);
    collapseAllLabel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent evt) {
            libraryTreeTable.collapseAll();
        }
    });

    final TableCellEditor libraryCellEditor = new LibraryTreeCellEditor();

    libraryTreeTable = new MirthTreeTable() {
        @Override
        public TableCellEditor getCellEditor(int row, int column) {
            if (isHierarchical(column)) {
                return libraryCellEditor;
            } else {
                return super.getCellEditor(row, column);
            }
        }
    };

    DefaultTreeTableModel model = new SortableTreeTableModel();
    DefaultMutableTreeTableNode rootNode = new DefaultMutableTreeTableNode();
    model.setRoot(rootNode);

    libraryTreeTable.setLargeModel(true);
    libraryTreeTable.setTreeTableModel(model);
    libraryTreeTable.setOpenIcon(null);
    libraryTreeTable.setClosedIcon(null);
    libraryTreeTable.setLeafIcon(null);
    libraryTreeTable.setRootVisible(false);
    libraryTreeTable.setDoubleBuffered(true);
    libraryTreeTable.setDragEnabled(false);
    libraryTreeTable.setRowSelectionAllowed(true);
    libraryTreeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    libraryTreeTable.setRowHeight(UIConstants.ROW_HEIGHT);
    libraryTreeTable.setFocusable(true);
    libraryTreeTable.setOpaque(true);
    libraryTreeTable.setEditable(true);
    libraryTreeTable.setSortable(false);
    libraryTreeTable.setAutoCreateColumnsFromModel(false);
    libraryTreeTable.setShowGrid(true, true);
    libraryTreeTable.setTableHeader(null);

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        libraryTreeTable.setHighlighters(HighlighterFactory
                .createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR, UIConstants.BACKGROUND_COLOR));
    }

    libraryTreeTable.setTreeCellRenderer(new LibraryTreeCellRenderer());

    libraryTreeTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent evt) {
            checkSelection(evt);
        }

        @Override
        public void mouseReleased(MouseEvent evt) {
            checkSelection(evt);
        }

        private void checkSelection(MouseEvent evt) {
            if (libraryTreeTable.rowAtPoint(new Point(evt.getX(), evt.getY())) < 0) {
                libraryTreeTable.clearSelection();
            }
        }
    });

    libraryTreeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent evt) {
            if (!evt.getValueIsAdjusting()) {
                boolean visible = false;
                int selectedRow = libraryTreeTable.getSelectedRow();

                if (selectedRow >= 0) {
                    TreePath selectedPath = libraryTreeTable.getPathForRow(selectedRow);
                    if (selectedPath != null) {
                        visible = true;
                        Triple<String, String, Boolean> triple = (Triple<String, String, Boolean>) ((MutableTreeTableNode) selectedPath
                                .getLastPathComponent()).getUserObject();
                        String description = "";

                        if (selectedPath.getPathCount() == 2) {
                            description = libraryMap.get(triple.getLeft()).getDescription();
                        } else if (selectedPath.getPathCount() == 3) {
                            description = PlatformUI.MIRTH_FRAME.codeTemplatePanel.getCachedCodeTemplates()
                                    .get(triple.getLeft()).getDescription();
                        }

                        if (StringUtils.isBlank(description) || StringUtils.equals(description, CodeTemplateUtil
                                .getDocumentation(CodeTemplate.DEFAULT_CODE).getDescription())) {
                            descriptionTextPane.setText(
                                    "<html><body class=\"code-template-libraries-panel\"><i>No description.</i></body></html>");
                        } else {
                            descriptionTextPane.setText("<html><body class=\"code-template-libraries-panel\">"
                                    + MirthXmlUtil.encode(description) + "</body></html>");
                        }
                    }
                }

                descriptionScrollPane.setVisible(visible);
                updateUI();
            }
        }
    });

    libraryTreeTableScrollPane = new JScrollPane(libraryTreeTable);

    descriptionTextPane = new JTextPane();
    descriptionTextPane.setContentType("text/html");
    HTMLEditorKit editorKit = new HTMLEditorKit();
    StyleSheet styleSheet = editorKit.getStyleSheet();
    styleSheet.addRule(".code-template-libraries-panel {font-family:\"Tahoma\";font-size:11;text-align:top}");
    descriptionTextPane.setEditorKit(editorKit);
    descriptionTextPane.setEditable(false);
    descriptionScrollPane = new JScrollPane(descriptionTextPane);
    descriptionScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    descriptionScrollPane.setVisible(false);
}

From source file:net.chaosserver.timelord.swingui.Timelord.java

/**
 * Saves the size of the current frame into preferences.
 *//*w w  w .j a v  a  2  s  .  c  o  m*/
protected void saveFrameSize() {
    if (applicationFrame != null) {
        Dimension windowSize = applicationFrame.getSize();

        Preferences preferences = Preferences.userNodeForPackage(this.getClass());
        preferences.putDouble(FRAME_WIDTH, windowSize.getWidth());
        preferences.putDouble(FRAME_HEIGHT, windowSize.getHeight());
    }
}

From source file:org.broad.igv.DirectoryManager.java

/**
 * Move the "igv" directory to a new location, copying all contents.  Returns True if the directory
 * is successfully moved, irrespective of any errors that might occur later (e.g. when attempting to
 * remove the old directory).//ww w.j a  v  a  2  s  . c o  m
 *
 * @param newIGVDirectory
 * @return True if the directory is successfully moved, false otherwise
 */

public static Boolean moveIGVDirectory(final File newIGVDirectory) {

    if (newIGVDirectory.equals(IGV_DIRECTORY)) {
        return false; // Nothing to do
    }

    if (IGV_DIRECTORY != null && IGV_DIRECTORY.exists()) {

        File oldDirectory = IGV_DIRECTORY;

        try {
            log.info("Moving igv directory from " + oldDirectory.getParent() + " to "
                    + newIGVDirectory.getAbsolutePath());
            FileUtils.copyDirectory(IGV_DIRECTORY, newIGVDirectory);
            IGV_DIRECTORY = newIGVDirectory;

            // Store location of new directory in Java preferences node (not pref.properties)
            Preferences prefs = Preferences.userNodeForPackage(Globals.class);
            prefs.put(IGV_DIR_USERPREF, newIGVDirectory.getAbsolutePath());

            // Update preference manager with new file location
            PreferenceManager.getInstance().setPrefsFile(getPreferencesFile().getAbsolutePath());

        } catch (IOException e) {
            log.error("Error copying IGV directory", e);
            MessageUtils.showMessage("<html>Error moving IGV directory:<br/>&nbsp;nbsp;" + e.getMessage());
            return false;
        }

        // Restart the log
        LogManager.shutdown();
        initializeLog();

        // Try to delete the old directory
        try {
            deleteDirectory(oldDirectory);
        } catch (IOException e) {
            log.error("An error was encountered deleting the previous IGV directory", e);
            MessageUtils.showMessage("<html>An error was encountered deleting the previous IGV directory ("
                    + e.getMessage() + "):<br>&nbsp;nbsp;nbsp;" + oldDirectory.getAbsolutePath()
                    + "<br>Remaining files should be manually deleted.");
        }

    }

    GENOME_CACHE_DIRECTORY = null;
    GENE_LIST_DIRECTORY = null;
    BAM_CACHE_DIRECTORY = null;
    return true;

}