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:au.org.ala.delta.intkey.ui.UIUtils.java

/**
 * Save the dataset index to preferences.
 * //from   www .  j  av a  2  s  . c  o m
 * @param datasetIndexList
 *            The dataset index - a list of dataset description, dataset
 *            path value pairs
 */
public static void writeDatasetIndex(List<Pair<String, String>> datasetIndexList) {
    Preferences prefs = Preferences.userNodeForPackage(Intkey.class);

    List<List<String>> listToSerialize = new ArrayList<List<String>>();

    for (Pair<String, String> datasetInfoPair : datasetIndexList) {
        listToSerialize.add(Arrays.asList(datasetInfoPair.getFirst(), datasetInfoPair.getSecond()));
    }

    String jsonList = JSONSerializer.toJSON(listToSerialize).toString();
    prefs.put(DATASET_INDEX_PREF_KEY, jsonList);
    try {
        prefs.sync();
    } catch (BackingStoreException e) {
        throw new RuntimeException(e);
    }
}

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

public void resetSearchCriteria() {
    mirthDatePicker1.setDate(null);//from   w ww. j ava2 s  .c  o  m
    mirthDatePicker2.setDate(null);
    textSearchField.setText("");
    regexTextSearchCheckBox.setSelected(false);
    allDayCheckBox.setSelected(false);
    statusBoxReceived.setSelected(false);
    statusBoxTransformed.setSelected(false);
    statusBoxFiltered.setSelected(false);
    statusBoxQueued.setSelected(false);
    statusBoxSent.setSelected(false);
    statusBoxError.setSelected(false);
    pageSizeField.setText(
            String.valueOf(Preferences.userNodeForPackage(Mirth.class).getInt("messageBrowserPageSize", 20)));

    advancedSearchPopup.resetSelections();
    updateAdvancedSearchButtonFont();
}

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

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

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

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

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

        boolean error = false;
        boolean newlyCreatedFile = false;

        if (selectedFile == null) {

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

        } else {/*from   w w w  .j  av  a2  s  .  c  o m*/

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

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

                    selectedFile.createFile();
                    newlyCreatedFile = true;

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

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

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

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

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

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

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

    return returnVal;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return theFile;
}

