Search in sources :

Example 16 with FileEnvVar

use of CCDD.CcddClassesComponent.FileEnvVar 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 17 with FileEnvVar

use of CCDD.CcddClassesComponent.FileEnvVar 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)

Aggregations

FileEnvVar (CCDD.CcddClassesComponent.FileEnvVar)17 CCDDException (CCDD.CcddClassesDataTable.CCDDException)11 ArrayList (java.util.ArrayList)7 SimpleDateFormat (java.text.SimpleDateFormat)6 JPanel (javax.swing.JPanel)5 FileNameExtensionFilter (javax.swing.filechooser.FileNameExtensionFilter)5 GridBagConstraints (java.awt.GridBagConstraints)4 GridBagLayout (java.awt.GridBagLayout)4 Insets (java.awt.Insets)4 IOException (java.io.IOException)4 ResultSet (java.sql.ResultSet)4 SQLException (java.sql.SQLException)4 TypeDefinition (CCDD.CcddTableTypeHandler.TypeDefinition)3 ActionEvent (java.awt.event.ActionEvent)3 ActionListener (java.awt.event.ActionListener)3 JCheckBox (javax.swing.JCheckBox)3 TableDefinition (CCDD.CcddClassesDataTable.TableDefinition)2 File (java.io.File)2 Border (javax.swing.border.Border)2 BackgroundCommand (CCDD.CcddBackgroundCommand.BackgroundCommand)1