Search in sources :

Example 1 with InputVerifier

use of javax.swing.InputVerifier in project vcell by virtualcell.

the class OutputOptionsPanel method setSolverTaskDescription.

/**
 * set solver description. The contained {@link SolverTaskDescription#getSimulation()}
 * is usually a temporary cloned object with  a null {@link SimulationOwner}  ; therefore
 * we required the {@link UnitInfo} of the actual {@link Simulation} owner as a parameter
 * @param newValue
 * @param unitInfo not null
 */
public final void setSolverTaskDescription(SolverTaskDescription newValue, UnitInfo unitInfo) {
    Objects.requireNonNull(unitInfo);
    SolverTaskDescription oldValue = solverTaskDescription;
    /* Stop listening for events from the current object */
    if (oldValue != null) {
        oldValue.removePropertyChangeListener(ivjEventHandler);
    }
    solverTaskDescription = newValue;
    /* Listen for events from the new object */
    if (newValue != null) {
        newValue.addPropertyChangeListener(ivjEventHandler);
    }
    solverTaskDescription = newValue;
    chomboOutputOptionsPanel.setSolverTaskDescription(solverTaskDescription);
    firePropertyChange("solverTaskDescription", oldValue, newValue);
    getOutputTimeStepTextField().addFocusListener(ivjEventHandler);
    getDefaultOutputRadioButton().addActionListener(ivjEventHandler);
    getUniformOutputRadioButton().addActionListener(ivjEventHandler);
    getExplicitOutputRadioButton().addActionListener(ivjEventHandler);
    getKeepEveryTextField().addFocusListener(ivjEventHandler);
    getKeepAtMostTextField().addFocusListener(ivjEventHandler);
    getOutputTimesTextField().addFocusListener(ivjEventHandler);
    getOutputTimeStepTextField().setInputVerifier(new InputVerifier() {

        @Override
        public boolean verify(JComponent input) {
            return false;
        }

        @Override
        public boolean shouldYieldFocus(JComponent input) {
            boolean bValid = true;
            try {
                double outputTime = Double.parseDouble(getOutputTimeStepTextField().getText());
                if (solverTaskDescription.getOutputTimeSpec().isUniform() && !solverTaskDescription.getSolverDescription().hasVariableTimestep()) {
                    double timeStep = solverTaskDescription.getTimeStep().getDefaultTimeStep();
                    double suggestedInterval = outputTime;
                    if (outputTime < timeStep) {
                        suggestedInterval = timeStep;
                        bValid = false;
                    } else if (!BeanUtils.isIntegerMultiple(outputTime, timeStep)) {
                        double n = outputTime / timeStep;
                        int intn = (int) Math.round(n);
                        if (intn != n) {
                            bValid = false;
                            suggestedInterval = (intn * timeStep);
                        }
                    }
                    if (!bValid) {
                        String ret = PopupGenerator.showWarningDialog(OutputOptionsPanel.this, "Output Interval", "Output Interval must " + "be integer multiple of time step.\n\nChange Output Interval to " + suggestedInterval + "?", new String[] { UserMessage.OPTION_YES, UserMessage.OPTION_NO }, UserMessage.OPTION_YES);
                        if (ret.equals(UserMessage.OPTION_YES)) {
                            getOutputTimeStepTextField().setText(suggestedInterval + "");
                            bValid = true;
                        }
                    }
                }
            } catch (NumberFormatException ex) {
                DialogUtils.showErrorDialog(OutputOptionsPanel.this, "Wrong number format " + ex.getMessage().toLowerCase());
                bValid = false;
            }
            if (bValid) {
                getOutputTimeStepTextField().setBorder(UIManager.getBorder("TextField.border"));
            } else {
                getOutputTimeStepTextField().setBorder(GuiConstants.ProblematicTextFieldBorder);
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        getOutputTimeStepTextField().requestFocus();
                    }
                });
            }
            return bValid;
        }
    });
    getOutputTimesTextField().setInputVerifier(new InputVerifier() {

        @Override
        public boolean verify(JComponent input) {
            return false;
        }

        @Override
        public boolean shouldYieldFocus(JComponent input) {
            ExplicitOutputTimeSpec eots = ExplicitOutputTimeSpec.fromString(getOutputTimesTextField().getText());
            return checkExplicitOutputTimes(eots);
        }
    });
    // set time label units
    JLabel timeUnitsLabel = getTimeStepUnitsLabel();
    timeUnitsLabel.setText(unitInfo.getTimeUnitString());
}
Also used : ExplicitOutputTimeSpec(cbit.vcell.solver.ExplicitOutputTimeSpec) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) InputVerifier(javax.swing.InputVerifier)

Example 2 with InputVerifier

use of javax.swing.InputVerifier in project vcell by virtualcell.

the class MeshSpecificationPanel method initConnections.

/**
 * Initializes connections
 * @exception java.lang.Exception The exception description.
 */
