Search in sources :

Example 36 with TypeDefinition

use of CCDD.CcddTableTypeHandler.TypeDefinition 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 37 with TypeDefinition

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

the class CcddScriptHandler method readTable.

/**
 ********************************************************************************************
 * Recursive method to load a table, and all the tables referenced within it and its child
 * tables. The data is combined into a single array
 *
 * @param tablePath
 *            table path
 *
 * @param parent
 *            GUI component calling this method
 *
 * @return A reference to the TableInformation for the parent table; null if the table has
 *         already been loaded. The error flag for the table data handler is set if an error
 *         occurred loading the data
 ********************************************************************************************
 */
private TableInformation readTable(String tablePath, Component parent) {
    TableInformation tableInfo = null;
    // Check if the table is not already stored in the list
    if (!loadedTablePaths.contains(tablePath)) {
        // Add the table path to the list so that it is not reloaded
        loadedTablePaths.add(tablePath);
        // Read the table's data from the database
        tableInfo = dbTable.loadTableData(tablePath, false, false, false, parent);
        // isn't empty
        if (!tableInfo.isErrorFlag() && tableInfo.getData().length != 0) {
            // Get the table's type definition
            TypeDefinition typeDefn = tableTypeHandler.getTypeDefinition(tableInfo.getType());
            // Get the data and place it in an array for reference below. Add columns to
            // contain the table type and path
            String[][] data = CcddUtilities.appendArrayColumns(tableInfo.getData(), 2);
            int typeColumn = data[0].length - TYPE_COLUMN_DELTA;
            int pathColumn = data[0].length - PATH_COLUMN_DELTA;
            // Get the index of the column containing the data type for this table if it has
            // one
            int dataTypeColumn = typeDefn.getColumnIndexByInputType(InputDataType.PRIM_AND_STRUCT);
            // Step through each row
            for (int row = 0; row < data.length && !tableInfo.isErrorFlag(); row++) {
                // Use the index column to store the table path and type for reference during
                // script execution
                data[row][typeColumn] = tableInfo.getType();
                data[row][pathColumn] = tablePath;
                // Store the data from the table in the combined storage array
                combinedData = CcddUtilities.concatenateArrays(combinedData, new String[][] { data[row] });
                // not contain a primitive data type)
                if (dataTypeColumn != -1 && !dataTypeHandler.isPrimitive(data[row][dataTypeColumn])) {
                    // Get the column containing the variable name for this table
                    int varNameColumn = typeDefn.getColumnIndexByInputType(InputDataType.VARIABLE);
                    // Check that a variable name column was found
                    if (varNameColumn != -1) {
                        // Get the column containing the array size for this table
                        int arraySizeColumn = typeDefn.getColumnIndexByInputType(InputDataType.ARRAY_INDEX);
                        // information for this data type structure
                        if ((!data[row][dataTypeColumn].isEmpty() || !data[row][varNameColumn].isEmpty()) && (arraySizeColumn == -1 || data[row][arraySizeColumn].isEmpty() || ArrayVariable.isArrayMember(data[row][varNameColumn]))) {
                            // Get the variable in the format dataType.variableName, prepend a
                            // comma to separate the new variable from the preceding variable
                            // path, then break down the child table
                            TableInformation childInfo = readTable(tablePath + "," + data[row][dataTypeColumn] + "." + data[row][varNameColumn], parent);
                            // Check if an error occurred loading the child table
                            if (childInfo != null && childInfo.isErrorFlag()) {
                                // Set the error flag and stop processing this table
                                tableInfo.setErrorFlag();
                                break;
                            }
                        }
                    } else // Table has no variable name column
                    {
                        // Set the error flag and stop processing this table
                        tableInfo.setErrorFlag();
                        break;
                    }
                }
            }
        }
    }
    return tableInfo;
}
Also used : TableInformation(CCDD.CcddClassesDataTable.TableInformation) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition)

Example 38 with TypeDefinition

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

the class CcddSearchHandler method searchTablesOrScripts.

