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:de.thomasbolz.renamer.RenamerGUI.java

private Preferences getPreferences() {
    return Preferences.userNodeForPackage(getClass());
}

From source file:com.mirth.connect.client.ui.panels.connectors.PollingSettingsPanel.java

private void initComponents() {
    scheduleTypeLabel = new JLabel("Schedule Type:");
    scheduleTypeComboBox = new MirthComboBox();
    // @formatter:off
    scheduleTypeComboBox/*from  w w  w .  j  a v  a2  s .co m*/
            .setToolTipText("<html>This connector polls to determine when new messages have arrived.<br>"
                    + "Select \"Interval\" to poll each n units of time.<br>"
                    + "Select \"Time\" to poll once a day at the specified time.<br>"
                    + "Select \"Cron\" to poll at the specified cron expression(s).</html>");
    // @formatter:on
    scheduleTypeComboBox.addItem(PollingType.INTERVAL.getDisplayName());
    scheduleTypeComboBox.addItem(PollingType.TIME.getDisplayName());
    scheduleTypeComboBox.addItem(PollingType.CRON.getDisplayName());

    scheduleTypeActionListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            scheduleTypeActionPerformed();
            updateNextFireTime();
        }
    };

    nextPollLabel = new JLabel("Next poll at: ");

    yesStartPollRadioButton = new MirthRadioButton("Yes");
    yesStartPollRadioButton.setToolTipText(
            "<html>Select Yes to immediately poll once on start.<br/>All subsequent polling will follow the specified schedule.</html>");
    yesStartPollRadioButton.setBackground(UIConstants.BACKGROUND_COLOR);
    yesStartPollRadioButton.setFocusable(false);

    noStartPollRadioButton = new MirthRadioButton("No");
    noStartPollRadioButton.setToolTipText(
            "<html>Select Yes to immediately poll once on start.<br/>All subsequent polling will follow the specified schedule.</html>");
    noStartPollRadioButton.setBackground(UIConstants.BACKGROUND_COLOR);
    noStartPollRadioButton.setSelected(true);
    noStartPollRadioButton.setFocusable(false);

    pollOnStartButtonGroup = new ButtonGroup();
    pollOnStartButtonGroup.add(yesStartPollRadioButton);
    pollOnStartButtonGroup.add(noStartPollRadioButton);

    pollingTimePicker = new MirthTimePicker();
    pollingTimePicker.setToolTipText("The time of day to poll.");
    pollingTimePicker.setVisible(false);
    JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) pollingTimePicker.getEditor();
    JTextField textField = editor.getTextField();
    textField.getDocument().addDocumentListener(new DocumentListener() {
        public void insertUpdate(DocumentEvent event) {
            updateNextFireTime();
        }

        public void removeUpdate(DocumentEvent e) {
        }

        public void changedUpdate(DocumentEvent e) {
        }
    });

    pollingFrequencySettingsPanel = new JPanel();
    pollingFrequencySettingsPanel.setBackground(UIConstants.BACKGROUND_COLOR);
    pollingFrequencySettingsPanel.setVisible(true);

    pollingFrequencyField = new MirthTextField();
    pollingFrequencyField.setToolTipText(
            "<html>The specified repeating time interval.<br/>Units must be less than 24 hours of time<br/>when converted to milliseconds.</html>");
    pollingFrequencyField.setSize(new Dimension(200, 20));
    pollingFrequencyField.setDocument(new MirthFieldConstraints(0, false, false, true));
    pollingFrequencyField.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void insertUpdate(DocumentEvent e) {
            updateNextFireTime();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            updateNextFireTime();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
        }
    });

    pollingFrequencyTypeComboBox = new MirthComboBox();
    pollingFrequencyTypeComboBox.setToolTipText("The interval's unit of time.");
    pollingFrequencyTypeComboBox.addItem(POLLING_FREQUENCY_MILLISECONDS);
    pollingFrequencyTypeComboBox.addItem(POLLING_FREQUENCY_SECONDS);
    pollingFrequencyTypeComboBox.addItem(POLLING_FREQUENCY_MINUTES);
    pollingFrequencyTypeComboBox.addItem(POLLING_FREQUENCY_HOURS);
    pollingFrequencyTypeComboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            updateNextFireTime();
        }
    });

    pollingCronSettingsPanel = new JPanel();
    pollingCronSettingsPanel.setBackground(UIConstants.BACKGROUND_COLOR);
    pollingCronSettingsPanel.setVisible(false);

    cronJobsTable = new MirthTable();
    Object[][] tableData = new Object[0][1];
    cronJobsTable.setModel(new RefreshTableModel(tableData, new String[] { "Expression", "Description" }));
    cronJobsTable.setOpaque(true);
    cronJobsTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    cronJobsTable.getTableHeader().setReorderingAllowed(false);
    cronJobsTable.setSortable(false);
    cronJobsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    cronJobsTable.getColumnModel().getColumn(0).setResizable(false);
    cronJobsTable.getColumnModel().getColumn(0).setCellEditor(new CronTableCellEditor(true));
    cronJobsTable.getColumnModel().getColumn(1).setResizable(false);
    cronJobsTable.getColumnModel().getColumn(1).setCellEditor(new CronTableCellEditor(true));

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

    HighlightPredicate errorHighlighterPredicate = new HighlightPredicate() {
        public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
            if (adapter.column == cronJobsTable.getColumnViewIndex("Expression")) {
                String cronExpression = (String) cronJobsTable.getValueAt(adapter.row, adapter.column);

                if (invalidExpressions.contains(cronExpression)) {
                    return true;
                }
            }
            return false;
        }
    };
    errorHighlighter = new ColorHighlighter(errorHighlighterPredicate, Color.PINK, Color.BLACK, Color.PINK,
            Color.BLACK);

    //@formatter:off
    String tooltip = "<html><head><style>td {text-align:center;}</style></head>"
            + "Cron expressions must be in Quartz format with at least 6 fields.<br/>" + "<br/>Format:"
            + "<table>" + "<tr><td>Field</td><td>Required</td><td>Values</td><td>Special Characters</td></tr>"
            + "<tr><td>Seconds</td><td>YES</td><td>0-59</td><td>, - * /</td></tr>"
            + "<tr><td>Minutes</td><td>YES</td><td>0-59</td><td>, - * /</td></tr>"
            + "<tr><td>Hours</td><td>YES</td><td>0-23</td><td>, - * /</td></tr>"
            + "<tr><td>Day of Month</td><td>YES</td><td>1-31</td><td>, - * ? / L W</td></tr>"
            + "<tr><td>Month</td><td>YES</td><td>1-12 or JAN-DEC</td><td>, - * /</td></tr>"
            + "<tr><td>Day of Week</td><td>YES</td><td>1-7 or SUN-SAT</td><td>, - * ? / L #</td></tr>"
            + "<tr><td>Year</td><td>NO</td><td>empty, 1970-2099</td><td>, - * /</td></tr>" + "</table>"
            + "<br/>Special Characters:" + "<br/> &nbsp <b>*</b> : all values"
            + "<br/> &nbsp <b>?</b> : no specific value" + "<br/> &nbsp <b>-</b> : used to specify ranges"
            + "<br/> &nbsp <b>,</b> : used to specify list of values"
            + "<br/> &nbsp <b>/</b> : used to specify increments"
            + "<br/> &nbsp <b>L</b> : used to specify the last of"
            + "<br/> &nbsp <b>W</b> : used to specify the nearest weekday"
            + "<br/> &nbsp <b>#</b> : used to specify the nth day of the month"
            + "<br/><br/>Example: 0 */5 8-17 * * ? means to fire every 5 minutes starting at 8am<br/>and ending at 5pm everyday"
            + "<br/><br/><b>Note:</b> Support for specifying both a day-of-week and day-of-month<br/>is not yet supported. A ? must be used in one of these fields.</html>";
    //@formatter:on
    cronJobsTable.setToolTipText(tooltip);
    cronJobsTable.getTableHeader().setToolTipText(tooltip);

    cronScrollPane = new JScrollPane();
    cronScrollPane.getViewport().add(cronJobsTable);

    addJobButton = new JButton("Add");
    addJobButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            ((DefaultTableModel) cronJobsTable.getModel()).addRow(new Vector<String>());

            int rowSelectionNumber = cronJobsTable.getRowCount() - 1;
            cronJobsTable.setRowSelectionInterval(rowSelectionNumber, rowSelectionNumber);
            PlatformUI.MIRTH_FRAME.setSaveEnabled(true);

            Boolean enabled = deleteJobButton.isEnabled();
            if (!enabled) {
                deleteJobButton.setEnabled(true);
            }
            updateNextFireTime();
        }
    });

    deleteJobButton = new JButton("Delete");
    deleteJobButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            int rowSelectionNumber = cronJobsTable.getSelectedRow();

            if (rowSelectionNumber > -1) {
                DefaultTableModel model = (DefaultTableModel) cronJobsTable.getModel();
                model.removeRow(rowSelectionNumber);

                rowSelectionNumber--;
                if (rowSelectionNumber > -1) {
                    cronJobsTable.setRowSelectionInterval(rowSelectionNumber, rowSelectionNumber);
                } else if (cronJobsTable.getRowCount() > 0) {
                    cronJobsTable.setRowSelectionInterval(0, 0);
                }

                if (cronJobsTable.getRowCount() == 0) {
                    deleteJobButton.setEnabled(false);
                }
            }

            updateNextFireTime();
            PlatformUI.MIRTH_FRAME.setSaveEnabled(true);
        }
    });
    deleteJobButton.setEnabled(false);

    advancedSettingsButton = new JButton(new ImageIcon(Frame.class.getResource("images/wrench.png")));
    advancedSettingsButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            lastSelectedPollingType = StringUtils.isBlank(lastSelectedPollingType) ? "Interval"
                    : lastSelectedPollingType;
            new AdvancedPollingSettingsDialog(lastSelectedPollingType, cachedAdvancedConnectorProperties,
                    channelContext);
            updateNextFireTime();
        }
    });

    timeSettingsLabel = new JLabel("Interval:");
    timeSettingsLabel.setBackground(UIConstants.BACKGROUND_COLOR);

    scheduleSettingsPanel = new JPanel();
    scheduleSettingsPanel.setBackground(UIConstants.BACKGROUND_COLOR);

    if (!channelContext) {
        // @formatter:off
        scheduleTypeComboBox.setToolTipText("<html>Select the pruning schedule type.<br>"
                + "Select \"Interval\" to prune each n units of time.<br>"
                + "Select \"Time\" to prune once a day at the specified time.<br>"
                + "Select \"Cron\" to prune at the specified cron expression(s).</html>");
        // @formatter:on 
        pollingFrequencyField.setToolTipText(
                "<html>The specified repeating time interval.<br/>Units must be between 1 and 24 hours of time<br/>when converted to milliseconds.</html>");
    }
}

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;//from   www.j ava  2 s .  co m
    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:com.mirth.connect.connectors.http.HttpSender.java