private void initConnections() {
    // user code begin {1}
    // user code end
    getXTextField().addFocusListener(ivjEventHandler);
    getYTextField().addFocusListener(ivjEventHandler);
    getZTextField().addFocusListener(ivjEventHandler);
    getXTextField().getDocument().addDocumentListener(ivjEventHandler);
    getYTextField().getDocument().addDocumentListener(ivjEventHandler);
    getZTextField().getDocument().addDocumentListener(ivjEventHandler);
    getAutoMeshSizeCheckBox().addItemListener(ivjEventHandler);
    InputVerifier iv = new InputVerifier() {

        @Override
        public boolean verify(JComponent input) {
            return false;
        }

        @Override
        public boolean shouldYieldFocus(final JComponent input) {
            boolean bValid = true;
            JTextField jtf = (JTextField) input;
            try {
                Integer.parseInt(jtf.getText());
            } catch (NumberFormatException ex) {
                DialogUtils.showErrorDialog(MeshSpecificationPanel.this, "Wrong number format " + ex.getMessage().toLowerCase());
                bValid = false;
            }
            if (bValid) {
                input.setBorder(UIManager.getBorder("TextField.border"));
            } else {
                input.setBorder(GuiConstants.ProblematicTextFieldBorder);
                SwingUtilities.invokeLater(new Runnable() {

                    public void run() {
                        input.requestFocusInWindow();
                    }
                });
            }
            return bValid;
        }
    };
    getXTextField().setInputVerifier(iv);
    getYTextField().setInputVerifier(iv);
    getZTextField().setInputVerifier(iv);
}
Also used : JComponent(javax.swing.JComponent) JTextField(javax.swing.JTextField) InputVerifier(javax.swing.InputVerifier)

Example 3 with InputVerifier

use of javax.swing.InputVerifier in project CCDD by nasa.

the class CcddRateParameterDialog method addStreamTabs.

/**
 ********************************************************************************************
 * Create the tabs for the stream specific input fields
 *
 * @param rateInfo
 *            list containing the rate information
 ********************************************************************************************
 */