/**
 ********************************************************************************************
 * Search for occurrences of a string in the tables or scripts
 *
 * @param searchText
 *            text string to search for in the database
 *
 * @param ignoreCase
 *            true to ignore case when looking for matching text
 *
 * @param allowRegex
 *            true to allow a regular expression search string
 *
 * @param dataTablesOnly
 *            true if only the data tables, and not references in the internal tables, are to
 *            be searched
 *
 * @param searchColumns
 *            string containing the names of columns, separated by commas, to which to
 *            constrain a table search
 *
 * @return Search results List containing object arrays providing each match's location in the
 *         database tables or event log, the column within the location, and an extract for the
 *         located match showing its context
 ********************************************************************************************
 */
protected List<Object[]> searchTablesOrScripts(String searchText, boolean ignoreCase, boolean allowRegex, boolean dataTablesOnly, String searchColumns) {
    // Initialize the list to contain the search results
    List<Object[]> resultsDataList = new ArrayList<Object[]>();
    // Set the search type based on the dialog type and, for a table search, the state of the
    // 'data tables only' check box
    String searchType = searchDlgType == SearchDialogType.TABLES ? (dataTablesOnly ? SearchType.DATA.toString() : SearchType.ALL.toString()) : SearchType.SCRIPT.toString();
    // Search the database for the text
    String[] hits = dbCommand.getList(DatabaseListCommand.SEARCH, new String[][] { { "_search_text_", searchText }, { "_case_insensitive_", String.valueOf(ignoreCase) }, { "_allow_regex_", String.valueOf(allowRegex) }, { "_selected_tables_", searchType }, { "_columns_", searchColumns } }, CcddSearchHandler.this);
    // Step through each table/column containing the search text
    for (String hit : hits) {
        // Split the found item into table, column, description, and context
        String[] tblColDescAndCntxt = hit.split(TABLE_DESCRIPTION_SEPARATOR, 4);
        // Create a reference to the search result's column name to shorten comparisons below
        String hitColumnName = tblColDescAndCntxt[SearchResultsQueryColumn.COLUMN.ordinal()];
        // Check that the column isn't the primary key or row index
        if (!hitColumnName.equals(DefaultColumn.PRIMARY_KEY.getDbName()) && !hitColumnName.equals(DefaultColumn.ROW_INDEX.getDbName())) {
            // Create references to the the remaining search result columns to shorten
            // comparisons below
            String hitTableName = tblColDescAndCntxt[SearchResultsQueryColumn.TABLE.ordinal()];
            String hitTableComment = tblColDescAndCntxt[SearchResultsQueryColumn.COMMENT.ordinal()];
            String hitContext = tblColDescAndCntxt[SearchResultsQueryColumn.CONTEXT.ordinal()];
            // Separate the table comment into the viewable table name and table type, or for
            // scripts the script name and description
            String[] nameAndType = hitTableComment.split(",");
            // Split the row in which the match is found into its separate columns, accounting
            // for quotes around the comma separated column values (i.e., ignore commas within
            // quotes)
            String[] columnValue = CcddUtilities.splitAndRemoveQuotes(hitContext);
            String target = null;
            String location = null;
            String context = null;
            // Check if this is a table search
            if (searchDlgType == SearchDialogType.TABLES) {
                // The reference is to a prototype table
                if (!hitTableName.startsWith(INTERNAL_TABLE_PREFIX)) {
                    // Get the table's type definition based on its table type
                    TypeDefinition typeDefn = tableTypeHandler.getTypeDefinition(nameAndType[1]);
                    // Get the index of the column where the match exists
                    int colIndex = typeDefn.getColumnIndexByDbName(hitColumnName);
                    // Set the row number for the row location if the variable name or command
                    // name aren't present
                    String row = "row " + columnValue[DefaultColumn.ROW_INDEX.ordinal()];
                    // Check if this is a structure table
                    if (typeDefn.isStructure()) {
                        // Get the variable name column index
                        int index = typeDefn.getColumnIndexByInputType(InputDataType.VARIABLE);
                        // Check that a variable name exists
                        if (index != -1 && !columnValue[index].isEmpty()) {
                            // Set the row location to the variable name
                            row = "variable '" + columnValue[index] + "'";
                        }
                    } else // Check if this is a command table
                    if (typeDefn.isCommand()) {
                        // Get the command name column index
                        int index = typeDefn.getColumnIndexByInputType(InputDataType.COMMAND_NAME);
                        // Check that a command name exists
                        if (index != -1 && !columnValue[index].isEmpty()) {
                            // Set the row location to the command name
                            row = "command '" + columnValue[index] + "'";
                        }
                    }
                    // Set the search result table values
                    target = SearchTarget.TABLE.getTargetName(true) + nameAndType[0];
                    location = "Column '" + typeDefn.getColumnNamesUser()[colIndex] + "', " + row;
                    context = columnValue[colIndex];
                } else // Check if the match is in the custom values internal table
                if (hitTableName.equals(InternalTable.VALUES.getTableName())) {
                    // Check if the match is in the value column
                    if (hitColumnName.equals(ValuesColumn.VALUE.getColumnName())) {
                        // Get the column values from the row in which the match occurs
                        String tablePath = columnValue[ValuesColumn.TABLE_PATH.ordinal()];
                        String columnName = columnValue[ValuesColumn.COLUMN_NAME.ordinal()];
                        String value = columnValue[ValuesColumn.VALUE.ordinal()];
                        // Check if this is a table definition entry in the values table
                        if (columnName.isEmpty()) {
                            // Set the location
                            location = "Table description";
                        } else // Column value from a child table stored in the internal values table.
                        // Since this isn't a table description the reference must be to a
                        // structure table (for other table types the match would be in the
                        // table prototype)
                        {
                            // Set the location
                            location = "Column '" + columnName + "'";
                            // Initialize the variable name and get the index where the last
                            // variable name begins
                            int index = tablePath.lastIndexOf(',');
                            // Check if a variable name exists
                            if (index != -1) {
                                // Extract the variable from the path, then remove it from the
                                // variable path
                                location += ", variable '" + tablePath.substring(index + 1).replaceFirst("^.+\\.", "") + "'";
                            }
                        }
                        // Set the search result table values
                        target = CcddUtilities.highlightDataType(SearchTarget.TABLE.getTargetName(true) + ": " + tablePath);
                        context = value;
                    }
                } else // Check if the match is in the data types internal table
                if (hitTableName.equals(InternalTable.DATA_TYPES.getTableName())) {
                    target = SearchTarget.DATA_TYPE.getTargetName(true) + CcddDataTypeHandler.getDataTypeName(columnValue[DataTypesColumn.USER_NAME.ordinal()], columnValue[DataTypesColumn.C_NAME.ordinal()]);
                    // Check if the match is with the user-defined name
                    if (hitColumnName.equals(DataTypesColumn.USER_NAME.getColumnName())) {
                        location = "User-defined name";
                        context = columnValue[DataTypesColumn.USER_NAME.ordinal()];
                    } else // Check if the match is with the C-language name
                    if (hitColumnName.equals(DataTypesColumn.C_NAME.getColumnName())) {
                        location = "C-language name";
                        context = columnValue[DataTypesColumn.C_NAME.ordinal()];
                    } else // Check if the match is with the data type size
                    if (hitColumnName.equals(DataTypesColumn.SIZE.getColumnName())) {
                        location = "Data type size";
                        context = columnValue[DataTypesColumn.SIZE.ordinal()];
                    } else // Check if the match is with the base type
                    if (hitColumnName.equals(DataTypesColumn.BASE_TYPE.getColumnName())) {
                        location += "Base data type";
                        context = columnValue[DataTypesColumn.BASE_TYPE.ordinal()];
                    }
                } else // Check if the match is in the groups table
                if (hitTableName.equals(InternalTable.GROUPS.getTableName())) {
                    target = SearchTarget.GROUP.getTargetName(true) + columnValue[GroupsColumn.GROUP_NAME.ordinal()];
                    // Check if the match is with the group name
                    if (hitColumnName.equals(GroupsColumn.GROUP_NAME.getColumnName())) {
                        location = "Name";
                        context = columnValue[GroupsColumn.GROUP_NAME.ordinal()];
                    } else // The match is with a group definition or member
                    {
                        // definition
                        if (columnValue[GroupsColumn.MEMBERS.ordinal()].matches("^\\d+")) {
                            // Get the group description (remove the dummy number and comma
                            // that flags this as a group definition)
                            context = columnValue[GroupsColumn.MEMBERS.ordinal()].split(",")[1];
                            // dummy number and comma aren't part of the match)
                            if (context.toLowerCase().contains(searchText.toLowerCase())) {
                                location = "Description";
                            } else // The match includes the dummy number and comma; ignore
                            {
                                target = null;
                            }
                        } else // This is a group member
                        {
                            location = "Member table";
                            context = columnValue[GroupsColumn.MEMBERS.ordinal()];
                        }
                    }
                } else // Check if the match is in the fields internal table
                if (hitTableName.equals(InternalTable.FIELDS.getTableName())) {
                    // Check if this is a default data field
                    if ((columnValue[FieldsColumn.OWNER_NAME.ordinal()] + ":").startsWith(CcddFieldHandler.getFieldTypeName(""))) {
                        target = SearchTarget.DEFAULT_FIELD.getTargetName(true) + columnValue[FieldsColumn.OWNER_NAME.ordinal()].replaceFirst("^.*:", "");
                    } else // Check if this is a group data field
                    if ((columnValue[FieldsColumn.OWNER_NAME.ordinal()] + ":").startsWith(CcddFieldHandler.getFieldGroupName(""))) {
                        target = SearchTarget.GROUP_FIELD.getTargetName(true) + columnValue[FieldsColumn.OWNER_NAME.ordinal()].replaceFirst("^.*:", "");
                    } else // This is a table data field
                    {
                        target = CcddUtilities.highlightDataType(SearchTarget.TABLE_FIELD.getTargetName(true) + columnValue[FieldsColumn.OWNER_NAME.ordinal()]);
                    }
                    location = "Field name '" + columnValue[FieldsColumn.FIELD_NAME.ordinal()] + "' ";
                    // Check if the match is with the field owner name
                    if (hitColumnName.equals(FieldsColumn.OWNER_NAME.getColumnName())) {
                        location += "owner";
                        context = columnValue[FieldsColumn.OWNER_NAME.ordinal()];
                    } else // Check if the match is with the field name
                    if (hitColumnName.equals(FieldsColumn.FIELD_NAME.getColumnName())) {
                        location += "name";
                        context = columnValue[FieldsColumn.FIELD_NAME.ordinal()];
                    } else // Check if the match is with the field description
                    if (hitColumnName.equals(FieldsColumn.FIELD_DESC.getColumnName())) {
                        location += "description";
                        context = columnValue[FieldsColumn.FIELD_DESC.ordinal()];
                    } else // Check if the match is with the field size
                    if (hitColumnName.equals(FieldsColumn.FIELD_SIZE.getColumnName())) {
                        location += "size";
                        context = columnValue[FieldsColumn.FIELD_SIZE.ordinal()];
                    } else // Check if the match is with the field input type
                    if (hitColumnName.equals(FieldsColumn.FIELD_TYPE.getColumnName())) {
                        location += "input type";
                        context = columnValue[FieldsColumn.FIELD_TYPE.ordinal()];
                    } else // Check if the match is with the field applicability
                    if (hitColumnName.equals(FieldsColumn.FIELD_APPLICABILITY.getColumnName())) {
                        location += "applicability";
                        context = columnValue[FieldsColumn.FIELD_APPLICABILITY.ordinal()];
                    } else // Check if the match is with the field value
                    if (hitColumnName.equals(FieldsColumn.FIELD_VALUE.getColumnName())) {
                        location += "value";
                        context = columnValue[FieldsColumn.FIELD_VALUE.ordinal()];
                    } else // Check if the match is with the field required flag
                    if (hitColumnName.equals(FieldsColumn.FIELD_REQUIRED.getColumnName())) {
                        location += "required flag";
                        context = columnValue[FieldsColumn.FIELD_REQUIRED.ordinal()];
                    }
                } else // Check if the match is in the associations internal table
                if (hitTableName.equals(InternalTable.ASSOCIATIONS.getTableName())) {
                    target = SearchTarget.SCRIPT_ASSN.getTargetName(true) + columnValue[AssociationsColumn.SCRIPT_FILE.ordinal()];
                    // Check if the match is with the script file path and/or name
                    if (hitColumnName.equals(AssociationsColumn.SCRIPT_FILE.getColumnName())) {
                        location = "File path and name";
                        context = columnValue[AssociationsColumn.SCRIPT_FILE.ordinal()];
                    } else // The match is with a script association member
                    {
                        location = "Member table";
                        context = columnValue[AssociationsColumn.MEMBERS.ordinal()];
                    }
                } else // Check if the match is in the telemetry scheduler internal table
                if (hitTableName.equals(InternalTable.TLM_SCHEDULER.getTableName())) {
                    target = SearchTarget.TLM_MESSAGE.getTargetName(true) + columnValue[TlmSchedulerColumn.MESSAGE_NAME.ordinal()];
                    // Check if the match is with the message name
                    if (hitColumnName.equals(TlmSchedulerColumn.MESSAGE_NAME.getColumnName())) {
                        location = "Name";
                        context = columnValue[TlmSchedulerColumn.MESSAGE_NAME.ordinal()];
                    } else // Check if the match is with the message rate name
                    if (hitColumnName.equals(TlmSchedulerColumn.RATE_NAME.getColumnName())) {
                        location = "Rate name";
                        context = columnValue[TlmSchedulerColumn.RATE_NAME.ordinal()];
                    } else // Check if the match is with the message ID
                    if (hitColumnName.equals(TlmSchedulerColumn.MESSAGE_ID.getColumnName())) {
                        location = "ID";
                        context = columnValue[TlmSchedulerColumn.MESSAGE_ID.ordinal()];
                    } else // The match is with a message definition or member
                    {
                        context = columnValue[TlmSchedulerColumn.MEMBER.ordinal()];
                        // definition
                        if (columnValue[TlmSchedulerColumn.MEMBER.ordinal()].matches("^\\d+")) {
                            location = "Rate and description";
                        } else // This is a message member
                        {
                            location = "Member rate, table, and variable";
                        }
                    }
                } else // Check if the match is in the links internal table
                if (hitTableName.equals(InternalTable.LINKS.getTableName())) {
                    target = SearchTarget.TLM_LINK.getTargetName(true) + columnValue[LinksColumn.LINK_NAME.ordinal()];
                    // Check if the match is with the link name
                    if (hitColumnName.equals(LinksColumn.LINK_NAME.getColumnName())) {
                        location = "Name";
                        context = columnValue[LinksColumn.LINK_NAME.ordinal()];
                    } else // Check if the match is with the link rate name
                    if (hitColumnName.equals(LinksColumn.RATE_NAME.getColumnName())) {
                        location = "Rate name";
                        context = columnValue[LinksColumn.RATE_NAME.ordinal()];
                    } else // The match is with a link definition or member
                    {
                        context = columnValue[LinksColumn.MEMBER.ordinal()];
                        // definition
                        if (columnValue[1].matches("^\\d+")) {
                            location = "Rate and description";
                        } else // This is a link member
                        {
                            location = "Member table and variable";
                        }
                    }
                } else // Check if the match is in the table types internal table
                if (hitTableName.equals(InternalTable.TABLE_TYPES.getTableName())) {
                    target = SearchTarget.TABLE_TYPE.getTargetName(true) + columnValue[TableTypesColumn.TYPE_NAME.ordinal()];
                    // Check if the match is with the column name
                    if (hitColumnName.equals(TableTypesColumn.COLUMN_NAME_VISIBLE.getColumnName())) {
                        location = "Column name";
                        context = columnValue[TableTypesColumn.COLUMN_NAME_VISIBLE.ordinal()];
                    } else // Check if the match is with the column description
                    if (hitColumnName.equals(TableTypesColumn.COLUMN_DESCRIPTION.getColumnName())) {
                        location = "Column description";
                        context = columnValue[TableTypesColumn.COLUMN_DESCRIPTION.ordinal()];
                    } else // Check if the match is with the column input type
                    if (hitColumnName.equals(TableTypesColumn.INPUT_TYPE.getColumnName())) {
                        location = "Column input type";
                        context = columnValue[TableTypesColumn.INPUT_TYPE.ordinal()];
                    } else // Check if the match is with the column required flag
                    if (hitColumnName.equals(TableTypesColumn.COLUMN_REQUIRED.getColumnName())) {
                        location = "Column required flag";
                        context = columnValue[TableTypesColumn.COLUMN_REQUIRED.ordinal()];
                    } else // Check if the match is with the row value unique flag
                    if (hitColumnName.equals(TableTypesColumn.ROW_VALUE_UNIQUE.getColumnName())) {
                        location = "Row value unique flag";
                        context = columnValue[TableTypesColumn.ROW_VALUE_UNIQUE.ordinal()];
                    } else // Match is in one of the remaining table type columns
                    {
                        // Ignore this match
                        target = null;
                    }
                } else // Check if the match is in the application scheduler internal table
                if (hitTableName.equals(InternalTable.APP_SCHEDULER.getTableName())) {
                    target = SearchTarget.APP_SCHEDULER.getTargetName(true);
                    location = "Time slot '" + columnValue[AppSchedulerColumn.TIME_SLOT.ordinal()] + "' ";
                    // Check if the match is with the application name
                    if (hitColumnName.equals(AppSchedulerColumn.TIME_SLOT.getColumnName())) {
                        location += "name";
                        context = columnValue[AppSchedulerColumn.TIME_SLOT.ordinal()];
                    } else // The match is with a scheduler member
                    {
                        context = columnValue[AppSchedulerColumn.APP_INFO.ordinal()];
                        location += "member information";
                    }
                }
            } else // This is a script search and the match is in a stored script
            {
                // Set the search result table values
                target = nameAndType[0];
                location = columnValue[ScriptColumn.LINE_NUM.ordinal()];
                context = columnValue[ScriptColumn.LINE_TEXT.ordinal()];
            }
            // Check if a search result exists
            if (target != null) {
                // Add the search result to the list
                resultsDataList.add(new Object[] { target, location, context });
            }
        }
    }
    // Display the search results
    return sortSearchResults(resultsDataList);
}
Also used : ArrayList(java.util.ArrayList) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition)

