Search in sources :

Example 26 with TypeDefinition

use of CCDD.CcddTableTypeHandler.TypeDefinition in project CCDD by nasa.

the class CcddWebDataAccessHandler method getCommandInformation.

/**
 ********************************************************************************************
 * Get the information for each command matching the specified filters
 *
 * @param groupFilter
 *            group (or application) name. A table must belong to the specified group in order
 *            for its telemetered variables to be returned; blank to get all telemetered
 *            variables (regardless of group)
 *
 * @return JSON encoded string containing information for each command matching the specified
 *         filters
 *
 * @throws CCDDException
 *             If the supplied group name is unrecognized
 ********************************************************************************************
 */
@SuppressWarnings("unchecked")
private String getCommandInformation(String groupFilter) throws CCDDException {
    JSONArray commandsJA = new JSONArray();
    TypeDefinition typeDefn = null;
    int commandNameIndex = -1;
    int commandCodeIndex = -1;
    int commandDescriptionIndex = -1;
    List<AssociatedColumns> commandArguments = null;
    List<String> groupTables = null;
    // Table type name for the previous table type loaded
    String lastType = "";
    // Check if a group name filter is specified
    if (!groupFilter.isEmpty()) {
        // Create a group handler and extract the table names belonging to the group
        CcddGroupHandler groupHandler = new CcddGroupHandler(ccddMain, null, ccddMain.getMainFrame());
        GroupInformation groupInfo = groupHandler.getGroupInformationByName(groupFilter);
        // Check if the group doesn't exist
        if (groupInfo == null) {
            throw new CCDDException("unrecognized group name");
        }
        // Get the tables associated with the group
        groupTables = groupInfo.getTablesAndAncestors();
    }
    // Step through each command table
    for (String commandTable : dbTable.getPrototypeTablesOfType(TYPE_COMMAND)) {
        // requested that the table is a member of the group
        if (groupFilter.isEmpty() || groupTables.contains(commandTable)) {
            // Get the information from the database for the specified table
            TableInformation tableInfo = dbTable.loadTableData(commandTable, false, false, false, ccddMain.getMainFrame());
            // Check if the table loaded successfully
            if (!tableInfo.isErrorFlag()) {
                // every table
                if (!tableInfo.getType().equals(lastType)) {
                    String descColName;
                    commandDescriptionIndex = -1;
                    // Store the table type name
                    lastType = tableInfo.getType();
                    // Get the table's type definition
                    typeDefn = tableTypeHandler.getTypeDefinition(tableInfo.getType());
                    // Get the command name column
                    commandNameIndex = typeDefn.getColumnIndexByUserName(typeDefn.getColumnNameByInputType(InputDataType.COMMAND_NAME));
                    // Get the command name column
                    commandCodeIndex = typeDefn.getColumnIndexByUserName(typeDefn.getColumnNameByInputType(InputDataType.COMMAND_CODE));
                    // Check if a command description column exists
                    if ((descColName = typeDefn.getColumnNameByInputType(InputDataType.DESCRIPTION)) != null) {
                        // Get the command description column
                        commandDescriptionIndex = typeDefn.getColumnIndexByUserName(descColName);
                    }
                    // Get the list containing command argument column indices for each
                    // argument grouping
                    commandArguments = typeDefn.getAssociatedCommandArgumentColumns(false);
                }
                // values
                if (!isReplaceMacro) {
                    // Replace all macros in the table
                    tableInfo.setData(ccddMain.getMacroHandler().replaceAllMacros(tableInfo.getData()));
                }
                // Step through each command in the command table
                for (int row = 0; row < tableInfo.getData().length; row++) {
                    JSONObject commandJO = new JSONObject();
                    String cellValue;
                    // on this row is skipped
                    if (!(cellValue = tableInfo.getData()[row][commandNameIndex]).isEmpty()) {
                        JSONArray commandArgumentsJA = new JSONArray();
                        // Store the name of the command table from which this command is taken
                        commandJO.put("Command Table Name", commandTable);
                        // Store the command name in the JSON output
                        commandJO.put(typeDefn.getColumnNamesUser()[commandNameIndex], cellValue);
                        // Check if the command code is present
                        if (!(cellValue = tableInfo.getData()[row][commandCodeIndex]).isEmpty()) {
                            // Store the command code in the JSON output
                            commandJO.put(typeDefn.getColumnNamesUser()[commandCodeIndex], cellValue);
                        }
                        // Check if the command description is present
                        if (commandDescriptionIndex != -1 && !(cellValue = tableInfo.getData()[row][commandDescriptionIndex]).isEmpty()) {
                            // Store the command description in the JSON output
                            commandJO.put(typeDefn.getColumnNamesUser()[commandDescriptionIndex], cellValue);
                        }
                        // command row
                        for (AssociatedColumns cmdArgument : commandArguments) {
                            JSONObject commandArgumentJO = new JSONObject();
                            // all associated argument values are skipped
                            if (!(cellValue = tableInfo.getData()[row][cmdArgument.getName()]).isEmpty()) {
                                // Store the command argument name in the JSON output
                                commandArgumentJO.put(typeDefn.getColumnNamesUser()[cmdArgument.getName()], cellValue);
                                // Check if the command argument data type column has a value
                                if (!(cellValue = tableInfo.getData()[row][cmdArgument.getDataType()]).isEmpty()) {
                                    // Store the data type in the JSON output
                                    commandArgumentJO.put(typeDefn.getColumnNamesUser()[cmdArgument.getDataType()], cellValue);
                                }
                                // Check if the command argument array size column has a value
                                if (!(cellValue = tableInfo.getData()[row][cmdArgument.getArraySize()]).isEmpty()) {
                                    // Store the array size in the JSON output
                                    commandArgumentJO.put(typeDefn.getColumnNamesUser()[cmdArgument.getArraySize()], cellValue);
                                }
                                // Check if the command argument bit length column has a value
                                if (!(cellValue = tableInfo.getData()[row][cmdArgument.getBitLength()]).isEmpty()) {
                                    // Store the bit length in the JSON output
                                    commandArgumentJO.put(typeDefn.getColumnNamesUser()[cmdArgument.getBitLength()], cellValue);
                                }
                                // Check if the command argument enumeration column has a value
                                if (!(cellValue = tableInfo.getData()[row][cmdArgument.getEnumeration()]).isEmpty()) {
                                    // Store the enumeration in the JSON output
                                    commandArgumentJO.put(typeDefn.getColumnNamesUser()[cmdArgument.getEnumeration()], cellValue);
                                }
                                // Check if the command argument minimum column has a value
                                if (!(cellValue = tableInfo.getData()[row][cmdArgument.getMinimum()]).isEmpty()) {
                                    // Store the minimum value in the JSON output
                                    commandArgumentJO.put(typeDefn.getColumnNamesUser()[cmdArgument.getMinimum()], cellValue);
                                }
                                // Check if the command argument maximum column has a value
                                if (!(cellValue = tableInfo.getData()[row][cmdArgument.getMaximum()]).isEmpty()) {
                                    // Store the maximum value in the JSON output
                                    commandArgumentJO.put(typeDefn.getColumnNamesUser()[cmdArgument.getMaximum()], cellValue);
                                }
                                // argument
                                for (int otherArg : cmdArgument.getOther()) {
                                    // Check if the other argument column has a value
                                    if (!(cellValue = tableInfo.getData()[row][otherArg]).isEmpty()) {
                                        // Store the value in the JSON output
                                        commandArgumentJO.put(typeDefn.getColumnNamesUser()[otherArg], cellValue);
                                    }
                                }
                            }
                            // Store the command arguments in the JSON array
                            commandArgumentsJA.add(commandArgumentJO);
                        }
                        // Check if the command has an argument
                        if (!commandArgumentsJA.isEmpty()) {
                            // Store the command arguments in the JSON output
                            commandJO.put("Arguments", commandArgumentsJA);
                        }
                    }
                    // Add the command to the JSON array
                    commandsJA.add(commandJO);
                }
            }
        }
    }
    return commandsJA.toString();
}
Also used : AssociatedColumns(CCDD.CcddClassesDataTable.AssociatedColumns) GroupInformation(CCDD.CcddClassesDataTable.GroupInformation) CCDDException(CCDD.CcddClassesDataTable.CCDDException) JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) TableInformation(CCDD.CcddClassesDataTable.TableInformation) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition)

