Search in sources :

Example 1 with TypeDefinition

use of CCDD.CcddTableTypeHandler.TypeDefinition 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);
        }
    }
}
Also used : CCDDException(CCDD.CcddClassesDataTable.CCDDException) ArrayList(java.util.ArrayList) JSONArray(org.json.simple.JSONArray) TableTypeDefinition(CCDD.CcddClassesDataTable.TableTypeDefinition) IOException(java.io.IOException) TableTypeDefinition(CCDD.CcddClassesDataTable.TableTypeDefinition) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition) JSONObject(org.json.simple.JSONObject) BufferedReader(java.io.BufferedReader) TableDefinition(CCDD.CcddClassesDataTable.TableDefinition) JSONParser(org.json.simple.parser.JSONParser) FileReader(java.io.FileReader) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException)

Example 2 with TypeDefinition

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

the class CcddJSONHandler method exportToFile.

/**
 ********************************************************************************************
 * Export the project in JSON format to the specified file
 *
 * @param exportFile
 *            reference to the user-specified output file
 *
 * @param tableNames
 *            array of table names to convert
 *
 * @param replaceMacros
 *            true to replace any embedded macros with their corresponding values
 *
 * @param includeReservedMsgIDs
 *            true to include the contents of the reserved message ID table in the export file
 *
 * @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
 *
 * @param extraInfo
 *            unused
 *
 * @return true if an error occurred preventing exporting the project to the file
 ********************************************************************************************
 */