From source file:com.mirth.connect.plugins.httpauth.HttpAuthConnectorPropertiesPanel.java

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

    typeLabel = new JLabel("Authentication Type:");
    typeLabel.setHorizontalAlignment(SwingConstants.RIGHT);

    typeComboBox = new MirthComboBox();
    typeComboBox.setModel(new DefaultComboBoxModel<AuthType>(AuthType.values()));
    typeComboBox.addActionListener(new ActionListener() {
        @Override/*from   w w  w  .  j  av a  2s . c o  m*/
        public void actionPerformed(ActionEvent evt) {
            authTypeChanged();
        }
    });
    typeComboBox.setToolTipText("Select the type of HTTP authentication to perform for incoming requests.");

    basicRealmLabel = new JLabel("Realm:");
    basicRealmField = new MirthTextField();
    basicRealmField.setToolTipText("The protection space for this server.");
    basicCredentialsLabel = new JLabel("Credentials:");

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

    basicCredentialsTable = new MirthTable();
    basicCredentialsTable.setModel(new RefreshTableModel(new String[] { "Username", "Password" }, 0));
    basicCredentialsTable.setCustomEditorControls(true);
    basicCredentialsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    basicCredentialsTable.setRowSelectionAllowed(true);
    basicCredentialsTable.setRowHeight(UIConstants.ROW_HEIGHT);
    basicCredentialsTable.setDragEnabled(false);
    basicCredentialsTable.setOpaque(true);
    basicCredentialsTable.setSortable(false);
    basicCredentialsTable.getTableHeader().setReorderingAllowed(false);
    basicCredentialsTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    basicCredentialsTable.setToolTipText(
            "<html>Username and password pairs to authenticate<br/>users with. At least one pair is required.</html>");

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

    CredentialsTableCellEditor basicCredentialsTableCellEditor = new CredentialsTableCellEditor(
            basicCredentialsTable);
    basicCredentialsTable.getColumnExt(0).setCellEditor(basicCredentialsTableCellEditor);
    basicCredentialsTable.getColumnExt(0).setToolTipText("The username to authenticate with.");
    basicCredentialsTable.getColumnExt(1).setCellRenderer(new PasswordCellRenderer());
    basicCredentialsTable.getColumnExt(1).setCellEditor(new DefaultCellEditor(new JPasswordField()));
    basicCredentialsTable.getColumnExt(1).setToolTipText("The password to authenticate with.");

    basicCredentialsTableScrollPane = new JScrollPane(basicCredentialsTable);

    basicCredentialsNewButton = new MirthButton("New");
    basicCredentialsNewButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            int num = 0;
            String username;
            boolean found;
            do {
                num++;
                username = "user" + num;

                found = false;
                for (int row = 0; row < basicCredentialsTable.getModel().getRowCount(); row++) {
                    if (StringUtils.equals(username,
                            (String) basicCredentialsTable.getModel().getValueAt(row, 0))) {
                        found = true;
                    }
                }
            } while (found);

            ((DefaultTableModel) basicCredentialsTable.getModel()).addRow(new String[] { username, "" });
            basicCredentialsTable.setRowSelectionInterval(basicCredentialsTable.getRowCount() - 1,
                    basicCredentialsTable.getRowCount() - 1);
            PlatformUI.MIRTH_FRAME.setSaveEnabled(true);
        }
    });

    basicCredentialsDeleteButton = new MirthButton("Delete");
    basicCredentialsDeleteButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            int selectedRow = getSelectedRow(basicCredentialsTable);
            if (selectedRow >= 0) {
                if (basicCredentialsTable.isEditing()) {
                    basicCredentialsTable.getCellEditor().cancelCellEditing();
                }

                ((DefaultTableModel) basicCredentialsTable.getModel()).removeRow(selectedRow);

                int rowCount = basicCredentialsTable.getRowCount();
                if (selectedRow < rowCount) {
                    basicCredentialsTable.setRowSelectionInterval(selectedRow, selectedRow);
                } else if (rowCount > 0) {
                    basicCredentialsTable.setRowSelectionInterval(rowCount - 1, rowCount - 1);
                }

                PlatformUI.MIRTH_FRAME.setSaveEnabled(true);
            }
        }
    });
    basicCredentialsTableCellEditor.setDeleteButton(basicCredentialsDeleteButton);

    digestRealmLabel = new JLabel("Realm:");
    digestRealmField = new MirthTextField();
    digestRealmField.setToolTipText("The protection space for this server.");

    digestAlgorithmLabel = new JLabel("Algorithms:");
    ButtonGroup digestAlgorithmButtonGroup = new ButtonGroup();
    String toolTipText = "<html>Specifies the digest algorithms supported by this server.<br/><b>&nbsp;- MD5:</b> The security data A1 will contain the username, realm, and password.<br/><b>&nbsp;- MD5-sess:</b> The security data A1 will also contain the server and client nonces.</html>";

    digestAlgorithmMD5Radio = new MirthRadioButton(Algorithm.MD5.toString());
    digestAlgorithmMD5Radio.setBackground(getBackground());
    digestAlgorithmMD5Radio.setToolTipText(toolTipText);
    digestAlgorithmButtonGroup.add(digestAlgorithmMD5Radio);

    digestAlgorithmMD5SessRadio = new MirthRadioButton(Algorithm.MD5_SESS.toString());
    digestAlgorithmMD5SessRadio.setBackground(getBackground());
    digestAlgorithmMD5SessRadio.setToolTipText(toolTipText);
    digestAlgorithmButtonGroup.add(digestAlgorithmMD5SessRadio);

    digestAlgorithmBothRadio = new MirthRadioButton("Both");
    digestAlgorithmBothRadio.setBackground(getBackground());
    digestAlgorithmBothRadio.setToolTipText(toolTipText);
    digestAlgorithmButtonGroup.add(digestAlgorithmBothRadio);

    digestQOPLabel = new JLabel("QOP Modes:");
    toolTipText = "<html>The quality of protection modes to support.<br/><b>&nbsp;- auth:</b> Regular auth with client nonce and count in the digest.<br/><b>&nbsp;- auth-int:</b> Same as auth, but also with message integrity protection enabled.</html>";

    digestQOPAuthCheckBox = new MirthCheckBox(QOPMode.AUTH.toString());
    digestQOPAuthCheckBox.setBackground(getBackground());
    digestQOPAuthCheckBox.setToolTipText(toolTipText);

    digestQOPAuthIntCheckBox = new MirthCheckBox(QOPMode.AUTH_INT.toString());
    digestQOPAuthIntCheckBox.setBackground(getBackground());
    digestQOPAuthIntCheckBox.setToolTipText(toolTipText);

    digestOpaqueLabel = new JLabel("Opaque:");
    digestOpaqueField = new MirthTextField();
    digestOpaqueField.setToolTipText("A string of data that should be returned by the client unchanged.");
    digestCredentialsLabel = new JLabel("Credentials:");

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

    digestCredentialsTable = new MirthTable();
    digestCredentialsTable.setModel(new RefreshTableModel(new String[] { "Username", "Password" }, 0));
    digestCredentialsTable.setCustomEditorControls(true);
    digestCredentialsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    digestCredentialsTable.setRowSelectionAllowed(true);
    digestCredentialsTable.setRowHeight(UIConstants.ROW_HEIGHT);
    digestCredentialsTable.setDragEnabled(false);
    digestCredentialsTable.setOpaque(true);
    digestCredentialsTable.setSortable(false);
    digestCredentialsTable.getTableHeader().setReorderingAllowed(false);
    digestCredentialsTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    digestCredentialsTable.setToolTipText(
            "<html>Username and password pairs to authenticate<br/>users with. At least one pair is required.</html>");

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

    CredentialsTableCellEditor digestCredentialsTableCellEditor = new CredentialsTableCellEditor(
            digestCredentialsTable);
    digestCredentialsTable.getColumnExt(0).setCellEditor(digestCredentialsTableCellEditor);
    digestCredentialsTable.getColumnExt(0).setToolTipText("The username to authenticate with.");
    digestCredentialsTable.getColumnExt(1).setCellRenderer(new PasswordCellRenderer());
    digestCredentialsTable.getColumnExt(1).setCellEditor(new DefaultCellEditor(new JPasswordField()));
    digestCredentialsTable.getColumnExt(1).setToolTipText("The password to authenticate with.");

    digestCredentialsTableScrollPane = new JScrollPane(digestCredentialsTable);

    digestCredentialsNewButton = new MirthButton("New");
    digestCredentialsNewButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            int num = 0;
            String username;
            boolean found;
            do {
                num++;
                username = "user" + num;

                found = false;
                for (int row = 0; row < digestCredentialsTable.getModel().getRowCount(); row++) {
                    if (StringUtils.equals(username,
                            (String) digestCredentialsTable.getModel().getValueAt(row, 0))) {
                        found = true;
                    }
                }
            } while (found);

            ((DefaultTableModel) digestCredentialsTable.getModel()).addRow(new String[] { username, "" });
            digestCredentialsTable.setRowSelectionInterval(digestCredentialsTable.getRowCount() - 1,
                    digestCredentialsTable.getRowCount() - 1);
            PlatformUI.MIRTH_FRAME.setSaveEnabled(true);
        }
    });

    digestCredentialsDeleteButton = new MirthButton("Delete");
    digestCredentialsDeleteButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            int selectedRow = getSelectedRow(digestCredentialsTable);
            if (selectedRow >= 0) {
                if (digestCredentialsTable.isEditing()) {
                    digestCredentialsTable.getCellEditor().cancelCellEditing();
                }

                ((DefaultTableModel) digestCredentialsTable.getModel()).removeRow(selectedRow);

                int rowCount = digestCredentialsTable.getRowCount();
                if (selectedRow < rowCount) {
                    digestCredentialsTable.setRowSelectionInterval(selectedRow, selectedRow);
                } else if (rowCount > 0) {
                    digestCredentialsTable.setRowSelectionInterval(rowCount - 1, rowCount - 1);
                }

                PlatformUI.MIRTH_FRAME.setSaveEnabled(true);
            }
        }
    });
    digestCredentialsTableCellEditor.setDeleteButton(digestCredentialsDeleteButton);

    jsScriptLabel = new JLabel("Script:");
    jsScriptField = new JTextField();
    jsScriptField.setEditable(false);
    jsScriptField.setBackground(getBackground());
    jsScriptField.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    jsScriptField.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent evt) {
            JavaScriptHttpAuthDialog dialog = new JavaScriptHttpAuthDialog(PlatformUI.MIRTH_FRAME, jsScript);
            if (dialog.wasSaved()) {
                PlatformUI.MIRTH_FRAME.setSaveEnabled(true);
                jsScript = dialog.getScript();
                updateJSScriptField();
            }
        }
    });
    jsScriptField.setToolTipText(
            "<html>Click here to open the JavaScript editor dialog.<br/>The return value of this script is used to accept or reject requests.</html>");

    customClassNameLabel = new JLabel("Class Name:");
    customClassNameField = new MirthTextField();
    customClassNameField
            .setToolTipText("The fully-qualified Java class name of the Authenticator class to use.");
    customPropertiesLabel = new JLabel("Properties:");

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

    customPropertiesTable = new MirthTable();
    customPropertiesTable.setModel(new RefreshTableModel(new String[] { "Name", "Value" }, 0));
    customPropertiesTable.setCustomEditorControls(true);
    customPropertiesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    customPropertiesTable.setRowSelectionAllowed(true);
    customPropertiesTable.setRowHeight(UIConstants.ROW_HEIGHT);
    customPropertiesTable.setDragEnabled(false);
    customPropertiesTable.setOpaque(true);
    customPropertiesTable.setSortable(false);
    customPropertiesTable.getTableHeader().setReorderingAllowed(false);
    customPropertiesTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    customPropertiesTable.setToolTipText(
            "Optional properties to pass into the Authenticator class when it is instantiated.");

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

    CredentialsTableCellEditor customPropertiesTableCellEditor = new CredentialsTableCellEditor(
            customPropertiesTable);
    customPropertiesTable.getColumnExt(0).setCellEditor(customPropertiesTableCellEditor);
    customPropertiesTable.getColumnExt(0).setToolTipText("The name of the property to include.");
    customPropertiesTable.getColumnExt(1).setToolTipText("The value of the property to include.");

    customPropertiesTableScrollPane = new JScrollPane(customPropertiesTable);

    customPropertiesNewButton = new MirthButton("New");
    customPropertiesNewButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            int num = 0;
            String name;
            boolean found;
            do {
                num++;
                name = "Property " + num;

                found = false;
                for (int row = 0; row < customPropertiesTable.getModel().getRowCount(); row++) {
                    if (StringUtils.equals(name,
                            (String) customPropertiesTable.getModel().getValueAt(row, 0))) {
                        found = true;
                    }
                }
            } while (found);

            ((DefaultTableModel) customPropertiesTable.getModel()).addRow(new String[] { name, "" });
            customPropertiesTable.setRowSelectionInterval(customPropertiesTable.getRowCount() - 1,
                    customPropertiesTable.getRowCount() - 1);
            PlatformUI.MIRTH_FRAME.setSaveEnabled(true);
        }
    });

    customPropertiesDeleteButton = new MirthButton("Delete");
    customPropertiesDeleteButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            int selectedRow = getSelectedRow(customPropertiesTable);
            if (selectedRow >= 0) {
                if (customPropertiesTable.isEditing()) {
                    customPropertiesTable.getCellEditor().cancelCellEditing();
                }

                ((DefaultTableModel) customPropertiesTable.getModel()).removeRow(selectedRow);

                int rowCount = customPropertiesTable.getRowCount();
                if (selectedRow < rowCount) {
                    customPropertiesTable.setRowSelectionInterval(selectedRow, selectedRow);
                } else if (rowCount > 0) {
                    customPropertiesTable.setRowSelectionInterval(rowCount - 1, rowCount - 1);
                }

                PlatformUI.MIRTH_FRAME.setSaveEnabled(true);
            }
        }
    });
    customPropertiesTableCellEditor.setDeleteButton(customPropertiesDeleteButton);

    oauth2TokenLabel = new JLabel("Access Token Location:");

    oauth2TokenLocationComboBox = new MirthComboBox();
    oauth2TokenLocationComboBox.setModel(new DefaultComboBoxModel<TokenLocation>(TokenLocation.values()));
    oauth2TokenLocationComboBox
            .setToolTipText("Determines where the access token is located in client requests.");

    oauth2TokenField = new MirthTextField();
    oauth2TokenField
            .setToolTipText("The header or query parameter to pass along with the verification request.");

    oauth2VerificationURLLabel = new JLabel("Verification URL:");
    oauth2VerificationURLField = new MirthTextField();
    oauth2VerificationURLField.setToolTipText(
            "<html>The HTTP URL to perform a GET request to for access<br/>token verification. If the response code is >= 400,<br/>the authentication attempt is rejected by the server.</html>");

    for (ConnectorPropertiesPlugin connectorPropertiesPlugin : LoadedExtensions.getInstance()
            .getConnectorPropertiesPlugins().values()) {
        if (connectorPropertiesPlugin
                .isConnectorPropertiesPluginSupported(HttpAuthConnectorPluginProperties.PLUGIN_POINT)) {
            connectorPropertiesPanel = connectorPropertiesPlugin.getConnectorPropertiesPanel();
        }
    }
}