Example 27 with TypeDefinition

use of CCDD.CcddTableTypeHandler.TypeDefinition in project CCDD by nasa.

the class CcddDbTableCommandHandler method modifyTableData.

/**
 ********************************************************************************************
 * Add, modify, and/or delete data in a table. If the table is a prototype then its database
 * table is altered; if the table is an instance then the changes are made to the custom values
 * table
 *
 * @param tableInfo
 *            table information
 *
 * @param additions
 *            list of row addition information
 *
 * @param modifications
 *            list of row update information
 *
 * @param deletions
 *            list of row deletion information
 *
 * @param forceUpdate
 *            true to make the changes to other data tables; false to only make changes to
 *            tables other than the one in which the changes originally took place
 *
 * @param skipInternalTables
 *            true to not build and execute the commands to update the internal tables. This is
 *            used during a data type update where only the data type name has changed in order
 *            to speed up the operation
 *
 * @param updateDescription
 *            true to update the table description from the table information; false to not
 *            change the table description
 *
 * @param updateColumnOrder
 *            true to update the table column order from the table information; false to not
 *            change the table column order
 *
 * @param updateFieldInfo
 *            true to update the table data fields from the table information; false to not
 *            change the table data fields
 *
 * @param newDataTypeHandler
 *            data type handler with data type modifications. null (or a reference to the
 *            current data type handler) if the change does not originate from the data type
 *            editor
 *
 * @param parent
 *            reference to the GUI component over which any error dialogs should be centered
 *
 * @return true if an error occurs while updating the table
 ********************************************************************************************
 */