Example 39 with TypeDefinition

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

the class CcddFileIOHandler method importFile.

/**
 ********************************************************************************************
 * Import one or more files, creating new tables and optionally replacing existing ones. The
 * file(s) may contain definitions for more than one table. This method 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 method completes execution
 *
 * @param dataFile
 *            array of files to import
 *
 * @param backupFirst
 *            true to create a backup of the database before importing tables
 *
 * @param replaceExisting
 *            true to replace a table that already exists in the database
 *
 * @param appendExistingFields
 *            true to append the existing data fields for a table (if any) to the imported ones
 *            (if any). Only valid when replaceExisting is true
 *
 * @param useExistingFields
 *            true to replace an existing data field with the imported ones if the field names
 *            match. Only valid when replaceExisting and appendExistingFields are true
 *
 * @param parent
 *            GUI component calling this method
 ********************************************************************************************
 */
protected void importFile(final FileEnvVar[] dataFile, final boolean backupFirst, final boolean replaceExisting, final boolean appendExistingFields, final boolean useExistingFields, final Component parent) {
    // Create a data field handler
    final CcddFieldHandler fieldHandler = new CcddFieldHandler(ccddMain, null, parent);
    // Store the current table type, data type, macro, reserved message ID, and data field
    // information in case it needs to be restored
    final List<TypeDefinition> originalTableTypes = new ArrayList<TypeDefinition>(tableTypeHandler.getTypeDefinitions());
    final List<String[]> originalDataTypes = new ArrayList<String[]>(dataTypeHandler.getDataTypeData());
    final List<String[]> originalMacros = new ArrayList<String[]>(macroHandler.getMacroData());
    final List<String[]> originalReservedMsgIDs = new ArrayList<String[]>(rsvMsgIDHandler.getReservedMsgIDData());
    final List<String[]> originalDataFields = new ArrayList<String[]>(fieldHandler.getFieldDefinitions());
    // Execute the import operation in the background
    CcddBackgroundCommand.executeInBackground(ccddMain, new BackgroundCommand() {

        List<TableDefinition> allTableDefinitions = new ArrayList<TableDefinition>();

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

        boolean errorFlag = false;

        /**
         ************************************************************************************
         * Import the selected table(s)
         ************************************************************************************
         */
        @Override
        protected void execute() {
            CcddImportExportInterface ioHandler = null;
            // Create a reference to a table editor dialog
            tableEditorDlg = null;
            // Check if the user elected to back up the project before importing tables
            if (backupFirst) {
                // Back up the project database
                backupDatabaseToFile(false);
            }
            // Step through each selected file
            for (FileEnvVar file : dataFile) {
                try {
                    // Check if the file doesn't exist
                    if (!file.exists()) {
                        throw new CCDDException("Cannot locate import file<br>'</b>" + file.getAbsolutePath() + "<b>'");
                    }
                    // Check if the file to import is in CSV format based on the extension
                    if (file.getAbsolutePath().endsWith(FileExtension.CSV.getExtension())) {
                        // Create a CSV handler
                        ioHandler = new CcddCSVHandler(ccddMain, fieldHandler, parent);
                    } else // Check if the file to import is in EDS format based on the extension
                    if (file.getAbsolutePath().endsWith(FileExtension.EDS.getExtension())) {
                        // Create a EDS handler
                        ioHandler = new CcddEDSHandler(ccddMain, fieldHandler, parent);
                    } else // Check if the file to import is in JSON format based on the extension
                    if (file.getAbsolutePath().endsWith(FileExtension.JSON.getExtension())) {
                        // Create a JSON handler
                        ioHandler = new CcddJSONHandler(ccddMain, fieldHandler, parent);
                    } else // Check if the file to import is in XTCE format based on the extension
                    if (file.getAbsolutePath().endsWith(FileExtension.XTCE.getExtension())) {
                        // Create a XTCE handler
                        ioHandler = new CcddXTCEHandler(ccddMain, fieldHandler, parent);
                    } else // The file extension isn't recognized
                    {
                        throw new CCDDException("Cannot import file '" + file.getAbsolutePath() + "'; unrecognized file type");
                    }
                    // Check that no error occurred creating the format conversion handler
                    if (!ioHandler.getErrorStatus()) {
                        // Import the table definition(s) from the file
                        ioHandler.importFromFile(file, ImportType.IMPORT_ALL);
                        // existing ones for a table
                        if (appendExistingFields) {
                            // Step through each table definition
                            for (TableDefinition tableDefn : ioHandler.getTableDefinitions()) {
                                // Build the field information for this table
                                fieldHandler.buildFieldInformation(tableDefn.getName());
                                // Add the imported data field(s) to the table
                                addImportedDataField(fieldHandler, tableDefn, tableDefn.getName(), useExistingFields);
                            }
                        }
                        // Step through each table definition from the import file
                        for (TableDefinition newDefn : ioHandler.getTableDefinitions()) {
                            boolean isFound = false;
                            // Step through each table definition already in the list
                            for (TableDefinition existingDefn : allTableDefinitions) {
                                // Check if the table is already defined in the list
                                if (newDefn.getName().equals(existingDefn.getName())) {
                                    // Add the table name and associated file name to the list
                                    // of duplicates
                                    duplicateDefinitions.add(newDefn.getName() + " (file: " + file.getName() + ")");
                                    // Set the flag indicating the table definition is a
                                    // duplicate and stop searching
                                    isFound = true;
                                    break;
                                }
                            }
                            // Check if the table is not already defined
                            if (!isFound) {
                                // Add the table definition to the list
                                allTableDefinitions.add(newDefn);
                            }
                        }
                    } else // An error occurred creating the format conversion handler
                    {
                        errorFlag = true;
                    }
                } catch (IOException ioe) {
                    // Inform the user that the data file cannot be read
                    new CcddDialogHandler().showMessageDialog(parent, "<html><b>Cannot read import file<br>'</b>" + file.getAbsolutePath() + "<b>'", "File Error", JOptionPane.ERROR_MESSAGE, DialogOption.OK_OPTION);
                    errorFlag = true;
                } catch (CCDDException ce) {
                    // Check if an error message is provided
                    if (!ce.getMessage().isEmpty()) {
                        // Inform the user that an error occurred reading the import file
                        new CcddDialogHandler().showMessageDialog(parent, "<html><b>" + ce.getMessage(), "Import Error", ce.getMessageType(), DialogOption.OK_OPTION);
                    }
                    errorFlag = true;
                } catch (Exception e) {
                    // Display a dialog providing details on the unanticipated error
                    CcddUtilities.displayException(e, parent);
                    errorFlag = true;
                }
            }
        }

        /**
         ************************************************************************************
         * Import table(s) command complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            // Check if no errors occurred importing the table(s)
            if (!errorFlag) {
                try {
                    // Enable creation of a save point in case an error occurs while creating
                    // or modifying a table. This prevents committing the changes to the
                    // database until after all database transactions are complete
                    dbCommand.setSavePointEnable(true);
                    // Create the data tables from the imported table definitions from all
                    // files
                    createTablesFromDefinitions(allTableDefinitions, replaceExisting, parent);
                    // Commit the change(s) to the database
                    dbCommand.getConnection().commit();
                } catch (CCDDException | SQLException cse) {
                    errorFlag = true;
                    // message is provided
                    if (cse instanceof CCDDException && !cse.getMessage().isEmpty()) {
                        // Inform the user that an error occurred reading the import file
                        new CcddDialogHandler().showMessageDialog(parent, "<html><b>" + cse.getMessage(), "File Error", ((CCDDException) cse).getMessageType(), DialogOption.OK_OPTION);
                    }
                    try {
                        // Revert the changes to the tables that were successfully updated
                        // prior the current table
                        dbCommand.executeDbCommand("ROLLBACK TO SAVEPOINT " + DB_SAVE_POINT_NAME + ";", parent);
                    } catch (SQLException se) {
                        // Inform the user that the reversion to the save point failed
                        eventLog.logFailEvent(parent, "Cannot revert changes to table(s); cause '" + se.getMessage() + "'", "<html><b>Cannot revert changes to table(s)");
                    }
                } finally {
                    // Reset the flag for creating a save point
                    dbCommand.setSavePointEnable(false);
                }
            }
            // Check if no errors occurred importing and creating the table(s)
            if (!errorFlag) {
                // Store the data file path in the program preferences backing store
                storePath(ccddMain, dataFile[0].getAbsolutePathWithEnvVars(), true, ModifiablePathInfo.TABLE_EXPORT_PATH);
                // Update any open editor's data type columns to include the new table(s), if
                // applicable
                dbTable.updateDataTypeColumns(parent);
                // Update any open editor's message ID names columns to include any new message
                // ID names, if applicable
                dbTable.updateMessageIDNamesColumns(parent);
                eventLog.logEvent(EventLogMessageType.SUCCESS_MSG, "Table import completed successfully");
                // Check if any duplicate table definitions were detected
                if (!duplicateDefinitions.isEmpty()) {
                    // Inform the user that one or more duplicate table definitions were
                    // detected
                    new CcddDialogHandler().showMessageDialog(parent, "<html><b>Ignored the following duplicate table definition(s):</b><br>" + dbTable.getShortenedTableNames(duplicateDefinitions.toArray(new String[0])), "Duplicate Table(s)", JOptionPane.INFORMATION_MESSAGE, DialogOption.OK_OPTION);
                }
            } else // An error occurred while importing the table(s)
            {
                // Restore the table types, data types, macros, reserved message IDs, and data
                // fields to the values prior to the import operation
                tableTypeHandler.setTypeDefinitions(originalTableTypes);
                dataTypeHandler.setDataTypeData(originalDataTypes);
                macroHandler.setMacroData(originalMacros);
                rsvMsgIDHandler.setReservedMsgIDData(originalReservedMsgIDs);
                dbTable.storeInformationTable(InternalTable.FIELDS, originalDataFields, null, parent);
                eventLog.logFailEvent(parent, "Import Error", "Table import completed with errors", "<html><b>Table import completed with errors");
            }
        }
    });
}
Also used : CCDDException(CCDD.CcddClassesDataTable.CCDDException) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) FileEnvVar(CCDD.CcddClassesComponent.FileEnvVar) IOException(java.io.IOException) CCDDException(CCDD.CcddClassesDataTable.CCDDException) SQLException(java.sql.SQLException) IOException(java.io.IOException) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition) TableDefinition(CCDD.CcddClassesDataTable.TableDefinition) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand)

Example 40 with TypeDefinition

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

the class CcddFieldTableEditorDialog method getDataFieldInformation.

/**
 ********************************************************************************************
 * Get the data field information from the database
 ********************************************************************************************
 */
private void getDataFieldInformation() {
    // Get the array containing the data fields
    dataFields = dbTable.retrieveInformationTable(InternalTable.FIELDS, CcddFieldTableEditorDialog.this);
    // Create a list to contain all non-structure table names
    nonStructureTableNames = new ArrayList<String>();
    // Step through each table type
    for (TypeDefinition typeDefn : tableTypeHandler.getTypeDefinitions()) {
        // Check if the type doesn't represent a structure
        if (!typeDefn.isStructure()) {
            // Add all table names of this type to the list of non-structure tables
            nonStructureTableNames.addAll(Arrays.asList(dbTable.queryTablesOfTypeList(typeDefn.getName(), CcddFieldTableEditorDialog.this)));
        }
    }
}
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