From source file:com.mirth.connect.connectors.http.HttpSender.java

public void setHeaders(Map<String, List<String>> properties) {
    int size = 0;
    for (List<String> property : properties.values()) {
        size += property.size();//from   w  w  w  .  ja v  a 2 s  . c  om
    }

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

    headersTable = new MirthTable();

    int j = 0;
    Iterator i = properties.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry entry = (Map.Entry) i.next();
        for (String keyValue : (List<String>) entry.getValue()) {
            tableData[j][NAME_COLUMN] = (String) entry.getKey();
            tableData[j][VALUE_COLUMN] = keyValue;
            j++;
        }
    }

    headersTable.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];
        }
    });

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

        public void valueChanged(ListSelectionEvent evt) {
            if (getSelectedRow(headersTable) != -1) {
                headerLastIndex = getSelectedRow(headersTable);
                headersDeleteButton.setEnabled(true);
            } else {
                headersDeleteButton.setEnabled(false);
            }
        }
    });

    class HTTPTableCellEditor extends TextFieldCellEditor {
        boolean checkProperties;

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

        public boolean checkUniqueProperty(String property) {
            boolean exists = false;

            for (int i = 0; i < headersTable.getRowCount(); i++) {
                if (headersTable.getValueAt(i, NAME_COLUMN) != null
                        && ((String) headersTable.getValueAt(i, NAME_COLUMN)).equalsIgnoreCase(property)) {
                    exists = true;
                }
            }

            return exists;
        }

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

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

            return editable;
        }

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

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

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

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

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

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

    headersPane.setViewportView(headersTable);
}