private void addStreamTabs(List<RateInformation> rateInfo) {
    // Step through each stream
    for (int index = 0; index < rateInfo.size(); index++) {
        // Set the initial layout manager characteristics
        GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2), 0, 0);
        // Create a panel for the rate calculation button and results
        JPanel availRatesPnl = new JPanel(new GridBagLayout());
        availRatesPnl.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
        JLabel availRatesLbl = new JLabel("Available rates");
        availRatesLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
        availRatesLbl.setForeground(ModifiableColorInfo.SPECIAL_LABEL_TEXT.getColor());
        availRatesPnl.add(availRatesLbl, gbc);
        // Create the available rates field and add it to the rates panel
        availRatesFld[index] = new JTextArea("", 3, 1);
        availRatesFld[index].setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
        availRatesFld[index].setEditable(false);
        availRatesFld[index].setWrapStyleWord(true);
        availRatesFld[index].setLineWrap(true);
        availRatesFld[index].setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
        availRatesFld[index].setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
        availRatesFld[index].setBorder(emptyBorder);
        JScrollPane scrollPane = new JScrollPane(availRatesFld[index]);
        scrollPane.setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
        scrollPane.setBorder(emptyBorder);
        scrollPane.setViewportBorder(border);
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.weightx = 1.0;
        gbc.gridx++;
        availRatesPnl.add(scrollPane, gbc);
        // Create a panel to contain the stream's text fields
        JPanel streamPnl = new JPanel(new GridBagLayout());
        JLabel streamNameLbl = new JLabel("Data stream name");
        streamNameLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
        gbc.insets.top = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing();
        gbc.insets.bottom = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing();
        gbc.gridwidth = 1;
        gbc.gridx = 0;
        streamPnl.add(streamNameLbl, gbc);
        // Create the data stream name input field
        streamNameFld[index] = new JTextField(String.valueOf(rateInfo.get(index).getStreamName()), 7);
        streamNameFld[index].setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
        streamNameFld[index].setEditable(true);
        streamNameFld[index].setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
        streamNameFld[index].setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
        streamNameFld[index].setBorder(border);
        // Get the initial field value
        final String initStreamName = streamNameFld[index].getText();
        // Set the field's input verifier
        streamNameFld[index].setInputVerifier(new InputVerifier() {

            // Storage for the last valid value entered; used to restore the input field value
            // if an invalid value is entered. Initialize to the value at the time the field is
            // created
            String lastValid = initStreamName;

            /**
             ********************************************************************************
             * Verify the contents of the input field
             ********************************************************************************
             */
            @Override
            public boolean verify(JComponent input) {
                JTextField field = (JTextField) input;
                // Remove any leading and trailing white space characters
                field.setText(field.getText().trim());
                // Assume the dialog input is valid
                boolean isValid = true;
                // Check if a matching stream name is found for a rate other than this one
                if (rateHandler.getRateInformationIndexByStreamName(field.getText()) != tabbedPane.getSelectedIndex()) {
                    // Inform the user that a stream name is duplicated
                    new CcddDialogHandler().showMessageDialog(CcddRateParameterDialog.this, "<html><b>Duplicate stream name", "Missing/Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                    // Restore the previous value in the field
                    field.setText(lastValid);
                    // Set the flag to indicate the dialog input is invalid
                    isValid = false;
                    // Toggle the controls enable status so that the buttons are redrawn
                    // correctly
                    CcddRateParameterDialog.this.setControlsEnabled(false);
                    CcddRateParameterDialog.this.setControlsEnabled(true);
                } else // The stream name is unique to this rate
                {
                    // Update the last valid input
                    lastValid = field.getText();
                }
                return isValid;
            }
        });
        gbc.gridx++;
        streamPnl.add(streamNameFld[index], gbc);
        // Create the maximum messages per cycle label
        JLabel maxMsgsPerCycleLbl = new JLabel("Maximum messages per cycle");
        maxMsgsPerCycleLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
        gbc.gridx = 0;
        gbc.gridy++;
        streamPnl.add(maxMsgsPerCycleLbl, gbc);
        // Create the maximum messages per cycle input field
        maxMsgsPerCycleFld[index] = new JTextField(String.valueOf(rateInfo.get(index).getMaxMsgsPerCycle()), 7);
        maxMsgsPerCycleFld[index].setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
        maxMsgsPerCycleFld[index].setEditable(true);
        maxMsgsPerCycleFld[index].setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
        maxMsgsPerCycleFld[index].setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
        maxMsgsPerCycleFld[index].setBorder(border);
        // Get the initial field value
        final String initMaxMsgsPerCycle = maxMsgsPerCycleFld[index].getText();
        // Set the field's input verifier
        maxMsgsPerCycleFld[index].setInputVerifier(new InputVerifier() {

            // Storage for the last valid value entered; used to restore the input field value
            // if an invalid value is entered. Initialize to the value at the time the field is
            // created
            String lastValid = initMaxMsgsPerCycle;

            /**
             ********************************************************************************
             * Verify the contents of the input field
             ********************************************************************************
             */
            @Override
            public boolean verify(JComponent input) {
                // Verify the field contents
                InputVerificationResult doneIt = verifyInputField((JTextField) input, lastValid);
                // Update the last valid value
                lastValid = doneIt.getLastValid();
                return doneIt.isValid();
            }
        });
        gbc.gridx++;
        streamPnl.add(maxMsgsPerCycleFld[index], gbc);
        // Create the maximum bytes per second label
        JLabel bytesPerSecLbl = new JLabel("Maximum bytes per second");
        bytesPerSecLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
        gbc.gridx = 0;
        gbc.gridy++;
        streamPnl.add(bytesPerSecLbl, gbc);
        // Create the maximum bytes per second input field
        maxBytesPerSecFld[index] = new JTextField(String.valueOf(rateInfo.get(index).getMaxBytesPerSec()), 7);
        maxBytesPerSecFld[index].setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
        maxBytesPerSecFld[index].setEditable(true);
        maxBytesPerSecFld[index].setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
        maxBytesPerSecFld[index].setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
        maxBytesPerSecFld[index].setBorder(border);
        // Get the initial field value
        final String initMaxBytesPerSec = maxBytesPerSecFld[index].getText();
        // Set the field's input verifier
        maxBytesPerSecFld[index].setInputVerifier(new InputVerifier() {

            // Storage for the last valid value entered; used to restore the input field value
            // if an invalid value is entered. Initialize to the value at the time the field is
            // created
            String lastValid = initMaxBytesPerSec;

            /**
             ********************************************************************************
             * Verify the contents of the input field
             ********************************************************************************
             */
            @Override
            public boolean verify(JComponent input) {
                // Verify the field contents
                InputVerificationResult doneIt = verifyInputField((JTextField) input, lastValid);
                // Update the last valid value
                lastValid = doneIt.getLastValid();
                return doneIt.isValid();
            }
        });
        gbc.gridx++;
        streamPnl.add(maxBytesPerSecFld[index], gbc);
        // Add the rate calculator panel to the dialog
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.gridx = 0;
        gbc.gridy++;
        streamPnl.add(availRatesPnl, gbc);
        // Create a tab for each stream
        tabbedPane.addTab(rateInfo.get(index).getRateName(), null, streamPnl, null);
    }
}
Also used : JScrollPane(javax.swing.JScrollPane) JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) JTextArea(javax.swing.JTextArea) GridBagLayout(java.awt.GridBagLayout) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) JTextField(javax.swing.JTextField) InputVerifier(javax.swing.InputVerifier)

Example 4 with InputVerifier

use of javax.swing.InputVerifier in project CCDD by nasa.

the class CcddRateParameterDialog method initialize.

/**
 ********************************************************************************************
 * Create the rate parameter assignment dialog
 ********************************************************************************************
 */
