use of CCDD.CcddClassesDataTable.TableDefinition in project CCDD by nasa.
the class CcddJSONHandler method importFromFile.
/**
********************************************************************************************
* Build the information from the table definition(s) in the current file
*
* @param importFile
* import file reference
*
* @param importAll
* ImportType.IMPORT_ALL to import the table type, data type, and macro definitions,
* and the data from all the table definitions; ImportType.FIRST_DATA_ONLY to load
* only the data for the first table defined
*
* @throws CCDDException
* If a data is missing, extraneous, or in error in the import file
*
* @throws IOException
* If an import file I/O error occurs
*
* @throws Exception
* For any unanticipated errors
********************************************************************************************
*/
@Override
public void importFromFile(FileEnvVar importFile, ImportType importType) throws CCDDException, IOException, Exception {
BufferedReader br = null;
try {
List<TableTypeDefinition> tableTypeDefinitions = new ArrayList<TableTypeDefinition>();
tableDefinitions = new ArrayList<TableDefinition>();
// Flags indicating if importing should continue after an input error is detected
boolean continueOnTableTypeError = false;
boolean continueOnDataTypeError = false;
boolean continueOnMacroError = false;
boolean continueOnReservedMsgIDError = false;
boolean continueOnColumnError = false;
boolean continueOnDataFieldError = false;
boolean continueOnTableTypeFieldError = false;
// Create a JSON parser and use it to parse the import file contents
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader(importFile));
// Get the table type definitions JSON object
Object defn = jsonObject.get(JSONTags.TABLE_TYPE_DEFN.getTag());
// Check if the table type definitions exist
if (defn != null && defn instanceof JSONArray) {
// Step through each table type definition
for (JSONObject tableTypeJO : parseJSONArray(defn)) {
// Get the table type definition components
String typeName = getString(tableTypeJO, JSONTags.TABLE_TYPE_NAME.getTag());
String typeDesc = getString(tableTypeJO, JSONTags.TABLE_TYPE_DESCRIPTION.getTag());
Object typeColumn = getObject(tableTypeJO, JSONTags.TABLE_TYPE_COLUMN.getTag());
// Check if the expected inputs are present
if (!typeName.isEmpty() && typeColumn != null && typeColumn instanceof JSONArray) {
// Create a new table type definition
TableTypeDefinition tableTypeDefn = new TableTypeDefinition(typeName, typeDesc);
int columnNumber = 0;
// Step through each table type column definition
for (JSONObject typeJO : parseJSONArray(typeColumn)) {
// Check if the expected input is present
if (typeJO.keySet().size() == TableTypeEditorColumnInfo.values().length - 1) {
// Add the table type column definition, checking for (and if
// possible, correcting) errors
continueOnTableTypeError = addImportedTableTypeDefinition(continueOnTableTypeError, tableTypeDefn, new String[] { String.valueOf(columnNumber), getString(typeJO, TableTypeEditorColumnInfo.NAME.getColumnName()), getString(typeJO, TableTypeEditorColumnInfo.DESCRIPTION.getColumnName()), getString(typeJO, TableTypeEditorColumnInfo.INPUT_TYPE.getColumnName()), getString(typeJO, TableTypeEditorColumnInfo.UNIQUE.getColumnName()), getString(typeJO, TableTypeEditorColumnInfo.REQUIRED.getColumnName()), getString(typeJO, CcddUtilities.removeHTMLTags(TableTypeEditorColumnInfo.STRUCTURE_ALLOWED.getColumnName())), getString(typeJO, CcddUtilities.removeHTMLTags(TableTypeEditorColumnInfo.POINTER_ALLOWED.getColumnName())) }, importFile.getAbsolutePath(), parent);
// Update the column index number for the next column definition
columnNumber++;
} else // The number of inputs is incorrect
{
// Check if the error should be ignored or the import canceled
continueOnTableTypeError = getErrorResponse(continueOnTableTypeError, "<html><b>Table type '" + typeName + "' definition has missing or extra " + "input(s) in import file '</b>" + importFile.getAbsolutePath() + "<b>'; continue?", "Table Type Error", "Ignore this table type", "Ignore this and any remaining invalid table types", "Stop importing", parent);
}
}
// Get the data fields for this table type
Object typeField = getObject(tableTypeJO, JSONTags.TABLE_TYPE_FIELD.getTag());
// Check if any data fields exists for this table type
if (typeField != null) {
// Step through each table type data field definition
for (JSONObject typeJO : parseJSONArray(typeField)) {
// Add the data field definition, checking for (and if possible,
// correcting) errors
continueOnTableTypeFieldError = addImportedDataFieldDefinition(continueOnTableTypeFieldError, tableTypeDefn, new String[] { CcddFieldHandler.getFieldTypeName(tableTypeDefn.getTypeName()), getString(typeJO, FieldEditorColumnInfo.NAME.getColumnName()), getString(typeJO, FieldEditorColumnInfo.DESCRIPTION.getColumnName()), getString(typeJO, FieldEditorColumnInfo.SIZE.getColumnName()), getString(typeJO, FieldEditorColumnInfo.INPUT_TYPE.getColumnName()), getString(typeJO, FieldEditorColumnInfo.REQUIRED.getColumnName()), getString(typeJO, FieldEditorColumnInfo.APPLICABILITY.getColumnName()), getString(typeJO, FieldEditorColumnInfo.VALUE.getColumnName()) }, importFile.getAbsolutePath(), parent);
}
}
// Add the table type definition to the list
tableTypeDefinitions.add(tableTypeDefn);
}
}
}
// Add the table type if it's new or match it to an existing one with the same name if
// the type definitions are the same
String badDefn = tableTypeHandler.updateTableTypes(tableTypeDefinitions, fieldHandler);
// Check if a table type isn't new and doesn't match an existing one with the same name
if (badDefn != null) {
throw new CCDDException("Imported table type '" + badDefn + "' doesn't match the existing definition");
}
// Check if all definitions are to be loaded
if (importType == ImportType.IMPORT_ALL) {
List<String[]> dataTypeDefns = new ArrayList<String[]>();
List<String[]> macroDefns = new ArrayList<String[]>();
List<String[]> reservedMsgIDDefns = new ArrayList<String[]>();
// Get the data type definitions JSON object
defn = jsonObject.get(JSONTags.DATA_TYPE_DEFN.getTag());
// Check if the data type definitions exist
if (defn != null && defn instanceof JSONArray) {
// Step through each data type definition
for (JSONObject typeJO : parseJSONArray(defn)) {
// Get the data type definition components
String userName = getString(typeJO, DataTypeEditorColumnInfo.USER_NAME.getColumnName());
String cName = getString(typeJO, DataTypeEditorColumnInfo.C_NAME.getColumnName());
String size = getString(typeJO, DataTypeEditorColumnInfo.SIZE.getColumnName());
String baseType = getString(typeJO, DataTypeEditorColumnInfo.BASE_TYPE.getColumnName());
// Check if the expected inputs are present
if ((!userName.isEmpty() || !cName.isEmpty()) && !size.isEmpty() && !baseType.isEmpty() && typeJO.keySet().size() < DataTypeEditorColumnInfo.values().length) {
// Add the data type definition (add a blank to represent the OID)
dataTypeDefns.add(new String[] { userName, cName, size, baseType, "" });
} else // The number of inputs is incorrect
{
// Check if the error should be ignored or the import canceled
continueOnDataTypeError = getErrorResponse(continueOnDataTypeError, "<html><b>Missing or extra data type definition " + "input(s) in import file '</b>" + importFile.getAbsolutePath() + "<b>'; continue?", "Data Type Error", "Ignore this data type", "Ignore this and any remaining invalid data types", "Stop importing", parent);
}
}
}
// Get the macro definitions JSON object
defn = jsonObject.get(JSONTags.MACRO_DEFN.getTag());
// Check if the macro definitions exist
if (defn != null && defn instanceof JSONArray) {
// Step through each macro definition
for (JSONObject macroJO : parseJSONArray(defn)) {
// Get the macro definition components
String name = getString(macroJO, MacroEditorColumnInfo.NAME.getColumnName());
String value = getString(macroJO, MacroEditorColumnInfo.VALUE.getColumnName());
// Check if the expected inputs are present
if (!name.isEmpty() && macroJO.keySet().size() < MacroEditorColumnInfo.values().length) {
// Add the macro definition (add a blank to represent the OID)
macroDefns.add(new String[] { name, value, "" });
} else // The number of inputs is incorrect
{
// Check if the error should be ignored or the import canceled
continueOnMacroError = getErrorResponse(continueOnMacroError, "<html><b>Missing or extra macro definition " + "input(s) in import file '</b>" + importFile.getAbsolutePath() + "<b>'; continue?", "Macro Error", "Ignore this macro", "Ignore this and any remaining invalid macros", "Stop importing", parent);
}
}
}
// Get the reserved message ID definitions JSON object
defn = jsonObject.get(JSONTags.RESERVED_MSG_ID_DEFN.getTag());
// Check if the reserved message ID definitions exist
if (defn != null && defn instanceof JSONArray) {
// Step through each reserved message ID definition
for (JSONObject reservedMsgIDJO : parseJSONArray(defn)) {
// Get the reserved message ID definition components
String name = getString(reservedMsgIDJO, ReservedMsgIDEditorColumnInfo.MSG_ID.getColumnName());
String value = getString(reservedMsgIDJO, ReservedMsgIDEditorColumnInfo.DESCRIPTION.getColumnName());
// Check if the expected inputs are present
if (!name.isEmpty() && reservedMsgIDJO.keySet().size() < ReservedMsgIDEditorColumnInfo.values().length) {
// Add the reserved message ID definition (add a blank to represent the
// OID)
reservedMsgIDDefns.add(new String[] { name, value, "" });
} else // The number of inputs is incorrect
{
// Check if the error should be ignored or the import canceled
continueOnReservedMsgIDError = getErrorResponse(continueOnReservedMsgIDError, "<html><b>Missing or extra reserved message ID " + "definition input(s) in import file '</b>" + importFile.getAbsolutePath() + "<b>'; continue?", "Reserved Message ID Error", "Ignore this reserved message ID", "Ignore this and any remaining invalid reserved message IDs", "Stop importing", parent);
}
}
}
// Add the data type if it's new or match it to an existing one with the same name
// if the type definitions are the same
badDefn = dataTypeHandler.updateDataTypes(dataTypeDefns);
// name
if (badDefn != null) {
throw new CCDDException("Imported data type '" + badDefn + "' doesn't match the existing definition");
}
// Add the macro if it's new or match it to an existing one with the same name if
// the values are the same
badDefn = macroHandler.updateMacros(macroDefns);
// Add the reserved message ID definition if it's new
rsvMsgIDHandler.updateReservedMsgIDs(reservedMsgIDDefns);
// Check if a macro isn't new and doesn't match an existing one with the same name
if (badDefn != null) {
throw new CCDDException("Imported macro '" + badDefn + "' doesn't match the existing definition");
}
}
// Get the table definitions JSON object
defn = jsonObject.get(JSONTags.TABLE_DEFN.getTag());
// Check if the table definitions exist
if (defn != null && defn instanceof JSONArray) {
// Step through each table definition
for (JSONObject tableJO : parseJSONArray(defn)) {
// Get the table definition components
String tableName = getString(tableJO, JSONTags.TABLE_NAME.getTag());
String tableType = getString(tableJO, JSONTags.TABLE_TYPE.getTag());
String tableDesc = getString(tableJO, JSONTags.TABLE_DESCRIPTION.getTag());
Object tableDataJA = getObject(tableJO, JSONTags.TABLE_DATA.getTag());
Object dataFieldsJA = getObject(tableJO, JSONTags.TABLE_FIELD.getTag());
// Check if the expected inputs are present
if (!tableName.isEmpty() && tableDataJA != null && tableDataJA instanceof JSONArray && (dataFieldsJA == null || dataFieldsJA instanceof JSONArray)) {
// Create a new table type definition
TableDefinition tableDefn = new TableDefinition(tableName, tableDesc);
// Get the table's type definition
TypeDefinition typeDefn = tableTypeHandler.getTypeDefinition(tableType);
// Check if the table type doesn't exist
if (typeDefn == null) {
throw new CCDDException("Unknown table type '" + tableType + "'");
}
// Store the table's type name
tableDefn.setTypeName(tableType);
// Get the number of expected columns (the hidden columns, primary key and
// row index, should not be included in the JSON file)
int numColumns = typeDefn.getColumnCountVisible();
// Create storage for the row of cell data
String[] rowData = new String[numColumns];
// Step through each row of data
for (JSONObject rowDataJO : parseJSONArray(tableDataJA)) {
// Initialize the column values to blanks
Arrays.fill(rowData, null);
// Step through each key (column name)
for (Object columnName : rowDataJO.keySet()) {
// Get the column index based on the column name
int column = typeDefn.getVisibleColumnIndexByUserName(columnName.toString());
// Check if a column by this name exists
if (column != -1) {
// Get the value from the JSON input, if present; use a blank
// if a value for this column doesn't exist
rowData[column] = getString(rowDataJO, typeDefn.getColumnNamesVisible()[column]);
} else // The number of inputs is incorrect
{
// Check if the error should be ignored or the import canceled
continueOnColumnError = getErrorResponse(continueOnColumnError, "<html><b>Table '</b>" + tableName + "<b>' column name '</b>" + columnName + "<b>' unrecognized in import file '</b>" + importFile.getAbsolutePath() + "<b>'; continue?", "Column Error", "Ignore this invalid column name", "Ignore this and any remaining invalid column names", "Stop importing", parent);
}
}
// Add the row of data read in from the file to the cell data list
tableDefn.addData(rowData);
}
// defined
if (dataFieldsJA != null) {
// Step through each data field definition
for (JSONObject dataFieldJO : parseJSONArray(dataFieldsJA)) {
// Add the data field definition, checking for (and if possible,
// correcting) errors
continueOnDataFieldError = addImportedDataFieldDefinition(continueOnDataFieldError, tableDefn, new String[] { tableName, getString(dataFieldJO, FieldEditorColumnInfo.NAME.getColumnName()), getString(dataFieldJO, FieldEditorColumnInfo.DESCRIPTION.getColumnName()), getString(dataFieldJO, FieldEditorColumnInfo.SIZE.getColumnName()), getString(dataFieldJO, FieldEditorColumnInfo.INPUT_TYPE.getColumnName()), getString(dataFieldJO, FieldEditorColumnInfo.REQUIRED.getColumnName()), getString(dataFieldJO, FieldEditorColumnInfo.APPLICABILITY.getColumnName()), getString(dataFieldJO, FieldEditorColumnInfo.VALUE.getColumnName()) }, importFile.getAbsolutePath(), parent);
}
}
// Add the table's definition to the list
tableDefinitions.add(tableDefn);
}
// Check if only the data from the first table is to be read
if (importType == ImportType.FIRST_DATA_ONLY) {
// Stop reading table definitions
break;
}
}
}
} catch (ParseException pe) {
// Inform the user that the file cannot be closed
new CcddDialogHandler().showMessageDialog(parent, "<html><b>Cannot parse import file<br>'</b>" + importFile.getAbsolutePath() + "<b>'; cause '" + pe.getMessage() + "'", "File Warning", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
} finally {
try {
// Check that the buffered reader exists
if (br != null) {
// Close the file
br.close();
}
} catch (IOException ioe) {
// Inform the user that the file cannot be closed
new CcddDialogHandler().showMessageDialog(parent, "<html><b>Cannot close import file<br>'</b>" + importFile.getAbsolutePath() + "<b>'", "File Warning", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
}
}
}
use of CCDD.CcddClassesDataTable.TableDefinition in project CCDD by nasa.
the class CcddFileIOHandler method createTablesFromDefinitions.
/**
********************************************************************************************
* Create one or more data tables from the supplied table definitions
*
* @param tableDefinitions
* list of table definitions for the table(s) to create
*
* @param replaceExisting
* true to replace a table that already exists in the database
*
* @param parent
* GUI component calling this method
*
* @throws CCDDException
* If the table path name is invalid or the table cannot be created from the table
* definition
********************************************************************************************
*/
private void createTablesFromDefinitions(List<TableDefinition> tableDefinitions, boolean replaceExisting, final Component parent) throws CCDDException {
cancelImport = false;
boolean prototypesOnly = true;
List<String> skippedTables = new ArrayList<String>();
// Get the list of all tables, including the paths for child structure tables
CcddTableTreeHandler tableTree = new CcddTableTreeHandler(ccddMain, TableTreeType.TABLES, parent);
List<String> allTables = tableTree.getTableTreePathList(null);
// tables
for (int loop = 1; loop <= 2 && !cancelImport; loop++) {
// Step through each table definition
for (TableDefinition tableDefn : tableDefinitions) {
// Check if the table path/name format is valid
if (!tableDefn.getName().matches(InputDataType.VARIABLE.getInputMatch() + "(?:$|(?:," + InputDataType.VARIABLE.getInputMatch() + "\\." + InputDataType.VARIABLE.getInputMatch() + ")+)")) {
// Inform the user the table path/name isn't in the correct format
throw new CCDDException("Invalid table path/name '</b>" + tableDefn.getName() + "<b>' format");
}
// Check if the table import was canceled by the user
if (cancelImport) {
// Add the table to the list of those skipped
skippedTables.add(tableDefn.getName());
continue;
}
// or if this is a child table and this is the second pass
if (!tableDefn.getData().isEmpty() && (!tableDefn.getName().contains(",") != !prototypesOnly)) {
// Get the table type definition for this table
TypeDefinition typeDefn = tableTypeHandler.getTypeDefinition(tableDefn.getTypeName());
// Get the number of table columns
int numColumns = typeDefn.getColumnCountVisible();
// Create the table information for the new table
TableInformation tableInfo = new TableInformation(tableDefn.getTypeName(), tableDefn.getName(), new String[0][0], tableTypeHandler.getDefaultColumnOrder(tableDefn.getTypeName()), tableDefn.getDescription(), !tableDefn.getName().contains("."), tableDefn.getDataFields().toArray(new String[0][0]));
// Check if the new table is not a prototype
if (!tableInfo.isPrototype()) {
// Break the path into the individual structure variable references
String[] ancestors = tableInfo.getTablePath().split(",");
// table
for (int index = ancestors.length - 1; index >= 0 && !cancelImport; index--) {
// Split the ancestor into the data type (i.e., structure name) and
// variable name
String[] typeAndVar = ancestors[index].split("\\.");
// Check if the ancestor prototype table doesn't exist
if (!dbTable.isTableExists(typeAndVar[0].toLowerCase(), ccddMain.getMainFrame())) {
// Create the table information for the new prototype table
TableInformation ancestorInfo = new TableInformation(tableDefn.getTypeName(), typeAndVar[0], new String[0][0], tableTypeHandler.getDefaultColumnOrder(tableDefn.getTypeName()), "", true, tableDefn.getDataFields().toArray(new String[0][0]));
// Check if this is the child table and not one of its ancestors
if (index == ancestors.length - 1) {
// Create a list to store a copy of the cell data
List<String> protoData = new ArrayList<String>(tableDefn.getData());
// Step through each row of the cell data
for (int cellIndex = 0; cellIndex < tableDefn.getData().size(); cellIndex += numColumns) {
// Step through each column in the row
for (int colIndex = 0; colIndex < numColumns; colIndex++) {
// type
if (!DefaultColumn.isTypeRequiredColumn((typeDefn.isStructure() ? TYPE_STRUCTURE : (typeDefn.isCommand() ? TYPE_COMMAND : TYPE_OTHER)), typeDefn.getInputTypesVisible()[colIndex])) {
// Replace the non-required column value with a
// blank. The child's non-required values are
// therefore not inherited from the prototype
protoData.set(cellIndex + colIndex, "");
}
}
}
// the protected column data
if (!createImportedTable(ancestorInfo, protoData, numColumns, replaceExisting, "Cannot create prototype '" + ancestorInfo.getPrototypeName() + "' of child table", allTables, parent)) {
// Add the skipped table to the list
skippedTables.add(ancestorInfo.getTablePath());
}
} else // This is an ancestor of the child table
{
// Split the ancestor into the data type (i.e., structure name)
// and variable name
typeAndVar = ancestors[index + 1].split("\\.|$", -1);
// Add the variable reference to the new table
String[] rowData = new String[typeDefn.getColumnCountVisible()];
Arrays.fill(rowData, "");
rowData[typeDefn.getVisibleColumnIndexByUserName(typeDefn.getColumnNameByInputType(InputDataType.VARIABLE))] = typeAndVar[1];
rowData[typeDefn.getVisibleColumnIndexByUserName(typeDefn.getColumnNameByInputType(InputDataType.PRIM_AND_STRUCT))] = typeAndVar[0];
// the protected column data
if (!createImportedTable(ancestorInfo, Arrays.asList(rowData), numColumns, replaceExisting, "Cannot create prototype '" + ancestorInfo.getPrototypeName() + "' of child table's ancestor", allTables, parent)) {
// Add the skipped table to the list
skippedTables.add(ancestorInfo.getTablePath());
}
}
}
}
// Load the table's prototype data from the database and copy the
// prototype's data to the table
TableInformation protoInfo = dbTable.loadTableData(tableInfo.getPrototypeName(), false, false, false, ccddMain.getMainFrame());
tableInfo.setData(protoInfo.getData());
}
// Create a table from the imported information
if (!createImportedTable(tableInfo, tableDefn.getData(), numColumns, replaceExisting, "Cannot create prototype '" + tableInfo.getPrototypeName() + "'", allTables, parent)) {
// Add the skipped table to the list
skippedTables.add(tableInfo.getTablePath());
}
}
}
prototypesOnly = false;
}
// Check if any tables were skipped
if (!skippedTables.isEmpty()) {
// Inform the user that one or more tables were not imported
new CcddDialogHandler().showMessageDialog(parent, "<html><b>Table(s) not imported<br>'</b>" + dbTable.getShortenedTableNames(skippedTables.toArray(new String[0])) + "<b>';<br>table already exists", "Import Warning", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
}
// Store the table types
dbTable.storeInformationTable(InternalTable.TABLE_TYPES, null, null, parent);
// Store the data types
dbTable.storeInformationTable(InternalTable.DATA_TYPES, CcddUtilities.removeArrayListColumn(dataTypeHandler.getDataTypeData(), DataTypesColumn.OID.ordinal()), null, parent);
// Check if any macros are defined
if (!macroHandler.getMacroData().isEmpty()) {
// Store the macros in the database
dbTable.storeInformationTable(InternalTable.MACROS, CcddUtilities.removeArrayListColumn(macroHandler.getMacroData(), MacrosColumn.OID.ordinal()), null, parent);
}
// Check if any reserved message IDs are defined
if (!rsvMsgIDHandler.getReservedMsgIDData().isEmpty()) {
// Store the reserved message IDs in the database
dbTable.storeInformationTable(InternalTable.RESERVED_MSG_IDS, CcddUtilities.removeArrayListColumn(rsvMsgIDHandler.getReservedMsgIDData(), ReservedMsgIDsColumn.OID.ordinal()), null, parent);
}
}
use of CCDD.CcddClassesDataTable.TableDefinition in project CCDD by nasa.
the class CcddFileIOHandler method importSelectedFileIntoTable.
/**
********************************************************************************************
* Import the contents of a file selected by the user into the specified existing table
*
* @param tableHandler
* reference to the table handler for the table into which to import the data
********************************************************************************************
*/
protected void importSelectedFileIntoTable(CcddTableEditorHandler tableHandler) {
// Set the initial layout manager characteristics
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2, 0, 0), 0, 0);
// Create an empty border
Border emptyBorder = BorderFactory.createEmptyBorder();
// Create overwrite check box
JCheckBox overwriteChkBx = new JCheckBox("Overwrite existing cells");
overwriteChkBx.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
overwriteChkBx.setBorder(emptyBorder);
overwriteChkBx.setToolTipText(CcddUtilities.wrapText("Overwrite existing cell data; if unchecked then new " + "rows are inserted to contain the imported data", ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
overwriteChkBx.setSelected(false);
// Create a check box for indicating existing tables can be replaced
JCheckBox useExistingFieldsCb = new JCheckBox("Use existing field if duplicate");
useExistingFieldsCb.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
useExistingFieldsCb.setBorder(emptyBorder);
useExistingFieldsCb.setToolTipText(CcddUtilities.wrapText("Use the existing data field definition if " + "a field with the same name is imported", ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
useExistingFieldsCb.setSelected(true);
// Create a panel to contain the overwrite check box
JPanel checkBoxPnl = new JPanel(new GridBagLayout());
checkBoxPnl.setBorder(emptyBorder);
checkBoxPnl.add(overwriteChkBx, gbc);
gbc.insets.top = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing();
gbc.gridy++;
checkBoxPnl.add(useExistingFieldsCb, gbc);
// Allow the user to select the data file path + name to import from
FileEnvVar[] dataFile = new CcddDialogHandler().choosePathFile(ccddMain, tableHandler.getOwner(), null, "export", new FileNameExtensionFilter[] { new FileNameExtensionFilter(FileExtension.CSV.getDescription(), FileExtension.CSV.getExtensionName()), new FileNameExtensionFilter(FileExtension.EDS.getDescription(), FileExtension.EDS.getExtensionName()), new FileNameExtensionFilter(FileExtension.JSON.getDescription(), FileExtension.JSON.getExtensionName()), new FileNameExtensionFilter(FileExtension.XTCE.getDescription(), FileExtension.XTCE.getExtensionName()) }, false, false, "Import Table Data", ccddMain.getProgPrefs().get(ModifiablePathInfo.TABLE_EXPORT_PATH.getPreferenceKey(), null), DialogOption.IMPORT_OPTION, checkBoxPnl);
// Check if a file was chosen
if (dataFile != null && dataFile[0] != null) {
try {
List<TableDefinition> tableDefinitions = null;
CcddImportExportInterface ioHandler = null;
// Check if the file to import is in CSV format based on the extension
if (dataFile[0].getAbsolutePath().endsWith(FileExtension.CSV.getExtension())) {
// Create a CSV handler
ioHandler = new CcddCSVHandler(ccddMain, tableHandler.getFieldHandler(), tableHandler.getOwner());
} else // Check if the file to import is in EDS XML format based on the extension
if (dataFile[0].getAbsolutePath().endsWith(FileExtension.EDS.getExtension())) {
// Create an EDS handler
ioHandler = new CcddEDSHandler(ccddMain, tableHandler.getFieldHandler(), tableHandler.getOwner());
} else // Check if the file to import is in JSON format based on the extension
if (dataFile[0].getAbsolutePath().endsWith(FileExtension.JSON.getExtension())) {
// Create a JSON handler
ioHandler = new CcddJSONHandler(ccddMain, tableHandler.getFieldHandler(), tableHandler.getOwner());
} else // Check if the file to import is in XTCE XML format based on the extension
if (dataFile[0].getAbsolutePath().endsWith(FileExtension.XTCE.getExtension())) {
// Create an XTCE handler
ioHandler = new CcddXTCEHandler(ccddMain, tableHandler.getFieldHandler(), tableHandler.getOwner());
} else // The file extension isn't recognized
{
throw new CCDDException("Cannot import file '" + dataFile[0].getAbsolutePath() + "' into table; unrecognized file type");
}
// Check that no error occurred creating the format conversion handler
if (!ioHandler.getErrorStatus()) {
// Store the current table type information so that it can be restored
List<TypeDefinition> originalTableTypes = tableTypeHandler.getTypeDefinitions();
// Import the data file into a table definition
ioHandler.importFromFile(dataFile[0], ImportType.FIRST_DATA_ONLY);
tableDefinitions = ioHandler.getTableDefinitions();
// Check if a table definition was successfully created
if (tableDefinitions != null && !tableDefinitions.isEmpty()) {
// Get a short-cut to the table definition to shorten subsequent calls
TableDefinition tableDefn = tableDefinitions.get(0);
// End any active edit sequence, then disable auto-ending so that the
// import operation can be handled as a single edit for undo/redo purposes
tableHandler.getTable().getUndoManager().endEditSequence();
tableHandler.getTable().getUndoHandler().setAutoEndEditSequence(false);
// Update the table description field in case the description changed
tableHandler.setDescription(tableDefn.getDescription());
// Add the imported data field(s) to the table
addImportedDataField(tableHandler.getFieldHandler(), tableDefn, tableHandler.getTableInformation().getTablePath(), useExistingFieldsCb.isSelected());
// Update the field information in case the field values changed
tableHandler.getFieldHandler().setFieldDefinitions(tableDefn.getDataFields());
tableHandler.getFieldHandler().buildFieldInformation(tableHandler.getTableInformation().getTablePath());
// Rebuild the table's editor panel which contains the data fields
tableHandler.createDataFieldPanel(true);
// Check if cell data is provided in the table definition
if (tableDefn.getData() != null && !tableDefn.getData().isEmpty()) {
// Get the original number of rows in the table
int numRows = tableHandler.getTableModel().getRowCount();
// importing the table following a cell validation error
if (!tableHandler.getTable().pasteData(tableDefn.getData().toArray(new String[0]), tableHandler.getTable().getColumnCount(), !overwriteChkBx.isSelected(), !overwriteChkBx.isSelected(), true, false)) {
// Let the user know how many rows were added
new CcddDialogHandler().showMessageDialog(tableHandler.getOwner(), "<html><b>" + (tableHandler.getTableModel().getRowCount() - numRows) + " row(s) added", "Paste Table Data", JOptionPane.INFORMATION_MESSAGE, DialogOption.OK_OPTION);
}
}
// Restore the table types to the values prior to the import operation
tableTypeHandler.setTypeDefinitions(originalTableTypes);
// Re-enable auto-ending of the edit sequence and end the sequence. The
// imported data can be removed with a single undo if desired
tableHandler.getTable().getUndoHandler().setAutoEndEditSequence(true);
tableHandler.getTable().getUndoManager().endEditSequence();
// Store the data file path in the program preferences backing store
storePath(ccddMain, dataFile[0].getAbsolutePathWithEnvVars(), true, ModifiablePathInfo.TABLE_EXPORT_PATH);
}
}
} catch (IOException ioe) {
// Inform the user that the data file cannot be read
new CcddDialogHandler().showMessageDialog(tableHandler.getOwner(), "<html><b>Cannot read import file<br>'</b>" + dataFile[0].getAbsolutePath() + "<b>'", "File Error", JOptionPane.ERROR_MESSAGE, DialogOption.OK_OPTION);
} 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(tableHandler.getOwner(), "<html><b>" + ce.getMessage(), "File Error", ce.getMessageType(), DialogOption.OK_OPTION);
}
} catch (Exception e) {
// Display a dialog providing details on the unanticipated error
CcddUtilities.displayException(e, tableHandler.getOwner());
}
}
}
use of CCDD.CcddClassesDataTable.TableDefinition in project CCDD by nasa.
the class CcddEDSHandler method importCommandTable.
/**
********************************************************************************************
* Build a command table from the specified command metadata
*
* @param namespace
* name space
*
* @param commandSet
* reference to the command set from which to build the command table
*
* @param table
* name table name, including the full system path
*
* @param hasParameter
* true if the name space also has a parameter set
*
* @throws CCDDException
* If an input error is detected
********************************************************************************************
*/
private void importCommandTable(NamespaceType namespace, List<InterfaceCommandType> commandSet, String tableName, boolean hasParameter) throws CCDDException {
// Create a table definition for this command table. If the name space also includes a
// parameter set (which creates a structure table) then ensure the two tables have
// different names
TableDefinition tableDefn = new TableDefinition(tableName + (hasParameter ? "_cmd" : ""), namespace.getLongDescription());
// Check if a description exists for this command table
if (namespace.getLongDescription() != null && !namespace.getLongDescription().isEmpty()) {
// Store the table's description
tableDefn.setDescription(namespace.getLongDescription());
}
// Set the new command table's table type name
tableDefn.setTypeName(commandTypeDefn.getName());
// Check if the description column belongs to a command argument
if (commandArguments.size() != 0 && cmdDescriptionIndex > commandArguments.get(0).getName()) {
// Reset the command description index to indicate no description exists
cmdDescriptionIndex = -1;
}
// Step through each command
for (InterfaceCommandType cmdType : commandSet) {
// Create a new row of data in the table definition to contain this command's
// information. Initialize all columns to blanks except for the command name
String[] newRow = new String[commandTypeDefn.getColumnCountVisible()];
Arrays.fill(newRow, null);
newRow[commandNameIndex] = cmdType.getName();
// table type definition
if (cmdType.getLongDescription() != null && cmdDescriptionIndex != -1) {
// Store the command description in the row's description
// column
newRow[cmdDescriptionIndex] = cmdType.getLongDescription();
}
int cmdArgIndex = 0;
// Step through each of the command's arguments
for (CommandArgumentType argList : cmdType.getArgument()) {
// type
if (namespace.getDataTypeSet() != null && commandNameIndex != -1) {
// Step through each data type set
for (RootDataType argType : namespace.getDataTypeSet().getArrayDataTypeOrBinaryDataTypeOrBooleanDataType()) {
// list (by matching the command and argument names between the two)
if (argList.getType().equals(argType.getName())) {
boolean isInteger = false;
boolean isUnsigned = false;
boolean isFloat = false;
boolean isString = false;
String dataType = null;
String arraySize = null;
BigInteger bitLength = null;
long sizeInBytes = 0;
String enumeration = null;
String description = null;
Unit units = null;
String minimum = null;
String maximum = null;
// Check if the argument is an array data type
if (argType instanceof ArrayDataType) {
arraySize = "";
// Store the reference to the array parameter type
ArrayDataType arrayType = (ArrayDataType) argType;
argType = null;
// Step through each dimension for the array variable
for (DimensionSizeType dim : arrayType.getDimensionList().getDimension()) {
// Build the array size string
arraySize += String.valueOf(dim.getSize().longValue()) + ",";
}
arraySize = CcddUtilities.removeTrailer(arraySize, ",");
// type entry Step through each data type set
for (RootDataType type : namespace.getDataTypeSet().getArrayDataTypeOrBinaryDataTypeOrBooleanDataType()) {
// the data type name
if (arrayType.getDataTypeRef().equals(type.getName())) {
// Store the reference to the array parameter's data type
// and stop searching
argType = type;
break;
}
}
}
// locate the data type entry for the individual array members)
if (argType != null) {
// Check if the argument is an integer data type
if (argType instanceof IntegerDataType) {
IntegerDataType icmd = (IntegerDataType) argType;
// Get the number of bits occupied by the argument
bitLength = icmd.getIntegerDataEncoding().getSizeInBits();
// Check if units exist for this argument
if (icmd.getSemantics() != null && icmd.getSemantics().getUnit() != null) {
// Get the argument units reference
units = icmd.getSemantics().getUnit();
}
// Check if integer encoding is set to 'unsigned'
if (icmd.getIntegerDataEncoding().getEncoding() == IntegerEncodingType.UNSIGNED) {
isUnsigned = true;
}
// Determine the smallest integer size that contains the number
// of bits occupied by the argument
sizeInBytes = 8;
while (bitLength.longValue() > sizeInBytes) {
sizeInBytes *= 2;
}
sizeInBytes /= 8;
// Get the argument range
IntegerDataTypeRangeType range = icmd.getRange();
// Check if the argument has a range
if (range != null && range.getMinMaxRange() != null) {
MinMaxRangeType minMax = range.getMinMaxRange();
// Check if the argument has a minimum value
if (minMax.getMin() != null) {
// Store the minimum value
minimum = minMax.getMin().toString();
}
// Check if the argument has a maximum value
if (minMax.getMax() != null) {
// Store the maximum value
maximum = minMax.getMax().toString();
}
}
isInteger = true;
} else // Check if the argument is a floating point data type
if (argType instanceof FloatDataType) {
// Get the float argument attributes
FloatDataType fcmd = (FloatDataType) argType;
// Check if units exist for this argument
if (fcmd.getSemantics() != null && fcmd.getSemantics().getUnit() != null) {
// Get the argument units reference
units = fcmd.getSemantics().getUnit();
}
switch(fcmd.getFloatDataEncoding().getEncodingAndPrecision()) {
case IEEE_754_2008_SINGLE:
sizeInBytes = 4;
break;
case IEEE_754_2008_DOUBLE:
sizeInBytes = 8;
break;
case IEEE_754_2008_QUAD:
sizeInBytes = 16;
break;
default:
break;
}
// Get the argument range
FloatDataTypeRangeType range = fcmd.getRange();
// Check if the argument has a range
if (range != null && range.getMinMaxRange() != null) {
MinMaxRangeType minMax = range.getMinMaxRange();
// Check if the argument has a minimum value
if (minMax.getMin() != null) {
// Store the minimum value
minimum = minMax.getMin().toString();
}
// Check if the argument has a maximum value
if (minMax.getMax() != null) {
// Store the maximum value
maximum = minMax.getMax().toString();
}
}
isFloat = true;
} else // Check if the argument is a string data type
if (argType instanceof StringDataType) {
// Get the string argument attributes
StringDataType scmd = (StringDataType) argType;
sizeInBytes = scmd.getLength().longValue();
// Check if units exist for this argument
if (scmd.getSemantics() != null && scmd.getSemantics().getUnit() != null) {
// Get the argument units reference
units = scmd.getSemantics().getUnit();
}
isString = true;
} else // Check if the argument is an enumerated data type
if (argType instanceof EnumeratedDataType) {
EnumeratedDataType ecmd = (EnumeratedDataType) argType;
EnumerationListType enumList = ecmd.getEnumerationList();
// Check if any enumeration parameters are defined
if (enumList != null) {
// Step through each enumeration parameter
for (ValueEnumerationType enumType : enumList.getEnumeration()) {
// Check if this is the first parameter
if (enumeration == null) {
// Initialize the enumeration string
enumeration = "";
} else // Not the first parameter
{
// Add the separator for the enumerations
enumeration += ",";
}
// Begin building this enumeration
enumeration += enumType.getValue() + " | " + enumType.getLabel();
}
bitLength = ecmd.getIntegerDataEncoding().getSizeInBits();
// Check if units exist for this argument
if (ecmd.getSemantics() != null && ecmd.getSemantics().getUnit() != null) {
// Get the argument units reference
units = ecmd.getSemantics().getUnit();
}
// Check if integer encoding is set to 'unsigned'
if (ecmd.getIntegerDataEncoding().getEncoding() == IntegerEncodingType.UNSIGNED) {
isUnsigned = true;
}
// Determine the smallest integer size that contains the
// number of bits occupied by the parameter
sizeInBytes = 8;
while (bitLength.longValue() > sizeInBytes) {
sizeInBytes *= 2;
}
sizeInBytes /= 8;
isInteger = true;
}
}
// Get the name of the data type from the data type table that
// matches the base type and size of the parameter
dataType = getDataType(dataTypeHandler, sizeInBytes, isInteger, isUnsigned, isFloat, isString);
// Check if the description exists
if (argList.getLongDescription() != null) {
// Store the description
description = argList.getLongDescription();
}
// dictated by the table type definition
if (cmdArgIndex < commandArguments.size()) {
// Get the command argument reference
AssociatedColumns acmdArg = commandArguments.get(cmdArgIndex);
// Check if the command argument name is present
if (acmdArg.getName() != -1) {
// Store the command argument name
newRow[acmdArg.getName()] = argList.getName();
}
// Check if the command argument data type is present
if (acmdArg.getDataType() != -1 && dataType != null) {
// Store the command argument data type
newRow[acmdArg.getDataType()] = dataType;
}
// Check if the command argument array size is present
if (acmdArg.getArraySize() != -1 && arraySize != null) {
// Store the command argument array size
newRow[acmdArg.getArraySize()] = arraySize;
}
// Check if the command argument bit length is present
if (acmdArg.getBitLength() != -1 && bitLength != null) {
// Store the command argument bit length
newRow[acmdArg.getBitLength()] = bitLength.toString();
}
// Check if the command argument enumeration is present
if (acmdArg.getEnumeration() != -1 && enumeration != null) {
// Store the command argument enumeration
newRow[acmdArg.getEnumeration()] = enumeration;
}
// Check if the command argument description is present
if (acmdArg.getDescription() != -1 && description != null) {
// Store the command argument description
newRow[acmdArg.getDescription()] = description;
}
// Check if the command argument units is present
if (acmdArg.getUnits() != -1 && units != null) {
// Store the command argument units
newRow[acmdArg.getUnits()] = units.toString();
}
// Check if the command argument minimum is present
if (acmdArg.getMinimum() != -1 && minimum != null) {
// Store the command argument minimum
newRow[acmdArg.getMinimum()] = minimum;
}
// Check if the command argument maximum is present
if (acmdArg.getMaximum() != -1 && maximum != null) {
// Store the command argument maximum
newRow[acmdArg.getMaximum()] = maximum;
}
}
}
// Increment the argument index
cmdArgIndex++;
break;
}
}
}
}
// Add the new row to the table definition
tableDefn.addData(newRow);
}
// Add the command table definition to the list
tableDefinitions.add(tableDefn);
}
use of CCDD.CcddClassesDataTable.TableDefinition in project CCDD by nasa.
the class CcddEDSHandler method importFromFile.
/**
********************************************************************************************
* Import the the table definitions from an EDS XML formatted file
*
* @param importFile
* reference to the user-specified XML input file
*
* @param importType
* ImportType.IMPORT_ALL to import the table type, data type, and macro definitions,
* and the data from all the table definitions; ImportType.FIRST_DATA_ONLY to load
* only the data for the first table defined
*
* @throws CCDDException
* If a data is missing, extraneous, or in error in the import file
*
* @throws IOException
* If an import file I/O error occurs
*
* @throws Exception
* For any unanticipated errors
********************************************************************************************
*/
@Override
public void importFromFile(FileEnvVar importFile, ImportType importType) throws CCDDException, IOException, Exception {
try {
// Import the XML from the specified file
JAXBElement<?> jaxbElement = (JAXBElement<?>) unmarshaller.unmarshal(importFile);
// Get the data sheet reference
dataSheet = (DataSheetType) jaxbElement.getValue();
tableDefinitions = new ArrayList<TableDefinition>();
structureTypeDefn = null;
commandTypeDefn = null;
// Get the telemetry and command header argument column names for the application ID
// and the command function code. These are stored as project-level data fields
ccsdsAppID = fieldHandler.getFieldValue(CcddFieldHandler.getFieldProjectName(), InputDataType.XML_APP_ID);
ccsdsFuncCode = fieldHandler.getFieldValue(CcddFieldHandler.getFieldProjectName(), InputDataType.XML_FUNC_CODE);
// Step through each name space in the data sheet
for (NamespaceType namespace : dataSheet.getNamespace()) {
// Step through the interfaces
for (InterfaceDeclarationType intfcDecType : namespace.getDeclaredInterfaceSet().getInterface()) {
// Check if this interface contains a generic type set
if (intfcDecType.getGenericTypeSet() != null && !intfcDecType.getGenericTypeSet().getGenericType().isEmpty()) {
// Step through each generic type data
for (GenericTypeType genType : intfcDecType.getGenericTypeSet().getGenericType()) {
// column name indicator
if (genType.getName().equals(ArgumentColumnName.APP_ID.getAncillaryName())) {
// Store the item value as the application ID argument column name.
// Note that this overrides the value extracted from the project
// data field
ccsdsAppID = genType.getBaseType();
} else // argument column name indicator
if (genType.getName().equals(ArgumentColumnName.FUNC_CODE.getAncillaryName())) {
// Store the item value as the command function code argument
// column name. Note that this overrides the value extracted from
// the project data field
ccsdsFuncCode = genType.getBaseType();
}
// project or the import file
if (ccsdsAppID == null) {
// Use the default application ID argument column name
ccsdsAppID = ArgumentColumnName.APP_ID.getDefaultArgColName();
}
// the project or the import file
if (ccsdsFuncCode == null) {
// Use the default command function code argument column name
ccsdsFuncCode = ArgumentColumnName.FUNC_CODE.getDefaultArgColName();
}
}
}
}
}
// Create the table type definitions for any new structure and command tables
createTableTypeDefinitions(importType);
// Check if at least one structure or command table needs to be built
if (structureTypeDefn != null || commandTypeDefn != null) {
// Step through each space system
for (NamespaceType namespace : dataSheet.getNamespace()) {
// Recursively step through the EDS-formatted data and extract the telemetry
// and command information
unbuildSpaceSystems(namespace, importType);
// Check if only the data from the first table is to be read
if (importType == ImportType.FIRST_DATA_ONLY) {
// Stop reading table definitions
break;
}
}
}
} catch (JAXBException je) {
// Inform the user that the database import failed
new CcddDialogHandler().showMessageDialog(parent, "<html><b>Cannot import EDS XML from file<br>'</b>" + importFile.getAbsolutePath() + "<b>'; cause '" + je.getMessage() + "'", "File Error", JOptionPane.ERROR_MESSAGE, DialogOption.OK_OPTION);
}
}
Aggregations