@SuppressWarnings("unchecked")
@Override
public boolean exportToFile(FileEnvVar exportFile, String[] tableNames, boolean replaceMacros, boolean includeReservedMsgIDs, boolean includeVariablePaths, CcddVariableSizeAndConversionHandler variableHandler, String[] separators, Object... extraInfo) {
    boolean errorFlag = false;
    FileWriter fw = null;
    BufferedWriter bw = null;
    PrintWriter pw = null;
    try {
        List<String> referencedTableTypes = new ArrayList<String>();
        List<String> referencedDataTypes = new ArrayList<String>();
        List<String> referencedMacros = new ArrayList<String>();
        List<String[]> variablePaths = new ArrayList<String[]>();
        // Output the table data to the selected file. Multiple writers are needed in case
        // tables are appended to an existing file
        fw = new FileWriter(exportFile, true);
        bw = new BufferedWriter(fw);
        pw = new PrintWriter(bw);
        // Create the file creation comment
        JSONObject outputJO = new JSONObject();
        outputJO.put(JSONTags.FILE_DESCRIPTION.getTag(), "Created " + new Date().toString() + " : project = " + dbControl.getDatabaseName() + " : host = " + dbControl.getServer() + " : user = " + dbControl.getUser());
        // Check if any tables are provided
        if (tableNames.length != 0) {
            JSONArray tableJA = new JSONArray();
            // Step through each table
            for (String tblName : tableNames) {
                // Get the table's information
                JSONObject tableInfoJO = getTableInformation(tblName, !replaceMacros, includeVariablePaths, variableHandler, separators);
                // Check if the table's data successfully loaded
                if (tableInfoJO != null && !tableInfoJO.isEmpty()) {
                    // Add the wrapper for the table
                    tableJA.add(tableInfoJO);
                    // Get the table type definition based on the type name
                    TypeDefinition typeDefn = tableTypeHandler.getTypeDefinition(tableInfo.getType());
                    // Check if this table type is not already output
                    if (!referencedTableTypes.contains(tableInfo.getType())) {
                        // Add the table type to the list of those referenced
                        referencedTableTypes.add(tableInfo.getType());
                    }
                    // Get the visible column names based on the table's type
                    String[] columnNames = typeDefn.getColumnNamesUser();
                    // Step through each row in the table
                    for (int row = 0; row < tableInfo.getData().length; row++) {
                        // Step through each column in the row
                        for (int column = 0; column < columnNames.length; column++) {
                            // Check if the column isn't the primary key or row index
                            if (column != DefaultColumn.PRIMARY_KEY.ordinal() && column != DefaultColumn.ROW_INDEX.ordinal()) {
                                List<Integer> dataTypeColumns = new ArrayList<Integer>();
                                // Get the column indices for all columns that can contain a
                                // primitive data type
                                dataTypeColumns.addAll(typeDefn.getColumnIndicesByInputType(InputDataType.PRIM_AND_STRUCT));
                                dataTypeColumns.addAll(typeDefn.getColumnIndicesByInputType(InputDataType.PRIMITIVE));
                                // Step through each data type column
                                for (int dataTypeColumn : dataTypeColumns) {
                                    // Get the value column
                                    String dataTypeName = tableInfo.getData()[row][dataTypeColumn].toString();
                                    // in the list
                                    if (dataTypeHandler.isPrimitive(dataTypeName) && !referencedDataTypes.contains(dataTypeName)) {
                                        // Add the data type name to the list of references
                                        // data types
                                        referencedDataTypes.add(dataTypeName);
                                    }
                                }
                                // Get the names of the macros referenced in the cell and add
                                // them to the list
                                referencedMacros.addAll(macroHandler.getReferencedMacros(tableInfo.getData()[row][column].toString()));
                            }
                        }
                        // represents a structure
                        if (includeVariablePaths && typeDefn.isStructure()) {
                            // Get the variable path
                            String variablePath = tableInfo.getTablePath() + "," + tableInfo.getData()[row][typeDefn.getColumnIndexByInputType(InputDataType.PRIM_AND_STRUCT)] + "." + tableInfo.getData()[row][typeDefn.getColumnIndexByInputType(InputDataType.VARIABLE)];
                            // Add the path, in both application and user-defined formats, to
                            // the list to be output
                            variablePaths.add(new String[] { variablePath, variableHandler.getFullVariableName(variablePath, separators[0], Boolean.parseBoolean(separators[1]), separators[2]) });
                        }
                    }
                }
            }
            // Check if any tables were processed successfully
            if (tableJA != null) {
                // Add the table information to the JSON output
                outputJO.put(JSONTags.TABLE_DEFN.getTag(), tableJA);
            }
        }
        // Add the referenced table type definition(s), if any, to the output
        outputJO = getTableTypeDefinitions(referencedTableTypes, outputJO);
        // Add the referenced data type definition(s), if any, to the output
        outputJO = getDataTypeDefinitions(referencedDataTypes, outputJO);
        // Add the referenced macro definition(s), if any, to the output
        outputJO = getMacroDefinitions(referencedMacros, outputJO);
        // Check if the user elected to store the reserved message IDs
        if (includeReservedMsgIDs) {
            // Add the reserved message ID definition(s), if any, to the output
            outputJO = getReservedMsgIDDefinitions(outputJO);
        }
        // Check if variable paths are to be output
        if (includeVariablePaths) {
            // Add the variable paths, if any, to the output
            outputJO = getVariablePaths(variablePaths, outputJO);
        }
        // Create a JavaScript engine for use in formatting the JSON output
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine scriptEngine = manager.getEngineByName("JavaScript");
        // Output the formatted JSON object to the file
        scriptEngine.put("jsonString", outputJO.toString());
        scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 2)");
        pw.println((String) scriptEngine.get("result"));
    } catch (IOException ioe) {
        // Inform the user that the data file cannot be written to
        new CcddDialogHandler().showMessageDialog(parent, "<html><b>Cannot write to export file<br>'</b>" + exportFile.getAbsolutePath() + "<b>'", "File Error", JOptionPane.ERROR_MESSAGE, DialogOption.OK_OPTION);
        errorFlag = true;
    } catch (ScriptException se) {
        // Inform the user that formatting the JSON output failed
        new CcddDialogHandler().showMessageDialog(parent, "<html><b>Cannot format JSON output using JavaScript; cause '" + se.getMessage() + "'", "JavaScript Error", JOptionPane.ERROR_MESSAGE, DialogOption.OK_OPTION);
        errorFlag = true;
    } catch (Exception e) {
        // Display a dialog providing details on the unanticipated error
        CcddUtilities.displayException(e, parent);
        errorFlag = true;
    } finally {
        // Check if the PrintWriter was opened
        if (pw != null) {
            // Close the file
            pw.close();
        }
        try {
            // Check if the BufferedWriter was opened
            if (bw != null) {
                // Close the file
                bw.close();
            }
            // Check if the FileWriter was opened
            if (fw != null) {
                // Close the file
                fw.close();
            }
        } catch (IOException ioe) {
            // Inform the user that the data file cannot be closed
            new CcddDialogHandler().showMessageDialog(parent, "<html><b>Cannot close export file<br>'</b>" + exportFile.getAbsolutePath() + "<b>'", "File Warning", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
        }
    }
    return errorFlag;
}
Also used : FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) JSONArray(org.json.simple.JSONArray) ScriptEngineManager(javax.script.ScriptEngineManager) IOException(java.io.IOException) Date(java.util.Date) ScriptEngine(javax.script.ScriptEngine) CCDDException(CCDD.CcddClassesDataTable.CCDDException) ParseException(org.json.simple.parser.ParseException) ScriptException(javax.script.ScriptException) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) TableTypeDefinition(CCDD.CcddClassesDataTable.TableTypeDefinition) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition) ScriptException(javax.script.ScriptException) JSONObject(org.json.simple.JSONObject) PrintWriter(java.io.PrintWriter)

