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:com.mirth.connect.client.ui.ChannelPanel.java

public void importGroup(ChannelGroup importGroup, boolean showAlerts, boolean synchronous) {
    // First consolidate and import code template libraries
    Map<String, CodeTemplateLibrary> codeTemplateLibraryMap = new LinkedHashMap<String, CodeTemplateLibrary>();
    Set<String> codeTemplateIds = new HashSet<String>();

    for (Channel channel : importGroup.getChannels()) {
        if (channel.getCodeTemplateLibraries() != null) {
            for (CodeTemplateLibrary library : channel.getCodeTemplateLibraries()) {
                CodeTemplateLibrary matchingLibrary = codeTemplateLibraryMap.get(library.getId());

                if (matchingLibrary != null) {
                    for (CodeTemplate codeTemplate : library.getCodeTemplates()) {
                        if (codeTemplateIds.add(codeTemplate.getId())) {
                            matchingLibrary.getCodeTemplates().add(codeTemplate);
                        }// w ww.j av  a  2s.  com
                    }
                } else {
                    matchingLibrary = library;
                    codeTemplateLibraryMap.put(matchingLibrary.getId(), matchingLibrary);

                    List<CodeTemplate> codeTemplates = new ArrayList<CodeTemplate>();
                    for (CodeTemplate codeTemplate : matchingLibrary.getCodeTemplates()) {
                        if (codeTemplateIds.add(codeTemplate.getId())) {
                            codeTemplates.add(codeTemplate);
                        }
                    }
                    matchingLibrary.setCodeTemplates(codeTemplates);
                }

                // Combine the library enabled / disabled channel IDs
                matchingLibrary.getEnabledChannelIds().addAll(library.getEnabledChannelIds());
                matchingLibrary.getEnabledChannelIds().add(channel.getId());
                matchingLibrary.getDisabledChannelIds().addAll(library.getDisabledChannelIds());
                matchingLibrary.getDisabledChannelIds().removeAll(matchingLibrary.getEnabledChannelIds());
            }

            channel.getCodeTemplateLibraries().clear();
        }
    }

    List<CodeTemplateLibrary> codeTemplateLibraries = new ArrayList<CodeTemplateLibrary>(
            codeTemplateLibraryMap.values());

    parent.removeInvalidItems(codeTemplateLibraries, CodeTemplateLibrary.class);
    if (CollectionUtils.isNotEmpty(codeTemplateLibraries)) {
        boolean importLibraries;
        String importChannelCodeTemplateLibraries = Preferences.userNodeForPackage(Mirth.class)
                .get("importChannelCodeTemplateLibraries", null);

        if (importChannelCodeTemplateLibraries == null) {
            JCheckBox alwaysChooseCheckBox = new JCheckBox(
                    "Always choose this option by default in the future (may be changed in the Administrator settings)");
            Object[] params = new Object[] {
                    "Group \"" + importGroup.getName()
                            + "\" has code template libraries included with it. Would you like to import them?",
                    alwaysChooseCheckBox };
            int result = JOptionPane.showConfirmDialog(this, params, "Select an Option",
                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (result == JOptionPane.YES_OPTION || result == JOptionPane.NO_OPTION) {
                importLibraries = result == JOptionPane.YES_OPTION;
                if (alwaysChooseCheckBox.isSelected()) {
                    Preferences.userNodeForPackage(Mirth.class).putBoolean("importChannelCodeTemplateLibraries",
                            importLibraries);
                }
            } else {
                return;
            }
        } else {
            importLibraries = Boolean.parseBoolean(importChannelCodeTemplateLibraries);
        }

        if (importLibraries) {
            CodeTemplateImportDialog dialog = new CodeTemplateImportDialog(parent, codeTemplateLibraries, false,
                    true);

            if (dialog.wasSaved()) {
                CodeTemplateLibrarySaveResult updateSummary = parent.codeTemplatePanel.attemptUpdate(
                        dialog.getUpdatedLibraries(), new HashMap<String, CodeTemplateLibrary>(),
                        dialog.getUpdatedCodeTemplates(), new HashMap<String, CodeTemplate>(), true, null,
                        null);

                if (updateSummary == null || updateSummary.isOverrideNeeded()
                        || !updateSummary.isLibrariesSuccess()) {
                    return;
                } else {
                    for (CodeTemplateUpdateResult result : updateSummary.getCodeTemplateResults().values()) {
                        if (!result.isSuccess()) {
                            return;
                        }
                    }
                }

                parent.codeTemplatePanel.doRefreshCodeTemplates();
            }
        }
    }

    List<Channel> successfulChannels = new ArrayList<Channel>();
    for (Channel channel : importGroup.getChannels()) {
        Channel importChannel = importChannel(channel, false, false);
        if (importChannel != null) {
            successfulChannels.add(importChannel);
        }
    }

    if (!StringUtils.equals(importGroup.getId(), ChannelGroup.DEFAULT_ID)) {
        ChannelTreeTableModel model = (ChannelTreeTableModel) channelTable.getTreeTableModel();
        AbstractChannelTableNode importGroupNode = null;

        String groupName = importGroup.getName();
        String tempId;
        try {
            tempId = parent.mirthClient.getGuid();
        } catch (ClientException e) {
            tempId = UUID.randomUUID().toString();
        }

        // Check to see that the channel name doesn't already exist.
        if (!checkGroupName(groupName)) {
            if (!parent.alertOption(parent,
                    "Would you like to overwrite the existing group?  Choose 'No' to create a new group.")) {
                importGroup.setRevision(0);

                do {
                    groupName = JOptionPane.showInputDialog(this, "Please enter a new name for the group.",
                            groupName);
                    if (groupName == null) {
                        return;
                    }
                } while (!checkGroupName(groupName));

                importGroup.setId(tempId);
                importGroup.setName(groupName);
            } else {
                MutableTreeTableNode root = (MutableTreeTableNode) model.getRoot();
                for (Enumeration<? extends MutableTreeTableNode> groupNodes = root.children(); groupNodes
                        .hasMoreElements();) {
                    AbstractChannelTableNode groupNode = (AbstractChannelTableNode) groupNodes.nextElement();

                    if (StringUtils.equals(groupNode.getGroupStatus().getGroup().getName(), groupName)) {
                        importGroupNode = groupNode;
                    }
                }
            }
        } else {
            // Start the revision number over for a new channel group
            importGroup.setRevision(0);

            // If the channel name didn't already exist, make sure
            // the id doesn't exist either.
            if (!checkGroupId(importGroup.getId())) {
                importGroup.setId(tempId);
            }
        }

        Set<ChannelGroup> channelGroups = new HashSet<ChannelGroup>();
        Set<String> removedChannelGroupIds = new HashSet<String>(groupStatuses.keySet());
        removedChannelGroupIds.remove(ChannelGroup.DEFAULT_ID);

        MutableTreeTableNode root = (MutableTreeTableNode) channelTable.getTreeTableModel().getRoot();
        if (root == null) {
            return;
        }

        for (Enumeration<? extends MutableTreeTableNode> groupNodes = root.children(); groupNodes
                .hasMoreElements();) {
            ChannelGroup group = ((AbstractChannelTableNode) groupNodes.nextElement()).getGroupStatus()
                    .getGroup();

            if (!StringUtils.equals(group.getId(), ChannelGroup.DEFAULT_ID)) {
                // If the current group is the one we're overwriting, merge the channels
                if (importGroupNode != null && StringUtils.equals(group.getId(),
                        importGroupNode.getGroupStatus().getGroup().getId())) {
                    group = importGroup;
                    group.setRevision(importGroupNode.getGroupStatus().getGroup().getRevision());

                    Set<String> channelIds = new HashSet<String>();
                    for (Channel channel : group.getChannels()) {
                        channelIds.add(channel.getId());
                    }

                    // Add the imported channels
                    for (Channel channel : successfulChannels) {
                        channelIds.add(channel.getId());
                    }

                    List<Channel> channels = new ArrayList<Channel>();
                    for (String channelId : channelIds) {
                        channels.add(new Channel(channelId));
                    }
                    group.setChannels(channels);
                }

                channelGroups.add(group);
                removedChannelGroupIds.remove(group.getId());
            }
        }

        if (importGroupNode == null) {
            List<Channel> channels = new ArrayList<Channel>();
            for (Channel channel : successfulChannels) {
                channels.add(new Channel(channel.getId()));
            }
            importGroup.setChannels(channels);

            channelGroups.add(importGroup);
            removedChannelGroupIds.remove(importGroup.getId());
        }

        Set<String> channelIds = new HashSet<String>();
        for (Channel channel : importGroup.getChannels()) {
            channelIds.add(channel.getId());
        }

        for (ChannelGroup group : channelGroups) {
            if (group != importGroup) {
                for (Iterator<Channel> channels = group.getChannels().iterator(); channels.hasNext();) {
                    if (!channelIds.add(channels.next().getId())) {
                        channels.remove();
                    }
                }
            }
        }

        attemptUpdate(channelGroups, removedChannelGroupIds, false);
    }

    if (synchronous) {
        retrieveChannels();
        updateModel(getCurrentTableState());
        updateTasks();
        parent.setSaveEnabled(false);
    } else {
        doRefreshChannels();
    }
}

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

public void updateMappingsTable(String[][] tableData, boolean cleared) {
    if (tableData == null || tableData.length == 0) {
        tableData = new String[1][3];
        if (cleared) {
            tableData[0][1] = "Please select a message to view mappings.";
        } else {//from  w w  w.  j a va 2s.c  o m
            tableData[0][1] = "There are no mappings present.";
        }
        tableData[0][0] = "";
        tableData[0][2] = "";
    }

    if (mappingsTable != null) {
        RefreshTableModel model = (RefreshTableModel) mappingsTable.getModel();
        model.refreshDataVector(tableData);
    } else {
        mappingsTable = new MirthTable();

        mappingsTable.setModel(new RefreshTableModel(tableData,
                new String[] { SCOPE_COLUMN_NAME, KEY_COLUMN_NAME, VALUE_COLUMN_NAME }) {

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

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

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

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

public void updateAttachmentsTable(Long messageId) {

    Object[][] tableData = updateAttachmentList(messageId);

    // Create attachment Table if it has not been created yet. 
    if (attachmentTable != null) {
        RefreshTableModel model = (RefreshTableModel) attachmentTable.getModel();
        if (tableData != null) {
            model.refreshDataVector(tableData);
        }/*ww  w.  j a  v a  2  s .c  o m*/
    } else {
        attachmentTable = new MirthTable();
        attachmentTable.setModel(new RefreshTableModel(tableData,
                new String[] { NUMBER_COLUMN_NAME, TYPE_COLUMN_NAME, ATTACHMENTID_COLUMN_NAME }) {

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

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });
        attachmentTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent evt) {
                if (attachmentTable != null && attachmentTable.getSelectedRow() != -1) {
                    parent.setVisibleTasks(parent.messageTasks, parent.messagePopupMenu, 9, 10, true);
                } else {
                    parent.setVisibleTasks(parent.messageTasks, parent.messagePopupMenu, 9, 10, false);
                }
            }
        });
        // listen for trigger button and double click to edit channel.
        attachmentTable.addMouseListener(new java.awt.event.MouseAdapter() {

            public void mousePressed(java.awt.event.MouseEvent evt) {
                checkAttachmentSelectionAndPopupMenu(evt);
            }

            public void mouseReleased(java.awt.event.MouseEvent evt) {
                checkAttachmentSelectionAndPopupMenu(evt);
            }

            public void mouseClicked(java.awt.event.MouseEvent evt) {
                if (attachmentTable.rowAtPoint(new Point(evt.getX(), evt.getY())) == -1) {
                    return;
                }

                if (evt.getClickCount() >= 2) {
                    viewAttachment();// do view

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

        attachmentTable.setSelectionMode(0);
        attachmentTable.getColumnExt(NUMBER_COLUMN_NAME).setMinWidth(UIConstants.WIDTH_SHORT_MIN);
        attachmentTable.getColumnExt(NUMBER_COLUMN_NAME).setMaxWidth(UIConstants.WIDTH_SHORT_MAX);
        attachmentTable.getColumnExt(TYPE_COLUMN_NAME).setMinWidth(UIConstants.MIN_WIDTH);
        attachmentTable.getColumnExt(TYPE_COLUMN_NAME).setMaxWidth(UIConstants.MAX_WIDTH);
        attachmentsPane.setViewportView(attachmentTable);
    }
}

From source file:net.sf.jabref.JabRefPreferences.java

/**
 * Fetches key patterns from preferences.
 * The implementation doesn't cache the results
 *
 * @return LabelPattern containing all keys. Returned LabelPattern has no parent
 *///w  w  w.j  a v a  2  s  .  c  o  m
public GlobalLabelPattern getKeyPattern() {
    keyPattern = new GlobalLabelPattern();
    Preferences pre = Preferences.userNodeForPackage(GlobalLabelPattern.class);
    try {
        String[] keys = pre.keys();
        if (keys.length > 0) {
            for (String key : keys) {
                keyPattern.addLabelPattern(key, pre.get(key, null));
            }
        }
    } catch (BackingStoreException ex) {
        LOGGER.info("BackingStoreException in JabRefPreferences.getKeyPattern", ex);
    }
    return keyPattern;
}

From source file:net.sf.jabref.JabRefPreferences.java

/**
 * Adds the given key pattern to the preferences
 *
 * @param pattern the pattern to store/*w w w  .  j  av a  2  s . c  o m*/
 */
public void putKeyPattern(GlobalLabelPattern pattern) {
    keyPattern = pattern;

    // Store overridden definitions to Preferences.
    Preferences pre = Preferences.userNodeForPackage(GlobalLabelPattern.class);
    try {
        pre.clear(); // We remove all old entries.
    } catch (BackingStoreException ex) {
        LOGGER.info("BackingStoreException in JabRefPreferences.putKeyPattern", ex);
    }

    Set<String> allKeys = pattern.getAllKeys();
    for (String key : allKeys) {
        if (!pattern.isDefaultValue(key)) {
            // no default value
            // the first entry in the array is the full pattern
            // see net.sf.jabref.logic.labelPattern.LabelPatternUtil.split(String)
            pre.put(key, pattern.getValue(key).get(0));
        }
    }
}

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

public Channel importChannel(Channel importChannel, boolean showAlerts, boolean refreshStatuses) {
    boolean overwrite = false;

    try {//from   w w w. j  ava  2 s . c  o  m
        String channelName = importChannel.getName();
        String tempId = parent.mirthClient.getGuid();

        // Check to see that the channel name doesn't already exist.
        if (!parent.checkChannelName(channelName, tempId)) {
            if (!parent.alertOption(parent,
                    "Would you like to overwrite the existing channel?  Choose 'No' to create a new channel.")) {
                importChannel.setRevision(0);

                do {
                    channelName = JOptionPane.showInputDialog(this, "Please enter a new name for the channel.",
                            channelName);
                    if (channelName == null) {
                        return null;
                    }
                } while (!parent.checkChannelName(channelName, tempId));

                importChannel.setName(channelName);
                setIdAndUpdateLibraries(importChannel, tempId);
            } else {
                overwrite = true;

                for (ChannelStatus channelStatus : channelStatuses.values()) {
                    Channel channel = channelStatus.getChannel();
                    if (channel.getName().equalsIgnoreCase(channelName)) {
                        // If overwriting, use the old revision number and id
                        importChannel.setRevision(channel.getRevision());
                        setIdAndUpdateLibraries(importChannel, channel.getId());
                    }
                }
            }
        } else {
            // Start the revision number over for a new channel
            importChannel.setRevision(0);

            // If the channel name didn't already exist, make sure
            // the id doesn't exist either.
            if (!checkChannelId(importChannel.getId())) {
                setIdAndUpdateLibraries(importChannel, tempId);
            }

        }

        channelStatuses.put(importChannel.getId(), new ChannelStatus(importChannel));
        parent.updateChannelTags(false);
    } catch (ClientException e) {
        parent.alertThrowable(parent, e);
    }

    // Import code templates / libraries if applicable
    parent.removeInvalidItems(importChannel.getCodeTemplateLibraries(), CodeTemplateLibrary.class);
    if (!(importChannel instanceof InvalidChannel) && !importChannel.getCodeTemplateLibraries().isEmpty()) {
        boolean importLibraries;
        String importChannelCodeTemplateLibraries = Preferences.userNodeForPackage(Mirth.class)
                .get("importChannelCodeTemplateLibraries", null);

        if (importChannelCodeTemplateLibraries == null) {
            JCheckBox alwaysChooseCheckBox = new JCheckBox(
                    "Always choose this option by default in the future (may be changed in the Administrator settings)");
            Object[] params = new Object[] {
                    "Channel \"" + importChannel.getName()
                            + "\" has code template libraries included with it. Would you like to import them?",
                    alwaysChooseCheckBox };
            int result = JOptionPane.showConfirmDialog(this, params, "Select an Option",
                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (result == JOptionPane.YES_OPTION || result == JOptionPane.NO_OPTION) {
                importLibraries = result == JOptionPane.YES_OPTION;
                if (alwaysChooseCheckBox.isSelected()) {
                    Preferences.userNodeForPackage(Mirth.class).putBoolean("importChannelCodeTemplateLibraries",
                            importLibraries);
                }
            } else {
                return null;
            }
        } else {
            importLibraries = Boolean.parseBoolean(importChannelCodeTemplateLibraries);
        }

        if (importLibraries) {
            CodeTemplateImportDialog dialog = new CodeTemplateImportDialog(parent,
                    importChannel.getCodeTemplateLibraries(), false, true);

            if (dialog.wasSaved()) {
                CodeTemplateLibrarySaveResult updateSummary = parent.codeTemplatePanel.attemptUpdate(
                        dialog.getUpdatedLibraries(), new HashMap<String, CodeTemplateLibrary>(),
                        dialog.getUpdatedCodeTemplates(), new HashMap<String, CodeTemplate>(), true, null,
                        null);

                if (updateSummary == null || updateSummary.isOverrideNeeded()
                        || !updateSummary.isLibrariesSuccess()) {
                    return null;
                } else {
                    for (CodeTemplateUpdateResult result : updateSummary.getCodeTemplateResults().values()) {
                        if (!result.isSuccess()) {
                            return null;
                        }
                    }
                }

                parent.codeTemplatePanel.doRefreshCodeTemplates();
            }
        }

        importChannel.getCodeTemplateLibraries().clear();
    }

    if (CollectionUtils.isNotEmpty(importChannel.getDependentIds())
            || CollectionUtils.isNotEmpty(importChannel.getDependencyIds())) {
        Set<ChannelDependency> channelDependencies = new HashSet<ChannelDependency>(
                getCachedChannelDependencies());

        if (CollectionUtils.isNotEmpty(importChannel.getDependentIds())) {
            for (String dependentId : importChannel.getDependentIds()) {
                if (StringUtils.isNotBlank(dependentId)
                        && !StringUtils.equals(dependentId, importChannel.getId())) {
                    channelDependencies.add(new ChannelDependency(dependentId, importChannel.getId()));
                }
            }
        }

        if (CollectionUtils.isNotEmpty(importChannel.getDependencyIds())) {
            for (String dependencyId : importChannel.getDependencyIds()) {
                if (StringUtils.isNotBlank(dependencyId)
                        && !StringUtils.equals(dependencyId, importChannel.getId())) {
                    channelDependencies.add(new ChannelDependency(importChannel.getId(), dependencyId));
                }
            }
        }

        if (!channelDependencies.equals(getCachedChannelDependencies())) {
            try {
                parent.mirthClient.setChannelDependencies(channelDependencies);
            } catch (ClientException e) {
                parent.alertThrowable(parent, e, "Unable to save channel dependencies.");
            }
        }

        importChannel.clearDependencies();
    }

    // Update resource names
    parent.updateResourceNames(importChannel);

    /*
     * Update the channel if we're overwriting an imported channel, if we're not showing alerts
     * (dragging/dropping multiple channels), or if we're working with an invalid channel.
     */
    if (overwrite || !showAlerts || importChannel instanceof InvalidChannel) {
        try {
            parent.updateChannel(importChannel, overwrite);

            if (importChannel instanceof InvalidChannel && showAlerts) {
                InvalidChannel invalidChannel = (InvalidChannel) importChannel;
                Throwable cause = invalidChannel.getCause();
                parent.alertThrowable(parent, cause, "Channel \"" + importChannel.getName() + "\" is invalid. "
                        + getMissingExtensions(invalidChannel) + " Original cause:\n" + cause.getMessage());
            }
        } catch (Exception e) {
            channelStatuses.remove(importChannel.getId());
            parent.updateChannelTags(false);
            parent.alertThrowable(parent, e);
            return null;
        } finally {
            if (refreshStatuses) {
                doRefreshChannels();
            }
        }
    }

    if (showAlerts) {
        final Channel importChannelFinal = importChannel;
        final boolean overwriteFinal = overwrite;

        /*
         * MIRTH-2048 - This is a hack to fix the memory access error that only occurs on OS X.
         * The block of code that edits the channel needs to be invoked later so that the screen
         * does not change before the drag/drop action of a channel finishes.
         */
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    parent.editChannel(importChannelFinal);
                    parent.setSaveEnabled(!overwriteFinal);
                } catch (Exception e) {
                    channelStatuses.remove(importChannelFinal.getId());
                    parent.updateChannelTags(false);
                    parent.alertError(parent, "Channel had an unknown problem. Channel import aborted.");
                    parent.channelEditPanel = new ChannelSetup();
                    parent.doShowChannel();
                }
            }

        });
    }

    return importChannel;
}

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

private void initComponents() {
    splitPane = new JSplitPane();
    splitPane.setBackground(getBackground());
    splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
    splitPane.setBorder(BorderFactory.createEmptyBorder());
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(/*  ww w. j  a  v a2 s .c  om*/
            Preferences.userNodeForPackage(Mirth.class).getInt("height", UIConstants.MIRTH_HEIGHT) / 3);
    splitPane.setResizeWeight(0.5);

    topPanel = new JPanel();
    topPanel.setBackground(UIConstants.COMBO_BOX_BACKGROUND);

    final CodeTemplateTreeTableCellEditor templateCellEditor = new CodeTemplateTreeTableCellEditor(this);

    templateTreeTable = new MirthTreeTable("CodeTemplate", new HashSet<String>(
            Arrays.asList(new String[] { "Name", "Description", "Revision", "Last Modified" }))) {

        private TreeTableNode selectedNode;

        @Override
        public boolean isCellEditable(int row, int column) {
            return column == TEMPLATE_NAME_COLUMN;
        }

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

        @Override
        protected void beforeSort() {
            updateCurrentNode();
            updateCurrentNode.set(false);

            int selectedRow = templateTreeTable.getSelectedRow();
            selectedNode = selectedRow >= 0
                    ? (TreeTableNode) templateTreeTable.getPathForRow(selectedRow).getLastPathComponent()
                    : null;
        }

        @Override
        protected void afterSort() {
            final TreePath selectedPath = selectPathFromNodeId(selectedNode,
                    (CodeTemplateRootTreeTableNode) templateTreeTable.getTreeTableModel().getRoot());
            if (selectedPath != null) {
                selectTemplatePath(selectedPath);
            }

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (selectedPath != null) {
                        selectTemplatePath(selectedPath);
                    }
                    updateCurrentNode.set(true);
                }
            });
        }
    };

    DefaultTreeTableModel model = new CodeTemplateTreeTableModel();
    model.setColumnIdentifiers(
            Arrays.asList(new String[] { "Name", "Id", "Type", "Description", "Revision", "Last Modified" }));

    CodeTemplateRootTreeTableNode rootNode = new CodeTemplateRootTreeTableNode();
    model.setRoot(rootNode);

    fullModel = new CodeTemplateTreeTableModel();
    fullModel.setColumnIdentifiers(
            Arrays.asList(new String[] { "Name", "Id", "Type", "Description", "Revision", "Last Modified" }));

    CodeTemplateRootTreeTableNode fullRootNode = new CodeTemplateRootTreeTableNode();
    fullModel.setRoot(fullRootNode);

    templateTreeTable.setColumnFactory(new CodeTemplateTableColumnFactory());
    templateTreeTable.setTreeTableModel(model);
    templateTreeTable.setOpenIcon(null);
    templateTreeTable.setClosedIcon(null);
    templateTreeTable.setLeafIcon(null);
    templateTreeTable.setRootVisible(false);
    templateTreeTable.setDoubleBuffered(true);
    templateTreeTable.setDragEnabled(false);
    templateTreeTable.setRowSelectionAllowed(true);
    templateTreeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    templateTreeTable.setRowHeight(UIConstants.ROW_HEIGHT);
    templateTreeTable.setFocusable(true);
    templateTreeTable.setOpaque(true);
    templateTreeTable.getTableHeader().setReorderingAllowed(true);
    templateTreeTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    templateTreeTable.setEditable(true);
    templateTreeTable.setSortable(true);
    templateTreeTable.setAutoCreateColumnsFromModel(false);
    templateTreeTable.setShowGrid(true, true);
    templateTreeTable.restoreColumnPreferences();
    templateTreeTable.setMirthColumnControlEnabled(true);

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

    templateTreeTable.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 = templateTreeTable.rowAtPoint(new Point(evt.getX(), evt.getY()));

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

            if (evt.isPopupTrigger()) {
                if (row != -1) {
                    if (!templateTreeTable.isRowSelected(row)) {
                        templateTreeTable.setRowSelectionInterval(row, row);
                    }
                }
                codeTemplatePopupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
            }
        }
    });

    templateTreeTable.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                TreePath selectedPath = templateTreeTable.getTreeSelectionModel().getSelectionPath();
                if (selectedPath != null) {
                    MutableTreeTableNode selectedNode = (MutableTreeTableNode) selectedPath
                            .getLastPathComponent();
                    if (selectedNode instanceof CodeTemplateLibraryTreeTableNode && codeTemplateTasks
                            .getContentPane().getComponent(TASK_CODE_TEMPLATE_LIBRARY_DELETE).isVisible()) {
                        doDeleteLibrary();
                    } else if (selectedNode instanceof CodeTemplateTreeTableNode && codeTemplateTasks
                            .getContentPane().getComponent(TASK_CODE_TEMPLATE_DELETE).isVisible()) {
                        doDeleteCodeTemplate();
                    }
                }
            }
        }
    });

    templateTreeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent evt) {
            if (!evt.getValueIsAdjusting() && !templateTreeTable.getSelectionModel().getValueIsAdjusting()) {
                int selectedRow = templateTreeTable.getSelectedRow();

                boolean saveEnabled = isSaveEnabled();
                boolean adjusting = saveAdjusting.getAndSet(true);

                printTreeTable();

                updateCurrentNode();
                currentSelectedRow = selectedRow;

                if (selectedRow < 0) {
                    if (!adjusting) {
                        switchSplitPaneComponent(blankPanel);
                    }
                } else {
                    TreePath path = templateTreeTable.getPathForRow(selectedRow);
                    if (path != null) {
                        TreeTableNode node = (TreeTableNode) path.getLastPathComponent();

                        if (node instanceof CodeTemplateLibraryTreeTableNode) {
                            setLibraryProperties((CodeTemplateLibraryTreeTableNode) node);
                            switchSplitPaneComponent(libraryPanel);
                        } else if (node instanceof CodeTemplateTreeTableNode) {
                            setCodeTemplateProperties((CodeTemplateTreeTableNode) node);
                            switchSplitPaneComponent(templatePanel);
                        }
                    }
                }

                updateTasks();

                setSaveEnabled(saveEnabled);
                if (!adjusting) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            saveAdjusting.set(false);
                        }
                    });
                }
            }
        }
    });

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

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

        private void treeExpansionChanged() {
            updateCurrentNode();
            updateCurrentNode.set(false);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    updateCurrentNode.set(true);
                }
            });
        }
    });

    templateTreeTableScrollPane = new JScrollPane(templateTreeTable);
    templateTreeTableScrollPane.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0x6E6E6E)));

    templateFilterNotificationLabel = new JLabel();

    templateFilterLabel = new JLabel("Filter:");

    templateFilterField = new JTextField();
    templateFilterField.setToolTipText(
            "Filters (by name) the code templates and libraries that show up in the table above.");

    templateFilterField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent evt) {
            filterChanged(evt);
        }

        @Override
        public void insertUpdate(DocumentEvent evt) {
            filterChanged(evt);
        }

        @Override
        public void changedUpdate(DocumentEvent evt) {
            filterChanged(evt);
        }

        private void filterChanged(DocumentEvent evt) {
            try {
                updateTemplateFilter(evt.getDocument().getText(0, evt.getLength()));
            } catch (BadLocationException e) {
            }
        }
    });

    templateFilterField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent evt) {
            updateTemplateFilter(templateFilterField.getText());
        }
    });

    blankPanel = new JPanel();

    libraryPanel = new JPanel();
    libraryPanel.setBackground(splitPane.getBackground());

    libraryLeftPanel = new JPanel();
    libraryLeftPanel.setBackground(libraryPanel.getBackground());

    librarySummaryLabel = new JLabel("Summary:");
    librarySummaryValue = new JLabel();

    libraryDescriptionLabel = new JLabel("Description:");
    libraryDescriptionScrollPane = new MirthRTextScrollPane(null, false, SyntaxConstants.SYNTAX_STYLE_NONE,
            false);

    DocumentListener codeChangeListener = new DocumentListener() {

        @Override
        public void removeUpdate(DocumentEvent evt) {
            codeChanged();
        }

        @Override
        public void insertUpdate(DocumentEvent evt) {
            codeChanged();
        }

        @Override
        public void changedUpdate(DocumentEvent evt) {
            codeChanged();
        }

        private void codeChanged() {
            if (codeChangeWorker != null) {
                codeChangeWorker.cancel(true);
            }

            int selectedRow = templateTreeTable.getSelectedRow();
            if (selectedRow >= 0) {
                TreePath selectedPath = templateTreeTable.getPathForRow(selectedRow);
                if (selectedPath != null) {
                    codeChangeWorker = new CodeChangeWorker(
                            (String) ((TreeTableNode) selectedPath.getLastPathComponent())
                                    .getValueAt(TEMPLATE_ID_COLUMN));
                    codeChangeWorker.execute();
                }
            }
        }
    };
    libraryDescriptionScrollPane.getDocument().addDocumentListener(codeChangeListener);

    libraryRightPanel = new JPanel();
    libraryRightPanel.setBackground(libraryPanel.getBackground());

    libraryChannelsSelectPanel = new JPanel();
    libraryChannelsSelectPanel.setBackground(libraryRightPanel.getBackground());

    libraryChannelsLabel = new JLabel("<html><b>Channels</b></html>");
    libraryChannelsLabel.setForeground(new Color(64, 64, 64));

    libraryChannelsSelectAllLabel = new JLabel("<html><u>Select All</u></html>");
    libraryChannelsSelectAllLabel.setForeground(Color.BLUE);
    libraryChannelsSelectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    libraryChannelsSelectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            if (evt.getComponent().isEnabled()) {
                for (int row = 0; row < libraryChannelsTable.getRowCount(); row++) {
                    ChannelInfo channelInfo = (ChannelInfo) libraryChannelsTable.getValueAt(row,
                            LIBRARY_CHANNELS_NAME_COLUMN);
                    channelInfo.setEnabled(true);
                    libraryChannelsTable.setValueAt(channelInfo, row, LIBRARY_CHANNELS_NAME_COLUMN);
                }
                setSaveEnabled(true);
            }
        }
    });

    libraryChannelsDeselectAllLabel = new JLabel("<html><u>Deselect All</u></html>");
    libraryChannelsDeselectAllLabel.setForeground(Color.BLUE);
    libraryChannelsDeselectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    libraryChannelsDeselectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            if (evt.getComponent().isEnabled()) {
                for (int row = 0; row < libraryChannelsTable.getRowCount(); row++) {
                    ChannelInfo channelInfo = (ChannelInfo) libraryChannelsTable.getValueAt(row,
                            LIBRARY_CHANNELS_NAME_COLUMN);
                    channelInfo.setEnabled(false);
                    libraryChannelsTable.setValueAt(channelInfo, row, LIBRARY_CHANNELS_NAME_COLUMN);
                }
                setSaveEnabled(true);
            }
        }
    });

    libraryChannelsFilterLabel = new JLabel("Filter:");
    libraryChannelsFilterField = new JTextField();
    libraryChannelsFilterField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent evt) {
            libraryChannelsTable.getRowSorter().allRowsChanged();
        }

        @Override
        public void insertUpdate(DocumentEvent evt) {
            libraryChannelsTable.getRowSorter().allRowsChanged();
        }

        @Override
        public void changedUpdate(DocumentEvent evt) {
            libraryChannelsTable.getRowSorter().allRowsChanged();
        }
    });

    libraryChannelsTable = new MirthTable();
    libraryChannelsTable.setModel(new RefreshTableModel(new Object[] { "Name", "Id" }, 0));
    libraryChannelsTable.setDragEnabled(false);
    libraryChannelsTable.setRowSelectionAllowed(false);
    libraryChannelsTable.setRowHeight(UIConstants.ROW_HEIGHT);
    libraryChannelsTable.setFocusable(false);
    libraryChannelsTable.setOpaque(true);
    libraryChannelsTable.getTableHeader().setReorderingAllowed(false);
    libraryChannelsTable.setEditable(true);

    OffsetRowSorter libraryChannelsRowSorter = new OffsetRowSorter(libraryChannelsTable.getModel(), 1);
    libraryChannelsRowSorter.setRowFilter(new RowFilter<TableModel, Integer>() {
        @Override
        public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
            String name = entry.getStringValue(LIBRARY_CHANNELS_NAME_COLUMN);
            return name.equals(NEW_CHANNELS) || StringUtils.containsIgnoreCase(name,
                    StringUtils.trim(libraryChannelsFilterField.getText()));
        }
    });
    libraryChannelsTable.setRowSorter(libraryChannelsRowSorter);

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

    libraryChannelsTable.getColumnExt(LIBRARY_CHANNELS_NAME_COLUMN)
            .setCellRenderer(new ChannelsTableCellRenderer());
    libraryChannelsTable.getColumnExt(LIBRARY_CHANNELS_NAME_COLUMN)
            .setCellEditor(new ChannelsTableCellEditor());

    // Hide ID column
    libraryChannelsTable.getColumnExt(LIBRARY_CHANNELS_ID_COLUMN).setVisible(false);

    libraryChannelsScrollPane = new JScrollPane(libraryChannelsTable);

    templatePanel = new JPanel();
    templatePanel.setBackground(splitPane.getBackground());

    templateLeftPanel = new JPanel();
    templateLeftPanel.setBackground(templatePanel.getBackground());

    templateLibraryLabel = new JLabel("Library:");
    templateLibraryComboBox = new JComboBox<String>();
    templateLibraryComboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            libraryComboBoxActionPerformed();
        }
    });

    templateTypeLabel = new JLabel("Type:");
    templateTypeComboBox = new JComboBox<CodeTemplateType>(CodeTemplateType.values());
    templateTypeComboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            setSaveEnabled(true);
        }
    });

    templateCodeLabel = new JLabel("Code:");
    templateCodeTextArea = new MirthRTextScrollPane(ContextType.GLOBAL_DEPLOY);
    templateCodeTextArea.getDocument().addDocumentListener(codeChangeListener);

    templateAutoGenerateDocumentationButton = new JButton("Update JSDoc");
    templateAutoGenerateDocumentationButton.setToolTipText(
            "<html>Generates/updates a JSDoc at the beginning of your<br/>code, with parameter/return annotations as needed.</html>");
    templateAutoGenerateDocumentationButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            String currentText = templateCodeTextArea.getText();
            String newText = CodeTemplateUtil.updateCode(templateCodeTextArea.getText());
            templateCodeTextArea.setText(newText, false);
            if (!currentText.equals(newText)) {
                setSaveEnabled(true);
            }
        }
    });

    templateRightPanel = new JPanel();
    templateRightPanel.setBackground(templatePanel.getBackground());

    templateContextSelectPanel = new JPanel();
    templateContextSelectPanel.setBackground(templateRightPanel.getBackground());

    templateContextLabel = new JLabel("<html><b>Context</b></html>");
    templateContextLabel.setForeground(new Color(64, 64, 64));

    templateContextSelectAllLabel = new JLabel("<html><u>Select All</u></html>");
    templateContextSelectAllLabel.setForeground(Color.BLUE);
    templateContextSelectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    templateContextSelectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            TreeTableNode root = (TreeTableNode) templateContextTreeTable.getTreeTableModel().getRoot();
            for (Enumeration<? extends TreeTableNode> groups = root.children(); groups.hasMoreElements();) {
                TreeTableNode group = groups.nextElement();
                ((MutablePair<Integer, String>) group.getUserObject()).setLeft(MirthTriStateCheckBox.CHECKED);
                for (Enumeration<? extends TreeTableNode> children = group.children(); children
                        .hasMoreElements();) {
                    ((MutablePair<Integer, String>) children.nextElement().getUserObject())
                            .setLeft(MirthTriStateCheckBox.CHECKED);
                }
            }
            templateContextTreeTable.updateUI();
            setSaveEnabled(true);
        }
    });

    templateContextDeselectAllLabel = new JLabel("<html><u>Deselect All</u></html>");
    templateContextDeselectAllLabel.setForeground(Color.BLUE);
    templateContextDeselectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    templateContextDeselectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            TreeTableNode root = (TreeTableNode) templateContextTreeTable.getTreeTableModel().getRoot();
            for (Enumeration<? extends TreeTableNode> groups = root.children(); groups.hasMoreElements();) {
                TreeTableNode group = groups.nextElement();
                ((MutablePair<Integer, String>) group.getUserObject()).setLeft(MirthTriStateCheckBox.UNCHECKED);
                for (Enumeration<? extends TreeTableNode> children = group.children(); children
                        .hasMoreElements();) {
                    ((MutablePair<Integer, String>) children.nextElement().getUserObject())
                            .setLeft(MirthTriStateCheckBox.UNCHECKED);
                }
            }
            templateContextTreeTable.updateUI();
            setSaveEnabled(true);
        }
    });

    final TableCellEditor contextCellEditor = new ContextTreeTableCellEditor(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            setSaveEnabled(true);
        }
    });

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

    DefaultMutableTreeTableNode rootContextNode = new DefaultMutableTreeTableNode();
    DefaultMutableTreeTableNode globalScriptsNode = new DefaultMutableTreeTableNode(
            new MutablePair<Integer, String>(MirthTriStateCheckBox.CHECKED, "Global Scripts"));
    globalScriptsNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.GLOBAL_DEPLOY)));
    globalScriptsNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.GLOBAL_UNDEPLOY)));
    globalScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.GLOBAL_PREPROCESSOR)));
    globalScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.GLOBAL_POSTPROCESSOR)));
    rootContextNode.add(globalScriptsNode);
    DefaultMutableTreeTableNode channelScriptsNode = new DefaultMutableTreeTableNode(
            new MutablePair<Integer, String>(MirthTriStateCheckBox.CHECKED, "Channel Scripts"));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_DEPLOY)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_UNDEPLOY)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_PREPROCESSOR)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_POSTPROCESSOR)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_ATTACHMENT)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_BATCH)));
    rootContextNode.add(channelScriptsNode);
    DefaultMutableTreeTableNode sourceConnectorNode = new DefaultMutableTreeTableNode(
            new MutablePair<Integer, String>(MirthTriStateCheckBox.CHECKED, "Source Connector"));
    sourceConnectorNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.SOURCE_RECEIVER)));
    sourceConnectorNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.SOURCE_FILTER_TRANSFORMER)));
    rootContextNode.add(sourceConnectorNode);
    DefaultMutableTreeTableNode destinationConnectorNode = new DefaultMutableTreeTableNode(
            new MutablePair<Integer, String>(MirthTriStateCheckBox.CHECKED, "Destination Connector"));
    destinationConnectorNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.DESTINATION_FILTER_TRANSFORMER)));
    destinationConnectorNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.DESTINATION_DISPATCHER)));
    destinationConnectorNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.DESTINATION_RESPONSE_TRANSFORMER)));
    rootContextNode.add(destinationConnectorNode);

    DefaultTreeTableModel contextModel = new SortableTreeTableModel(rootContextNode);
    contextModel.setColumnIdentifiers(Arrays.asList(new String[] { "Context" }));
    templateContextTreeTable.setTreeTableModel(contextModel);

    templateContextTreeTable.setRootVisible(false);
    templateContextTreeTable.setDragEnabled(false);
    templateContextTreeTable.setRowSelectionAllowed(false);
    templateContextTreeTable.setRowHeight(UIConstants.ROW_HEIGHT);
    templateContextTreeTable.setFocusable(false);
    templateContextTreeTable.setOpaque(true);
    templateContextTreeTable.getTableHeader().setReorderingAllowed(false);
    templateContextTreeTable.setEditable(true);
    templateContextTreeTable.setSortable(false);
    templateContextTreeTable.setShowGrid(true, true);

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

    templateContextTreeTable.setTreeCellRenderer(new ContextTreeTableCellRenderer());
    templateContextTreeTable.setOpenIcon(null);
    templateContextTreeTable.setClosedIcon(null);
    templateContextTreeTable.setLeafIcon(null);

    templateContextTreeTable.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 (templateContextTreeTable.rowAtPoint(new Point(evt.getX(), evt.getY())) < 0) {
                templateContextTreeTable.clearSelection();
            }
        }
    });

    templateContextTreeTable.getTreeTableModel().addTreeModelListener(new TreeModelListener() {
        @Override
        public void treeNodesChanged(TreeModelEvent evt) {
            if (ArrayUtils.isNotEmpty(evt.getChildren())) {
                TreeTableNode node = (TreeTableNode) evt.getChildren()[0];

                if (evt.getTreePath().getPathCount() == 2) {
                    boolean allChildren = true;
                    boolean noChildren = true;
                    for (Enumeration<? extends TreeTableNode> children = node.getParent().children(); children
                            .hasMoreElements();) {
                        TreeTableNode child = children.nextElement();
                        if (((Pair<Integer, ContextType>) child.getUserObject())
                                .getLeft() == MirthTriStateCheckBox.UNCHECKED) {
                            allChildren = false;
                        } else {
                            noChildren = false;
                        }
                    }

                    int value;
                    if (allChildren) {
                        value = MirthTriStateCheckBox.CHECKED;
                    } else if (noChildren) {
                        value = MirthTriStateCheckBox.UNCHECKED;
                    } else {
                        value = MirthTriStateCheckBox.PARTIAL;
                    }

                    ((MutablePair<Integer, String>) node.getParent().getUserObject()).setLeft(value);
                } else if (evt.getTreePath().getPathCount() == 1) {
                    int value = ((Pair<Integer, String>) node.getUserObject()).getLeft();

                    for (Enumeration<? extends TreeTableNode> children = node.children(); children
                            .hasMoreElements();) {
                        ((MutablePair<Integer, ContextType>) children.nextElement().getUserObject())
                                .setLeft(value);
                    }
                }
            }
        }

        @Override
        public void treeNodesInserted(TreeModelEvent evt) {
        }

        @Override
        public void treeNodesRemoved(TreeModelEvent evt) {
        }

        @Override
        public void treeStructureChanged(TreeModelEvent evt) {
        }
    });

    templateContextTreeTableScrollPane = new JScrollPane(templateContextTreeTable);
}

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

