use of CCDD.CcddClassesDataTable.TableInformation 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();
}
use of CCDD.CcddClassesDataTable.TableInformation 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);
}
}
});
}
use of CCDD.CcddClassesDataTable.TableInformation in project CCDD by nasa.
the class CcddDbTableCommandHandler method loadTableData.
/**
********************************************************************************************
* Perform the database query to load the contents of a database table. The data is sorted in
* ascending numerical order based on the index (primary key) column
*
* @param tablePath
* table path in the format rootTable[,dataType1.variable1[,dataType2
* .variable2[,...]]]. The table path for a non-structure table is simply the root
* table name. For a structure table the root table is the top level structure table
* from which this table descends. The first data type/variable name pair is from
* the root table, with each succeeding pair coming from the next level down in the
* structure's hierarchy
*
* @param loadDescription
* true to load the table's description
*
* @param loadColumnOrder
* true to load the table's column order
*
* @param loadFieldInfo
* true to retrieve the data field information to include with the table
* information; false to not load the field information
*
* @param parent
* GUI component calling this method
*
* @return TableInformation class containing the table data from the database. If the error
* flag is set the an error occurred and the data is invalid
********************************************************************************************
*/
protected TableInformation loadTableData(String tablePath, boolean loadDescription, boolean loadColumnOrder, boolean loadFieldInfo, Component parent) {
// Create an empty table information class
TableInformation tableInfo = new TableInformation(tablePath);
// Strip the variable name, if present, from the table name
String tableName = tableInfo.getPrototypeName();
// Convert the table name to lower case. PostgreSQL ignores case; it's done here just to
// differentiate the table name from the database commands in the event log
String dbTableName = tableName.toLowerCase();
try {
// Check if the table doesn't exist in the database
if (!isTableExists(dbTableName, parent)) {
throw new CCDDException("table doesn't exist");
}
// Get the table comment
String[] comment = queryDataTableComment(tableName, parent);
// Get the table type definition for this table
TypeDefinition typeDefn = tableTypeHandler.getTypeDefinition(comment[TableCommentIndex.TYPE.ordinal()]);
// Get a comma-separated list of the columns for this table's type
String columnNames = CcddUtilities.convertArrayToString(typeDefn.getColumnNamesDatabase());
// Get the table's row information for the specified columns. The table must have all
// of its table type's columns or else it fails to load
ResultSet rowData = dbCommand.executeDbQuery("SELECT " + columnNames + " FROM " + dbTableName + " ORDER BY " + DefaultColumn.ROW_INDEX.getDbName() + ";", parent);
// Create a list to contain the database table rows
List<String[]> dbRows = new ArrayList<String[]>();
// Step through each of the query results
while (rowData.next()) {
// Create an array to contain the column values
String[] columnValues = new String[typeDefn.getColumnCountDatabase()];
// Step through each column in the row
for (int column = 0; column < typeDefn.getColumnCountDatabase(); column++) {
// Add the column value to the array. Note that the first column's index in
// the database is 1, not 0
columnValues[column] = rowData.getString(column + 1);
// Check if the value is null
if (columnValues[column] == null) {
// Replace the null with a blank
columnValues[column] = "";
}
}
// Add the row data to the list
dbRows.add(columnValues);
}
rowData.close();
// Create the table information handler for this table
tableInfo = new TableInformation(comment[TableCommentIndex.TYPE.ordinal()], tablePath, dbRows.toArray(new String[0][0]), (loadColumnOrder ? queryColumnOrder(tablePath, comment[TableCommentIndex.TYPE.ordinal()], parent) : ""), (loadDescription ? queryTableDescription(tablePath, parent) : ""), rootStructures.contains(tablePath), (loadFieldInfo ? retrieveInformationTable(InternalTable.FIELDS, parent).toArray(new String[0][0]) : null));
// Get the index of the variable name and data type columns
int varNameIndex = typeDefn.getColumnIndexByInputType(InputDataType.VARIABLE);
int dataTypeIndex = typeDefn.getColumnIndexByInputType(InputDataType.PRIM_AND_STRUCT);
// must be loaded
if (varNameIndex != -1 && dataTypeIndex != -1 && tablePath.contains(",")) {
// Get the column index for the variable path
int varPathIndex = typeDefn.getColumnIndexByInputType(InputDataType.VARIABLE_PATH);
// Check if the variable path column is present
if (varPathIndex != -1) {
// Step through each row in the table
for (int row = 0; row < tableInfo.getData().length; row++) {
// Blank the variable path. This prevents the child table from inheriting a
// user-defined variable path from the prototype
tableInfo.getData()[row][varPathIndex] = "";
}
}
// Place double back slashes before each square brace character in an array index
// so that the brackets are interpreted correctly in the query's regular expression
// comparisons
tablePath = tablePath.replaceAll("\\[(\\d+)\\]", "\\\\\\\\[$1\\\\\\\\]");
// Get the rows from the custom values table that match the specified parent table
// and variable path. These values replace those loaded for the prototype of this
// table
rowData = dbCommand.executeDbQuery("SELECT * FROM " + InternalTable.VALUES.getTableName() + " WHERE " + ValuesColumn.TABLE_PATH.getColumnName() + " ~ E'^" + tablePath + ",[^,]+$' AND " + ValuesColumn.COLUMN_NAME.getColumnName() + " != '';", parent);
// Step through each of the query results
while (rowData.next()) {
// Get the variable name that will have its value replaced
String variableName = rowData.getString(ValuesColumn.TABLE_PATH.getColumnName());
// Get the index of the last data type/variable name separator character (if
// present)
int varIndex = variableName.lastIndexOf(".");
// Check if a variable name exists
if (varIndex != -1) {
// Get the row index for the referenced variable
int row = typeDefn.getRowIndexByColumnValue(tableInfo.getData(), variableName.substring(varIndex + 1), varNameIndex);
// values table
if (row != -1 && tableInfo.getData()[row][dataTypeIndex].equals(variableName.subSequence(variableName.lastIndexOf(",") + 1, varIndex))) {
// Get the index of the column that will have its data replaced
int column = typeDefn.getColumnIndexByUserName(rowData.getString(ValuesColumn.COLUMN_NAME.getColumnName()));
// Check if the table contains the column
if (column != -1) {
// Replace the value in the table with the one from the custom
// values table
tableInfo.getData()[row][column] = rowData.getString(ValuesColumn.VALUE.getColumnName());
}
}
}
}
rowData.close();
}
} catch (SQLException | CCDDException se) {
// Inform the user that loading the table failed
eventLog.logFailEvent(parent, "Cannot load table '" + tableInfo.getProtoVariableName() + "'; cause '" + se.getMessage() + "'", "<html><b>Cannot load table '</b>" + tableInfo.getProtoVariableName() + "<b>'");
} catch (Exception e) {
// Display a dialog providing details on the unanticipated error
CcddUtilities.displayException(e, parent);
}
return tableInfo;
}
use of CCDD.CcddClassesDataTable.TableInformation in project CCDD by nasa.
the class CcddAssignMessageIDDialog method assignTableMessageIDs.
/**
********************************************************************************************
* Assign message ID values to the structure, command, or other table type message ID columns
* and data fields
*
* @param tabInfo
* message ID tab information reference
*
* @param tables
* list of structure, command, or other tables, with paths
*
* @param fieldInformation
* list of data field information
*
* @return true if a message ID value changed
********************************************************************************************
*/
private boolean assignTableMessageIDs(MsgTabInfo type, List<String> tables, List<FieldInformation> fieldInformation) {
boolean isChanges = false;
// Get the starting message ID and ID interval values
int startID = Integer.decode(type.getStartFld().getText());
int interval = Integer.valueOf(type.getIntervalFld().getText());
// Step through each table type
for (TypeDefinition typeDefn : tableTypeHandler.getTypeDefinitions()) {
// Check if the tab information type and table type match the table type definition
if ((type.getName().equals(TYPE_STRUCTURE) && typeDefn.isStructure()) || type.getName().equals(TYPE_COMMAND) && typeDefn.isCommand() || (type.getName().equals(TYPE_OTHER) && !typeDefn.isStructure() && !typeDefn.isCommand())) {
// Get a list of the columns in this table type that are message IDs
List<Integer> msgIDColumns = typeDefn.getColumnIndicesByInputType(InputDataType.MESSAGE_ID);
// Check if the table type has any columns that are message IDs
if (!msgIDColumns.isEmpty()) {
// Step through each table
for (String tablePath : tables) {
// Load the table's information from the project database
TableInformation tableInformation = dbTable.loadTableData(tablePath, false, false, false, CcddAssignMessageIDDialog.this);
// the current type definition
if (!tableInformation.isErrorFlag() && tableInformation.getType().equals(typeDefn.getName())) {
// Create a table editor handler, but without displaying the editor
// itself
CcddTableEditorHandler editor = new CcddTableEditorHandler(ccddMain, tableInformation, null);
// Check if the table arrays aren't expanded
if (!editor.isExpanded()) {
// Expand the table arrays
editor.showHideArrayMembers();
}
// Get the table's data (again if a name change occurred since changes
// were made)
Object[][] tableData = editor.getTable().getTableData(false);
// Step through each row in the table
for (int row = 0; row < editor.getTable().getModel().getRowCount(); row++) {
// Step through each column that contains message IDs
for (int idColumn : msgIDColumns) {
// values should be overwritten or if the cell is empty
if (editor.getTable().isCellEditable(editor.getTable().convertRowIndexToView(row), editor.getTable().convertColumnIndexToView(idColumn)) && !tableData[row][idColumn].toString().endsWith(PROTECTED_MSG_ID_IDENT) && (type.getOverwriteCbx().isSelected() || tableData[row][idColumn].toString().isEmpty())) {
// Set the column message ID value to the next unused
// message ID
startID = getNextMessageID(startID, interval);
tableData[row][idColumn] = formatMessageID(startID);
}
}
}
// Check if the a message ID in the table was changed
if (editor.getTable().isTableChanged(tableData)) {
// Load the updated array of data into the table
editor.getTable().loadDataArrayIntoTable(tableData, false);
// Build the table updates
editor.buildUpdates();
// Make the table modifications to the project database and to any
// open table editors
dbTable.modifyTableData(editor.getTableInformation(), editor.getAdditions(), editor.getModifications(), editor.getDeletions(), true, false, false, false, false, null, CcddAssignMessageIDDialog.this);
}
}
}
}
}
}
// Step through each defined data field
for (int index = 0; index < fieldInformation.size(); index++) {
// Get the reference to the field information
FieldInformation fieldInfo = fieldInformation.get(index);
// blank
if (fieldInfo.getInputType().equals(InputDataType.MESSAGE_ID) && tables.contains(fieldInfo.getOwnerName()) && !fieldInfo.getValue().endsWith(PROTECTED_MSG_ID_IDENT) && (type.getOverwriteCbx().isSelected() || fieldInfo.getValue().isEmpty())) {
// Set the message ID data field value to the next unused message ID
startID = getNextMessageID(startID, interval);
fieldInfo.setValue(formatMessageID(startID));
// the database. Step through each table editor dialog
for (CcddTableEditorDialog editorDialog : ccddMain.getTableEditorDialogs()) {
boolean isUpdate = false;
// Step through each table editor in the editor dialog
for (CcddTableEditorHandler editor : editorDialog.getTableEditors()) {
// Get the reference to the table's field handler
CcddFieldHandler editorFldHandler = editor.getTableInformation().getFieldHandler();
// to the new value
if (editorFldHandler.updateField(fieldInfo)) {
// Update the committed message ID value
editor.getCommittedTableInformation().getFieldHandler().updateField(fieldInfo);
// Update the editor data fields
editor.updateDataFields();
// Set the flag to indicate the table/field combination was located and
// stop searching
isUpdate = true;
break;
}
}
// Check if this table/field combination has been located
if (isUpdate) {
// Stop searching
break;
}
}
// Set the flag to indicate a message ID value is changed
isChanges = true;
}
}
return isChanges;
}
use of CCDD.CcddClassesDataTable.TableInformation in project CCDD by nasa.
the class CcddEDSHandler method buildNamespaces.
/**
********************************************************************************************
* Build the name spaces for the list of tables specified
*
* @param tableNames
* array of table names
*
* @param includeVariablePaths
* true to include the variable path for each variable in a structure table, both in
* application format and using the user-defined separator characters
*
* @param variableHandler
* variable handler class reference; null if includeVariablePaths is false
*
* @param separators
* string array containing the variable path separator character(s), show/hide data
* types flag ('true' or 'false'), and data type/variable name separator
* character(s); null if includeVariablePaths is false
********************************************************************************************
*/
private void buildNamespaces(String[] tableNames, boolean includeVariablePaths, CcddVariableSizeAndConversionHandler variableHandler, String[] separators) {
// Build the data field information for all fields
fieldHandler.buildFieldInformation(null);
// Get the names of the tables representing the CCSDS telemetry and command headers
tlmHeaderTable = fieldHandler.getFieldValue(CcddFieldHandler.getFieldProjectName(), InputDataType.XML_TLM_HDR);
cmdHeaderTable = fieldHandler.getFieldValue(CcddFieldHandler.getFieldProjectName(), InputDataType.XML_CMD_HDR);
// Get the command header argument names for the application ID and the command function
// code. These are stored as project-level data fields
String ccsdsAppID = fieldHandler.getFieldValue(CcddFieldHandler.getFieldProjectName(), InputDataType.XML_APP_ID);
String ccsdsFuncCode = fieldHandler.getFieldValue(CcddFieldHandler.getFieldProjectName(), InputDataType.XML_FUNC_CODE);
// Step through each table name
for (String tableName : tableNames) {
// Check if this is a child (instance) table
if (!TableInformation.isPrototype(tableName)) {
// Get the prototype of the instance table. Only prototypes of the tables are
// used to create the space systems
tableName = TableInformation.getPrototypeName(tableName);
// Get the name of the system to which this table belongs from the table's
// system path data field (if present)
String systemPath = cleanSystemPath(fieldHandler.getFieldValue(tableName, InputDataType.SYSTEM_PATH));
// created
if (searchNamespacesForName(systemPath, tableName) != null) {
// Skip this table since it's space system has already been created
continue;
}
}
// Get the information from the database for the specified table
TableInformation tableInfo = dbTable.loadTableData(tableName, true, false, true, parent);
// Check if the table's data successfully loaded
if (!tableInfo.isErrorFlag()) {
// Get the table type and from the type get the type definition. The type
// definition can be a global parameter since if the table represents a structure,
// then all of its children are also structures, and if the table represents
// commands or other table type then it is processed within this nest level
typeDefn = tableTypeHandler.getTypeDefinition(tableInfo.getType());
// Check if the table type represents a structure or command
if (typeDefn != null && (typeDefn.isStructure() || typeDefn.isCommand())) {
// Replace all macro names with their corresponding values
tableInfo.setData(macroHandler.replaceAllMacros(tableInfo.getData()));
// Get the application ID data field value, if present
String applicationID = fieldHandler.getFieldValue(tableName, InputDataType.MESSAGE_ID);
// Get the name of the system to which this table belongs from the table's
// system path data field (if present)
String systemPath = cleanSystemPath(fieldHandler.getFieldValue(tableName, InputDataType.SYSTEM_PATH));
// Add the name space
NamespaceType namespace = addNamespace(systemPath, tableName, tableInfo.getDescription());
// Check if this is a structure table
if (typeDefn.isStructure()) {
// Get the default column indices
int varColumn = typeDefn.getColumnIndexByInputType(InputDataType.VARIABLE);
int typeColumn = typeDefn.getColumnIndexByInputType(InputDataType.PRIM_AND_STRUCT);
int sizeColumn = typeDefn.getColumnIndexByInputType(InputDataType.ARRAY_INDEX);
int bitColumn = typeDefn.getColumnIndexByInputType(InputDataType.BIT_LENGTH);
int enumColumn = typeDefn.getColumnIndexByInputType(InputDataType.ENUMERATION);
int descColumn = typeDefn.getColumnIndexByInputType(InputDataType.DESCRIPTION);
int unitsColumn = typeDefn.getColumnIndexByInputType(InputDataType.UNITS);
int minColumn = typeDefn.getColumnIndexByInputType(InputDataType.MINIMUM);
int maxColumn = typeDefn.getColumnIndexByInputType(InputDataType.MAXIMUM);
// Set the flag to indicate if this is the telemetry header table
boolean isTlmHeaderTable = tableName.equals(tlmHeaderTable);
// Check if this is the telemetry header table
if (isTlmHeaderTable) {
// Store the telemetry header's path
tlmHeaderPath = systemPath;
}
// Export the parameter container for this structure
addParameterContainer(namespace, tableInfo, varColumn, typeColumn, sizeColumn, minColumn, maxColumn, isTlmHeaderTable, applicationID, ccsdsAppID);
// Step through each row in the structure table
for (String[] rowData : tableInfo.getData()) {
// used to define the array)
if (!ArrayVariable.isArrayMember(rowData[varColumn])) {
// Add the variable to the data sheet
addParameter(namespace, rowData[varColumn], rowData[typeColumn], rowData[sizeColumn], rowData[bitColumn], (enumColumn != -1 && !rowData[enumColumn].isEmpty() ? rowData[enumColumn] : null), (unitsColumn != -1 && !rowData[unitsColumn].isEmpty() ? rowData[unitsColumn] : null), (descColumn != -1 && !rowData[descColumn].isEmpty() ? rowData[descColumn] : null), (dataTypeHandler.isString(rowData[typeColumn]) && !rowData[sizeColumn].isEmpty() ? Integer.valueOf(rowData[sizeColumn].replaceAll("^.*(\\d+)$", "$1")) : 1));
}
}
} else // This is a command table
{
// Check if this is the command header table
if (tableName.equals(cmdHeaderTable)) {
// Store the command header's path
cmdHeaderPath = systemPath;
}
// Add the command(s) from this table to the data sheet
addNamespaceCommands(namespace, tableInfo, tableName.equals(cmdHeaderTable), applicationID, ccsdsAppID, ccsdsFuncCode);
}
}
}
}
// Step through each table name
for (String tableName : tableNames) {
// Get the prototype for the child
tableName = TableInformation.getPrototypeName(tableName);
// Get the name of the system to which this table belongs from the table's
// system path data field (if present)
String systemPath = cleanSystemPath(fieldHandler.getFieldValue(tableName, InputDataType.SYSTEM_PATH));
// Get the name space for this table
NamespaceType namespace = searchNamespacesForName(systemPath, tableName);
// Check if the table's name space exists
if (namespace != null) {
// Step through the each parameter type
for (RootDataType type : namespace.getDataTypeSet().getArrayDataTypeOrBinaryDataTypeOrBooleanDataType()) {
// base type it's a reference to a child structure
if (type instanceof ContainerDataType && ((ContainerDataType) type).getBaseType() != null) {
// Get the base type, which has the name space path for the child structure
String typeName = ((ContainerDataType) type).getBaseType();
// Get the beginning of the last portion of the path, which is the
// structure data type
int index = ((ContainerDataType) type).getBaseType().lastIndexOf("/");
// Check if the structure data type exists
if (index != -1) {
// Remove the structure data type, leaving only the name space path to
// the child structure's definition
typeName = typeName.substring(0, index);
}
// Get the name space for the child structure's definition
NamespaceType nmspc = searchNamespacesForName(null, typeName);
// Check if the name space exists
if (nmspc != null) {
DataTypeSetType dataTypeSet = nmspc.getDataTypeSet();
// Check if the child's data type set exists
if (dataTypeSet != null && !dataTypeSet.getArrayDataTypeOrBinaryDataTypeOrBooleanDataType().isEmpty()) {
// Step through each data type
for (RootDataType rootData : dataTypeSet.getArrayDataTypeOrBinaryDataTypeOrBooleanDataType()) {
// Check if this is the container with the structure's members
if (rootData instanceof ContainerDataType && rootData.getName().equals(type.getName())) {
// Set the parent structure table's list of members of the
// child structure using the child structure definition's
// list, and stop searching
((ContainerDataType) type).setEntryList(((ContainerDataType) rootData).getEntryList());
break;
}
}
}
}
}
}
}
}
}
Aggregations