Example 3 with TypeDefinition

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

the class CcddJSONHandler method getTableData.

/**
 ********************************************************************************************
 * Get the data for the specified data table
 *
 * @param tableName
 *            table name and path in the format rootTable[,dataType1.variable1[,...]]. Blank to
 *            return the data for all tables
 *
 * @param getDescription
 *            true to get the table description when loading the table data
 *
 * @param replaceMacros
 *            true to display the macro values in place of the corresponding macro names; false
 *            to display the macro names
 *
 * @param includeVariablePaths
 *            true to include a column, 'Variable Path', showing the variable path for each
 *            variable in a structure table using the user-defined separator characters
 *
 * @param variableHandler
 *            variable handler class reference; null if isIncludePath 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 isIncludePath is false
 *
 * @param outputJO
 *            JSON object to which the data types are added
 *
 * @return The supplied JSON object, with the table data added (if any); null if the table
 *         doesn't exists or an error occurs when loading the data. Empty table cells are
 *         omitted
 ********************************************************************************************
 */
@SuppressWarnings("unchecked")
protected JSONObject getTableData(String tableName, boolean getDescription, boolean replaceMacros, boolean includeVariablePaths, CcddVariableSizeAndConversionHandler variableHandler, String[] separators, JSONObject outputJO) {
    JSONArray tableDataJA = null;
    // Get the information from the database for the specified table
    tableInfo = dbTable.loadTableData(tableName, !getDescription, false, false, ccddMain.getMainFrame());
    // Check if the table exists and successfully loaded
    if (tableInfo != null && !tableInfo.isErrorFlag()) {
        JSONObject columnJO = new JSONObject();
        tableDataJA = new JSONArray();
        // Check if the macro names should be replaced with the corresponding macro values
        if (replaceMacros) {
            // Replace all macros in the table
            tableInfo.setData(macroHandler.replaceAllMacros(tableInfo.getData()));
        }
        // Check if the table has any data
        if (tableInfo.getData().length != 0) {
            // Get the column names for this table's type definition
            TypeDefinition typeDefn = ccddMain.getTableTypeHandler().getTypeDefinition(tableInfo.getType());
            String[] columnNames = typeDefn.getColumnNamesUser();
            // Step through each table row
            for (int row = 0; row < tableInfo.getData().length; row++) {
                columnJO = new JSONObject();
                // Step through each table column
                for (int column = NUM_HIDDEN_COLUMNS; column < tableInfo.getData()[row].length; column++) {
                    // Check if a cell isn't blank
                    if (!tableInfo.getData()[row][column].isEmpty()) {
                        // Add the column name and value to the cell object
                        columnJO.put(columnNames[column], tableInfo.getData()[row][column]);
                        // separators are supplied
                        if (typeDefn.isStructure() && includeVariablePaths && variableHandler != null && separators != null) {
                            // Get the variable's data type
                            String dataType = tableInfo.getData()[row][typeDefn.getColumnIndexByInputType(InputDataType.PRIM_AND_STRUCT)];
                            // Check if the data type is a primitive
                            if (dataTypeHandler.isPrimitive(dataType)) {
                                // Build the variable's full path
                                String variablePath = tableInfo.getTablePath() + "," + dataType + "." + tableInfo.getData()[row][typeDefn.getColumnIndexByInputType(InputDataType.VARIABLE)];
                                // Add the formatted path in the 'Variable Path' column
                                columnJO.put("Variable Path", variableHandler.getFullVariableName(variablePath, separators[0], Boolean.valueOf(separators[1]), separators[2]));
                            }
                        }
                    }
                }
                // Add the column values to the data array. An array is used to preserve the
                // order of the rows
                tableDataJA.add(columnJO);
            }
        }
        // Check if any table data was loaded
        if (!tableDataJA.isEmpty()) {
            // Add the table data to the JSON output
            outputJO.put(JSONTags.TABLE_DATA.getTag(), tableDataJA);
        }
    } else // The table failed to load (database error or the table doesn't exist)
    {
        // Set the output to null in order to indicate the error
        outputJO = null;
    }
    return outputJO;
}
Also used : JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) TableTypeDefinition(CCDD.CcddClassesDataTable.TableTypeDefinition) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition)

Example 4 with TypeDefinition

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

