Search in sources :

Example 31 with CCDDException

use of CCDD.CcddClassesDataTable.CCDDException in project CCDD by nasa.

the class CcddTableManagerDialog method verifySelection.

/**
 ********************************************************************************************
 * Verify that the dialog content is valid
 *
 * @return true if the input values are valid
 ********************************************************************************************
 */
@Override
protected boolean verifySelection() {
    // Assume the dialog input is valid
    boolean isValid = true;
    try {
        // Verify the dialog content based on the supplied dialog type
        switch(dialogType) {
            case NEW:
                // Remove any excess white space
                String names = nameFld.getText().trim();
                descriptionFld.setText(descriptionFld.getText().trim());
                // Store the cleaned table name
                nameFld.setText(names);
                // Check if a table type is selected
                if (getRadioButtonSelected() == null) {
                    // Inform the user that a table type must be selected
                    throw new CCDDException("Table type must be selected");
                }
                // Create a list to hold the new names already checked
                List<String> newNames = new ArrayList<String>();
                // Break the string of names into separate strings
                tableNames = names.split(",");
                // Step through each table name
                for (int index = 0; index < tableNames.length; index++) {
                    // Remove leading and trailing white space characters
                    String tableName = tableNames[index].trim();
                    // Force to lower case to remove case sensitivity
                    if (newNames.contains(tableName.toLowerCase())) {
                        // Inform the user that a table name is a duplicate
                        throw new CCDDException("Table name '" + tableName + "' is a duplicate");
                    }
                    // Check if the name is valid
                    verifyTableName(tableName);
                    // Add the new table name to the comparison list
                    newNames.add(tableName.toLowerCase());
                    // Store the cleaned table name into the array
                    tableNames[index] = tableName;
                }
                break;
            case RENAME:
            case COPY:
                // Remove any excess white space
                String tableName = nameFld.getText().trim();
                descriptionFld.setText(descriptionFld.getText().trim());
                // Store the cleaned table name
                nameFld.setText(tableName);
                // Check if the name is valid
                verifyTableName(tableName);
                break;
            case EDIT:
            case DELETE:
                // Check if no table has been selected
                if (tableTree.getSelectedTablesWithChildren().size() == 0) {
                    // Inform the user that no item has been selected
                    throw new CCDDException("Must select a table from the tree");
                }
                break;
            case IMPORT:
                // Remove any leading or trailing white space characters from the file
                // path/name
                getFileNameField().setText(getFileNameField().getText().trim());
                // Check if the name field is empty or contains no file name in the path
                if (getFileNameField().getText().isEmpty() || getFileNameField().getText().matches(".*\\" + File.separator + "\\.*?$")) {
                    // Inform the user that the import file is missing
                    new CcddDialogHandler().showMessageDialog(CcddTableManagerDialog.this, "<html><b>Must select an import file name", "Missing/Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                    // Set the flag to indicate the dialog input is invalid
                    isValid = false;
                }
                break;
            case EXPORT_CSV:
            case EXPORT_EDS:
            case EXPORT_JSON:
            case EXPORT_XTCE:
                // Remove any leading or trailing white space characters from the file
                // path/name
                pathFld.setText(pathFld.getText().trim());
                // been selected
                if (callingEditorDialog == null && tableTree.getSelectedTablesWithChildren().size() == 0) {
                    // Inform the user that no table has been selected
                    throw new CCDDException("Must select a table from the tree");
                }
                // Check if the table(s) are to be stored in a single file
                if (singleFileRBtn.isSelected()) {
                    // Check if the name field is empty or contains no file name in the path
                    if (pathFld.getText().isEmpty() || pathFld.getText().matches(".*\\" + File.separator + "\\.*?$")) {
                        // Inform the user that no file name has been selected
                        throw new CCDDException("Must select an export file name");
                    }
                    // Create a file reference from the file path/name
                    FileEnvVar file = new FileEnvVar(pathFld.getText());
                    // Check if the selection is a directory instead of a file name
                    if (file.isDirectory()) {
                        // selected
                        throw new CCDDException("Directory name cannot be selected as the file name");
                    } else // Check if the file already exists; if so, the name is valid
                    if (!file.exists()) {
                        try {
                            // Attempt to create the file; an exception is thrown if
                            // unsuccessful
                            file.createNewFile();
                            // The file was successfully created; delete it
                            file.delete();
                        } catch (Exception e) {
                            // file can't be created
                            throw new CCDDException("Invalid export file name");
                        }
                    }
                }
                // Check if exporting in XTCE XML format
                if (dialogType == ManagerDialogType.EXPORT_XTCE) {
                    // Remove any excess white space
                    versionFld.setText(versionFld.getText().trim());
                    validStatFld.setText(validStatFld.getText().trim());
                    class1Fld.setText(class1Fld.getText().trim());
                    class2Fld.setText(class2Fld.getText().trim());
                    class3Fld.setText(class3Fld.getText().trim());
                    // Check if any of the fields is blank
                    if (versionFld.getText().isEmpty() || validStatFld.getText().isEmpty() || class1Fld.getText().isEmpty() || class2Fld.getText().isEmpty() || class3Fld.getText().isEmpty()) {
                        // Inform the user that a required field is missing
                        throw new CCDDException("System data field name, version, " + "validation status, and/or " + "classification missing");
                    }
                }
                break;
        }
    } catch (CCDDException ce) {
        // Inform the user that the input value is invalid
        new CcddDialogHandler().showMessageDialog(CcddTableManagerDialog.this, "<html><b>" + ce.getMessage(), "Missing/Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
        // Set the flag to indicate the dialog input is invalid
        isValid = false;
    }
    return isValid;
}
Also used : CCDDException(CCDD.CcddClassesDataTable.CCDDException) ArrayList(java.util.ArrayList) FileEnvVar(CCDD.CcddClassesComponent.FileEnvVar) CCDDException(CCDD.CcddClassesDataTable.CCDDException)

Example 32 with CCDDException

use of CCDD.CcddClassesDataTable.CCDDException in project CCDD by nasa.

the class CcddFileIOHandler method restoreDatabaseFromFile.

/**
 ********************************************************************************************
 * Restore a project's database from a user-selected backup file. The backup is a plain text
 * file containing the PostgreSQL commands necessary to rebuild the database
 ********************************************************************************************
 */
protected void restoreDatabaseFromFile() {
    File tempFile = null;
    // Allow the user to select the backup file path + name to load from
    FileEnvVar[] dataFile = new CcddDialogHandler().choosePathFile(ccddMain, ccddMain.getMainFrame(), null, null, new FileNameExtensionFilter[] { new FileNameExtensionFilter(FileExtension.DBU.getDescription(), FileExtension.DBU.getExtensionName()) }, false, "Restore Project", ccddMain.getProgPrefs().get(ModifiablePathInfo.DATABASE_BACKUP_PATH.getPreferenceKey(), null), DialogOption.RESTORE_OPTION);
    // Check if a file was chosen
    if (dataFile != null && dataFile[0] != null) {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            // Check if the file doesn't exist
            if (!dataFile[0].exists()) {
                throw new CCDDException("Cannot locate backup file<br>'</b>" + dataFile[0].getAbsolutePath() + "'");
            }
            boolean ownerFound = false;
            boolean commentFound = false;
            String line;
            String projectName = null;
            String projectOwner = null;
            String projectDescription = null;
            // Create a temporary file in which to copy the backup file contents
            tempFile = File.createTempFile(dataFile[0].getName(), "");
            // Create a buffered reader to read the file and a buffered writer to write the
            // file
            br = new BufferedReader(new FileReader(dataFile[0]));
            bw = new BufferedWriter(new FileWriter(tempFile));
            // Read each line in the backup file
            while ((line = br.readLine()) != null) {
                // contains the owner information
                if (!ownerFound && line.matches("-- Name: [^;]+; Type: [^;]+; Schema: [^;]+; Owner: .+")) {
                    // Get the owner and store it, and set the flag indicating the owner is
                    // located
                    projectOwner = line.replaceFirst(".*Owner: ", "");
                    ownerFound = true;
                }
                // contains the comment information
                if (!commentFound && line.matches("COMMENT ON DATABASE .+ IS '" + CCDD_PROJECT_IDENTIFIER + ".+")) {
                    // Split the line read from the file in order to get the project name and
                    // description
                    String[] parts = line.trim().split(DATABASE_COMMENT_SEPARATOR, 3);
                    // Check if the necessary components of the comment exist
                    if (parts.length == 3) {
                        // Extract the project name (with case preserved) and description, and
                        // set the flag indicating the comment is located
                        projectName = parts[DatabaseComment.PROJECT_NAME.ordinal()];
                        projectDescription = CcddUtilities.removeTrailer(parts[DatabaseComment.DESCRIPTION.ordinal()], "';");
                        commentFound = true;
                        // Insert a comment indicator into the file so that this line isn't
                        // executed when the database is restored
                        line = "-- " + line;
                    }
                }
                // Write the line to the temporary file
                bw.write(line + "\n");
            }
            // Check if the project owner, name, and description exist
            if (ownerFound && commentFound) {
                // Restore the database from the temporary file. This file has the line that
                // disables creation of the database comment, which is handled when the
                // restored database is created
                dbControl.restoreDatabase(projectName, projectOwner, projectDescription, tempFile);
                // Store the data file path in the program preferences backing store
                storePath(ccddMain, dataFile[0].getAbsolutePathWithEnvVars(), true, ModifiablePathInfo.DATABASE_BACKUP_PATH);
            } else // The project owner, name, and description don't exist
            {
                throw new CCDDException("File<br>'</b>" + dataFile[0].getAbsolutePath() + "'<br><b> is not a backup file");
            }
        } catch (CCDDException ce) {
            // Inform the user that the backup file error occurred
            new CcddDialogHandler().showMessageDialog(ccddMain.getMainFrame(), "<html><b>" + ce.getMessage(), "File Error", ce.getMessageType(), DialogOption.OK_OPTION);
        } catch (Exception e) {
            // Inform the user that the backup file cannot be read
            new CcddDialogHandler().showMessageDialog(ccddMain.getMainFrame(), "<html><b>Cannot read backup file<br>'</b>" + dataFile[0].getAbsolutePath() + "<b>'; cause '" + e.getMessage() + "'", "File Error", JOptionPane.ERROR_MESSAGE, DialogOption.OK_OPTION);
        } finally {
            try {
                // Check if the input file is open
                if (br != null) {
                    // Close the input file
                    br.close();
                }
            } catch (IOException ioe) {
                // Inform the user that the input file cannot be closed
                new CcddDialogHandler().showMessageDialog(ccddMain.getMainFrame(), "<html><b>Cannot close backup file<br>'</b>" + dataFile[0].getAbsolutePath() + "<b>'", "File Warning", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
            } finally {
                try {
                    // Check if the output file is open
                    if (bw != null) {
                        // Close the output file
                        bw.close();
                    }
                } catch (IOException ioe) {
                    // Inform the user that the output file cannot be closed
                    new CcddDialogHandler().showMessageDialog(ccddMain.getMainFrame(), "<html><b>Cannot close backup file<br>'</b>" + tempFile.getAbsolutePath() + "<b>'", "File Warning", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                }
            }
        }
    }
}
Also used : CCDDException(CCDD.CcddClassesDataTable.CCDDException) FileWriter(java.io.FileWriter) FileEnvVar(CCDD.CcddClassesComponent.FileEnvVar) IOException(java.io.IOException) FileNameExtensionFilter(javax.swing.filechooser.FileNameExtensionFilter) CCDDException(CCDD.CcddClassesDataTable.CCDDException) SQLException(java.sql.SQLException) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) File(java.io.File)

Example 33 with CCDDException

use of CCDD.CcddClassesDataTable.CCDDException in project CCDD by nasa.

the class CcddFileIOHandler method importFile.

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

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

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

        boolean errorFlag = false;

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

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

Example 34 with CCDDException

use of CCDD.CcddClassesDataTable.CCDDException in project CCDD by nasa.

the class CcddWebDataAccessHandler method getTableInformation.

/**
 ********************************************************************************************
 * Get the type, description, size, data, and data fields 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 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)
 *
 * @return JSON encoded string containing the specified table information; null if a table name
 *         is specified and the table doesn't exist or if no data tables exist in the project
 *         database
 *
 * @throws CCDDException
 *             If an error occurs while parsing the table information
 ********************************************************************************************
 */
@SuppressWarnings("unchecked")
private String getTableInformation(String tableName, String[] separators) throws CCDDException {
    JSONArray responseJA = new JSONArray();
    JSONParser parser = new JSONParser();
    String response = null;
    // Check if no table name is provided (i.e., get the information for all tables)
    if (tableName.isEmpty()) {
        // Get the list of all data table names
        List<String> tableNameList = getTableList();
        // Check that at least one table exists in the project database
        if (!tableNameList.isEmpty()) {
            response = "";
            // Step through each table name
            for (String name : tableNameList) {
                try {
                    // Get the fields for this table as a JSON string, then format it as a JSON
                    // object so that is can be added to the response array. This is needed to
                    // get the brackets and commas in the JSON formatted string correct
                    responseJA.add(parser.parse(getTableInformation(name, separators)));
                } catch (ParseException pe) {
                    throw new CCDDException("error parsing table information");
                }
            }
            // Convert the response array to a JSON string
            response = responseJA.toString();
        }
    }
    // A table name is provided
    {
        // Get the tables information
        JSONObject tableInfoJO = jsonHandler.getTableInformation(tableName, isReplaceMacro, isIncludePath, variableHandler, separators);
        // Check if the table loaded successfully
        if (tableInfoJO != null) {
            // Add the table's information to the output
            response = tableInfoJO.toString();
        }
    }
    return response;
}
Also used : CCDDException(CCDD.CcddClassesDataTable.CCDDException) JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 35 with CCDDException

use of CCDD.CcddClassesDataTable.CCDDException in project CCDD by nasa.

the class CcddWebDataAccessHandler method getTelemetrySchedulerData.

/**
 ********************************************************************************************
 * Get the telemetry scheduler's copy table entries
 *
 * @param parameters
 *            comma-separated string containing the data stream name, header size (in bytes),
 *            message ID name data field name, and the optimize result flag ('true' or 'false')
 *
 * @return JSON encoded string containing the specified copy table entries; null if the number
 *         of parameters or their formats are incorrect
 *
 * @throws CCDDException
 *             If an error occurs while parsing the telemetry scheduler data
 ********************************************************************************************
 */
@SuppressWarnings("unchecked")
private String getTelemetrySchedulerData(String parameters) throws CCDDException {
    String response = null;
    // Separate the input parameters
    String[] parameter = getParts(parameters, ",", 4, true);
    // Check if all the input parameters are present and that they're in the expected formats
    if (parameter[1].matches("\\d+") && parameter[3].matches(TRUE_OR_FALSE)) {
        JSONArray tableJA = new JSONArray();
        // Get the individual parameters and format them if needed
        String streamName = parameter[0];
        int headerSize = Integer.valueOf(parameter[1]);
        String messageIDNameField = parameter[2];
        boolean optimize = Boolean.valueOf(parameter[3]);
        // Get the rate information based on the supplied data stream name
        RateInformation rateInfo = rateHandler.getRateInformationByStreamName(streamName);
        // Check if the rate information doesn't exist with this stream name
        if (rateInfo == null) {
            throw new CCDDException("unknown data stream name");
        }
        // Create an instance of the copy table handler in order to read the information from
        // the database
        CcddCopyTableHandler copyHandler = new CcddCopyTableHandler(ccddMain);
        // Create the copy table entries based on the supplied parameters
        String[][] copyTable = copyHandler.createCopyTable(new CcddFieldHandler(ccddMain, null, ccddMain.getMainFrame()), new CcddLinkHandler(ccddMain, ccddMain.getMainFrame()), rateInfo.getStreamName(), headerSize, messageIDNameField, null, optimize, isReplaceMacro);
        // Check if there are any entries in the table
        if (copyTable.length != 0) {
            // Step through each row in the table
            for (String[] row : copyTable) {
                JSONObject rowJO = new JSONObject();
                // Step through each column in the row
                for (int column = 0; column < row.length; column++) {
                    // Add the copy table value to the array. An array is used to preserve the
                    // order of the items
                    rowJO.put(CopyTableEntry.values()[column].getColumnName(), row[column]);
                }
                // Add the row's copy table values to the table array
                tableJA.add(rowJO);
            }
        }
        // Store the copy table information
        JSONObject copyJO = new JSONObject();
        copyJO.put(JSONTags.COPY_TABLE_STREAM.getTag(), streamName);
        copyJO.put(JSONTags.COPY_TABLE_HDR_SIZE.getTag(), String.valueOf(headerSize));
        copyJO.put(JSONTags.COPY_TABLE_OPTIMIZE.getTag(), String.valueOf(optimize));
        copyJO.put(JSONTags.COPY_TABLE_DATA.getTag(), tableJA);
        response = copyJO.toString();
    } else // Invalid parameter format
    {
        throw new CCDDException("parameter type mismatch");
    }
    return response;
}
Also used : CCDDException(CCDD.CcddClassesDataTable.CCDDException) JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) RateInformation(CCDD.CcddClassesDataTable.RateInformation)

Aggregations

CCDDException (CCDD.CcddClassesDataTable.CCDDException)44 ArrayList (java.util.ArrayList)17 TypeDefinition (CCDD.CcddTableTypeHandler.TypeDefinition)13 JSONObject (org.json.simple.JSONObject)12 FileEnvVar (CCDD.CcddClassesComponent.FileEnvVar)11 JSONArray (org.json.simple.JSONArray)11 JScrollPane (javax.swing.JScrollPane)10 JComponent (javax.swing.JComponent)9 Component (java.awt.Component)8 ParseException (org.json.simple.parser.ParseException)8 IOException (java.io.IOException)7 TableCellRenderer (javax.swing.table.TableCellRenderer)7 JSONParser (org.json.simple.parser.JSONParser)7 GroupInformation (CCDD.CcddClassesDataTable.GroupInformation)6 GridBagConstraints (java.awt.GridBagConstraints)6 GridBagLayout (java.awt.GridBagLayout)6 Insets (java.awt.Insets)6 JPanel (javax.swing.JPanel)6 TableDefinition (CCDD.CcddClassesDataTable.TableDefinition)5 TableInformation (CCDD.CcddClassesDataTable.TableInformation)5