From source file:com.moteiv.trawler.Trawler.java

private void savePrefs() {
    Preferences prefs = Preferences.userNodeForPackage(com.moteiv.trawler.Trawler.class);
    prefs.putBoolean(PREF_V_SAVE, vSave.isSelected());
    prefs.putBoolean(PREF_V_BLINK, vBlink.isSelected());
    prefs.putBoolean(PREF_V_LABELS, vLabels.isSelected());
    prefs.putBoolean(PREF_E_LABELS, eLabels.isSelected());
    prefs.putBoolean(PREF_E_FILTER, eFilter.isSelected());
    prefs.putInt(PREF_V_DISPOSE, vDispose.getValue());
    prefs.putInt(PREF_E_DISPOSE, eDispose.getValue());
}

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

public ChannelPanel() {
    this.parent = PlatformUI.MIRTH_FRAME;
    initComponents();//from www  . j a  va 2  s.  com
    initLayout();

    channelTasks = new JXTaskPane();
    channelTasks.setTitle("Channel Tasks");
    channelTasks.setName(TaskConstants.CHANNEL_KEY);
    channelTasks.setFocusable(false);

    channelPopupMenu = new JPopupMenu();
    channelTable.setComponentPopupMenu(channelPopupMenu);

    parent.addTask(TaskConstants.CHANNEL_REFRESH, "Refresh", "Refresh the list of channels.", "",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/arrow_refresh.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_REDEPLOY_ALL, "Redeploy All",
            "Undeploy all channels and deploy all currently enabled channels.", "A",
            new ImageIcon(
                    com.mirth.connect.client.ui.Frame.class.getResource("images/arrow_rotate_clockwise.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_DEPLOY, "Deploy Channel", "Deploys the currently selected channel.",
            "", new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/arrow_redo.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_EDIT_GLOBAL_SCRIPTS, "Edit Global Scripts",
            "Edit scripts that are not channel specific.", "G",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/script_edit.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_EDIT_CODE_TEMPLATES, "Edit Code Templates",
            "Create and manage templates to be used in JavaScript throughout Mirth.", "",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/page_edit.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_NEW_CHANNEL, "New Channel", "Create a new channel.", "N",
            new ImageIcon(
                    com.mirth.connect.client.ui.Frame.class.getResource("images/application_form_add.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_IMPORT_CHANNEL, "Import Channel", "Import a channel from an XML file.",
            "", new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/report_go.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_EXPORT_ALL_CHANNELS, "Export All Channels",
            "Export all of the channels to XML files.", "",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/report_disk.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_EXPORT_CHANNEL, "Export Channel",
            "Export the currently selected channel to an XML file.", "",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/report_disk.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_DELETE_CHANNEL, "Delete Channel",
            "Delete the currently selected channel.", "L",
            new ImageIcon(
                    com.mirth.connect.client.ui.Frame.class.getResource("images/application_form_delete.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_CLONE, "Clone Channel", "Clone the currently selected channel.", "",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/page_copy.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_EDIT, "Edit Channel", "Edit the currently selected channel.", "I",
            new ImageIcon(
                    com.mirth.connect.client.ui.Frame.class.getResource("images/application_form_edit.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_ENABLE, "Enable Channel", "Enable the currently selected channel.", "",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/control_play_blue.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_DISABLE, "Disable Channel", "Disable the currently selected channel.",
            "",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/control_stop_blue.png")),
            channelTasks, channelPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_VIEW_MESSAGES, "View Messages",
            "Show the messages for the currently selected channel.", "",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/page_white_stack.png")),
            channelTasks, channelPopupMenu, this);

    parent.setNonFocusable(channelTasks);
    parent.taskPaneContainer.add(channelTasks, parent.taskPaneContainer.getComponentCount() - 1);

    groupTasks = new JXTaskPane();
    groupTasks.setTitle("Group Tasks");
    groupTasks.setName(TaskConstants.CHANNEL_GROUP_KEY);
    groupTasks.setFocusable(false);

    groupPopupMenu = new JPopupMenu();

    parent.addTask(TaskConstants.CHANNEL_GROUP_SAVE, "Save Group Changes",
            "Save all changes made to channel groups.", "",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/disk.png")), groupTasks,
            groupPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_GROUP_ASSIGN_CHANNEL, "Assign To Group",
            "Assign channel(s) to a group.", "A",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/report_go.png")),
            groupTasks, groupPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_GROUP_NEW_GROUP, "New Group", "Create a new channel group.", "N",
            new ImageIcon(
                    com.mirth.connect.client.ui.Frame.class.getResource("images/application_form_add.png")),
            groupTasks, groupPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_GROUP_EDIT_DETAILS, "Edit Group Details",
            "Edit group name and description.", "E",
            new ImageIcon(
                    com.mirth.connect.client.ui.Frame.class.getResource("images/application_form_edit.png")),
            groupTasks, groupPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_GROUP_EXPORT_ALL_GROUPS, "Export All Groups",
            "Export all of the channel groups to XML files.", "",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/report_disk.png")),
            groupTasks, groupPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_GROUP_IMPORT_GROUP, "Import Group",
            "Import a channel group from an XML file.", "",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/report_go.png")),
            groupTasks, groupPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_GROUP_EXPORT_GROUP, "Export Group",
            "Export the currently selected channel group to an XML file.", "",
            new ImageIcon(com.mirth.connect.client.ui.Frame.class.getResource("images/report_disk.png")),
            groupTasks, groupPopupMenu, this);
    parent.addTask(TaskConstants.CHANNEL_GROUP_DELETE_GROUP, "Delete Group",
            "Delete the currently selected channel group.", "L",
            new ImageIcon(
                    com.mirth.connect.client.ui.Frame.class.getResource("images/application_form_delete.png")),
            groupTasks, groupPopupMenu, this);

    parent.setNonFocusable(groupTasks);
    parent.taskPaneContainer.add(groupTasks, parent.taskPaneContainer.getComponentCount() - 1);

    channelScrollPane.setComponentPopupMenu(channelPopupMenu);

    ChannelTreeTableModel model = (ChannelTreeTableModel) channelTable.getTreeTableModel();

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("channelGroupViewEnabled", true)) {
        tableModeGroupsButton.setSelected(true);
        tableModeGroupsButton.setContentFilled(true);
        tableModeChannelsButton.setContentFilled(false);
        model.setGroupModeEnabled(true);
    } else {
        tableModeChannelsButton.setSelected(true);
        tableModeChannelsButton.setContentFilled(true);
        tableModeGroupsButton.setContentFilled(false);
        model.setGroupModeEnabled(false);
    }

    updateModel(new TableState(new ArrayList<String>(), null));
    updateTasks();
}

From source file:com.mirth.connect.connectors.http.HttpListener.java

private void initComponentsManual() {
    staticResourcesTable.setModel(new RefreshTableModel(StaticResourcesColumn.getNames(), 0) {
        @Override/* w  ww  . j a v a 2  s.  c om*/
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return true;
        }
    });

    staticResourcesTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    staticResourcesTable.setRowHeight(UIConstants.ROW_HEIGHT);
    staticResourcesTable.setFocusable(true);
    staticResourcesTable.setSortable(false);
    staticResourcesTable.setOpaque(true);
    staticResourcesTable.setDragEnabled(false);
    staticResourcesTable.getTableHeader().setReorderingAllowed(false);
    staticResourcesTable.setShowGrid(true, true);
    staticResourcesTable.setAutoCreateColumnsFromModel(false);
    staticResourcesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    staticResourcesTable.setRowSelectionAllowed(true);
    staticResourcesTable.setCustomEditorControls(true);

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

    class ContextPathCellEditor extends TextFieldCellEditor {
        public ContextPathCellEditor() {
            getTextField().setDocument(new MirthFieldConstraints("^\\S*$"));
        }

        @Override
        protected boolean valueChanged(String value) {
            if (StringUtils.isEmpty(value) || value.equals("/")) {
                return false;
            }

            if (value.equals(getOriginalValue())) {
                return false;
            }

            for (int i = 0; i < staticResourcesTable.getRowCount(); i++) {
                if (value.equals(fixContentPath((String) staticResourcesTable.getValueAt(i,
                        StaticResourcesColumn.CONTEXT_PATH.getIndex())))) {
                    return false;
                }
            }

            parent.setSaveEnabled(true);
            return true;
        }

        @Override
        public Object getCellEditorValue() {
            String value = fixContentPath((String) super.getCellEditorValue());
            String baseContextPath = getBaseContextPath();
            if (value.equals(baseContextPath)) {
                return null;
            } else {
                return fixContentPath(StringUtils.removeStartIgnoreCase(value, baseContextPath + "/"));
            }
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
                int column) {
            String resourceContextPath = fixContentPath((String) value);
            setOriginalValue(resourceContextPath);
            getTextField().setText(getBaseContextPath() + resourceContextPath);
            return getTextField();
        }
    }
    ;

    staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTEXT_PATH.getIndex())
            .setCellEditor(new ContextPathCellEditor());
    staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTEXT_PATH.getIndex())
            .setCellRenderer(new DefaultTableCellRenderer() {
                @Override
                protected void setValue(Object value) {
                    super.setValue(getBaseContextPath() + fixContentPath((String) value));
                }
            });

    class ResourceTypeCellEditor extends MirthComboBoxTableCellEditor implements ActionListener {
        private Object originalValue;

        public ResourceTypeCellEditor(JTable table, Object[] items, int clickCount, boolean focusable) {
            super(table, items, clickCount, focusable, null);
            for (ActionListener actionListener : comboBox.getActionListeners()) {
                comboBox.removeActionListener(actionListener);
            }
            comboBox.addActionListener(this);
        }

        @Override
        public boolean stopCellEditing() {
            if (ObjectUtils.equals(getCellEditorValue(), originalValue)) {
                cancelCellEditing();
            } else {
                parent.setSaveEnabled(true);
            }
            return super.stopCellEditing();
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
                int column) {
            originalValue = value;
            return super.getTableCellEditorComponent(table, value, isSelected, row, column);
        }

        @Override
        public void actionPerformed(ActionEvent evt) {
            ((AbstractTableModel) staticResourcesTable.getModel()).fireTableCellUpdated(
                    staticResourcesTable.getSelectedRow(), StaticResourcesColumn.VALUE.getIndex());
            stopCellEditing();
            fireEditingStopped();
        }
    }

    String[] resourceTypes = ResourceType.stringValues();
    staticResourcesTable.getColumnExt(StaticResourcesColumn.RESOURCE_TYPE.getIndex()).setMinWidth(100);
    staticResourcesTable.getColumnExt(StaticResourcesColumn.RESOURCE_TYPE.getIndex()).setMaxWidth(100);
    staticResourcesTable.getColumnExt(StaticResourcesColumn.RESOURCE_TYPE.getIndex())
            .setCellEditor(new ResourceTypeCellEditor(staticResourcesTable, resourceTypes, 1, false));
    staticResourcesTable.getColumnExt(StaticResourcesColumn.RESOURCE_TYPE.getIndex())
            .setCellRenderer(new MirthComboBoxTableCellRenderer(resourceTypes));

    class ValueCellEditor extends AbstractCellEditor implements TableCellEditor {

        private JPanel panel;
        private JLabel label;
        private JTextField textField;
        private String text;
        private String originalValue;

        public ValueCellEditor() {
            panel = new JPanel(new MigLayout("insets 0 1 0 0, novisualpadding, hidemode 3"));
            panel.setBackground(UIConstants.BACKGROUND_COLOR);

            label = new JLabel();
            label.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseReleased(MouseEvent evt) {
                    new ValueDialog();
                    stopCellEditing();
                }
            });
            panel.add(label, "grow, pushx, h 19!");

            textField = new JTextField();
            panel.add(textField, "grow, pushx, h 19!");
        }

        @Override
        public boolean isCellEditable(EventObject evt) {
            if (evt == null) {
                return false;
            }
            if (evt instanceof MouseEvent) {
                return ((MouseEvent) evt).getClickCount() >= 2;
            }
            return true;
        }

        @Override
        public Object getCellEditorValue() {
            if (label.isVisible()) {
                return text;
            } else {
                return textField.getText();
            }
        }

        @Override
        public boolean stopCellEditing() {
            if (ObjectUtils.equals(getCellEditorValue(), originalValue)) {
                cancelCellEditing();
            } else {
                parent.setSaveEnabled(true);
            }
            return super.stopCellEditing();
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
                int column) {
            boolean custom = table.getValueAt(row, StaticResourcesColumn.RESOURCE_TYPE.getIndex())
                    .equals(ResourceType.CUSTOM.toString());
            label.setVisible(custom);
            textField.setVisible(!custom);

            panel.setBackground(table.getSelectionBackground());
            label.setBackground(panel.getBackground());
            label.setMaximumSize(new Dimension(table.getColumnModel().getColumn(column).getWidth(), 19));

            String text = (String) value;
            this.text = text;
            originalValue = text;
            label.setText(text);
            textField.setText(text);

            return panel;
        }

        class ValueDialog extends MirthDialog {

            public ValueDialog() {
                super(parent, true);
                setTitle("Custom Value");
                setPreferredSize(new Dimension(600, 500));
                setLayout(new MigLayout("insets 12, novisualpadding, hidemode 3, fill", "", "[grow]7[]"));
                setBackground(UIConstants.BACKGROUND_COLOR);
                getContentPane().setBackground(getBackground());

                final MirthSyntaxTextArea textArea = new MirthSyntaxTextArea();
                textArea.setSaveEnabled(false);
                textArea.setText(text);
                textArea.setBorder(BorderFactory.createEtchedBorder());
                add(textArea, "grow");

                add(new JSeparator(), "newline, grow");

                JPanel buttonPanel = new JPanel(new MigLayout("insets 0, novisualpadding, hidemode 3"));
                buttonPanel.setBackground(getBackground());

                JButton openFileButton = new JButton("Open File...");
                openFileButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        String content = parent.browseForFileString(null);
                        if (content != null) {
                            textArea.setText(content);
                        }
                    }
                });
                buttonPanel.add(openFileButton);

                JButton okButton = new JButton("OK");
                okButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent evt) {
                        text = textArea.getText();
                        label.setText(text);
                        textField.setText(text);
                        staticResourcesTable.getModel().setValueAt(text, staticResourcesTable.getSelectedRow(),
                                StaticResourcesColumn.VALUE.getIndex());
                        parent.setSaveEnabled(true);
                        dispose();
                    }
                });
                buttonPanel.add(okButton);

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

                add(buttonPanel, "newline, right");

                pack();
                setLocationRelativeTo(parent);
                setVisible(true);
            }
        }
    }
    ;

    staticResourcesTable.getColumnExt(StaticResourcesColumn.VALUE.getIndex())
            .setCellEditor(new ValueCellEditor());

    staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTENT_TYPE.getIndex()).setMinWidth(100);
    staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTENT_TYPE.getIndex()).setMaxWidth(150);
    staticResourcesTable.getColumnExt(StaticResourcesColumn.CONTENT_TYPE.getIndex())
            .setCellEditor(new TextFieldCellEditor() {
                @Override
                protected boolean valueChanged(String value) {
                    if (value.equals(getOriginalValue())) {
                        return false;
                    }
                    parent.setSaveEnabled(true);
                    return true;
                }
            });

    staticResourcesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent evt) {
            if (getSelectedRow(staticResourcesTable) != -1) {
                staticResourcesLastIndex = getSelectedRow(staticResourcesTable);
                staticResourcesDeleteButton.setEnabled(true);
            } else {
                staticResourcesDeleteButton.setEnabled(false);
            }
        }
    });

    contextPathField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent evt) {
            changedUpdate(evt);
        }

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

        @Override
        public void changedUpdate(DocumentEvent evt) {
            ((AbstractTableModel) staticResourcesTable.getModel()).fireTableDataChanged();
        }
    });

    staticResourcesDeleteButton.setEnabled(false);
}

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

public static void setPreferredLookAndFeel(String lookAndFeelName) {
    Preferences prefs = Preferences.userNodeForPackage(Intkey.class);
    if (prefs != null) {
        prefs.put(LOOK_AND_FEEL_KEY, lookAndFeelName);
        try {//from   w  w  w .  j a v a2s . c om
            prefs.sync();
        } catch (BackingStoreException e) {
            throw new RuntimeException(e);
        }
    }
}