Search in sources :

Example 26 with CCDDException

use of CCDD.CcddClassesDataTable.CCDDException in project CCDD by nasa.

the class CcddPatchHandler method updateFieldApplicability.

/**
 ********************************************************************************************
 * Update the data fields table applicability column to change "Parents only" to "Roots only".
 * Older versions of CCDD are not compatible with the project database after applying this
 * patch
 *
 * @throws CCDDException
 *             If the user elects to not install the patch or an error occurs while applying
 *             the patch
 ********************************************************************************************
 */
private void updateFieldApplicability() throws CCDDException {
    CcddEventLogDialog eventLog = ccddMain.getSessionEventLog();
    CcddDbControlHandler dbControl = ccddMain.getDbControlHandler();
    try {
        CcddDbCommandHandler dbCommand = ccddMain.getDbCommandHandler();
        // Read the contents of the data field table's applicability column
        ResultSet fieldData = dbCommand.executeDbQuery("SELECT * FROM " + InternalTable.FIELDS.getTableName() + " WHERE " + FieldsColumn.FIELD_APPLICABILITY.getColumnName() + " = 'Parents only';", ccddMain.getMainFrame());
        // Check if the patch hasn't already been applied
        if (fieldData.next()) {
            // Check if the user elects to not apply the patch
            if (new CcddDialogHandler().showMessageDialog(ccddMain.getMainFrame(), "<html><b>Apply patch to update the data " + "fields table?<br><br></b>Changes " + "data field applicability 'Parents " + "only' to 'Roots only'.<br><b><i>Older " + "versions of CCDD are imcompatible " + "with this project database after " + "applying the patch", "Apply Patch #09272017", JOptionPane.QUESTION_MESSAGE, DialogOption.OK_CANCEL_OPTION) != OK_BUTTON) {
                fieldData.close();
                throw new CCDDException("user elected to not install patch (#09272017)");
            }
            fieldData.close();
            // Back up the project database before applying the patch
            dbControl.backupDatabase(dbControl.getDatabaseName(), new FileEnvVar(ModifiablePathInfo.DATABASE_BACKUP_PATH.getPath() + File.separator + dbControl.getDatabaseName() + "_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) + FileExtension.DBU.getExtension()));
            // Update the data fields table
            dbCommand.executeDbCommand("UPDATE " + InternalTable.FIELDS.getTableName() + " SET " + FieldsColumn.FIELD_APPLICABILITY.getColumnName() + " = '" + ApplicabilityType.ROOT_ONLY.getApplicabilityName() + "' WHERE " + FieldsColumn.FIELD_APPLICABILITY.getColumnName() + " = 'Parents only';", ccddMain.getMainFrame());
            // Inform the user that updating the database data fields table completed
            eventLog.logEvent(EventLogMessageType.SUCCESS_MSG, "Project '" + dbControl.getProjectName() + "' data fields table conversion complete");
        }
    } catch (Exception e) {
        // Inform the user that converting the data fields table failed
        eventLog.logFailEvent(ccddMain.getMainFrame(), "Cannot convert project '" + dbControl.getProjectName() + "' data fields table to new format; cause '" + e.getMessage() + "'", "<html><b>Cannot convert project '" + dbControl.getProjectName() + "' data fields table to new format " + "(project database will be closed)");
        throw new CCDDException();
    }
}
Also used : CCDDException(CCDD.CcddClassesDataTable.CCDDException) ResultSet(java.sql.ResultSet) FileEnvVar(CCDD.CcddClassesComponent.FileEnvVar) SimpleDateFormat(java.text.SimpleDateFormat) CCDDException(CCDD.CcddClassesDataTable.CCDDException)

Example 27 with CCDDException

use of CCDD.CcddClassesDataTable.CCDDException in project CCDD by nasa.

the class CcddPreferencesDialog method addSpacingTab.

/**
 ********************************************************************************************
 * Add the spacing update tab to the tabbed pane
 ********************************************************************************************
 */
private void addSpacingTab() {
    // Set the initial layout manager characteristics
    GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, 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 a border for the input fields
    Border 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()));
    // Create storage for the description and input field representing each modifiable spacing
    JLabel[] spacingLbl = new JLabel[ModifiableSpacingInfo.values().length];
    JButton[] spacingBtn = new JButton[ModifiableSpacingInfo.values().length];
    spacingFld = new JTextField[ModifiableSpacingInfo.values().length];
    // Create a panel to contain the spacing components
    JPanel innerSpacingPnl = new JPanel(new GridBagLayout());
    innerSpacingPnl.setBorder(emptyBorder);
    // Use an outer panel so that the components can be forced to the top of the tab area
    JPanel spacingPnl = new JPanel(new BorderLayout());
    spacingPnl.setBorder(emptyBorder);
    spacingPnl.add(innerSpacingPnl, BorderLayout.PAGE_START);
    // Create a scroll pane in which to display the spacing labels and fields
    JScrollPane spacingScrollPane = new JScrollPane(spacingPnl);
    spacingScrollPane.setBorder(emptyBorder);
    spacingScrollPane.setViewportBorder(emptyBorder);
    // Add the note to the panel
    JLabel noteLbl = new JLabel("<html><i>Note: Open windows must be closed and " + "reopened for spacing changes to take effect");
    noteLbl.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
    noteLbl.setForeground(ModifiableColorInfo.SPECIAL_LABEL_TEXT.getColor());
    noteLbl.setBorder(BorderFactory.createEmptyBorder(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() * 2, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing(), ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing()));
    // Create a panel to contain the scroll pane and a note with fixed position at the bottom
    // of the panel
    JPanel scrollAndNotePnl = new JPanel(new BorderLayout());
    scrollAndNotePnl.add(spacingScrollPane, BorderLayout.CENTER);
    scrollAndNotePnl.add(noteLbl, BorderLayout.PAGE_END);
    // Add the spacing update tab to the tabbed pane
    tabbedPane.addTab(SPACING, null, scrollAndNotePnl, "Change program spacing values");
    // Create a listener for the default spacing buttons
    ActionListener defaultListener = new ActionListener() {

        /**
         ************************************************************************************
         * Update the spacing to the default value
         ************************************************************************************
         */
        @Override
        public void actionPerformed(ActionEvent ae) {
            // Get the index of the spacing field array, which is stored as the button's name
            int index = Integer.valueOf(((JButton) ae.getSource()).getName());
            // Set the spacing to its default value
            spacingFld[index].setText(String.valueOf(ModifiableSpacingInfo.values()[index].getDefault()));
        }
    };
    int index = 0;
    // Step through each modifiable spacing
    for (final ModifiableSpacingInfo modSpacing : ModifiableSpacingInfo.values()) {
        // Create the spacing label and input field
        spacingLbl[index] = new JLabel(modSpacing.getName() + " (" + modSpacing.getMinimum() + ", " + modSpacing.getMaximum() + ")");
        spacingLbl[index].setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
        spacingLbl[index].setToolTipText(CcddUtilities.wrapText(modSpacing.getDescription(), ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
        innerSpacingPnl.add(spacingLbl[index], gbc);
        spacingFld[index] = new JTextField(String.valueOf(modSpacing.getSpacing()), 3);
        spacingFld[index].setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
        spacingFld[index].setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
        spacingFld[index].setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
        spacingFld[index].setBorder(border);
        spacingFld[index].setName(modSpacing.getPreferenceKey());
        spacingFld[index].setToolTipText(CcddUtilities.wrapText(modSpacing.getDescription(), ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
        // Create an input verifier to keep the spacing value within its specified limits
        spacingFld[index].setInputVerifier(new InputVerifier() {

            // Storage for the last valid value entered; used to restore the spacing value if
            // an invalid value is entered
            String lastValid = String.valueOf(modSpacing.getSpacing());

            /**
             ********************************************************************************
             * Verify the contents of a the spacing field
             ********************************************************************************
             */
            @Override
            public boolean verify(JComponent input) {
                boolean isValid = true;
                JTextField spacingFld = (JTextField) input;
                try {
                    // Get the reference to the modifiable spacing information using its
                    // program preferences key, which is stored as the field's name
                    ModifiableSpacingInfo modSpacing = ModifiableSpacingInfo.getModifiableSpacingInfo(input.getName());
                    // Remove any leading or trailing white space characters
                    String spacing = spacingFld.getText().trim();
                    // Check if the spacing field is empty
                    if (spacing.isEmpty()) {
                        throw new CCDDException(modSpacing.getName() + "<b>' cannot be blank");
                    }
                    // Check if the spacing value isn't a positive integer
                    if (!spacing.matches(InputDataType.INT_POSITIVE.getInputMatch())) {
                        throw new CCDDException(modSpacing.getName() + "<b>' must be a positive integer value");
                    }
                    // Convert the text to an integer
                    int currentValue = Integer.valueOf(spacing);
                    // Check if the spacing value is outside of its specified limits
                    if (currentValue < modSpacing.getMinimum() || currentValue > modSpacing.getMaximum()) {
                        throw new CCDDException(modSpacing.getName() + "<b>' is outside allowable limits");
                    }
                    // Update the spacing field to the new (valid) value
                    spacingFld.setText(spacing);
                    // Store the new value as the last valid value
                    lastValid = spacingFld.getText();
                } catch (CCDDException ce) {
                    // Inform the user that the input value is invalid
                    new CcddDialogHandler().showMessageDialog(CcddPreferencesDialog.this, "<html><b>The value for '</b>" + ce.getMessage(), "Missing/Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                    // Restore the spacing field to the last valid value
                    spacingFld.setText(lastValid);
                    // Set the flag to indicate the spacing value is invalid
                    isValid = false;
                    // Toggle the controls enable status so that the buttons are redrawn
                    // correctly
                    CcddPreferencesDialog.this.setControlsEnabled(false);
                    CcddPreferencesDialog.this.setControlsEnabled(true);
                }
                return isValid;
            }
        });
        // Add the spacing field to the spacing panel
        gbc.gridx++;
        innerSpacingPnl.add(spacingFld[index], gbc);
        // Create a button for setting the spacing to its default value and add it to the
        // spacing panel
        spacingBtn[index] = new JButton("Default (" + modSpacing.getDefault() + ")");
        spacingBtn[index].setFont(ModifiableFontInfo.DIALOG_BUTTON.getFont());
        spacingBtn[index].setName(String.valueOf(index));
        spacingBtn[index].addActionListener(defaultListener);
        gbc.gridx++;
        innerSpacingPnl.add(spacingBtn[index], gbc);
        gbc.weightx = 1.0;
        gbc.gridx++;
        innerSpacingPnl.add(new JLabel(""), gbc);
        gbc.weightx = 0.0;
        gbc.gridx = 0;
        gbc.gridy++;
        index++;
    }
    // Set the scroll bar scroll increment
    spacingScrollPane.getVerticalScrollBar().setUnitIncrement(spacingFld[0].getPreferredSize().height / 2 + ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing());
    // Calculate the maximum required height of the panel containing the spacing labels and
    // fields (= # of rows * row height)
    maxScrollPaneHeight = Math.max(maxScrollPaneHeight, 10 * spacingScrollPane.getPreferredSize().height / spacingFld.length);
}
Also used : JScrollPane(javax.swing.JScrollPane) JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) CCDDException(CCDD.CcddClassesDataTable.CCDDException) GridBagLayout(java.awt.GridBagLayout) ActionEvent(java.awt.event.ActionEvent) JButton(javax.swing.JButton) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) JTextField(javax.swing.JTextField) InputVerifier(javax.swing.InputVerifier) BorderLayout(java.awt.BorderLayout) ActionListener(java.awt.event.ActionListener) ModifiableSpacingInfo(CCDD.CcddConstants.ModifiableSpacingInfo) Border(javax.swing.border.Border) BevelBorder(javax.swing.border.BevelBorder)

Example 28 with CCDDException

use of CCDD.CcddClassesDataTable.CCDDException in project CCDD by nasa.

the class CcddPreferencesDialog method addSizeTab.

/**
 ********************************************************************************************
 * Add the size update tab to the tabbed pane
 ********************************************************************************************
 */
private void addSizeTab() {
    // Set the initial layout manager characteristics
    GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, 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 a border for the input fields
    Border 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()));
    // Create storage for the description and input field representing each modifiable size
    JLabel[] sizeLbl = new JLabel[ModifiableSizeInfo.values().length];
    JButton[] sizeBtn = new JButton[ModifiableSizeInfo.values().length];
    sizeFld = new JTextField[ModifiableSizeInfo.values().length];
    // Create a panel to contain the size components
    JPanel innerSizePnl = new JPanel(new GridBagLayout());
    innerSizePnl.setBorder(emptyBorder);
    // Use an outer panel so that the components can be forced to the top of the tab area
    JPanel sizePnl = new JPanel(new BorderLayout());
    sizePnl.setBorder(emptyBorder);
    sizePnl.add(innerSizePnl, BorderLayout.PAGE_START);
    // Create a scroll pane in which to display the size labels and fields
    JScrollPane sizeScrollPane = new JScrollPane(sizePnl);
    sizeScrollPane.setBorder(emptyBorder);
    sizeScrollPane.setViewportBorder(emptyBorder);
    // Add the size update tab to the tabbed pane
    tabbedPane.addTab(SIZE, null, sizeScrollPane, "Change program maximum width and length values");
    // Create a listener for the default size buttons
    ActionListener defaultListener = new ActionListener() {

        /**
         ************************************************************************************
         * Update the size to the default value
         ************************************************************************************
         */
        @Override
        public void actionPerformed(ActionEvent ae) {
            // Get the index of the size field array, which is stored as the button's name
            int index = Integer.valueOf(((JButton) ae.getSource()).getName());
            // Set the size to its default value
            sizeFld[index].setText(String.valueOf(ModifiableSizeInfo.values()[index].getDefault()));
        }
    };
    int index = 0;
    // Step through each modifiable size
    for (final ModifiableSizeInfo modSize : ModifiableSizeInfo.values()) {
        // Create the size label and input field
        sizeLbl[index] = new JLabel(modSize.getName() + " (" + modSize.getMinimum() + ", " + modSize.getMaximum() + ")");
        sizeLbl[index].setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
        sizeLbl[index].setToolTipText(CcddUtilities.wrapText(modSize.getDescription(), ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
        innerSizePnl.add(sizeLbl[index], gbc);
        sizeFld[index] = new JTextField(String.valueOf(modSize.getSize()), 3);
        sizeFld[index].setFont(ModifiableFontInfo.INPUT_TEXT.getFont());
        sizeFld[index].setForeground(ModifiableColorInfo.INPUT_TEXT.getColor());
        sizeFld[index].setBackground(ModifiableColorInfo.INPUT_BACK.getColor());
        sizeFld[index].setBorder(border);
        sizeFld[index].setName(modSize.getPreferenceKey());
        sizeFld[index].setToolTipText(CcddUtilities.wrapText(modSize.getDescription(), ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
        // Create an input verifier to keep the size value within its specified limits
        sizeFld[index].setInputVerifier(new InputVerifier() {

            // Storage for the last valid value entered; used to restore the size value if an
            // invalid value is entered
            String lastValid = String.valueOf(modSize.getSize());

            /**
             ********************************************************************************
             * Verify the contents of a the size field
             ********************************************************************************
             */
            @Override
            public boolean verify(JComponent input) {
                boolean isValid = true;
                JTextField sizeFld = (JTextField) input;
                try {
                    // Get the reference to the modifiable size information using its program
                    // preferences key, which is stored as the field's name
                    ModifiableSizeInfo modSize = ModifiableSizeInfo.getModifiableSizeInfo(input.getName());
                    // Remove any leading or trailing white space characters
                    String size = sizeFld.getText().trim();
                    // Check if the size field is empty
                    if (size.isEmpty()) {
                        throw new CCDDException(modSize.getName() + "<b>' cannot be blank");
                    }
                    // Check if the size value isn't a positive integer
                    if (!size.matches(InputDataType.INT_POSITIVE.getInputMatch())) {
                        throw new CCDDException(modSize.getName() + "<b>' must be a positive integer value");
                    }
                    // Convert the text to an integer
                    int currentValue = Integer.valueOf(size);
                    // Check if the size value is outside of its specified limits
                    if (currentValue < modSize.getMinimum() || currentValue > modSize.getMaximum()) {
                        throw new CCDDException(modSize.getName() + "<b>' is outside allowable limits");
                    }
                    // Update the size field to the new (valid) value
                    sizeFld.setText(size);
                    // Store the new value as the last valid value
                    lastValid = sizeFld.getText();
                } catch (CCDDException ce) {
                    // Inform the user that the input value is invalid
                    new CcddDialogHandler().showMessageDialog(CcddPreferencesDialog.this, "<html><b>The value for '</b>" + ce.getMessage(), "Missing/Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                    // Restore the size field to the last valid value
                    sizeFld.setText(lastValid);
                    // Set the flag to indicate the size value is invalid
                    isValid = false;
                    // Toggle the controls enable status so that the buttons are redrawn
                    // correctly
                    CcddPreferencesDialog.this.setControlsEnabled(false);
                    CcddPreferencesDialog.this.setControlsEnabled(true);
                }
                return isValid;
            }
        });
        // Add the size field to the size panel
        gbc.gridx++;
        innerSizePnl.add(sizeFld[index], gbc);
        // Create a button for setting the size to its default value and add it to the size
        // panel
        sizeBtn[index] = new JButton("Default (" + modSize.getDefault() + ")");
        sizeBtn[index].setFont(ModifiableFontInfo.DIALOG_BUTTON.getFont());
        sizeBtn[index].setName(String.valueOf(index));
        sizeBtn[index].addActionListener(defaultListener);
        gbc.gridx++;
        innerSizePnl.add(sizeBtn[index], gbc);
        gbc.weightx = 1.0;
        gbc.gridx++;
        innerSizePnl.add(new JLabel(""), gbc);
        gbc.weightx = 0.0;
        gbc.gridx = 0;
        gbc.gridy++;
        index++;
    }
    // Set the scroll bar scroll increment
    sizeScrollPane.getVerticalScrollBar().setUnitIncrement(sizeFld[0].getPreferredSize().height / 2 + ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing());
    // Calculate the maximum required height of the panel containing the size labels and fields
    // (= # of rows * row height)
    maxScrollPaneHeight = Math.max(maxScrollPaneHeight, 10 * sizeScrollPane.getPreferredSize().height / sizeFld.length);
}
Also used : JScrollPane(javax.swing.JScrollPane) JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) CCDDException(CCDD.CcddClassesDataTable.CCDDException) GridBagLayout(java.awt.GridBagLayout) ActionEvent(java.awt.event.ActionEvent) JButton(javax.swing.JButton) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) JTextField(javax.swing.JTextField) InputVerifier(javax.swing.InputVerifier) BorderLayout(java.awt.BorderLayout) ActionListener(java.awt.event.ActionListener) ModifiableSizeInfo(CCDD.CcddConstants.ModifiableSizeInfo) Border(javax.swing.border.Border) BevelBorder(javax.swing.border.BevelBorder)

Example 29 with CCDDException

use of CCDD.CcddClassesDataTable.CCDDException in project CCDD by nasa.

the class CcddScriptHandler method getDataAndExecuteScript.

/**
 ********************************************************************************************
 * Get the table information array from the table data used by the script script
 * association(s), then execute the script(s)
 *
 * @param tree
 *            table tree of the table instances (parent tables with their child tables); null
 *            if the tree should be loaded
 *
 * @param associations
 *            list of script associations to execute
 *
 * @param parent
 *            GUI component calling this method; null if none (e.g., if called via the command
 *            line)
 *
 * @return Array containing flags that indicate, for each association, if the association did
 *         not complete successfully
 ********************************************************************************************
 */
protected boolean[] getDataAndExecuteScript(CcddTableTreeHandler tree, List<Object[]> associations, Component parent) {
    int assnIndex = 0;
    CcddTableTreeHandler tableTree = tree;
    // Create an array to indicate if an association has a problem that prevents its execution
    boolean[] isBad = new boolean[associations.size()];
    // Check if the script execution was initiated via command line command
    if (parent == null) {
        // Get the system environment variables map
        envVarMap = new HashMap<String, String>(System.getenv());
    }
    // Check if no table tree was provided
    if (tableTree == null) {
        // Build the table tree
        tableTree = new CcddTableTreeHandler(ccddMain, TableTreeType.INSTANCE_TABLES, parent);
    }
    // Create storage for the individual tables' data and table path+names
    List<TableInformation> tableInformation = new ArrayList<TableInformation>();
    loadedTablePaths = new ArrayList<String>();
    // Get the link assignment information, if any
    CcddLinkHandler linkHandler = new CcddLinkHandler(ccddMain, parent);
    // Load the data field information from the database
    CcddFieldHandler fieldHandler = new CcddFieldHandler(ccddMain, null, parent);
    // Load the group information from the database
    CcddGroupHandler groupHandler = new CcddGroupHandler(ccddMain, null, parent);
    // Get the list of the table paths in the order of appearance in the table tree. This
    // is used to sort the association table paths
    final List<String> allTablePaths = tableTree.getTableTreePathList(null);
    // once. Step through each script association definition
    for (Object[] assn : associations) {
        try {
            // Get the list of association table paths
            List<String> tablePaths = getAssociationTablePaths(assn[AssociationsColumn.MEMBERS.ordinal()].toString(), groupHandler, parent);
            // Check if at least one table is assigned to this script association
            if (!tablePaths.isEmpty()) {
                // Sort the table paths
                Collections.sort(tablePaths, new Comparator<String>() {

                    /**
                     ************************************************************************
                     * Sort the table paths so that the root tables are in alphabetical order
                     * and the child tables appear in the order defined by their table type
                     * definition
                     ************************************************************************
                     */
                    @Override
                    public int compare(String path1, String path2) {
                        int result = 0;
                        // Get the indices of the two paths within the table tree
                        int index1 = allTablePaths.indexOf(path1);
                        int index2 = allTablePaths.indexOf(path2);
                        // the lowest index first
                        if (index1 > index2) {
                            result = 1;
                        } else if (index2 > index1) {
                            result = -1;
                        }
                        return result;
                    }
                });
                // Step through each table path+name
                for (String tablePath : tablePaths) {
                    // Initialize the array for each of the tables to load from the database
                    combinedData = new String[0][0];
                    // Read the table and child table data from the database and store the
                    // results from the last table loaded
                    TableInformation tableInfo = readTable(tablePath, parent);
                    // Check if the table hasn't already been loaded
                    if (tableInfo != null) {
                        // Read the table and child table data from the database
                        tableInformation.add(tableInfo);
                        // Check if an error occurred loading the table data
                        if (tableInfo.isErrorFlag()) {
                            throw new CCDDException("table '" + tableInfo.getProtoVariableName() + "' (or one of its children) failed to load");
                        } else // The table loaded successfully
                        {
                            // Store the data for the table and its child table(s)
                            tableInfo.setData(combinedData);
                            // Get the type definition based on the table type name
                            TypeDefinition typeDefn = tableTypeHandler.getTypeDefinition(tableInfo.getType());
                            // Check if the type exists
                            if (typeDefn != null) {
                                // Check if this table represents a structure
                                if (typeDefn.isStructure()) {
                                    // Set the table type to indicate a structure
                                    tableInfo.setType(TYPE_STRUCTURE);
                                } else // Check if this table represents a command table
                                if (typeDefn.isCommand()) {
                                    // Set the table type to indicate a command table
                                    tableInfo.setType(TYPE_COMMAND);
                                }
                            } else // The table's type is invalid
                            {
                                throw new CCDDException("table '" + tableInfo.getProtoVariableName() + "' has unknown type '" + tableInfo.getType() + "'");
                            }
                        }
                    }
                }
            }
        } catch (CCDDException ce) {
            // Inform the user that script execution failed
            logScriptError(FileEnvVar.expandEnvVars(assn[AssociationsColumn.SCRIPT_FILE.ordinal()].toString(), envVarMap), assn[AssociationsColumn.MEMBERS.ordinal()].toString(), ce.getMessage(), parent);
            // Set the flag for this association indicating it can't be executed
            isBad[assnIndex] = true;
        } catch (Exception e) {
            // Display a dialog providing details on the unanticipated error
            CcddUtilities.displayException(e, ccddMain.getMainFrame());
        }
        assnIndex++;
    }
    assnIndex = 0;
    // execute it. Step through each script association definition
    for (Object[] assn : associations) {
        // Check that an error didn't occur loading the data for this association
        if (!isBad[assnIndex]) {
            TableInformation[] combinedTableInfo = null;
            List<String> groupNames = new ArrayList<String>();
            // Get the list of association table paths
            List<String> tablePaths = getAssociationTablePaths(assn[AssociationsColumn.MEMBERS.ordinal()].toString(), groupHandler, parent);
            String[] members = assn[AssociationsColumn.MEMBERS.ordinal()].toString().split(Pattern.quote(ASSN_TABLE_SEPARATOR));
            // Step through each table path+name or group
            for (String member : members) {
                // Check if this is a reference to a group
                if (member.startsWith(GROUP_DATA_FIELD_IDENT)) {
                    // Add the group name to the list of referenced groups
                    groupNames.add(member.substring(GROUP_DATA_FIELD_IDENT.length()));
                }
            }
            // Check if at least one table is assigned to this script association
            if (!tablePaths.isEmpty()) {
                // Create storage for the table types used by this script association
                List<String> tableTypes = new ArrayList<String>();
                // information instance
                for (TableInformation tableInfo : tableInformation) {
                    // Check if this table is a member of the association
                    if (tablePaths.contains(tableInfo.getTablePath())) {
                        // Check if the type for this table is not already in the list
                        if (!tableTypes.contains(tableInfo.getType())) {
                            // Add the table type to the list
                            tableTypes.add(tableInfo.getType());
                        }
                    }
                }
                // Create storage for the combined table data
                combinedTableInfo = new TableInformation[tableTypes.size()];
                // through each table type represented in this association
                for (int typeIndex = 0; typeIndex < tableTypes.size(); typeIndex++) {
                    String tableName = "";
                    String[][] allTableData = new String[0][0];
                    // Step through each table information instance
                    for (TableInformation tableInfo : tableInformation) {
                        // Check if this table is a member of the association
                        if (tablePaths.contains(tableInfo.getTablePath())) {
                            // Check if the table types match
                            if (tableTypes.get(typeIndex).equals(tableInfo.getType())) {
                                // Check if the name hasn't been stored
                                if (tableName.isEmpty()) {
                                    // Assign the name of the first table of this type as this
                                    // type's table name
                                    tableName += tableInfo.getTablePath();
                                }
                                // Append the table data to the combined data array
                                allTableData = CcddUtilities.concatenateArrays(allTableData, tableInfo.getData());
                            }
                        }
                    }
                    // Create the table information from the table data obtained from the
                    // database
                    combinedTableInfo[typeIndex] = new TableInformation(tableTypes.get(typeIndex), tableName, allTableData, null, null, false, new String[0][0]);
                }
            } else // No table is assigned to this script association
            {
                // Create a table information class in order to load and parse the data fields,
                // and to allow access to the field methods
                combinedTableInfo = new TableInformation[1];
                combinedTableInfo[0] = new TableInformation("", "", new String[0][0], null, null, false, new String[0][0]);
            }
            // Get the script file name with any environment variables expanded
            String scriptFileName = FileEnvVar.expandEnvVars(assn[AssociationsColumn.SCRIPT_FILE.ordinal()].toString(), envVarMap);
            try {
                // Execute the script using the indicated table data
                executeScript(scriptFileName, combinedTableInfo, groupNames, linkHandler, fieldHandler, groupHandler, parent);
            } catch (CCDDException ce) {
                // Inform the user that script execution failed
                logScriptError(scriptFileName, assn[AssociationsColumn.MEMBERS.ordinal()].toString(), ce.getMessage(), parent);
                // Set the flag for this association indicating it can't be executed
                isBad[assnIndex] = true;
            } catch (Exception e) {
                // Display a dialog providing details on the unanticipated error
                CcddUtilities.displayException(e, ccddMain.getMainFrame());
            }
        }
        assnIndex++;
    }
    return isBad;
}
Also used : CCDDException(CCDD.CcddClassesDataTable.CCDDException) ArrayList(java.util.ArrayList) CCDDException(CCDD.CcddClassesDataTable.CCDDException) ScriptException(javax.script.ScriptException) FileNotFoundException(java.io.FileNotFoundException) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition) TableInformation(CCDD.CcddClassesDataTable.TableInformation)

Example 30 with CCDDException

use of CCDD.CcddClassesDataTable.CCDDException in project CCDD by nasa.

the class CcddScriptHandler method executeScript.

/**
 ********************************************************************************************
 * Execute a script
 *
 * @param scriptFileName
 *            script file name. The file extension is used to determine the script engine and
 *            therefore must conform to standard extension usage
 *
 * @param tableInformation
 *            array of table information
 *
 * @param groupNames
 *            list containing the names of any groups referenced in the script association
 *
 * @param linkHandler
 *            link handler reference
 *
 * @param fieldHandler
 *            field handler reference
 *
 * @param groupHandler
 *            group handler reference
 *
 * @param parent
 *            GUI component calling this method
 *
 * @return true if an error occurs during script execution
 *
 * @throws CCDDException
 *             If an error occurs while attempting to access the script file
 ********************************************************************************************
 */
private void executeScript(String scriptFileName, TableInformation[] tableInformation, List<String> groupNames, CcddLinkHandler linkHandler, CcddFieldHandler fieldHandler, CcddGroupHandler groupHandler, Component parent) throws CCDDException {
    // Check if the script file doesn't exist
    if (!new File(scriptFileName).isFile()) {
        // Inform the user that the selected file is missing
        throw new CCDDException("cannot locate script file '" + scriptFileName + "'");
    }
    // Get the location of the file extension indicator
    int extensionStart = scriptFileName.lastIndexOf(".");
    // Check if the file name has no extension (i.e., "fileName.___")
    if (!(extensionStart > 0 && extensionStart != scriptFileName.length() - 1)) {
        // Inform the user that the selected file is missing the file extension
        throw new CCDDException("script file '" + scriptFileName + "' has no file extension");
    }
    // Extract the file extension from the file name
    String extension = scriptFileName.substring(extensionStart + 1);
    // Flag that indicates if a script engine is found that matches the script file extension
    boolean isValidExt = false;
    // Step through each engine factory
    for (ScriptEngineFactory factory : scriptFactories) {
        // Check if this script engine is applicable to the script file's extension
        if (factory.getExtensions().contains(extension)) {
            // Set the flag that indicates a script engine is found that matches the extension
            isValidExt = true;
            try {
                // Get the script engine
                ScriptEngine scriptEngine = factory.getScriptEngine();
                // Create an instance of the script data access handler, then use this as a
                // reference for the version of the access handler class that contains static
                // method calls to the non-static version. Some scripting languages work with
                // either the non-static or static version (Python, Groovy), but others only
                // work with either the non-static or static version (JavaScript, Ruby, Scala;
                // this can be Java version dependent as well).
                CcddScriptDataAccessHandler accessHandler = new CcddScriptDataAccessHandler(ccddMain, tableInformation, linkHandler, fieldHandler, groupHandler, scriptFileName, groupNames, parent);
                CcddScriptDataAccessHandlerStatic staticHandler = new CcddScriptDataAccessHandlerStatic(accessHandler);
                // Bind the script data access handlers (non-static and static versions) to the
                // script context so that the handlers' public access methods can be accessed
                // by the script using the binding names ('ccdd' or 'ccdds')
                Bindings scriptBindings = scriptEngine.createBindings();
                scriptBindings.put("ccdd", accessHandler);
                scriptBindings.put("ccdds", staticHandler);
                scriptEngine.setBindings(scriptBindings, ScriptContext.ENGINE_SCOPE);
                // Execute the script
                scriptEngine.eval(new FileReader(scriptFileName));
            } catch (FileNotFoundException fnfe) {
                // Inform the user that the selected file cannot be read
                throw new CCDDException("cannot read script file '" + scriptFileName + "'");
            } catch (ScriptException se) {
                // Inform the user that the script encountered an error
                throw new CCDDException("script file '" + scriptFileName + "' error '" + se.getMessage() + "'");
            } catch (Exception e) {
                // Display a dialog providing details on the unanticipated error
                CcddUtilities.displayException(e, ccddMain.getMainFrame());
            }
            // Stop searching since a match was found
            break;
        }
    }
    // engines
    if (!isValidExt) {
        // Inform the user that the selected file's extension isn't recognized
        throw new CCDDException("script file '" + scriptFileName + "' extension is unsupported");
    }
}
Also used : CCDDException(CCDD.CcddClassesDataTable.CCDDException) FileNotFoundException(java.io.FileNotFoundException) Bindings(javax.script.Bindings) ScriptEngine(javax.script.ScriptEngine) CCDDException(CCDD.CcddClassesDataTable.CCDDException) ScriptException(javax.script.ScriptException) FileNotFoundException(java.io.FileNotFoundException) ScriptException(javax.script.ScriptException) ScriptEngineFactory(javax.script.ScriptEngineFactory) FileReader(java.io.FileReader) File(java.io.File)

Aggregations

CCDDException (CCDD.CcddClassesDataTable.CCDDException)44 ArrayList (java.util.ArrayList)17 TypeDefinition (CCDD.CcddTableTypeHandler.TypeDefinition)13 JSONObject (org.json.simple.JSONObject)12 FileEnvVar (CCDD.CcddClassesComponent.FileEnvVar)11 JSONArray (org.json.simple.JSONArray)11 JScrollPane (javax.swing.JScrollPane)10 JComponent (javax.swing.JComponent)9 Component (java.awt.Component)8 ParseException (org.json.simple.parser.ParseException)8 IOException (java.io.IOException)7 TableCellRenderer (javax.swing.table.TableCellRenderer)7 JSONParser (org.json.simple.parser.JSONParser)7 GroupInformation (CCDD.CcddClassesDataTable.GroupInformation)6 GridBagConstraints (java.awt.GridBagConstraints)6 GridBagLayout (java.awt.GridBagLayout)6 Insets (java.awt.Insets)6 JPanel (javax.swing.JPanel)6 TableDefinition (CCDD.CcddClassesDataTable.TableDefinition)5 TableInformation (CCDD.CcddClassesDataTable.TableInformation)5