public void setParameters(Map<String, List<String>> properties) {
    int size = 0;
    for (List<String> property : properties.values()) {
        size += property.size();/* w ww .  j  av a  2s  . com*/
    }

    Object[][] tableData = new Object[size][2];

    queryParametersTable = new MirthTable();

    int j = 0;
    Iterator i = properties.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry entry = (Map.Entry) i.next();

        for (String keyValue : (ArrayList<String>) entry.getValue()) {
            tableData[j][NAME_COLUMN] = (String) entry.getKey();
            tableData[j][VALUE_COLUMN] = keyValue;
            j++;
        }
    }

    queryParametersTable.setModel(new javax.swing.table.DefaultTableModel(tableData,
            new String[] { NAME_COLUMN_NAME, VALUE_COLUMN_NAME }) {

        boolean[] canEdit = new boolean[] { true, true };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit[columnIndex];
        }
    });

    queryParametersTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        public void valueChanged(ListSelectionEvent evt) {
            if (getSelectedRow(queryParametersTable) != -1) {
                propertiesLastIndex = getSelectedRow(queryParametersTable);
                queryParametersDeleteButton.setEnabled(true);
            } else {
                queryParametersDeleteButton.setEnabled(false);
            }
        }
    });

    class HTTPTableCellEditor extends TextFieldCellEditor {
        boolean checkProperties;

        public HTTPTableCellEditor(boolean checkProperties) {
            super();
            this.checkProperties = checkProperties;
        }

        @Override
        public boolean isCellEditable(EventObject evt) {
            boolean editable = super.isCellEditable(evt);

            if (editable) {
                queryParametersDeleteButton.setEnabled(false);
            }

            return editable;
        }

        @Override
        protected boolean valueChanged(String value) {
            queryParametersDeleteButton.setEnabled(true);

            if (checkProperties && (value.length() == 0)) {
                return false;
            }

            parent.setSaveEnabled(true);
            return true;
        }
    }

    queryParametersTable.getColumnModel()
            .getColumn(queryParametersTable.getColumnModel().getColumnIndex(NAME_COLUMN_NAME))
            .setCellEditor(new HTTPTableCellEditor(true));
    queryParametersTable.getColumnModel()
            .getColumn(queryParametersTable.getColumnModel().getColumnIndex(VALUE_COLUMN_NAME))
            .setCellEditor(new HTTPTableCellEditor(false));
    queryParametersTable.setCustomEditorControls(true);

    queryParametersTable.setSelectionMode(0);
    queryParametersTable.setRowSelectionAllowed(true);
    queryParametersTable.setRowHeight(UIConstants.ROW_HEIGHT);
    queryParametersTable.setDragEnabled(false);
    queryParametersTable.setOpaque(true);
    queryParametersTable.setSortable(false);
    queryParametersTable.getTableHeader().setReorderingAllowed(false);

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

    queryParametersPane.setViewportView(queryParametersTable);
}

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