protected boolean modifyTableData(TableInformation tableInfo, List<TableModification> additions, List<TableModification> modifications, List<TableModification> deletions, boolean forceUpdate, boolean skipInternalTables, boolean updateDescription, boolean updateColumnOrder, boolean updateFieldInfo, CcddDataTypeHandler newDataTypeHandler, Component parent) {
    boolean errorFlag = false;
    try {
        CcddTableTreeHandler tableTree = null;
        ToolTipTreeNode orgTableNode = null;
        updateLinks = false;
        addLinkHandler = null;
        isPathUpdate = false;
        // Get the name of the table to modify and convert the table name to lower case.
        // PostgreSQL automatically does this, so it's done here just to differentiate the
        // table name from the database commands in the event log
        String dbTableName = tableInfo.getPrototypeName().toLowerCase();
        // Get the table type definition
        TypeDefinition typeDefinition = tableTypeHandler.getTypeDefinition(tableInfo.getType());
        // represents a structure
        if (!skipInternalTables && typeDefinition.isStructure()) {
            deletedArrayDefns = new ArrayList<String>();
            // Create the table tree. Suppress any warning messages when creating this tree
            tableTree = new CcddTableTreeHandler(ccddMain, TableTreeType.STRUCTURES_WITH_PRIMITIVES, true, parent);
            // Check if the table is a prototype
            if (tableInfo.isPrototype()) {
                // Copy the table tree node for the prototype table. This preserves a copy of
                // the table's variables before the changes are applied
                orgTableNode = copyPrototypeTableTreeNode(tableInfo.getPrototypeName(), tableTree);
            }
        }
        // Build the commands to add, modify, and delete table rows
        String command = buildAdditionCommand(tableInfo, additions, dbTableName, typeDefinition, skipInternalTables) + buildModificationCommand(tableInfo, modifications, typeDefinition, newDataTypeHandler, tableTree, skipInternalTables) + buildDeletionCommand(tableInfo, deletions, dbTableName, typeDefinition, skipInternalTables);
        // Get the table's description
        String description = tableInfo.getDescription();
        // for the prototype of this table
        if (!tableInfo.isPrototype() && description.equals(queryTableDescription(tableInfo.getPrototypeName(), parent))) {
            // Set the description to a blank since it inherits it from the prototype
            description = "";
        }
        // Combine the table, data fields table, table description, and column order update
        // commands
        command += (updateFieldInfo ? modifyFieldsCommand(tableInfo.getTablePath(), tableInfo.getFieldHandler().getFieldInformation()) : "") + (updateDescription ? buildTableDescription(tableInfo.getTablePath(), description) : "") + (updateColumnOrder ? buildColumnOrder(tableInfo.getTablePath(), tableInfo.getColumnOrder()) : "");
        // lists are empty)
        if (!command.isEmpty()) {
            // Execute the commands
            dbCommand.executeDbUpdate(command, parent);
            // Check if references in the internal tables are to be updated
            if (!skipInternalTables && typeDefinition.isStructure()) {
                // more variables to begin with
                if (tableInfo.isPrototype() && tableInfo.getData().length > 0) {
                    // Build the command to delete bit-packed variable references in the links
                    // and telemetry scheduler tables that changed due to the table
                    // modifications
                    command = updateLinksAndTlmForPackingChange(orgTableNode, parent);
                    // Check if there are any bit-packed variable references to delete
                    if (!command.isEmpty()) {
                        // Delete invalid bit-packed variable references
                        dbCommand.executeDbUpdate(command, parent);
                    }
                    // Check if the link definitions changed
                    if (updateLinks) {
                        // Store the updated link definitions in the project database
                        storeInformationTable(InternalTable.LINKS, addLinkHandler.getLinkDefinitions(), null, parent);
                    }
                }
                // Execute the command to reset the rate for links that no longer contain any
                // variables
                dbCommand.executeDbQuery("SELECT reset_link_rate();", parent);
            }
            // Check if the table type is a structure
            if (typeDefinition.isStructure()) {
                // Update the list of root structure tables
                rootStructures = getRootStructures(parent);
            }
            // Log that inserting data into the table succeeded
            eventLog.logEvent(SUCCESS_MSG, "Table '" + tableInfo.getProtoVariableName() + "' data modified");
        }
    } catch (SQLException se) {
        // Inform the user that updating the table failed
        eventLog.logFailEvent(parent, "Cannot modify data in table '" + tableInfo.getProtoVariableName() + "'; cause '" + se.getMessage() + "'", "<html><b>Cannot modify data in table '</b>" + tableInfo.getProtoVariableName() + "<b>'");
        errorFlag = true;
    } catch (Exception e) {
        // Display a dialog providing details on the unanticipated error
        CcddUtilities.displayException(e, parent);
        errorFlag = true;
    }
    // Check that no error occurred
    if (!errorFlag) {
        // type, array size, or bit length has changed
        if (isPathUpdate) {
            // Rebuild the variable paths and offsets lists
            variableHandler.buildPathAndOffsetLists();
        }
        // Make changes to any open table editors
        CcddTableEditorDialog.doTableModificationComplete(ccddMain, tableInfo, modifications, deletions, forceUpdate);
    }
    return errorFlag;
}
Also used : SQLException(java.sql.SQLException) CCDDException(CCDD.CcddClassesDataTable.CCDDException) SQLException(java.sql.SQLException) ToolTipTreeNode(CCDD.CcddClassesComponent.ToolTipTreeNode) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition)

Example 28 with TypeDefinition

use of CCDD.CcddTableTypeHandler.TypeDefinition in project CCDD by nasa.

the class CcddDbTableCommandHandler method modifyTablePerDataTypeOrMacroChanges.

/**
 ********************************************************************************************
 * Modify all tables affected by changes to the user-defined data type names, or macro names
 * and/or macro values. This command is executed in a separate thread since it can take a
 * noticeable amount time to complete, and by using a separate thread the GUI is allowed to
 * continue to update. The GUI menu commands, however, are disabled until the database command
 * completes execution
 *
 * @param modifications
 *            list of data type (macro) definition modifications
 *
 * @param updates
 *            list of string arrays reflecting the content of the data types (macros) after
 *            being changed in the data type (macro) editor
 *
 * @param dialog
 *            reference to the data type or macro editor dialog
 ********************************************************************************************
 */