public boolean doExportChannel() {
    if (isSaveEnabled() && !promptSave(true)) {
        return false;
    }/*  ww w .java  2 s  .  com*/

    if (isGroupSelected()) {
        JOptionPane.showMessageDialog(parent, "This operation can only be performed on channels.");
        return false;
    }

    if (parent.changesHaveBeenMade()) {
        if (parent.alertOption(this,
                "This channel has been modified. You must save the channel changes before you can export. Would you like to save them now?")) {
            if (!parent.channelEditPanel.saveChanges()) {
                return false;
            }
        } else {
            return false;
        }

        parent.setSaveEnabled(false);
    }

    Channel channel;
    if (parent.currentContentPage == parent.channelEditPanel
            || parent.currentContentPage == parent.channelEditPanel.filterPane
            || parent.currentContentPage == parent.channelEditPanel.transformerPane) {
        channel = parent.channelEditPanel.currentChannel;
    } else {
        List<Channel> selectedChannels = getSelectedChannels();
        if (selectedChannels.size() > 1) {
            exportChannels(selectedChannels);
            return true;
        }
        channel = selectedChannels.get(0);
    }

    // Add code template libraries if necessary
    if (channelHasLinkedCodeTemplates(channel)) {
        boolean addLibraries = true;
        String exportChannelCodeTemplateLibraries = Preferences.userNodeForPackage(Mirth.class)
                .get("exportChannelCodeTemplateLibraries", null);

        if (exportChannelCodeTemplateLibraries == null) {
            ExportChannelLibrariesDialog dialog = new ExportChannelLibrariesDialog(channel);
            if (dialog.getResult() == JOptionPane.NO_OPTION) {
                addLibraries = false;
            } else if (dialog.getResult() != JOptionPane.YES_OPTION) {
                return false;
            }
        } else {
            addLibraries = Boolean.parseBoolean(exportChannelCodeTemplateLibraries);
        }

        if (addLibraries) {
            addCodeTemplateLibrariesToChannel(channel);
        }
    }

    addDependenciesToChannel(channel);

    // Update resource names
    parent.updateResourceNames(channel);

    ObjectXMLSerializer serializer = ObjectXMLSerializer.getInstance();
    String channelXML = serializer.serialize(channel);
    // Reset the libraries on the cached channel
    channel.getCodeTemplateLibraries().clear();
    channel.clearDependencies();

    return parent.exportFile(channelXML, channel.getName(), "XML", "Channel");
}

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