the class CcddMessageIDHandler method getMessageIDsAndNames.

/**
 ********************************************************************************************
 * Get the list containing every message ID name and its corresponding message ID, and the
 * owning entity from every table cell, data field (table or group), and telemetry message. ID
 * names and IDs are determined by the input data type assigned to the table column or data
 * field, and are matched one-to-one by relative position; i.e., the first message ID name data
 * field for a table or group is paired with the first message ID data field, and so on. If
 * more names are defined than IDs or vice versa then a blank ID/name is paired with the
 * unmatched name/ID
 *
 * @param sortOrder
 *            order in which to sort the message ID list: BY_OWNER or BY_NAME
 *
 * @param hideProtectionFlag
 *            true to not display the flag character that protects a message ID from being
 *            changed by the auto-update methods; false to allow the flag to remain
 *
 * @param parent
 *            GUI component calling this method
 *
 * @return List containing every message ID name and its corresponding message ID, and the
 *         owning entity
 ********************************************************************************************
 */
protected List<String[]> getMessageIDsAndNames(MessageIDSortOrder sortOrder, boolean hideProtectionFlag, Component parent) {
    String id;
    ArrayListMultiple ownersNamesAndIDs = new ArrayListMultiple();
    ArrayListMultiple tableIDNames = new ArrayListMultiple();
    ArrayListMultiple tableIDs = new ArrayListMultiple();
    // Step through each table type
    for (TypeDefinition typeDefn : tableTypeHandler.getTypeDefinitions()) {
        // Step through each column that contains message ID names
        for (int idColumn : typeDefn.getColumnIndicesByInputType(InputDataType.MESSAGE_ID_NAME)) {
            // Query the database for those values in the specified message ID name column that
            // are in use in any table, including any references in the custom values table
            tableIDNames.addAll(dbTable.queryDatabase("SELECT " + "* FROM find_columns_by_name('" + typeDefn.getColumnNamesUser()[idColumn] + "', '" + typeDefn.getColumnNamesDatabase()[idColumn] + "', '{" + typeDefn.getName() + "}');", parent));
        }
        // Step through each column that contains message IDs
        for (int idColumn : typeDefn.getColumnIndicesByInputType(InputDataType.MESSAGE_ID)) {
            // Query the database for those values in the specified message ID column that are
            // in use in any table, including any references in the custom values table
            tableIDs.addAll(dbTable.queryDatabase("SELECT " + "* FROM find_columns_by_name('" + typeDefn.getColumnNamesUser()[idColumn] + "', '" + typeDefn.getColumnNamesDatabase()[idColumn] + "', '{" + typeDefn.getName() + "}');", parent));
        }
    }
    // Get the list of all message ID name data field values
    tableIDNames.addAll(dbTable.queryDatabase("SELECT " + InternalTable.FIELDS.getColumnName(FieldsColumn.OWNER_NAME.ordinal()) + ", " + InternalTable.FIELDS.getColumnName(FieldsColumn.FIELD_VALUE.ordinal()) + " FROM " + InternalTable.FIELDS.getTableName() + " WHERE " + InternalTable.FIELDS.getColumnName(FieldsColumn.FIELD_TYPE.ordinal()) + " = '" + InputDataType.MESSAGE_ID_NAME.getInputName() + "' AND " + InternalTable.FIELDS.getColumnName(FieldsColumn.FIELD_VALUE.ordinal()) + " != '' ORDER BY OID;", parent));
    // Get the list of all message ID data field values
    tableIDs.addAll(dbTable.queryDatabase("SELECT " + InternalTable.FIELDS.getColumnName(FieldsColumn.OWNER_NAME.ordinal()) + ", " + InternalTable.FIELDS.getColumnName(FieldsColumn.FIELD_VALUE.ordinal()) + " FROM " + InternalTable.FIELDS.getTableName() + " WHERE " + InternalTable.FIELDS.getColumnName(FieldsColumn.FIELD_TYPE.ordinal()) + " = '" + InputDataType.MESSAGE_ID.getInputName() + "' AND " + InternalTable.FIELDS.getColumnName(FieldsColumn.FIELD_VALUE.ordinal()) + " != '' ORDER BY OID;", parent));
    // Step through each ID name
    while (tableIDNames.size() > 0) {
        // Get the ID name owner and ID name from the first list member, then remove it from
        // the ID name list
        String idOwner = tableIDNames.get(0)[0];
        String idName = tableIDNames.get(0)[1];
        tableIDNames.remove(0);
        // Get the index in the ID list of the first member with the same owner
        int index = tableIDs.indexOf(idOwner);
        // Check if a matching owner is found
        if (index != -1) {
            // Get the ID with the matching owner and remove it from the ID list
            id = hideProtectionFlag ? removeProtectionFlag(tableIDs.get(index)[1]) : tableIDs.get(index)[1];
            tableIDs.remove(index);
        } else // No matching owner exists
        {
            // Set the ID to the default (a blank)
            id = "";
        }
        // Add the owner, ID name, and ID to the list
        ownersNamesAndIDs.add(new String[] { idOwner, idName, id });
    }
    // name
    while (tableIDs.size() > 0) {
        // Get the ID owner and ID from the first list member, then remove it from the ID list
        String idOwner = tableIDs.get(0)[0];
        id = hideProtectionFlag ? removeProtectionFlag(tableIDs.get(0)[1]) : tableIDs.get(0)[1];
        tableIDs.remove(0);
        // Add the owner, default ID name (a blank), and ID to the list
        ownersNamesAndIDs.add(new String[] { idOwner, "", id });
    }
    // Get the telemetry rates, message ID names, and IDs assigned in the telemetry scheduler
    // table. This query returns only those the message names with the sub-message index
    // appended, so for parent messages without any sub-messages this retrieves the 'default'
    // sub-message name
    ArrayListMultiple tlmMsgs = new ArrayListMultiple(1);
    tlmMsgs.addAll(dbTable.queryDatabase("SELECT DISTINCT ON (3,2) 'Tlm:' || " + InternalTable.TLM_SCHEDULER.getColumnName(TlmSchedulerColumn.RATE_NAME.ordinal()) + ", regexp_replace(" + InternalTable.TLM_SCHEDULER.getColumnName(TlmSchedulerColumn.MESSAGE_NAME.ordinal()) + ", E'\\\\.', '_'), " + InternalTable.TLM_SCHEDULER.getColumnName(TlmSchedulerColumn.MESSAGE_ID.ordinal()) + " FROM " + InternalTable.TLM_SCHEDULER.getTableName() + " WHERE " + InternalTable.TLM_SCHEDULER.getColumnName(TlmSchedulerColumn.MESSAGE_NAME.ordinal()) + " ~ E'\\\\.';", parent));
    // Step through each of the telemetry messages retrieved
    for (String[] tlmMsg : tlmMsgs) {
        // Check if this message has the default sub-message name
        if (tlmMsg[1].endsWith("_0")) {
            // Get the parent message name
            String parentMsg = tlmMsg[1].substring(0, tlmMsg[1].length() - 2);
            // indicates that the parent has no 'real' sub-messages
            if (!tlmMsgs.contains(parentMsg + "_1")) {
                // Store the parent message name in place of the default sub-message name
                tlmMsg[1] = parentMsg;
            }
        }
    }
    // Add the processed telemetry message to the list
    ownersNamesAndIDs.addAll(tlmMsgs);
    // Sort the message ID list in the order specified
    switch(sortOrder) {
        case BY_OWNER:
            // Sort the message ID list by owner
            ownersNamesAndIDs.setComparisonColumn(MsgIDListColumnIndex.OWNER.ordinal());
            ownersNamesAndIDs.sort(ArrayListMultipleSortType.STRING);
            break;
        case BY_NAME:
            // Sort the message ID list by ID name
            ownersNamesAndIDs.setComparisonColumn(MsgIDListColumnIndex.MESSAGE_ID_NAME.ordinal());
            ownersNamesAndIDs.sort(ArrayListMultipleSortType.STRING);
            break;
    }
    return ownersNamesAndIDs;
}
Also used : ArrayListMultiple(CCDD.CcddClassesComponent.ArrayListMultiple) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition)