/**
 * Save the mode in which the application was last used before shutdown -
 * advanced or basic - to the preferences
 * //from   ww  w .  j  ava  2 s.  c o m
 * @param advancedMode
 *            true if application was last used in advanced mode
 */
public static void savePreviousApplicationMode(boolean advancedMode) {
    Preferences prefs = Preferences.userNodeForPackage(Intkey.class);
    prefs.put(MODE_PREF_KEY, advancedMode ? ADVANCED_MODE_PREF_VALUE : BASIC_MODE_PREF_VALUE);
    try {
        prefs.sync();
    } catch (BackingStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.mirth.connect.client.ui.browsers.message.MessageBrowser.java

public void loadChannel(String channelId, Map<Integer, String> connectors, List<MetaDataColumn> metaDataColumns,
        List<Integer> selectedMetaDataIds, boolean isChannelDeployed) {
    this.isChannelDeployed = isChannelDeployed;
    this.selectedMetaDataIds = selectedMetaDataIds;
    parent.setVisibleTasks(parent.messageTasks, parent.messagePopupMenu, 1, 1, isChannelDeployed);
    parent.setVisibleTasks(parent.messageTasks, parent.messagePopupMenu, 7, 8, isChannelDeployed);

    //Set the FormatCheckboxes to their default setting
    formatMessageCheckBox/* www .ja v a  2s .c  o m*/
            .setSelected(Preferences.userNodeForPackage(Mirth.class).getBoolean("messageBrowserFormat", true));

    this.channelId = channelId;
    this.connectors = connectors;
    this.connectors.put(null, "Deleted Connectors");
    this.metaDataColumns = metaDataColumns;
    tableModel.clear();

    advancedSearchPopup.loadChannel();
    resetSearchCriteria();
    advancedSearchPopup.setSelectedMetaDataIds(selectedMetaDataIds);
    updateAdvancedSearchButtonFont();

    lastUserSelectedMessageType = "Raw";
    updateMessageRadioGroup();

    List<String> columnList = new ArrayList<String>();
    // Add standard columns
    columnList.addAll(columnMap.values());

    // Add custom columns
    Set<String> metaDataColumnNames = new LinkedHashSet<String>();

    for (MetaDataColumn column : metaDataColumns) {
        metaDataColumnNames.add(column.getName());
    }

    Map<String, Set<String>> customHiddenColumnMap = messageTreeTable.getCustomHiddenColumnMap();
    Set<String> hiddenCustomColumns = customHiddenColumnMap.get(channelId);
    if (hiddenCustomColumns == null) {
        hiddenCustomColumns = new HashSet<String>();
        customHiddenColumnMap.put(channelId, hiddenCustomColumns);
    } else {
        // If this channel was viewed before, remove any hidden custom columns that no longer exist
        Iterator<String> iterator = hiddenCustomColumns.iterator();
        while (iterator.hasNext()) {
            if (!metaDataColumnNames.contains(iterator.next())) {
                iterator.remove();
            }
        }
    }

    columnList.addAll(metaDataColumnNames);
    tableModel.setColumnIdentifiers(columnList);

    // Create the column objects and add them to the message table
    MessageBrowserTableColumnFactory columnFactory = (MessageBrowserTableColumnFactory) messageTreeTable
            .getColumnFactory();
    for (int modelIndex = 0; modelIndex < columnList.size(); modelIndex++) {
        TableColumnExt column = columnFactory.createAndConfigureTableColumn(messageTreeTable.getModel(),
                modelIndex);
        messageTreeTable.addColumn(column);
    }

    messageTreeTable.setMetaDataColumns(metaDataColumnNames, channelId);
    messageTreeTable.restoreColumnPreferences();

    runSearch();
}

From source file:speedith.cli.CliOptions.java

/**
 * Returns a key-value map of arguments to the chosen export format.
 * @return a key-value map of arguments to the chosen export format.
 *///  w w  w  .  ja v a  2s  . c  om
public Map<String, String> getOutputFormatArguments() {
    if (m_cachedOfa == null) {
        String keyValuesStr = getParsedOptions().getOptionValue(OPTION_OFA);
        if (keyValuesStr == null) {
            keyValuesStr = Preferences.userNodeForPackage(Main.class).get(PREF_OUTPUT_FORMAT_ARGS, null);
        } else {
            Preferences.userNodeForPackage(Main.class).put(PREF_OUTPUT_FORMAT_ARGS, keyValuesStr);
        }
        m_cachedOfa = parseKeyValues(keyValuesStr);
    }
    return m_cachedOfa == null ? null : Collections.unmodifiableMap(m_cachedOfa);
}

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

/**
 * @return the parent directory for the dataset that was most recently
 *         opened using intkey// w  w  w  .ja  v a  2  s.  co  m
 */
public static File getSavedLastOpenedDatasetDirectory() {
    Preferences prefs = Preferences.userNodeForPackage(Intkey.class);
    if (prefs != null) {
        String lastOpenedDirectoryPath = prefs.get(LAST_OPENED_DATASET_LOCATION_PREF_KEY, "");
        if (!StringUtils.isEmpty(lastOpenedDirectoryPath)) {
            return new File(lastOpenedDirectoryPath);
        }
    }
    return null;
}

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

private void initComponents() {
    setBackground(UIConstants.BACKGROUND_COLOR);
    getContentPane().setBackground(getBackground());

    topPanel = new JPanel();
    topPanel.setBackground(getBackground());

    linkPanel = new JPanel();
    linkPanel.setBackground(topPanel.getBackground());

    linkLeftPanel = new JPanel();
    linkLeftPanel.setBackground(linkPanel.getBackground());

    linkLeftSelectAllLabel = new JLabel("<html><u>All</u></html>");
    linkLeftSelectAllLabel.setForeground(Color.BLUE);
    linkLeftSelectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    linkLeftSelectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            for (int row = 0; row < importTreeTable.getRowCount(); row++) {
                importTreeTable.getModel().setValueAt(true, row, IMPORT_SELECTED_COLUMN);
            }//ww  w. jav  a2  s  .  c  o  m
        }
    });

    linkLeftDeselectAllLabel = new JLabel("<html><u>None</u></html>");
    linkLeftDeselectAllLabel.setForeground(Color.BLUE);
    linkLeftDeselectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    linkLeftDeselectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            for (int row = 0; row < importTreeTable.getRowCount(); row++) {
                importTreeTable.getModel().setValueAt(false, row, IMPORT_SELECTED_COLUMN);
            }
        }
    });

    linkRightPanel = new JPanel();
    linkRightPanel.setBackground(linkPanel.getBackground());

    linkRightOverwriteAllLabel = new JLabel("<html><u>All</u></html>");
    linkRightOverwriteAllLabel.setForeground(Color.BLUE);
    linkRightOverwriteAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    linkRightOverwriteAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            for (int row = 0; row < importTreeTable.getRowCount(); row++) {
                TreePath path = importTreeTable.getPathForRow(row);
                if (path != null) {
                    ImportTreeTableNode node = (ImportTreeTableNode) path.getLastPathComponent();
                    if (node instanceof ImportLibraryTreeTableNode) {
                        ImportLibraryTreeTableNode libraryNode = (ImportLibraryTreeTableNode) node;
                        if (libraryNode.getConflicts().getMatchingLibrary() != null) {
                            importTreeTable.getModel().setValueAt(true, row, IMPORT_OVERWRITE_COLUMN);
                        }
                    } else if (node instanceof ImportCodeTemplateTreeTableNode) {
                        ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) node;
                        if (codeTemplateNode.getConflicts().getMatchingCodeTemplate() != null) {
                            importTreeTable.getModel().setValueAt(true, row, IMPORT_OVERWRITE_COLUMN);
                        }
                    }
                }
            }
        }
    });

    linkRightOverwriteNoneLabel = new JLabel("<html><u>None</u></html>");
    linkRightOverwriteNoneLabel.setForeground(Color.BLUE);
    linkRightOverwriteNoneLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    linkRightOverwriteNoneLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            for (int row = 0; row < importTreeTable.getRowCount(); row++) {
                TreePath path = importTreeTable.getPathForRow(row);
                if (path != null) {
                    ImportTreeTableNode node = (ImportTreeTableNode) path.getLastPathComponent();
                    if (node instanceof ImportLibraryTreeTableNode) {
                        ImportLibraryTreeTableNode libraryNode = (ImportLibraryTreeTableNode) node;
                        if (libraryNode.getConflicts().getMatchingLibrary() != null) {
                            importTreeTable.getModel().setValueAt(false, row, IMPORT_OVERWRITE_COLUMN);
                        }
                    } else if (node instanceof ImportCodeTemplateTreeTableNode) {
                        ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) node;
                        if (codeTemplateNode.getConflicts().getMatchingCodeTemplate() != null) {
                            importTreeTable.getModel().setValueAt(false, row, IMPORT_OVERWRITE_COLUMN);
                        }
                    }
                }
            }
        }
    });

    final TableCellEditor templateCellEditor = new NameCellEditor();

    importTreeTable = new JXTreeTable() {
        @Override
        public boolean isCellEditable(int row, int column) {
            return (column == IMPORT_OVERWRITE_COLUMN || column == IMPORT_SELECTED_COLUMN
                    || column == IMPORT_NAME_COLUMN);
        }

        @Override
        public TableCellEditor getCellEditor(int row, int column) {
            if (isHierarchical(column)) {
                return templateCellEditor;
            } else {
                return super.getCellEditor(row, column);
            }
        }
    };

    importTreeTable.setLargeModel(true);
    DefaultTreeTableModel model = new ImportTreeTableModel();
    model.setColumnIdentifiers(Arrays.asList(new String[] { "", "Name", "Overwrite", "Conflicts", "Id" }));

    DefaultMutableTreeTableNode rootNode = new DefaultMutableTreeTableNode();
    model.setRoot(rootNode);
    importTreeTable.setTreeTableModel(model);

    Set<String> addedCodeTemplateIds = new HashSet<String>();

    if (unassignedCodeTemplates) {
        ImportTreeTableNode libraryNode = new ImportUnassignedLibraryTreeTableNode("Select a library", "");
        CodeTemplateLibrary library = importLibraries.get(0);

        for (CodeTemplate codeTemplate : library.getCodeTemplates()) {
            if (!addedCodeTemplateIds.contains(codeTemplate.getId())) {
                libraryNode
                        .add(new ImportCodeTemplateTreeTableNode(codeTemplate.getName(), codeTemplate.getId()));
                addedCodeTemplateIds.add(codeTemplate.getId());
                importCodeTemplateMap.put(codeTemplate.getId(), codeTemplate);
            }
        }

        rootNode.add(libraryNode);
    } else {
        Set<String> addedLibraryIds = new HashSet<String>();

        for (CodeTemplateLibrary library : importLibraries) {
            if (!addedLibraryIds.contains(library.getId())) {
                ImportTreeTableNode libraryNode = new ImportLibraryTreeTableNode(library.getName(),
                        library.getId());
                importLibraryMap.put(library.getId(), library);

                for (CodeTemplate codeTemplate : library.getCodeTemplates()) {
                    if (!addedCodeTemplateIds.contains(codeTemplate.getId())) {
                        libraryNode.add(new ImportCodeTemplateTreeTableNode(codeTemplate.getName(),
                                codeTemplate.getId()));
                        addedCodeTemplateIds.add(codeTemplate.getId());
                        importCodeTemplateMap.put(codeTemplate.getId(), codeTemplate);
                    }
                }

                rootNode.add(libraryNode);
                addedLibraryIds.add(library.getId());
            }
        }
    }

    importTreeTable.setOpenIcon(null);
    importTreeTable.setClosedIcon(null);
    importTreeTable.setLeafIcon(null);
    importTreeTable.setRootVisible(false);
    importTreeTable.setDoubleBuffered(true);
    importTreeTable.setDragEnabled(false);
    importTreeTable.setRowSelectionAllowed(true);
    importTreeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    importTreeTable.setRowHeight(UIConstants.ROW_HEIGHT);
    importTreeTable.setFocusable(true);
    importTreeTable.setOpaque(true);
    importTreeTable.getTableHeader().setReorderingAllowed(false);
    importTreeTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    importTreeTable.setEditable(true);
    importTreeTable.setSortable(false);
    importTreeTable.setAutoCreateColumnsFromModel(false);
    importTreeTable.setShowGrid(true, true);

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

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

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

        private void checkSelection(MouseEvent evt) {
            int row = importTreeTable.rowAtPoint(new Point(evt.getX(), evt.getY()));

            if (row < 0) {
                importTreeTable.clearSelection();
            }
        }
    });

    importTreeTable.addTreeWillExpandListener(new TreeWillExpandListener() {
        @Override
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
        }

        @Override
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
            throw new ExpandVetoException(event);
        }
    });

    importTreeTable.setTreeCellRenderer(new NameCellRenderer());

    importTreeTable.getModel().addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent evt) {
            if (evt.getColumn() != IMPORT_CONFLICTS_COLUMN) {
                for (int row = evt.getFirstRow(); row <= evt.getLastRow()
                        && row < importTreeTable.getRowCount(); row++) {
                    TreePath path = importTreeTable.getPathForRow(row);
                    if (path != null) {
                        ImportTreeTableNode node = (ImportTreeTableNode) path.getLastPathComponent();

                        if (path.getPathCount() == 2) {
                            if (node instanceof ImportUnassignedLibraryTreeTableNode) {
                                String libraryName = (String) node.getValueAt(IMPORT_NAME_COLUMN);
                                String libraryId = null;
                                for (CodeTemplateLibrary library : PlatformUI.MIRTH_FRAME.codeTemplatePanel
                                        .getCachedCodeTemplateLibraries().values()) {
                                    if (library.getName().equals(libraryName)) {
                                        libraryId = library.getId();
                                        break;
                                    }
                                }
                                node.setValueAt(libraryId, IMPORT_ID_COLUMN);
                            } else if (node instanceof ImportLibraryTreeTableNode) {
                                ImportLibraryTreeTableNode libraryNode = (ImportLibraryTreeTableNode) node;
                                libraryNode.setConflicts(getLibraryConflicts(node));
                            }

                            for (Enumeration<? extends TreeTableNode> codeTemplateNodes = node
                                    .children(); codeTemplateNodes.hasMoreElements();) {
                                ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) codeTemplateNodes
                                        .nextElement();
                                codeTemplateNode.setConflicts(getCodeTemplateConflicts(codeTemplateNode));
                            }

                            importTreeTable.updateUI();
                        } else if (path.getPathCount() == 3) {
                            ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) node;
                            codeTemplateNode.setConflicts(getCodeTemplateConflicts(node));
                        }
                    }
                }
            }

            updateImportButton();
            updateErrorsAndWarnings();
        }
    });

    importTreeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent evt) {
            if (!evt.getValueIsAdjusting()) {
                updateImportButton();
                updateErrorsAndWarnings();
            }
        }
    });

    importTreeTable.expandAll();

    importTreeTable.getColumnModel().getColumn(IMPORT_SELECTED_COLUMN).setMinWidth(20);
    importTreeTable.getColumnModel().getColumn(IMPORT_SELECTED_COLUMN).setMaxWidth(20);
    importTreeTable.getColumnModel().getColumn(IMPORT_SELECTED_COLUMN)
            .setCellRenderer(new ImportSelectedCellRenderer());
    importTreeTable.getColumnModel().getColumn(IMPORT_SELECTED_COLUMN)
            .setCellEditor(new ImportSelectedCellEditor());

    importTreeTable.getColumnModel().getColumn(IMPORT_OVERWRITE_COLUMN).setMinWidth(60);
    importTreeTable.getColumnModel().getColumn(IMPORT_OVERWRITE_COLUMN).setMaxWidth(60);
    importTreeTable.getColumnModel().getColumn(IMPORT_OVERWRITE_COLUMN)
            .setCellRenderer(new OverwriteCellRenderer());
    importTreeTable.getColumnModel().getColumn(IMPORT_OVERWRITE_COLUMN)
            .setCellEditor(new OverwriteCellEditor());

    importTreeTable.getColumnModel().getColumn(IMPORT_CONFLICTS_COLUMN).setMinWidth(60);
    importTreeTable.getColumnModel().getColumn(IMPORT_CONFLICTS_COLUMN).setMaxWidth(60);
    importTreeTable.getColumnModel().getColumn(IMPORT_CONFLICTS_COLUMN).setCellRenderer(new IconCellRenderer());

    importTreeTable.getColumnModel().removeColumn(importTreeTable.getColumnModel().getColumn(IMPORT_ID_COLUMN));

    importTreeTableScrollPane = new JScrollPane(importTreeTable);
    importTreeTableScrollPane.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, new Color(0x6E6E6E)));

    warningsPanel = new JPanel();
    warningsPanel.setBackground(getBackground());
    warningsPanel.setVisible(false);

    warningsLabel = new JLabel(UIConstants.ICON_WARNING);

    warningsTextArea = new JTextArea();
    warningsTextArea.setLineWrap(true);
    warningsTextArea.setWrapStyleWord(true);

    errorsPanel = new JPanel();
    errorsPanel.setBackground(getBackground());
    errorsPanel.setVisible(false);

    errorsLabel = new JLabel(UIConstants.ICON_ERROR);

    errorsTextArea = new JTextArea();
    errorsTextArea.setLineWrap(true);
    errorsTextArea.setWrapStyleWord(true);

    separator = new JSeparator();

    buttonPanel = new JPanel();
    buttonPanel.setBackground(getBackground());

    importButton = new JButton("Import");
    importButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            try {
                boolean warnings = false;
                for (Enumeration<? extends TreeTableNode> libraryNodes = ((TreeTableNode) importTreeTable
                        .getTreeTableModel().getRoot()).children(); libraryNodes.hasMoreElements();) {
                    for (Enumeration<? extends TreeTableNode> codeTemplateNodes = libraryNodes.nextElement()
                            .children(); codeTemplateNodes.hasMoreElements();) {
                        ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) codeTemplateNodes
                                .nextElement();

                        if ((boolean) codeTemplateNode.getValueAt(IMPORT_SELECTED_COLUMN)) {
                            CodeTemplateConflicts conflicts = codeTemplateNode.getConflicts();
                            if (conflicts.getMatchingCodeTemplate() != null) {
                                warnings = true;
                                break;
                            }
                        }
                    }

                    if (warnings) {
                        break;
                    }
                }

                if (!warnings || PlatformUI.MIRTH_FRAME.alertOption(CodeTemplateImportDialog.this,
                        "Some selected rows have warnings. Are you sure you wish to continue?")) {
                    save();
                    dispose();
                }
            } catch (Exception e) {
                PlatformUI.MIRTH_FRAME.alertThrowable(CodeTemplateImportDialog.this, e,
                        "Unable to import: " + e.getMessage());
            }
        }
    });

    cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (confirmClose()) {
                dispose();
            }
        }
    });

    updateImportButton();
}

From source file:com.mirth.connect.client.ui.components.rsta.MirthRSyntaxTextArea.java

public static void updateKeyStrokePreferences() {
    updateKeyStrokePreferences(Preferences.userNodeForPackage(Mirth.class));
}