private void exportChannels(List<Channel> channelList) {
    if (channelHasLinkedCodeTemplates(channelList)) {
        boolean addLibraries;
        String exportChannelCodeTemplateLibraries = Preferences.userNodeForPackage(Mirth.class)
                .get("exportChannelCodeTemplateLibraries", null);

        if (exportChannelCodeTemplateLibraries == null) {
            JCheckBox alwaysChooseCheckBox = new JCheckBox(
                    "Always choose this option by default in the future (may be changed in the Administrator settings)");
            Object[] params = new Object[] {
                    "<html>One or more channels has code template libraries linked to them.<br/>Do you wish to include these libraries in each respective channel export?</html>",
                    alwaysChooseCheckBox };
            int result = JOptionPane.showConfirmDialog(this, params, "Select an Option",
                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (result == JOptionPane.YES_OPTION || result == JOptionPane.NO_OPTION) {
                addLibraries = result == JOptionPane.YES_OPTION;
                if (alwaysChooseCheckBox.isSelected()) {
                    Preferences.userNodeForPackage(Mirth.class).putBoolean("exportChannelCodeTemplateLibraries",
                            addLibraries);
                }//from  w  ww  .  ja  v a2 s.c o m
            } else {
                return;
            }
        } else {
            addLibraries = Boolean.parseBoolean(exportChannelCodeTemplateLibraries);
        }

        if (addLibraries) {
            for (Channel channel : channelList) {
                addCodeTemplateLibrariesToChannel(channel);
            }
        }
    }

    for (Channel channel : channelList) {
        addDependenciesToChannel(channel);
    }

    JFileChooser exportFileChooser = new JFileChooser();
    exportFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    File currentDir = new File(Frame.userPreferences.get("currentDirectory", ""));
    if (currentDir.exists()) {
        exportFileChooser.setCurrentDirectory(currentDir);
    }

    int returnVal = exportFileChooser.showSaveDialog(this);
    File exportFile = null;
    File exportDirectory = null;
    String exportPath = "/";

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        Frame.userPreferences.put("currentDirectory", exportFileChooser.getCurrentDirectory().getPath());

        int exportCollisionCount = 0;
        exportDirectory = exportFileChooser.getSelectedFile();
        exportPath = exportDirectory.getAbsolutePath();

        for (Channel channel : channelList) {
            exportFile = new File(exportPath + "/" + channel.getName() + ".xml");

            if (exportFile.exists()) {
                exportCollisionCount++;
            }

            // Update resource names
            parent.updateResourceNames(channel);
        }

        try {
            int exportCount = 0;

            boolean overwriteAll = false;
            boolean skipAll = false;
            for (int i = 0, size = channelList.size(); i < size; i++) {
                Channel channel = channelList.get(i);
                exportFile = new File(exportPath + "/" + channel.getName() + ".xml");

                boolean fileExists = exportFile.exists();
                if (fileExists) {
                    if (!overwriteAll && !skipAll) {
                        if (exportCollisionCount == 1) {
                            if (!parent.alertOption(parent, "The file " + channel.getName()
                                    + ".xml already exists.  Would you like to overwrite it?")) {
                                continue;
                            }
                        } else {
                            ConflictOption conflictStatus = parent.alertConflict(parent,
                                    "<html>The file " + channel.getName()
                                            + ".xml already exists.<br>Would you like to overwrite it?</html>",
                                    exportCollisionCount);

                            if (conflictStatus == ConflictOption.YES_APPLY_ALL) {
                                overwriteAll = true;
                            } else if (conflictStatus == ConflictOption.NO) {
                                exportCollisionCount--;
                                continue;
                            } else if (conflictStatus == ConflictOption.NO_APPLY_ALL) {
                                skipAll = true;
                                continue;
                            }
                        }
                    }
                    exportCollisionCount--;
                }

                if (!fileExists || !skipAll) {
                    String channelXML = ObjectXMLSerializer.getInstance().serialize(channel);
                    FileUtils.writeStringToFile(exportFile, channelXML, UIConstants.CHARSET);
                    exportCount++;
                }
            }

            if (exportCount > 0) {
                parent.alertInformation(parent,
                        exportCount + " files were written successfully to " + exportPath + ".");
            }
        } catch (IOException ex) {
            parent.alertError(parent, "File could not be written.");
        }
    }

    // Reset the libraries on the cached channels
    for (Channel channel : channelList) {
        channel.getCodeTemplateLibraries().clear();
        channel.clearDependencies();
    }
}

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