Example 5 with TypeDefinition

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

the class CcddMacroEditorDialog method createMacroTable.

/**
 ********************************************************************************************
 * Create the macro table
 *
 * @return Reference to the scroll pane in which the table is placed
 ********************************************************************************************
 */
private JScrollPane createMacroTable() {
    // Define the macro editor JTable
    macroTable = new CcddJTableHandler() {

        /**
         ************************************************************************************
         * Highlight any macros in the macro values column
         *
         * @param component
         *            reference to the table cell renderer component
         *
         * @param text
         *            cell text
         *
         * @param isSelected
         *            true if the cell is to be rendered with the selection highlighted
         *
         * @param int
         *            row cell row, view coordinates
         *
         * @param column
         *            cell column, view coordinates
         ************************************************************************************
         */
        @Override
        protected void doSpecialRendering(Component component, String text, boolean isSelected, int row, int column) {
            // Check if this is the macro values column
            if (column == MacroEditorColumnInfo.VALUE.ordinal()) {
                // Highlight any macro names in the table cell. Adjust the highlight color to
                // account for the cell selection highlighting so that the macro is easily
                // readable
                macroHandler.highlightMacro(component, text, isSelected ? ModifiableColorInfo.INPUT_TEXT.getColor() : ModifiableColorInfo.TEXT_HIGHLIGHT.getColor());
                // Highlight 'sizeof(data type)' instances
                CcddDataTypeHandler.highlightSizeof(component, text, isSelected ? ModifiableColorInfo.INPUT_TEXT.getColor() : ModifiableColorInfo.TEXT_HIGHLIGHT.getColor());
            }
        }

        /**
         ************************************************************************************
         * Get the tool tip text for a table cell, showing any macro name replaced with its
         * corresponding macro value
         ************************************************************************************
         */
        @Override
        public String getToolTipText(MouseEvent me) {
            String toolTipText = null;
            // Get the row and column of the cell over which the mouse pointer is hovering
            Point point = me.getPoint();
            int row = rowAtPoint(point);
            int column = columnAtPoint(point);
            // Check if a cell is beneath the mouse pointer
            if (row != -1 && column != -1) {
                // Expand any macros in the cell text and display this as the cell's tool tip
                // text
                toolTipText = macroHandler.getMacroToolTipText(getValueAt(row, column).toString());
            }
            return toolTipText;
        }

        /**
         ************************************************************************************
         * Allow multiple line display in all columns
         ************************************************************************************
         */
        @Override
        protected boolean isColumnMultiLine(int column) {
            return true;
        }

        /**
         ************************************************************************************
         * Hide the the specified columns
         ************************************************************************************
         */
        @Override
        protected boolean isColumnHidden(int column) {
            return column == MacroEditorColumnInfo.OID.ordinal();
        }

        /**
         ************************************************************************************
         * Override isCellEditable so that all columns can be edited
         ************************************************************************************
         */
        @Override
        public boolean isCellEditable(int row, int column) {
            return true;
        }

        /**
         ************************************************************************************
         * Allow pasting data into the macro cells
         ************************************************************************************
         */
        @Override
        protected boolean isDataAlterable(Object[] rowData, int row, int column) {
            return isCellEditable(convertRowIndexToView(row), convertColumnIndexToView(column));
        }

        /**
         ************************************************************************************
         * Validate changes to the editable cells
         *
         * @param tableData
         *            list containing the table data row arrays
         *
         * @param row
         *            table model row number
         *
         * @param column
         *            table model column number
         *
         * @param oldValue
         *            original cell contents
         *
         * @param newValue
         *            new cell contents
         *
         * @param showMessage
         *            true to display the invalid input dialog, if applicable
         *
         * @param isMultiple
         *            true if this is one of multiple cells to be entered and checked; false if
         *            only a single input is being entered
         *
         * @return Always returns false
         ************************************************************************************
         */
        @Override
        protected Boolean validateCellContent(List<Object[]> tableData, int row, int column, Object oldValue, Object newValue, Boolean showMessage, boolean isMultiple) {
            // Reset the flag that indicates the last edited cell's content is invalid
            setLastCellValid(true);
            // Create a string version of the new value
            String newValueS = newValue.toString();
            try {
                // Check if the value isn't blank
                if (!newValueS.isEmpty()) {
                    // Check if the macro name has been changed and if the name isn't blank
                    if (column == MacroEditorColumnInfo.NAME.ordinal()) {
                        // Check if the macro name does not match the alphanumeric input type
                        if (!newValueS.matches(InputDataType.ALPHANUMERIC.getInputMatch())) {
                            throw new CCDDException("Illegal character(s) in macro name");
                        }
                        // creating a duplicate
                        for (int otherRow = 0; otherRow < getRowCount(); otherRow++) {
                            // name matches the one being added (case insensitive)
                            if (otherRow != row && newValueS.equalsIgnoreCase(tableData.get(otherRow)[column].toString())) {
                                throw new CCDDException("Macro name already in use");
                            }
                        }
                    } else // Check if the macro value changed
                    if (column == MacroEditorColumnInfo.VALUE.ordinal()) {
                        // Create a macro handler using the values currently displayed in the
                        // macro editor
                        CcddMacroHandler newMacroHandler = new CcddMacroHandler(ccddMain, getUpdatedData());
                        newMacroHandler.setHandlers(ccddMain.getVariableHandler());
                        // Get the macro's index and name
                        String index = tableData.get(row)[MacroEditorColumnInfo.OID.ordinal()].toString();
                        String macroName = tableData.get(row)[MacroEditorColumnInfo.NAME.ordinal()].toString();
                        // (doesn't cause a recursive reference)
                        if (!macroName.isEmpty() && newMacroHandler.isMacroRecursive(macroName)) {
                            throw new CCDDException("Macro '</b>" + macroName + "<b>' contains a recursive reference");
                        }
                        // Step through the committed macros
                        for (int commRow = 0; commRow < committedData.length; commRow++) {
                            // Check if the index matches that for the committed macro
                            if (index.equals(committedData[commRow][MacroEditorColumnInfo.OID.ordinal()])) {
                                List<String> tableNames = new ArrayList<String>();
                                // Get the macro name. Use the committed name (in place of the
                                // current name in the editor, in case it's been changed) since
                                // this is how the macro is referenced in the data tables
                                macroName = committedData[commRow][MacroEditorColumnInfo.NAME.ordinal()];
                                MacroReference macroRefs = null;
                                // loaded
                                for (MacroReference loadedRef : loadedReferences) {
                                    // searched macro
                                    if (macroName.equals(loadedRef.getMacroName())) {
                                        // Store the macro search reference and stop searching
                                        macroRefs = loadedRef;
                                        break;
                                    }
                                }
                                // Check if the macro references haven't already been loaded
                                if (macroRefs == null) {
                                    // Search for references to this macro
                                    macroRefs = new MacroReference(macroName);
                                    // Add the search results to the list so that this search
                                    // doesn't get performed again
                                    loadedReferences.add(macroRefs);
                                }
                                // Step through each reference to the macro in the tables
                                for (String macroRef : macroRefs.getReferences()) {
                                    // Split the reference into table name, column name, table
                                    // type, and context
                                    String[] tblColDescAndCntxt = macroRef.split(TABLE_DESCRIPTION_SEPARATOR, 4);
                                    String refComment = tblColDescAndCntxt[SearchResultsQueryColumn.COMMENT.ordinal()];
                                    // table
                                    if (!refComment.isEmpty()) {
                                        // Extract the viewable name and type of the table and
                                        // the name of the column containing the data type, and
                                        // separate the column string into the individual
                                        // column values
                                        String[] refNameAndType = refComment.split(",");
                                        // contain a type mismatch
                                        if (!tableNames.contains(refNameAndType[0])) {
                                            String refColumn = tblColDescAndCntxt[SearchResultsQueryColumn.COLUMN.ordinal()];
                                            String[] refContext = CcddUtilities.splitAndRemoveQuotes(tblColDescAndCntxt[SearchResultsQueryColumn.CONTEXT.ordinal()]);
                                            // Use the type and column to get the column's
                                            // input data type
                                            TypeDefinition typeDefn = ccddMain.getTableTypeHandler().getTypeDefinition(refNameAndType[1]);
                                            int columnIndex = typeDefn.getColumnIndexByDbName(refColumn);
                                            InputDataType inputType = typeDefn.getInputTypes()[columnIndex];
                                            // column value
                                            for (String oldName : macroHandler.getReferencedMacros(refContext[columnIndex])) {
                                                String newName = oldName;
                                                String oid = "";
                                                // Step through the updated macro definitions
                                                for (String[] oldMacro : macroHandler.getMacroData()) {
                                                    // Check if the macro names match
                                                    if (oldName.equals(oldMacro[MacrosColumn.MACRO_NAME.ordinal()])) {
                                                        // Store the OID value for the macro
                                                        // and stop searching
                                                        oid = oldMacro[MacrosColumn.OID.ordinal()];
                                                        break;
                                                    }
                                                }
                                                // Step through the updated macro definitions
                                                for (String[] newMacro : newMacroHandler.getMacroData()) {
                                                    // the target one
                                                    if (oid.equals(newMacro[MacrosColumn.OID.ordinal()])) {
                                                        // Since the OIDs match these are the
                                                        // same macro. Store the macro's new
                                                        // name (in case it changed) and stop
                                                        // searching
                                                        newName = newMacro[MacrosColumn.MACRO_NAME.ordinal()];
                                                        break;
                                                    }
                                                }
                                                // Replace all instances of the macro's old
                                                // name with its new name
                                                refContext[columnIndex] = macroHandler.replaceMacroName(CcddMacroHandler.getFullMacroName(oldName), CcddMacroHandler.getFullMacroName(newName), refContext[columnIndex]);
                                            }
                                            // macro's user
                                            if (!newMacroHandler.getMacroExpansion(refContext[columnIndex]).matches(inputType.getInputMatch())) {
                                                // Add the affected table name to the list
                                                tableNames.add(refNameAndType[0]);
                                            }
                                        }
                                    }
                                }
                                // were found
                                if (!tableNames.isEmpty()) {
                                    throw new CCDDException("Macro value is not consistent with macro usage in table(s) '</b>" + dbTable.getShortenedTableNames(tableNames.toArray(new String[0])) + "<b>'");
                                }
                                break;
                            }
                        }
                    }
                }
            } catch (CCDDException ce) {
                // Set the flag that indicates the last edited cell's content is invalid
                setLastCellValid(false);
                // Check if the input error dialog should be displayed
                if (showMessage) {
                    // Inform the user that the input value is invalid
                    new CcddDialogHandler().showMessageDialog(CcddMacroEditorDialog.this, "<html><b>" + ce.getMessage(), "Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                }
                // Restore the cell contents to its original value and pop the edit from the
                // stack
                tableData.get(row)[column] = oldValue;
                macroTable.getUndoManager().undoRemoveEdit();
            }
            return false;
        }

        /**
         ************************************************************************************
         * Load the table macro definition values into the table and format the table cells
         ************************************************************************************
         */
        @Override
        protected void loadAndFormatData() {
            // Place the data into the table model along with the column names, set up the
            // editors and renderers for the table cells, set up the table grid lines, and
            // calculate the minimum width required to display the table information
            setUpdatableCharacteristics(committedData, MacroEditorColumnInfo.getColumnNames(), null, MacroEditorColumnInfo.getToolTips(), true, true, true);
        }

        /**
         ************************************************************************************
         * Override prepareRenderer to allow adjusting the background colors of table cells
         ************************************************************************************
         */
        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            JComponent comp = (JComponent) super.prepareRenderer(renderer, row, column);
            // invalid highlighting, if applicable)
            if (!(isFocusOwner() && isRowSelected(row) && (isColumnSelected(column) || !getColumnSelectionAllowed()))) {
                boolean found = true;
                // Check if the cell is required and is empty
                if (MacroEditorColumnInfo.values()[macroTable.convertColumnIndexToModel(column)].isRequired() && macroTable.getValueAt(row, column).toString().isEmpty()) {
                    // Set the flag indicating that the cell value is invalid
                    found = false;
                }
                // Check if the cell value is invalid
                if (!found) {
                    // Change the cell's background color
                    comp.setBackground(ModifiableColorInfo.REQUIRED_BACK.getColor());
                }
            }
            return comp;
        }

        /**
         ************************************************************************************
         * Override the CcddJTableHandler method to produce an array containing empty values
         * for a new row in this table
         *
         * @return Array containing blank cell values for a new row
         ************************************************************************************
         */
        @Override
        protected Object[] getEmptyRow() {
            return MacroEditorColumnInfo.getEmptyRow();
        }

        /**
         ************************************************************************************
         * Handle a change to the table's content
         ************************************************************************************
         */
        @Override
        protected void processTableContentChange() {
            // Add or remove the change indicator based on whether or not any unstored changes
            // exist
            setTitle(DIALOG_TITLE + (macroTable.isTableChanged(committedData) ? "*" : ""));
            // Force the table to redraw so that changes to the cells are displayed
            repaint();
        }
    };
    // Place the table into a scroll pane
    JScrollPane scrollPane = new JScrollPane(macroTable);
    // Disable storage of edit operations during table creation
    macroTable.getUndoHandler().setAllowUndo(false);
    // Set common table parameters and characteristics
    macroTable.setFixedCharacteristics(scrollPane, true, ListSelectionModel.MULTIPLE_INTERVAL_SELECTION, TableSelectionMode.SELECT_BY_CELL, false, ModifiableColorInfo.TABLE_BACK.getColor(), true, true, ModifiableFontInfo.DATA_TABLE_CELL.getFont(), true);
    // Re-enable storage of edit operations
    macroTable.getUndoHandler().setAllowUndo(true);
    return scrollPane;
}
Also used : JScrollPane(javax.swing.JScrollPane) TableCellRenderer(javax.swing.table.TableCellRenderer) MouseEvent(java.awt.event.MouseEvent) CCDDException(CCDD.CcddClassesDataTable.CCDDException) ArrayList(java.util.ArrayList) JComponent(javax.swing.JComponent) Point(java.awt.Point) Point(java.awt.Point) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition) JComponent(javax.swing.JComponent) Component(java.awt.Component) InputDataType(CCDD.CcddConstants.InputDataType)

Aggregations

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