private void initialize() {
    // Set the initial layout manager characteristics
    GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2), 0, 0);
    // Create borders for the input fields
    border = BorderFactory.createCompoundBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.GRAY), BorderFactory.createEmptyBorder(ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing()));
    emptyBorder = BorderFactory.createEmptyBorder();
    // Create a panel to contain the dialog components
    JPanel dialogPnl = new JPanel(new GridBagLayout());
    dialogPnl.setBorder(emptyBorder);
    // Create the maximum seconds per message label
    JLabel maxSecPerMsgLbl = new JLabel("Maximum seconds per message");
    maxSecPerMsgLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
    dialogPnl.add(maxSecPerMsgLbl, gbc);
    // Create the maximum seconds per message input field
    maxSecPerMsgFld = new JTextField(String.valueOf(rateHandler.getMaxSecondsPerMsg()), 7);
    maxSecPerMsgFld.setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
    maxSecPerMsgFld.setEditable(true);
    maxSecPerMsgFld.setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
    maxSecPerMsgFld.setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
    maxSecPerMsgFld.setBorder(border);
    // Set the field's input verifier
    maxSecPerMsgFld.setInputVerifier(new InputVerifier() {

        // Storage for the last valid value entered; used to restore the input field value if
        // an invalid value is entered. Initialize to the value at the time the field is
        // created
        String lastValid = maxSecPerMsgFld.getText();

        /**
         ************************************************************************************
         * Verify the contents of the input field
         ************************************************************************************
         */
        @Override
        public boolean verify(JComponent input) {
            // Verify the field contents
            InputVerificationResult doneIt = verifyInputField((JTextField) input, lastValid);
            // Update the last valid value
            lastValid = doneIt.getLastValid();
            return doneIt.isValid();
        }
    });
    gbc.gridx++;
    dialogPnl.add(maxSecPerMsgFld, gbc);
    // Create the maximum messages per second label
    JLabel maxMsgsPerSecLbl = new JLabel("Maximum messages per second");
    maxMsgsPerSecLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
    gbc.gridx = 0;
    gbc.gridy++;
    dialogPnl.add(maxMsgsPerSecLbl, gbc);
    // Create the maximum messages per second input field
    maxMsgsPerSecFld = new JTextField(String.valueOf(rateHandler.getMaxMsgsPerSecond()), 7);
    maxMsgsPerSecFld.setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
    maxMsgsPerSecFld.setEditable(true);
    maxMsgsPerSecFld.setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
    maxMsgsPerSecFld.setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
    maxMsgsPerSecFld.setBorder(border);
    // Set the field's input verifier
    maxMsgsPerSecFld.setInputVerifier(new InputVerifier() {

        // Storage for the last valid value entered; used to restore the input field value if
        // an invalid value is entered. Initialize to the value at the time the field is
        // created
        String lastValid = maxMsgsPerSecFld.getText();

        /**
         ************************************************************************************
         * Verify the contents of the input field
         ************************************************************************************
         */
        @Override
        public boolean verify(JComponent input) {
            // Verify the field contents
            InputVerificationResult doneIt = verifyInputField((JTextField) input, lastValid);
            // Update the last valid value
            lastValid = doneIt.getLastValid();
            return doneIt.isValid();
        }
    });
    gbc.gridx++;
    dialogPnl.add(maxMsgsPerSecFld, gbc);
    // Get the rate information for all data streams
    List<RateInformation> rateInformation = rateHandler.getRateInformation();
    // Create text fields for the stream-specific rate parameters
    streamNameFld = new JTextField[rateInformation.size()];
    maxMsgsPerCycleFld = new JTextField[rateInformation.size()];
    maxBytesPerSecFld = new JTextField[rateInformation.size()];
    availRatesFld = new JTextArea[rateInformation.size()];
    // Create a tabbed pane to contain the rate parameters that are stream-specific
    tabbedPane = new DnDTabbedPane(SwingConstants.TOP) {

        /**
         ************************************************************************************
         * Update the rate arrays order following a tab move
         ************************************************************************************
         */
        @Override
        protected Object tabMoveCleanup(int oldTabIndex, int newTabIndex, Object tabContents) {
            // Adjust the new tab index if moving the tab to a higher index
            newTabIndex -= newTabIndex > oldTabIndex ? 1 : 0;
            // Re-order the rate information based on the new tab order
            RateInformation[] rateInfoArray = rateHandler.getRateInformation().toArray(new RateInformation[0]);
            rateInfoArray = (RateInformation[]) CcddUtilities.moveArrayMember(rateInfoArray, oldTabIndex, newTabIndex);
            List<RateInformation> rateInfoList = new ArrayList<RateInformation>(rateInfoArray.length);
            rateInfoList.addAll(Arrays.asList(rateInfoArray));
            rateHandler.setRateInformation(rateInfoList);
            // Re-order the fields based on the new tab order
            maxMsgsPerCycleFld = (JTextField[]) CcddUtilities.moveArrayMember(maxMsgsPerCycleFld, oldTabIndex, newTabIndex);
            maxBytesPerSecFld = (JTextField[]) CcddUtilities.moveArrayMember(maxBytesPerSecFld, oldTabIndex, newTabIndex);
            streamNameFld = (JTextField[]) CcddUtilities.moveArrayMember(streamNameFld, oldTabIndex, newTabIndex);
            availRatesFld = (JTextArea[]) CcddUtilities.moveArrayMember(availRatesFld, oldTabIndex, newTabIndex);
            return null;
        }
    };
    tabbedPane.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
    // Create a tab for each stream
    addStreamTabs(rateInformation);
    gbc.insets.left = 0;
    gbc.insets.right = 0;
    gbc.insets.bottom = 0;
    gbc.gridwidth = 2;
    gbc.gridx = 0;
    gbc.gridy++;
    dialogPnl.add(tabbedPane, gbc);
    // Create a panel for the uneven check box
    JPanel unevenPnl = new JPanel(new FlowLayout(FlowLayout.LEFT, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2, 0));
    unevenPnl.setBorder(emptyBorder);
    // Create a check box for including/excluding unevenly time-spaced sample rates
    unevenCb = new JCheckBox("Include unevenly time-spaced rates");
    unevenCb.setBorder(emptyBorder);
    unevenCb.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
    unevenCb.setSelected(rateHandler.isIncludeUneven() ? true : false);
    unevenCb.addActionListener(new ActionListener() {

        /**
         ************************************************************************************
         * Handle a change in the include uneven rates check box status
         ************************************************************************************
         */
        @Override
        public void actionPerformed(ActionEvent ae) {
            updateAvailableRates();
        }
    });
    gbc.insets.left = ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2;
    gbc.gridwidth = GridBagConstraints.HORIZONTAL;
    gbc.gridx = 0;
    gbc.gridy++;
    unevenPnl.add(unevenCb);
    dialogPnl.add(unevenPnl, gbc);
    // Listen for tab selection changes
    tabbedPane.addChangeListener(new ChangeListener() {

        /**
         ************************************************************************************
         * Update the available rates using the values in the selected tab
         ************************************************************************************
         */
        @Override
        public void stateChanged(ChangeEvent ce) {
            // Display the available rates for the currently selected rate column
            updateAvailableRates();
        }
    });
    // Display the available rates for the initially selected rate column
    updateAvailableRates();
    // Get the user's input
    if (showOptionsDialog(ccddMain.getMainFrame(), dialogPnl, "Rate Parameters", DialogOption.OK_CANCEL_OPTION) == OK_BUTTON) {
        // Convert the common rate parameters to integers
        int maxSecPerMsg = Integer.valueOf(maxSecPerMsgFld.getText());
        int maxMsgsPerSec = Integer.valueOf(maxMsgsPerSecFld.getText());
        // Create storage for the stream-specific parameters
        String[] streamNames = new String[tabbedPane.getTabCount()];
        int[] maxMsgsPerCycle = new int[tabbedPane.getTabCount()];
        int[] maxBytesPerSec = new int[tabbedPane.getTabCount()];
        // Step through each stream
        for (int index = 0; index < tabbedPane.getTabCount(); index++) {
            // Store the stream name, convert the rate parameters to numeric form, and
            // calculate the available rates
            streamNames[index] = streamNameFld[index].getText();
            maxMsgsPerCycle[index] = Integer.valueOf(maxMsgsPerCycleFld[index].getText());
            maxBytesPerSec[index] = Integer.valueOf(maxBytesPerSecFld[index].getText());
        }
        // Check if any rate parameter changed
        if (isRateChanges(maxSecPerMsg, maxMsgsPerSec, streamNames, maxMsgsPerCycle, maxBytesPerSec, unevenCb.isSelected())) {
            // Store the rate parameters and update the sample rates
            rateHandler.setRateParameters(maxSecPerMsg, maxMsgsPerSec, streamNames, maxMsgsPerCycle, maxBytesPerSec, unevenCb.isSelected(), CcddRateParameterDialog.this);
        }
    }
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) FlowLayout(java.awt.FlowLayout) GridBagLayout(java.awt.GridBagLayout) ActionEvent(java.awt.event.ActionEvent) RateInformation(CCDD.CcddClassesDataTable.RateInformation) JTextField(javax.swing.JTextField) ArrayList(java.util.ArrayList) List(java.util.List) ChangeListener(javax.swing.event.ChangeListener) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) InputVerifier(javax.swing.InputVerifier) JCheckBox(javax.swing.JCheckBox) DnDTabbedPane(CCDD.CcddClassesComponent.DnDTabbedPane) ActionListener(java.awt.event.ActionListener) ChangeEvent(javax.swing.event.ChangeEvent)