private boolean handleExportGroups(List<ChannelGroup> groups) {
    // Populate list of groups with full channels
    for (ChannelGroup group : groups) {
        List<Channel> channels = new ArrayList<Channel>();
        for (Channel channel : group.getChannels()) {
            ChannelStatus channelStatus = this.channelStatuses.get(channel.getId());
            if (channelStatus != null) {
                channels.add(channelStatus.getChannel());
            }/* ww  w .  j  av a 2 s .co  m*/
        }
        group.setChannels(channels);
    }

    try {
        // Add code template libraries to channels if necessary
        if (groupHasLinkedCodeTemplates(groups)) {
            boolean addLibraries;
            String exportChannelCodeTemplateLibraries = Preferences.userNodeForPackage(Mirth.class)
                    .get("exportChannelCodeTemplateLibraries", null);

            if (exportChannelCodeTemplateLibraries == null) {
                JCheckBox alwaysChooseCheckBox = new JCheckBox(
                        "Always choose this option by default in the future (may be changed in the Administrator settings)");
                Object[] params = new Object[] {
                        "<html>One or more channels has code template libraries linked to them.<br/>Do you wish to include these libraries in each respective channel export?</html>",
                        alwaysChooseCheckBox };
                int result = JOptionPane.showConfirmDialog(this, params, "Select an Option",
                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

                if (result == JOptionPane.YES_OPTION || result == JOptionPane.NO_OPTION) {
                    addLibraries = result == JOptionPane.YES_OPTION;
                    if (alwaysChooseCheckBox.isSelected()) {
                        Preferences.userNodeForPackage(Mirth.class)
                                .putBoolean("exportChannelCodeTemplateLibraries", addLibraries);
                    }
                } else {
                    return false;
                }
            } else {
                addLibraries = Boolean.parseBoolean(exportChannelCodeTemplateLibraries);
            }

            if (addLibraries) {
                for (ChannelGroup group : groups) {
                    for (Channel channel : group.getChannels()) {
                        addCodeTemplateLibrariesToChannel(channel);
                    }
                }
            }
        }

        // Update resource names
        for (ChannelGroup group : groups) {
            for (Channel channel : group.getChannels()) {
                addDependenciesToChannel(channel);
                parent.updateResourceNames(channel);
            }
        }

        if (groups.size() == 1) {
            return exportGroup(groups.iterator().next());
        } else {
            return exportGroups(groups);
        }
    } finally {
        // Reset the libraries on the cached channels
        for (ChannelGroup group : groups) {
            for (Channel channel : group.getChannels()) {
                channel.getCodeTemplateLibraries().clear();
                channel.clearDependencies();
            }
        }
    }
}