protected void modifyTablePerDataTypeOrMacroChanges(final List<TableModification> modifications, final List<String[]> updates, final CcddDialogHandler dialog) {
    final CcddDataTypeHandler newDataTypeHandler;
    final CcddMacroHandler newMacroHandler;
    final String changeName;
    // Set to true if the change is to a data type, and false if the change is to a macro
    final boolean isDataType = dialog instanceof CcddDataTypeEditorDialog;
    // Check if this is a data type change
    if (isDataType) {
        // Create new data type, macro, and variable size handlers using the updates from the
        // data type editor
        newDataTypeHandler = new CcddDataTypeHandler(updates);
        newMacroHandler = new CcddMacroHandler(ccddMain, ccddMain.getMacroHandler().getMacroData());
        changeName = "Data types";
    } else // This is a macro change
    {
        // Create new macro and variable size handlers using the updates from the macro editor
        newDataTypeHandler = dataTypeHandler;
        newMacroHandler = new CcddMacroHandler(ccddMain, updates);
        changeName = "Macros";
    }
    // Create a variable size handler accounting for the updates, then build the variable paths
    // and offsets lists
    final CcddVariableSizeAndConversionHandler newVariableHandler = new CcddVariableSizeAndConversionHandler(ccddMain, newDataTypeHandler, newMacroHandler);
    newMacroHandler.setHandlers(newVariableHandler);
    newVariableHandler.buildPathAndOffsetLists();
    /**
     ****************************************************************************************
     * Class for table information for those tables modified due to changes in a data type
     * (macro) definition
     ****************************************************************************************
     */
    class ModifiedTable {

        private final TableInformation tableInformation;

        private final CcddTableEditorHandler editor;

        /**
         ************************************************************************************
         * Class constructor for table information for those tables modified due to changes in
         * a data type (macro) definition
         *
         * @param tablePath
         *            table path (if applicable) and name
         ************************************************************************************
         */
        ModifiedTable(String tablePath) {
            // Load the table's information from the project database
            tableInformation = loadTableData(tablePath, false, true, false, dialog);
            // Create a table editor handler using the updated data types and/or macros, but
            // without displaying the editor itself
            editor = new CcddTableEditorHandler(ccddMain, tableInformation, newDataTypeHandler, newMacroHandler);
        }

        /**
         ************************************************************************************
         * Get the reference to the table information
         *
         * @return Reference to the table information
         ************************************************************************************
         */
        protected TableInformation getTableInformation() {
            return tableInformation;
        }

        /**
         ************************************************************************************
         * Get the reference to the table editor
         *
         * @return Reference to the table editor
         ************************************************************************************
         */
        protected CcddTableEditorHandler getEditor() {
            return editor;
        }
    }
    // Execute the command in the background
    CcddBackgroundCommand.executeInBackground(ccddMain, dialog, new BackgroundCommand() {

        boolean errorFlag = false;

        List<ModifiedTable> modifiedTables = new ArrayList<ModifiedTable>();

        /**
         ************************************************************************************
         * Modify data types (macros) command
         ************************************************************************************
         */
        @Override
        protected void execute() {
            TypeDefinition typeDefn = null;
            // Flag that indicates that only a data type (macro) name has been altered, or a
            // data type size where the new size is not larger than the old size. If this
            // remains true for all data type (macro) updates then the project database
            // internal table update process is streamlined, making it much faster in cases
            // where the internal tables reference a large number of variables and tables
            boolean nameChangeOnly = true;
            // Storage for the table's data. This is the table data as it exists in the project
            // database
            List<Object[]> tableData;
            // Step through each modification
            for (TableModification mod : modifications) {
                String oldName;
                String newName;
                String oldNameDelim = null;
                String newNameDelim = null;
                String[] references;
                // Check if this is a data type change
                if (isDataType) {
                    // Get the original and updated user-defined data type names
                    oldName = CcddDataTypeHandler.getDataTypeName(mod.getOriginalRowData()[DataTypesColumn.USER_NAME.ordinal()].toString(), mod.getOriginalRowData()[DataTypesColumn.C_NAME.ordinal()].toString());
                    newName = CcddDataTypeHandler.getDataTypeName(mod.getRowData()[DataTypesColumn.USER_NAME.ordinal()].toString(), mod.getRowData()[DataTypesColumn.C_NAME.ordinal()].toString());
                    // Get the references to the updated data type
                    references = dataTypeHandler.getDataTypeReferences(oldName, dialog);
                    // the initial pass)
                    if (nameChangeOnly) {
                        // Set to false if the size increased or the base type changed; keep
                        // equal to true if only the data type name has changed and the size is
                        // no larger
                        nameChangeOnly = Integer.valueOf(mod.getOriginalRowData()[DataTypesColumn.SIZE.ordinal()].toString()) >= Integer.valueOf(mod.getRowData()[DataTypesColumn.SIZE.ordinal()].toString()) && mod.getOriginalRowData()[DataTypesColumn.BASE_TYPE.ordinal()].toString().equals(mod.getRowData()[DataTypesColumn.BASE_TYPE.ordinal()].toString());
                    }
                } else // This is a macro change
                {
                    // Get the original and updated user-defined macro names
                    oldName = mod.getOriginalRowData()[MacrosColumn.MACRO_NAME.ordinal()].toString();
                    newName = mod.getRowData()[MacrosColumn.MACRO_NAME.ordinal()].toString();
                    // Get the original and updated macro names with the macro delimiters
                    oldNameDelim = CcddMacroHandler.getFullMacroName(mod.getOriginalRowData()[MacrosColumn.MACRO_NAME.ordinal()].toString());
                    newNameDelim = CcddMacroHandler.getFullMacroName(mod.getRowData()[MacrosColumn.MACRO_NAME.ordinal()].toString());
                    // Get the references to the updated macro
                    references = macroHandler.getMacroReferences(oldNameDelim, dialog);
                    // initial pass)
                    if (nameChangeOnly) {
                        // Set to false if the macro value changes; keep equal to true if only
                        // the macro name has changed
                        nameChangeOnly = macroHandler.getMacroExpansion(mod.getOriginalRowData()[MacrosColumn.VALUE.ordinal()].toString()).equals(newMacroHandler.getMacroExpansion(mod.getRowData()[MacrosColumn.VALUE.ordinal()].toString()));
                    }
                }
                // Step through each table/column containing the modification
                for (String ref : references) {
                    String tableName = null;
                    String changeColumn = null;
                    String matchColumn = null;
                    ModifiedTable modifiedTable = null;
                    // Split the reference into table name, column name, table type, and
                    // context
                    String[] tblColDescAndCntxt = ref.split(TABLE_DESCRIPTION_SEPARATOR, 4);
                    // Create a reference to the search result's database table name and row
                    // data to shorten comparisons below
                    String refTableName = tblColDescAndCntxt[SearchResultsQueryColumn.TABLE.ordinal()];
                    String[] refContext = CcddUtilities.splitAndRemoveQuotes(tblColDescAndCntxt[SearchResultsQueryColumn.CONTEXT.ordinal()]);
                    // Set to true if the referenced table is a prototype table and false if
                    // the reference is to the internal custom values table
                    boolean isPrototype = !refTableName.startsWith(INTERNAL_TABLE_PREFIX);
                    // Check if the referenced table is a prototype table
                    if (isPrototype) {
                        // Set the viewable table name (with capitalization intact) and get the
                        // column name containing the data type (macro) reference. Use the
                        // primary key as the matching column criteria
                        tableName = tblColDescAndCntxt[SearchResultsQueryColumn.COMMENT.ordinal()].split(",", 2)[0];
                        changeColumn = tblColDescAndCntxt[SearchResultsQueryColumn.COLUMN.ordinal()];
                        matchColumn = refContext[DefaultColumn.PRIMARY_KEY.ordinal()];
                    } else // change
                    if (!isDataType) {
                        // Get the table name from the variable path in the custom values table
                        // and get the column name containing the macro reference. Use the
                        // variable name as the matching column criteria
                        tableName = refContext[ValuesColumn.TABLE_PATH.ordinal()].replaceAll("(\"|\\s|,[^\\.]*\\.[^,]*$)", "");
                        changeColumn = refContext[ValuesColumn.COLUMN_NAME.ordinal()];
                        matchColumn = refContext[ValuesColumn.TABLE_PATH.ordinal()].replaceAll("(.*\\.|\")", "");
                    } else // This is a data type change and the reference is in the custom values
                    // table
                    {
                        // process
                        continue;
                    }
                    // Step through each table already loaded for modifications
                    for (ModifiedTable modTbl : modifiedTables) {
                        // Check if the table has already been loaded
                        if (modTbl.getTableInformation().getProtoVariableName().equals(tableName)) {
                            // Store the reference to the modified table and stop searching
                            modifiedTable = modTbl;
                            break;
                        }
                    }
                    // Check if the table isn't already loaded
                    if (modifiedTable == null) {
                        // Load the table and add it to the list
                        modifiedTable = new ModifiedTable(tableName);
                        modifiedTables.add(modifiedTable);
                        // Check if the table arrays aren't expanded
                        if (!modifiedTable.getEditor().isExpanded()) {
                            // Expand the table arrays
                            modifiedTable.getEditor().showHideArrayMembers();
                        }
                    }
                    // Get the reference to the table to shorten subsequent calls
                    CcddJTableHandler table = modifiedTable.getEditor().getTable();
                    // Use the table's type to get the index for the table column containing
                    // the data type (macro) reference
                    typeDefn = modifiedTable.getEditor().getTableTypeDefinition();
                    int changeColumnIndex = isPrototype ? typeDefn.getColumnIndexByDbName(changeColumn) : typeDefn.getColumnIndexByUserName(changeColumn);
                    String macroValue = null;
                    // Check is a change was made to a macro
                    if (!isDataType) {
                        // Get the original value of the macro
                        macroValue = macroHandler.getMacroValue(oldName);
                    }
                    // Set the flags that indicate if a name or value changed
                    boolean isNameChange = !oldName.equals(newName);
                    boolean isValueChange = (isDataType && (dataTypeHandler.getSizeInBytes(oldName) != newDataTypeHandler.getSizeInBytes(newName) || !dataTypeHandler.getBaseDataType(oldName).equals(newDataTypeHandler.getBaseDataType(newName)))) || (!isDataType && macroValue != null && !macroValue.equals(newMacroHandler.getMacroValue(newName)));
                    // base type, or macro value, changed
                    if (isNameChange || isValueChange) {
                        // Get the table's data (again if a name change occurred since changes
                        // were made)
                        tableData = table.getTableDataList(false);
                        // Step through each row
                        for (int row = 0; row < tableData.size(); row++) {
                            // column index for the variable name
                            if (isPrototype ? matchColumn.equals(tableData.get(row)[DefaultColumn.PRIMARY_KEY.ordinal()]) : matchColumn.equals(tableData.get(row)[typeDefn.getColumnIndexByInputType(InputDataType.VARIABLE)].toString())) {
                                // key and row index columns
                                for (int column = NUM_HIDDEN_COLUMNS; column < tableData.get(row).length; column++) {
                                    // macro
                                    if (column == changeColumnIndex) {
                                        // Check if the cell value is editable
                                        if (table.isCellEditable(table.convertRowIndexToView(row), table.convertColumnIndexToView(column))) {
                                            // Get the contents of the cell containing the data
                                            // type or macro reference
                                            String oldValue = tableData.get(row)[column].toString();
                                            String newValue = oldValue;
                                            // Check if the data type or macro name changed
                                            if (isNameChange) {
                                                // Check if this is a data type change
                                                if (isDataType) {
                                                    // the data type name
                                                    if (!oldValue.equals(oldName)) {
                                                        // sizeof() call for the data type
                                                        if (!CcddVariableSizeAndConversionHandler.hasSizeof(oldValue, oldName)) {
                                                            // type match is coincidental
                                                            continue;
                                                        }
                                                        // replacing each sizeof() instance
                                                        while (CcddVariableSizeAndConversionHandler.hasSizeof(newValue, oldName)) {
                                                            // Replace the data type in the
                                                            // sizeof() call with the new name
                                                            newValue = newValue.replaceFirst(CcddVariableSizeAndConversionHandler.getSizeofDataTypeMatch(oldName), "sizeof(" + newName + ")");
                                                        }
                                                    } else // The cell contains only the data type
                                                    // name
                                                    {
                                                        // Set the new cell value to the new
                                                        // data type name
                                                        newValue = newName;
                                                    }
                                                } else // This is a macro change
                                                {
                                                    // Replace all instances of the old macro
                                                    // name in the table cell with the new name
                                                    newValue = macroHandler.replaceMacroName(oldNameDelim, newNameDelim, oldValue);
                                                }
                                            }
                                            // size or base type
                                            if (isDataType && isValueChange) {
                                                // sizeof() call)
                                                if (!newValue.equals(newName) && !CcddVariableSizeAndConversionHandler.hasSizeof(newValue) && !CcddMacroHandler.hasMacro(newValue)) {
                                                    // match is coincidental
                                                    continue;
                                                }
                                            }
                                            // Store the change in the table data
                                            tableData.get(row)[column] = newValue;
                                            // Make the change to the cell, including any
                                            // updates to changes in array size
                                            table.validateCellContent(tableData, row, column, oldValue, newValue, false, true);
                                            // Load the updated array of data into the table
                                            table.loadDataArrayIntoTable(tableData.toArray(new Object[0][0]), false);
                                        }
                                        // located and processed
                                        break;
                                    }
                                }
                                // processed
                                break;
                            }
                        }
                    }
                }
            }
            try {
                // Enable creation of a save point in case an error occurs while modifying a
                // table. This prevents committing the changes to the database until after all
                // tables are modified
                dbCommand.setSavePointEnable(true);
                // simplified in order to speed it up
                if (nameChangeOnly) {
                    // references in the internal tables
                    for (TableModification mod : modifications) {
                        // Check if this is a data type change
                        if (isDataType) {
                            // Get the old and new data type name
                            String oldName = CcddDataTypeHandler.getDataTypeName(mod.getOriginalRowData()[DataTypesColumn.USER_NAME.ordinal()].toString(), mod.getOriginalRowData()[DataTypesColumn.C_NAME.ordinal()].toString());
                            String newName = CcddDataTypeHandler.getDataTypeName(mod.getRowData()[DataTypesColumn.USER_NAME.ordinal()].toString(), mod.getRowData()[DataTypesColumn.C_NAME.ordinal()].toString());
                            // Execute the command to update the internal tables that reference
                            // variable paths
                            dbCommand.executeDbUpdate("UPDATE " + InternalTable.LINKS.getTableName() + " SET " + LinksColumn.MEMBER.getColumnName() + " = regexp_replace(" + LinksColumn.MEMBER.getColumnName() + ", E'(.*,)" + oldName + "(\\..*)'" + ", E'\\\\1" + newName + "\\\\2'); UPDATE " + InternalTable.TLM_SCHEDULER.getTableName() + " SET " + TlmSchedulerColumn.MEMBER.getColumnName() + " = regexp_replace(" + TlmSchedulerColumn.MEMBER.getColumnName() + ", E'(.*,)" + oldName + "(\\..*)'" + ", E'\\\\1" + newName + "\\\\2'); UPDATE " + InternalTable.VALUES.getTableName() + " SET " + ValuesColumn.TABLE_PATH.getColumnName() + " = regexp_replace(" + ValuesColumn.TABLE_PATH.getColumnName() + ", E'(.*,)" + oldName + "(\\..*)'" + ", E'\\\\1" + newName + "\\\\2'); ", dialog);
                        } else // This is a macro change
                        {
                            // Get the original and updated user-defined macro names (with the
                            // delimiters)
                            String oldName = CcddMacroHandler.getFullMacroName(mod.getOriginalRowData()[MacrosColumn.MACRO_NAME.ordinal()].toString());
                            String newName = CcddMacroHandler.getFullMacroName(mod.getRowData()[MacrosColumn.MACRO_NAME.ordinal()].toString());
                            // Execute the command to update the internal tables that reference
                            // variable and table paths
                            dbCommand.executeDbUpdate("UPDATE " + InternalTable.ASSOCIATIONS.getTableName() + " SET " + AssociationsColumn.MEMBERS.getColumnName() + " = regexp_replace(" + AssociationsColumn.MEMBERS.getColumnName() + ", E'(.*)" + oldName + "(.*)'" + ", E'\\\\1" + newName + "\\\\2'); UPDATE " + InternalTable.FIELDS.getTableName() + " SET " + FieldsColumn.OWNER_NAME.getColumnName() + " = regexp_replace(" + FieldsColumn.OWNER_NAME.getColumnName() + ", E'(.*)" + oldName + "(.*)'" + ", E'\\\\1" + newName + "\\\\2'); UPDATE " + InternalTable.GROUPS.getTableName() + " SET " + GroupsColumn.MEMBERS.getColumnName() + " = regexp_replace(" + GroupsColumn.MEMBERS.getColumnName() + ", E'(.*)" + oldName + "(.*)'" + ", E'\\\\1" + newName + "\\\\2'); UPDATE " + InternalTable.LINKS.getTableName() + " SET " + LinksColumn.MEMBER.getColumnName() + " = regexp_replace(" + LinksColumn.MEMBER.getColumnName() + ", E'(.*)" + oldName + "(.*)'" + ", E'\\\\1" + newName + "\\\\2'); UPDATE " + InternalTable.TLM_SCHEDULER.getTableName() + " SET " + TlmSchedulerColumn.MEMBER.getColumnName() + " = regexp_replace(" + TlmSchedulerColumn.MEMBER.getColumnName() + ", E'(.*)" + oldName + "(.*)'" + ", E'\\\\1" + newName + "\\\\2'); UPDATE " + InternalTable.VALUES.getTableName() + " SET " + ValuesColumn.TABLE_PATH.getColumnName() + " = regexp_replace(" + ValuesColumn.TABLE_PATH.getColumnName() + ", E'(.*)" + oldName + "(.*)'" + ", E'\\\\1" + newName + "\\\\2'); ", dialog);
                        }
                    }
                }
                // Step through each modified table
                for (ModifiedTable modTbl : modifiedTables) {
                    // Build the additions, modifications, and deletions to the table
                    modTbl.getEditor().buildUpdates();
                    // table editors that contain the data type (macro) reference(s)
                    if (modifyTableData(modTbl.getTableInformation(), modTbl.getEditor().getAdditions(), modTbl.getEditor().getModifications(), modTbl.getEditor().getDeletions(), true, nameChangeOnly, false, false, false, newDataTypeHandler, dialog)) {
                        throw new SQLException("table modification error");
                    }
                }
                // Store the data type or macro table
                dbCommand.executeDbUpdate(storeNonTableTypesInfoTableCommand((isDataType ? InternalTable.DATA_TYPES : InternalTable.MACROS), CcddUtilities.removeArrayListColumn(updates, (isDataType ? DataTypesColumn.OID.ordinal() : MacrosColumn.OID.ordinal())), null, dialog), dialog);
                // Commit the change(s) to the database
                dbCommand.getConnection().commit();
                // Inform the user that the update succeeded
                eventLog.logEvent(SUCCESS_MSG, changeName + " and all affected tables updated");
            } catch (SQLException se) {
                try {
                    // Inform the user that updating the macros failed
                    eventLog.logFailEvent(dialog, "Cannot update " + changeName.toLowerCase() + "; cause '" + se.getMessage() + "'", "<html><b>Cannot update " + changeName.toLowerCase());
                    // Revert the changes to the tables that were successfully updated prior
                    // the current table
                    dbCommand.executeDbCommand("ROLLBACK TO SAVEPOINT " + DB_SAVE_POINT_NAME + ";", dialog);
                } catch (SQLException se2) {
                    // Inform the user that the reversion to the save point failed
                    eventLog.logFailEvent(dialog, "Cannot revert changes to table(s); cause '" + se.getMessage() + "'", "<html><b>Cannot revert changes to table(s)");
                }
                errorFlag = true;
            } catch (Exception e) {
                // Display a dialog providing details on the unanticipated error
                CcddUtilities.displayException(e, dialog);
            } finally {
                // Reset the flag for creating a save point
                dbCommand.setSavePointEnable(false);
            }
        }

        /**
         ************************************************************************************
         * Modify data types or macros command complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            // Rebuild the variable paths and offsets
            variableHandler.buildPathAndOffsetLists();
            // Check if this is a data type change
            if (isDataType) {
                ((CcddDataTypeEditorDialog) dialog).doDataTypeUpdatesComplete(errorFlag);
            } else // This is a macro change
            {
                ((CcddMacroEditorDialog) dialog).doMacroUpdatesComplete(errorFlag);
            }
        }
    });
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) TableModification(CCDD.CcddClassesDataTable.TableModification) CCDDException(CCDD.CcddClassesDataTable.CCDDException) SQLException(java.sql.SQLException) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition) TableInformation(CCDD.CcddClassesDataTable.TableInformation) List(java.util.List) ArrayList(java.util.ArrayList) DatabaseObject(CCDD.CcddConstants.DatabaseObject) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand)

Example 29 with TypeDefinition

use of CCDD.CcddTableTypeHandler.TypeDefinition in project CCDD by nasa.

the class CcddDbTableCommandHandler method deleteTableType.

/**
 ********************************************************************************************
 * Delete a table type and all tables of the deleted type. This command is executed in a
 * separate thread since it can take a noticeable amount time to complete, and by using a
 * separate thread the GUI is allowed to continue to update. The GUI menu commands, however,
 * are disabled until the database command completes execution
 *
 * @param typeName
 *            type of table to delete
 *
 * @param isStructure
 *            true if the table type represents a structure
 *
 * @param typeDialog
 *            reference to the type manager dialog
 *
 * @param parent
 *            GUI component calling this method
 ********************************************************************************************
 */
protected void deleteTableType(final String typeName, final boolean isStructure, final CcddTableTypeManagerDialog typeDialog, final Component parent) {
    // Execute the command in the background
    CcddBackgroundCommand.executeInBackground(ccddMain, new BackgroundCommand() {

        boolean errorFlag = false;

        boolean isStructure = false;

        String[] tableNames = null;

        String names = "";

        /**
         ************************************************************************************
         * Table type deletion command
         ************************************************************************************
         */
        @Override
        protected void execute() {
            try {
                // Get the reference to the type definition
                TypeDefinition typeDefn = tableTypeHandler.getTypeDefinition(typeName);
                // Set the flag to indicate if the type represents a structure
                boolean isStructure = typeDefn.isStructure();
                // Delete the table type definition from the table type handler
                tableTypeHandler.getTypeDefinitions().remove(typeDefn);
                // Create the command to update the table definitions table
                String command = storeTableTypesInfoTableCommand();
                // Get an array containing tables of the specified type
                tableNames = queryTablesOfTypeList(typeName, ccddMain.getMainFrame());
                // Check if there are any associated tables to delete
                if (tableNames.length != 0) {
                    // Convert the array of tables names into a single string and shorten it if
                    // too long
                    names = getShortenedTableNames(tableNames);
                    // Check if the user confirms deleting the affected table(s)
                    if (new CcddDialogHandler().showMessageDialog(parent, "<html><b>Delete table(s) '</b>" + names + "<b>' of type '</b>" + typeName + "<b>'?<br><br><i>Warning: This action cannot be undone!", "Delete Table(s)", JOptionPane.QUESTION_MESSAGE, DialogOption.OK_CANCEL_OPTION) == OK_BUTTON) {
                        // Add the command to delete the tables and all their references in the
                        // internal tables
                        command += deleteTableCommand(tableNames, true) + " ";
                    } else // The user canceled the operation
                    {
                        // Set the error flag to restore the deleted type definition
                        errorFlag = true;
                    }
                }
                // Check if the user didn't cancel the operation
                if (!errorFlag) {
                    // Add the command to remove any default data fields for this table type
                    command += modifyFieldsCommand(CcddFieldHandler.getFieldTypeName(typeName), null);
                    // Step through the array of table names
                    for (String name : tableNames) {
                        // Remove the table's data fields
                        command += modifyFieldsCommand(name, null);
                    }
                    // Modify the (shortened) names string for logging messages
                    names = " and table(s) '</b>" + names + "<b>'";
                    // Delete the table(s)
                    dbCommand.executeDbUpdate(command, parent);
                    // Execute the command to reset the rate for links that no longer contain
                    // any variables
                    dbCommand.executeDbQuery("SELECT reset_link_rate();", parent);
                    // Check if the the deleted type represented a structure
                    if (isStructure) {
                        // Update the list of root structure tables
                        rootStructures = getRootStructures(parent);
                    }
                    // Log that table deletion succeeded
                    eventLog.logEvent(SUCCESS_MSG, "Table type '" + typeName + "'" + CcddUtilities.removeHTMLTags(names) + " deleted");
                }
            } catch (SQLException se) {
                // Inform the user that the table deletion failed
                eventLog.logFailEvent(parent, "Cannot delete table type '" + typeName + "'" + CcddUtilities.removeHTMLTags(names) + "; cause '" + se.getMessage() + "'", "<html><b>Cannot delete table type '" + typeName + "'</b>" + names + "<b>'");
                errorFlag = true;
            }
        }

        /**
         ************************************************************************************
         * Delete table type command complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            // Check if no error occurred when deleting the table type
            if (!errorFlag) {
                // Check if the deleted type represents a structure
                if (isStructure) {
                    // Update the database functions that collect structure table members and
                    // structure-defining column data
                    dbControl.createStructureColumnFunctions();
                }
                // Check if the number of rate columns changed due to the type deletion
                if (rateHandler.setRateInformation()) {
                    // Store the rate parameters in the project database
                    storeRateParameters(ccddMain.getMainFrame());
                }
            }
            // Perform any remaining steps, based on if deleting the type was successful
            typeDialog.doTypeOperationComplete(errorFlag, null, tableNames);
        }
    });
}
Also used : SQLException(java.sql.SQLException) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition)

Example 30 with TypeDefinition

use of CCDD.CcddTableTypeHandler.TypeDefinition in project CCDD by nasa.

the class CcddDbTableCommandHandler method createTableCommand.

/**
 ********************************************************************************************
 * Build the command to create a table of the specified type
 *
 * @param tableName
 *            name of the table to create
 *
 * @param description
 *            description for the new table
 *
 * @param tableType
 *            type of table to create (e.g., Structure or Command)
 *
 * @param parent
 *            GUI component over which to center any dialogs
 *
 * @return The command to create the specified table
 ********************************************************************************************
 */
private String createTableCommand(String tableName, String description, String tableType, Component parent) {
    StringBuilder command = new StringBuilder("");
    // Convert the table name to lower case. This is done automatically by PostgreSQL, so this
    // is done here to differentiate the table name from the upper case database commands in
    // the event log
    String dbTableName = tableName.toLowerCase();
    // Get the column names defined in the template file for this table type
    TypeDefinition typeDefn = tableTypeHandler.getTypeDefinition(tableType);
    // Build the table creation and description commands
    command.append("CREATE TABLE " + dbTableName + " (");
    // Step through each column name
    for (int column = 0; column < typeDefn.getColumnNamesDatabase().length; column++) {
        // Add the column identifier and column data type to the command
        command.append("\"" + typeDefn.getColumnNamesDatabase()[column] + "\" " + DefaultColumn.getColumnDbType(column) + ", ");
    }
    // Remove the trailing comma and space, then append the closing portion of the command, add
    // the command to save the table comments, and add the column descriptions as table column
    // comments
    command = CcddUtilities.removeTrailer(command, ", ");
    command.append("); " + buildDataTableComment(tableName, tableType) + buildTableDescription(tableName, description) + buildColumnOrder(tableName, tableTypeHandler.getDefaultColumnOrder(tableType)));
    // Copy the default fields for the new table's type to the new table and set the table's
    // owner
    command.append(copyDataFieldCommand(CcddFieldHandler.getFieldTypeName(tableType), tableName, parent) + dbControl.buildOwnerCommand(DatabaseObject.TABLE, tableName));
    return command.toString();
}
Also used : TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition)

Aggregations

TypeDefinition (CCDD.CcddTableTypeHandler.TypeDefinition)64 TableInformation (CCDD.CcddClassesDataTable.TableInformation)30 ArrayList (java.util.ArrayList)24 CCDDException (CCDD.CcddClassesDataTable.CCDDException)18 AssociatedColumns (CCDD.CcddClassesDataTable.AssociatedColumns)10 SQLException (java.sql.SQLException)9 JSONArray (org.json.simple.JSONArray)8 JSONObject (org.json.simple.JSONObject)8 TableTypeDefinition (CCDD.CcddClassesDataTable.TableTypeDefinition)6 IOException (java.io.IOException)6 TableDefinition (CCDD.CcddClassesDataTable.TableDefinition)5 BackgroundCommand (CCDD.CcddBackgroundCommand.BackgroundCommand)4 ArrayListMultiple (CCDD.CcddClassesComponent.ArrayListMultiple)4 FileEnvVar (CCDD.CcddClassesComponent.FileEnvVar)3 FieldInformation (CCDD.CcddClassesDataTable.FieldInformation)3 Component (java.awt.Component)3 GridBagConstraints (java.awt.GridBagConstraints)3 GridBagLayout (java.awt.GridBagLayout)3 Insets (java.awt.Insets)3 ResultSet (java.sql.ResultSet)3