Example 5 with InputVerifier

use of javax.swing.InputVerifier in project gitblit by gitblit.

the class GitblitAuthority method getUI.

private Container getUI() {
    userCertificatePanel = new UserCertificatePanel(this) {

        private static final long serialVersionUID = 1L;

        @Override
        public Insets getInsets() {
            return Utils.INSETS;
        }

        @Override
        public boolean isAllowEmail() {
            return mail.isReady();
        }

        @Override
        public Date getDefaultExpiration() {
            Calendar c = Calendar.getInstance();
            c.add(Calendar.DATE, defaultDuration);
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
            return c.getTime();
        }

        @Override
        public boolean saveUser(String username, UserCertificateModel ucm) {
            return userService.updateUserModel(username, ucm.user);
        }

        @Override
        public boolean newCertificate(UserCertificateModel ucm, X509Metadata metadata, boolean sendEmail) {
            if (!prepareX509Infrastructure()) {
                return false;
            }
            Date notAfter = metadata.notAfter;
            setMetadataDefaults(metadata);
            metadata.notAfter = notAfter;
            // set user's specified OID values
            UserModel user = ucm.user;
            if (!StringUtils.isEmpty(user.organizationalUnit)) {
                metadata.oids.put("OU", user.organizationalUnit);
            }
            if (!StringUtils.isEmpty(user.organization)) {
                metadata.oids.put("O", user.organization);
            }
            if (!StringUtils.isEmpty(user.locality)) {
                metadata.oids.put("L", user.locality);
            }
            if (!StringUtils.isEmpty(user.stateProvince)) {
                metadata.oids.put("ST", user.stateProvince);
            }
            if (!StringUtils.isEmpty(user.countryCode)) {
                metadata.oids.put("C", user.countryCode);
            }
            File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
            File zip = X509Utils.newClientBundle(user, metadata, caKeystoreFile, caKeystorePassword, GitblitAuthority.this);
            // save latest expiration date
            if (ucm.expires == null || metadata.notAfter.before(ucm.expires)) {
                ucm.expires = metadata.notAfter;
            }
            updateAuthorityConfig(ucm);
            // refresh user
            ucm.certs = null;
            int selectedIndex = table.getSelectedRow();
            tableModel.fireTableDataChanged();
            table.getSelectionModel().setSelectionInterval(selectedIndex, selectedIndex);
            if (sendEmail) {
                sendEmail(user, metadata, zip);
            }
            return true;
        }

        @Override
        public boolean revoke(UserCertificateModel ucm, X509Certificate cert, RevocationReason reason) {
            if (!prepareX509Infrastructure()) {
                return false;
            }
            File caRevocationList = new File(folder, X509Utils.CA_REVOCATION_LIST);
            File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
            if (X509Utils.revoke(cert, reason, caRevocationList, caKeystoreFile, caKeystorePassword, GitblitAuthority.this)) {
                File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
                FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
                if (certificatesConfigFile.exists()) {
                    try {
                        config.load();
                    } catch (Exception e) {
                        Utils.showException(GitblitAuthority.this, e);
                    }
                }
                // add serial to revoked list
                ucm.revoke(cert.getSerialNumber(), reason);
                ucm.update(config);
                try {
                    config.save();
                } catch (Exception e) {
                    Utils.showException(GitblitAuthority.this, e);
                }
                // refresh user
                ucm.certs = null;
                int modelIndex = table.convertRowIndexToModel(table.getSelectedRow());
                tableModel.fireTableDataChanged();
                table.getSelectionModel().setSelectionInterval(modelIndex, modelIndex);
                return true;
            }
            return false;
        }
    };
    table = Utils.newTable(tableModel, Utils.DATE_FORMAT);
    table.setRowSorter(defaultSorter);
    table.setDefaultRenderer(CertificateStatus.class, new CertificateStatusRenderer());
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
                return;
            }
            int row = table.getSelectedRow();
            if (row < 0) {
                return;
            }
            int modelIndex = table.convertRowIndexToModel(row);
            UserCertificateModel ucm = tableModel.get(modelIndex);
            if (ucm.certs == null) {
                ucm.certs = findCerts(folder, ucm.user.username);
            }
            userCertificatePanel.setUserCertificateModel(ucm);
        }
    });
    JPanel usersPanel = new JPanel(new BorderLayout()) {

        private static final long serialVersionUID = 1L;

        @Override
        public Insets getInsets() {
            return Utils.INSETS;
        }
    };
    usersPanel.add(new HeaderPanel(Translation.get("gb.users"), "users_16x16.png"), BorderLayout.NORTH);
    usersPanel.add(new JScrollPane(table), BorderLayout.CENTER);
    usersPanel.setMinimumSize(new Dimension(400, 10));
    certificateDefaultsButton = new JButton(new ImageIcon(getClass().getResource("/settings_16x16.png")));
    certificateDefaultsButton.setFocusable(false);
    certificateDefaultsButton.setToolTipText(Translation.get("gb.newCertificateDefaults"));
    certificateDefaultsButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            X509Metadata metadata = new X509Metadata("whocares", "whocares");
            File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
            FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
            NewCertificateConfig certificateConfig = null;
            if (certificatesConfigFile.exists()) {
                try {
                    config.load();
                } catch (Exception x) {
                    Utils.showException(GitblitAuthority.this, x);
                }
                certificateConfig = NewCertificateConfig.KEY.parse(config);
                certificateConfig.update(metadata);
            }
            InputVerifier verifier = new InputVerifier() {

                @Override
                public boolean verify(JComponent comp) {
                    boolean returnValue;
                    JTextField textField = (JTextField) comp;
                    try {
                        Integer.parseInt(textField.getText());
                        returnValue = true;
                    } catch (NumberFormatException e) {
                        returnValue = false;
                    }
                    return returnValue;
                }
            };
            JTextField siteNameTF = new JTextField(20);
            siteNameTF.setText(gitblitSettings.getString(Keys.web.siteName, "Gitblit"));
            JPanel siteNamePanel = Utils.newFieldPanel(Translation.get("gb.siteName"), siteNameTF, Translation.get("gb.siteNameDescription"));
            JTextField validityTF = new JTextField(4);
            validityTF.setInputVerifier(verifier);
            validityTF.setVerifyInputWhenFocusTarget(true);
            validityTF.setText("" + certificateConfig.duration);
            JPanel validityPanel = Utils.newFieldPanel(Translation.get("gb.validity"), validityTF, Translation.get("gb.duration.days").replace("{0}", "").trim());
            JPanel p1 = new JPanel(new GridLayout(0, 1, 5, 2));
            p1.add(siteNamePanel);
            p1.add(validityPanel);
            DefaultOidsPanel oids = new DefaultOidsPanel(metadata);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(p1, BorderLayout.NORTH);
            panel.add(oids, BorderLayout.CENTER);
            int result = JOptionPane.showConfirmDialog(GitblitAuthority.this, panel, Translation.get("gb.newCertificateDefaults"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon(getClass().getResource("/settings_32x32.png")));
            if (result == JOptionPane.OK_OPTION) {
                try {
                    oids.update(metadata);
                    certificateConfig.duration = Integer.parseInt(validityTF.getText());
                    certificateConfig.store(config, metadata);
                    config.save();
                    Map<String, String> updates = new HashMap<String, String>();
                    updates.put(Keys.web.siteName, siteNameTF.getText());
                    gitblitSettings.saveSettings(updates);
                } catch (Exception e1) {
                    Utils.showException(GitblitAuthority.this, e1);
                }
            }
        }
    });
    newSSLCertificate = new JButton(new ImageIcon(getClass().getResource("/rosette_16x16.png")));
    newSSLCertificate.setFocusable(false);
    newSSLCertificate.setToolTipText(Translation.get("gb.newSSLCertificate"));
    newSSLCertificate.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Date defaultExpiration = new Date(System.currentTimeMillis() + 10 * TimeUtils.ONEYEAR);
            NewSSLCertificateDialog dialog = new NewSSLCertificateDialog(GitblitAuthority.this, defaultExpiration);
            dialog.setModal(true);
            dialog.setVisible(true);
            if (dialog.isCanceled()) {
                return;
            }
            final Date expires = dialog.getExpiration();
            final String hostname = dialog.getHostname();
            final boolean serveCertificate = dialog.isServeCertificate();
            AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {

                @Override
                protected Boolean doRequest() throws IOException {
                    if (!prepareX509Infrastructure()) {
                        return false;
                    }
                    // read CA private key and certificate
                    File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
                    PrivateKey caPrivateKey = X509Utils.getPrivateKey(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
                    X509Certificate caCert = X509Utils.getCertificate(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
                    // generate new SSL certificate
                    X509Metadata metadata = new X509Metadata(hostname, caKeystorePassword);
                    setMetadataDefaults(metadata);
                    metadata.notAfter = expires;
                    File serverKeystoreFile = new File(folder, X509Utils.SERVER_KEY_STORE);
                    X509Certificate cert = X509Utils.newSSLCertificate(metadata, caPrivateKey, caCert, serverKeystoreFile, GitblitAuthority.this);
                    boolean hasCert = cert != null;
                    if (hasCert && serveCertificate) {
                        // update Gitblit https connector alias
                        Map<String, String> updates = new HashMap<String, String>();
                        updates.put(Keys.server.certificateAlias, metadata.commonName);
                        gitblitSettings.saveSettings(updates);
                    }
                    return hasCert;
                }

                @Override
                protected void onSuccess() {
                    if (serveCertificate) {
                        JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.sslCertificateGeneratedRestart"), hostname), Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.sslCertificateGenerated"), hostname), Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            };
            worker.execute();
        }
    });
    JButton emailBundle = new JButton(new ImageIcon(getClass().getResource("/mail_16x16.png")));
    emailBundle.setFocusable(false);
    emailBundle.setToolTipText(Translation.get("gb.emailCertificateBundle"));
    emailBundle.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = table.getSelectedRow();
            if (row < 0) {
                return;
            }
            int modelIndex = table.convertRowIndexToModel(row);
            final UserCertificateModel ucm = tableModel.get(modelIndex);
            if (ArrayUtils.isEmpty(ucm.certs)) {
                JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.pleaseGenerateClientCertificate"), ucm.user.getDisplayName()));
            }
            final File zip = new File(folder, X509Utils.CERTS + File.separator + ucm.user.username + File.separator + ucm.user.username + ".zip");
            if (!zip.exists()) {
                return;
            }
            AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {

                @Override
                protected Boolean doRequest() throws IOException {
                    X509Metadata metadata = new X509Metadata(ucm.user.username, "whocares");
                    metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
                    if (StringUtils.isEmpty(metadata.serverHostname)) {
                        metadata.serverHostname = Constants.NAME;
                    }
                    metadata.userDisplayname = ucm.user.getDisplayName();
                    return sendEmail(ucm.user, metadata, zip);
                }

                @Override
                protected void onSuccess() {
                    JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.clientCertificateBundleSent"), ucm.user.getDisplayName()));
                }
            };
            worker.execute();
        }
    });
    JButton logButton = new JButton(new ImageIcon(getClass().getResource("/script_16x16.png")));
    logButton.setFocusable(false);
    logButton.setToolTipText(Translation.get("gb.log"));
    logButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            File log = new File(folder, X509Utils.CERTS + File.separator + "log.txt");
            if (log.exists()) {
                String content = FileUtils.readContent(log, "\n");
                JTextArea textarea = new JTextArea(content);
                JScrollPane scrollPane = new JScrollPane(textarea);
                scrollPane.setPreferredSize(new Dimension(700, 400));
                JOptionPane.showMessageDialog(GitblitAuthority.this, scrollPane, log.getAbsolutePath(), JOptionPane.INFORMATION_MESSAGE);
            }
        }
    });
    final JTextField filterTextfield = new JTextField(15);
    filterTextfield.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            filterUsers(filterTextfield.getText());
        }
    });
    filterTextfield.addKeyListener(new KeyAdapter() {

        @Override
        public void keyReleased(KeyEvent e) {
            filterUsers(filterTextfield.getText());
        }
    });
    JToolBar buttonControls = new JToolBar(JToolBar.HORIZONTAL);
    buttonControls.setFloatable(false);
    buttonControls.add(certificateDefaultsButton);
    buttonControls.add(newSSLCertificate);
    buttonControls.add(emailBundle);
    buttonControls.add(logButton);
    JPanel userControls = new JPanel(new FlowLayout(FlowLayout.RIGHT, Utils.MARGIN, Utils.MARGIN));
    userControls.add(new JLabel(Translation.get("gb.filter")));
    userControls.add(filterTextfield);
    JPanel topPanel = new JPanel(new BorderLayout(0, 0));
    topPanel.add(buttonControls, BorderLayout.WEST);
    topPanel.add(userControls, BorderLayout.EAST);
    JPanel leftPanel = new JPanel(new BorderLayout());
    leftPanel.add(topPanel, BorderLayout.NORTH);
    leftPanel.add(usersPanel, BorderLayout.CENTER);
    userCertificatePanel.setMinimumSize(new Dimension(375, 10));
    JLabel statusLabel = new JLabel();
    statusLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    if (X509Utils.unlimitedStrength) {
        statusLabel.setText("JCE Unlimited Strength Jurisdiction Policy");
    } else {
        statusLabel.setText("JCE Standard Encryption Policy");
    }
    JPanel root = new JPanel(new BorderLayout()) {

        private static final long serialVersionUID = 1L;

        @Override
        public Insets getInsets() {
            return Utils.INSETS;
        }
    };
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, userCertificatePanel);
    splitPane.setDividerLocation(1d);
    root.add(splitPane, BorderLayout.CENTER);
    root.add(statusLabel, BorderLayout.SOUTH);
    return root;
}
Also used : JPanel(javax.swing.JPanel) PrivateKey(java.security.PrivateKey) JTextArea(javax.swing.JTextArea) X509Metadata(com.gitblit.utils.X509Utils.X509Metadata) ActionEvent(java.awt.event.ActionEvent) KeyAdapter(java.awt.event.KeyAdapter) BorderLayout(java.awt.BorderLayout) X509Certificate(java.security.cert.X509Certificate) ListSelectionListener(javax.swing.event.ListSelectionListener) ActionListener(java.awt.event.ActionListener) JSplitPane(javax.swing.JSplitPane) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) ImageIcon(javax.swing.ImageIcon) Insets(java.awt.Insets) FlowLayout(java.awt.FlowLayout) ListSelectionEvent(javax.swing.event.ListSelectionEvent) JButton(javax.swing.JButton) JTextField(javax.swing.JTextField) UserModel(com.gitblit.models.UserModel) KeyEvent(java.awt.event.KeyEvent) GridLayout(java.awt.GridLayout) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) RevocationReason(com.gitblit.utils.X509Utils.RevocationReason) JScrollPane(javax.swing.JScrollPane) Calendar(java.util.Calendar) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) Dimension(java.awt.Dimension) IOException(java.io.IOException) JToolBar(javax.swing.JToolBar) InputVerifier(javax.swing.InputVerifier) Date(java.util.Date) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) IOException(java.io.IOException) HeaderPanel(com.gitblit.client.HeaderPanel)

Aggregations

InputVerifier (javax.swing.InputVerifier)11 JComponent (javax.swing.JComponent)11 JTextField (javax.swing.JTextField)9 JLabel (javax.swing.JLabel)8 JPanel (javax.swing.JPanel)7 Insets (java.awt.Insets)6 GridBagConstraints (java.awt.GridBagConstraints)5 GridBagLayout (java.awt.GridBagLayout)5 ActionEvent (java.awt.event.ActionEvent)4 ActionListener (java.awt.event.ActionListener)4 JScrollPane (javax.swing.JScrollPane)4 BorderLayout (java.awt.BorderLayout)3 FlowLayout (java.awt.FlowLayout)3 JButton (javax.swing.JButton)3 CCDDException (CCDD.CcddClassesDataTable.CCDDException)2 KeyAdapter (java.awt.event.KeyAdapter)2 KeyEvent (java.awt.event.KeyEvent)2 JCheckBox (javax.swing.JCheckBox)2 JTextArea (javax.swing.JTextArea)2 BevelBorder (javax.swing.border.BevelBorder)2