Search in sources :

Example 1 with FileEnvVar

use of CCDD.CcddClassesComponent.FileEnvVar in project CCDD by nasa.

the class CcddScriptHandler method getEnvironmentVariableMap.

/**
 ********************************************************************************************
 * Update the environment variable map with any variables specified by the user. Update the
 * association availability based on if the script exists, using the current environment
 * variables to expand its path
 *
 * @param parent
 *            GUI component calling this method
 *
 * @return true if the each key has a corresponding value; false if a value is missing
 ********************************************************************************************
 */
private boolean getEnvironmentVariableMap(Component parent) {
    boolean isValid = true;
    // Get the current system environment variable map
    envVarMap = new HashMap<String, String>(System.getenv());
    // Step through the overrides, if any
    for (String envVarDefn : envVarOverrideFld.getText().split("\\s*,\\s*")) {
        // Check that the definition isn't blank
        if (!envVarDefn.isEmpty()) {
            // Split the override into a key and value
            String[] keyAndValue = CcddUtilities.splitAndRemoveQuotes(envVarDefn.trim(), "\\s*=\\s*", 2, true);
            // Check if the key and value are present
            if (keyAndValue.length == 2) {
                // Add the key and value to the map if the key doesn't already exist; otherwise
                // replace the value for the key
                envVarMap.put(keyAndValue[0].trim().replaceAll("^\\$\\s*", ""), keyAndValue[1].trim());
            } else // Insufficient parameters
            {
                // Inform the user that script association execution can't continue due to an
                // invalid input
                new CcddDialogHandler().showMessageDialog(parent, "<html><b>Environment variable override key '" + keyAndValue[0] + "' has no corresponding value", "Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                isValid = false;
                break;
            }
        }
    }
    // Check if every key has a value
    if (isValid) {
        // Update the environment variable override preferences
        ModifiableOtherSettingInfo.ENV_VAR_OVERRIDE.setValue(envVarOverrideFld.getText().trim(), ccddMain.getProgPrefs());
        // Step through each script association
        for (int row = 0; row < assnsTable.getRowCount(); row++) {
            // Check if the association isn't unavailable due to a missing table
            if (assnsTable.getValueAt(row, AssociationsTableColumnInfo.SCRIPT_FILE.ordinal()) != AvailabilityType.TABLE_MISSING) {
                // Get the reference to the association's script file
                FileEnvVar file = new FileEnvVar(FileEnvVar.expandEnvVars(assnsTable.getValueAt(row, AssociationsTableColumnInfo.SCRIPT_FILE.ordinal()).toString(), envVarMap));
                // Set the availability status based on if the script file exists
                ((UndoableTableModel) assnsTable.getModel()).setValueAt((file.exists() ? AvailabilityType.AVAILABLE : AvailabilityType.SCRIPT_MISSING), row, AssociationsTableColumnInfo.AVAILABLE.ordinal(), false);
            }
        }
        // Force the table to redraw so that a change in an association's availability status
        // is reflected
        ((UndoableTableModel) assnsTable.getModel()).fireTableDataChanged();
        ((UndoableTableModel) assnsTable.getModel()).fireTableStructureChanged();
    }
    return isValid;
}
Also used : UndoableTableModel(CCDD.CcddUndoHandler.UndoableTableModel) FileEnvVar(CCDD.CcddClassesComponent.FileEnvVar)

Example 2 with FileEnvVar

use of CCDD.CcddClassesComponent.FileEnvVar in project CCDD by nasa.

the class CcddPatchHandler method updateAssociationsTable.

/**
 ********************************************************************************************
 * Update the associations table to include a description column and to change the table
 * separator characters in the member_table column. Older versions of CCDD are not compatible
 * with the project database after applying this patch
 *
 * @throws CCDDException
 *             If the user elects to not install the patch or an error occurs while applying
 *             the patch
 ********************************************************************************************
 */
private void updateAssociationsTable() throws CCDDException {
    CcddEventLogDialog eventLog = ccddMain.getSessionEventLog();
    CcddDbControlHandler dbControl = ccddMain.getDbControlHandler();
    try {
        CcddDbCommandHandler dbCommand = ccddMain.getDbCommandHandler();
        CcddDbTableCommandHandler dbTable = ccddMain.getDbTableCommandHandler();
        // Create lists to contain the old and new associations table items
        List<String[]> tableData = new ArrayList<String[]>();
        // Read the contents of the associations table
        ResultSet assnsData = dbCommand.executeDbQuery("SELECT * FROM " + InternalTable.ASSOCIATIONS.getTableName() + " ORDER BY OID;", ccddMain.getMainFrame());
        // Check if the patch hasn't already been applied
        if (assnsData.getMetaData().getColumnCount() == 2) {
            // Check if the user elects to not apply the patch
            if (new CcddDialogHandler().showMessageDialog(ccddMain.getMainFrame(), "<html><b>Apply patch to update the script " + "associations table?<br><br></b>" + "Incorporates a description column in the " + "script associations table.<br><b><i>Older " + "versions of CCDD will be incompatible " + "with this project database after " + "applying the patch", "Apply Patch #07212017", JOptionPane.QUESTION_MESSAGE, DialogOption.OK_CANCEL_OPTION) != OK_BUTTON) {
                assnsData.close();
                throw new CCDDException("user elected to not install patch (#0712017)");
            }
            // Step through each of the query results
            while (assnsData.next()) {
                // Create an array to contain the column values
                String[] columnValues = new String[3];
                // Step through each column in the row
                for (int column = 0; column < 2; column++) {
                    // Add the column value to the array. Note that the first column's index in
                    // the database is 1, not 0. Also, shift the old data over one column to
                    // make room for the description
                    columnValues[column + 1] = assnsData.getString(column + 1);
                    // Check if the value is null
                    if (columnValues[column] == null) {
                        // Replace the null with a blank
                        columnValues[column] = "";
                    }
                }
                // Add the row data to the list
                tableData.add(columnValues);
            }
            assnsData.close();
            // Check if there are any associations in the table
            if (tableData.size() != 0) {
                // Indicate in the log that the old data successfully loaded
                eventLog.logEvent(SUCCESS_MSG, InternalTable.ASSOCIATIONS.getTableName() + " retrieved");
                // Step through each script association
                for (int row = 0; row < tableData.size(); row++) {
                    // Set the description to a blank and replace the table name separator
                    // characters with the new ones
                    tableData.set(row, new String[] { "", tableData.get(row)[1], tableData.get(row)[2].replaceAll(" \\+ ", ASSN_TABLE_SEPARATOR) });
                }
            }
            // Back up the project database before applying the patch
            dbControl.backupDatabase(dbControl.getDatabaseName(), new FileEnvVar(ModifiablePathInfo.DATABASE_BACKUP_PATH.getPath() + File.separator + dbControl.getDatabaseName() + "_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) + FileExtension.DBU.getExtension()));
            // Store the updated associations table
            dbTable.storeInformationTable(InternalTable.ASSOCIATIONS, tableData, null, ccddMain.getMainFrame());
            // Inform the user that updating the database associations table completed
            eventLog.logEvent(EventLogMessageType.SUCCESS_MSG, "Project '" + dbControl.getProjectName() + "' associations table conversion complete");
        }
    } catch (Exception e) {
        // Inform the user that converting the associations table failed
        eventLog.logFailEvent(ccddMain.getMainFrame(), "Cannot convert project '" + dbControl.getProjectName() + "' associations table to new format; cause '" + e.getMessage() + "'", "<html><b>Cannot convert project '" + dbControl.getProjectName() + "' associations table to new format " + "(project database will be closed)");
        throw new CCDDException();
    }
}
Also used : CCDDException(CCDD.CcddClassesDataTable.CCDDException) ArrayList(java.util.ArrayList) FileEnvVar(CCDD.CcddClassesComponent.FileEnvVar) CCDDException(CCDD.CcddClassesDataTable.CCDDException) ResultSet(java.sql.ResultSet) SimpleDateFormat(java.text.SimpleDateFormat)

Example 3 with FileEnvVar

use of CCDD.CcddClassesComponent.FileEnvVar in project CCDD by nasa.

the class CcddDbControlHandler method connectToDatabase.

/**
 ********************************************************************************************
 * Connect to a database
 *
 * @param databaseName
 *            name of the database to open
 *
 * @return true if the connection attempt failed
 ********************************************************************************************
 */
private boolean connectToDatabase(String databaseName) {
    boolean errorFlag = false;
    try {
        connectionStatus = NO_CONNECTION;
        // Connect the user to the database
        connection = DriverManager.getConnection(getDatabaseURL(databaseName), activeUser, activePassword);
        dbCommand.setStatement(connection.createStatement());
        // Reset the flag that indicates a connection failure occurred due to a missing
        // password
        isMissingPassword = false;
        // Set the transaction isolation mode to serializable to prevent transaction collisions
        // if there are concurrent users of the database
        connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        // Disable automatic commit of database updates. This allows database commands to be
        // grouped prior to committing
        connection.setAutoCommit(false);
        // Store the database connection
        dbCommand.setConnection(connection);
        // Save the name of the newly connected database
        setDatabaseName(databaseName);
        // Check if the default database is selected
        if (databaseName.equals(DEFAULT_DATABASE)) {
            // Set the connection status to indicate the default database is connected
            connectionStatus = TO_SERVER_ONLY;
            // Inform the user that the server connection succeeded
            eventLog.logEvent(SUCCESS_MSG, "Connected to server as user '" + activeUser + "'");
        } else // A database other than the default is selected
        {
            // The connection to the server must exist in order to reach this point, so set the
            // connection status to indicate the server is connected. Once the project
            // connection is completed the flag is updated accordingly
            connectionStatus = TO_SERVER_ONLY;
            // lock status is ignored
            if (!ccddMain.isGUIHidden()) {
                // Get the database lock status
                Boolean isLocked = getDatabaseLockStatus(databaseName);
                // Check if an error occurred obtaining the lock status
                if (isLocked == null) {
                    // Set the error flag
                    throw new CCDDException("");
                }
                // Check if the database is locked
                if (isLocked) {
                    throw new SQLException("database is locked");
                }
            }
            boolean isAllowed = false;
            // Step through each database
            for (String database : queryDatabaseByUserList(ccddMain.getMainFrame(), activeUser)) {
                // access to this database
                if (databaseName.equalsIgnoreCase(database.split(DATABASE_COMMENT_SEPARATOR, 2)[0])) {
                    // Set the flag indicating the user has access and stop searching
                    isAllowed = true;
                    break;
                }
            }
            // Check if the user has access to this database
            if (!isAllowed) {
                // Set the error flag
                throw new CCDDException("");
            }
            // Get the database owner
            activeOwner = queryDatabaseOwner(databaseName, ccddMain.getMainFrame())[0];
            // Set the connection status to indicate a database is connected
            connectionStatus = TO_DATABASE;
            // Check if an automatic backup was scheduled via the command line argument
            if (!backupFileName.isEmpty()) {
                // Check if the backup file name is missing the correct extension
                if (!backupFileName.endsWith(FileExtension.DBU.getExtension())) {
                    // Append the backup file extension to the file name
                    backupFileName += FileExtension.DBU.getExtension();
                }
                // Backup the database
                backupDatabaseInBackground(databaseName, new FileEnvVar(backupFileName));
                // Reset the backup file name to prevent another automatic backup
                backupFileName = "";
            }
            // Inform the user that the database connection succeeded
            eventLog.logEvent(SUCCESS_MSG, "Connected to project '" + activeProject + "' as user '" + activeUser + "'");
        }
    } catch (SQLException se) {
        // Check if the connection failed due to a missing or invalid password
        if ((se.getMessage().contains("authentication failed") || se.getMessage().contains("password")) && !ccddMain.isGUIHidden()) {
            // Set the flag that indicates a connection failure occurred due to a missing
            // password
            isMissingPassword = true;
        } else // Connection failed for reason other than a missing password
        {
            // Inform the user that the database connection failed
            eventLog.logFailEvent(ccddMain.getMainFrame(), "Cannot connect to " + (activeDatabase.equals(DEFAULT_DATABASE) ? "server" : "project database '" + getServerAndDatabase(databaseName) + "'") + " as user '" + activeUser + "'; cause '" + se.getMessage() + "'", "<html><b>Cannot connect to " + (activeDatabase.equals(DEFAULT_DATABASE) ? "server" : "project '</b>" + databaseName + "<b>'"));
        }
        errorFlag = true;
    } catch (CCDDException ce) {
        errorFlag = true;
    }
    // Check if a connection is established
    if (!errorFlag) {
        // Log the PostgreSQL and JDBC versions
        eventLog.logEvent(EventLogMessageType.STATUS_MSG, "PostgreSQL: " + getDatabaseVersion() + "  *** JDBC: " + getJDBCVersion());
    }
    return errorFlag;
}
Also used : CCDDException(CCDD.CcddClassesDataTable.CCDDException) SQLException(java.sql.SQLException) FileEnvVar(CCDD.CcddClassesComponent.FileEnvVar)

Example 4 with FileEnvVar

use of CCDD.CcddClassesComponent.FileEnvVar in project CCDD by nasa.

the class CcddFileIOHandler method importSelectedFileIntoTable.

/**
 ********************************************************************************************
 * Import the contents of a file selected by the user into the specified existing table
 *
 * @param tableHandler
 *            reference to the table handler for the table into which to import the data
 ********************************************************************************************
 */
protected void importSelectedFileIntoTable(CcddTableEditorHandler tableHandler) {
    // Set the initial layout manager characteristics
    GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2, 0, 0), 0, 0);
    // Create an empty border
    Border emptyBorder = BorderFactory.createEmptyBorder();
    // Create overwrite check box
    JCheckBox overwriteChkBx = new JCheckBox("Overwrite existing cells");
    overwriteChkBx.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
    overwriteChkBx.setBorder(emptyBorder);
    overwriteChkBx.setToolTipText(CcddUtilities.wrapText("Overwrite existing cell data; if unchecked then new " + "rows are inserted to contain the imported data", ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
    overwriteChkBx.setSelected(false);
    // Create a check box for indicating existing tables can be replaced
    JCheckBox useExistingFieldsCb = new JCheckBox("Use existing field if duplicate");
    useExistingFieldsCb.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
    useExistingFieldsCb.setBorder(emptyBorder);
    useExistingFieldsCb.setToolTipText(CcddUtilities.wrapText("Use the existing data field definition if " + "a field with the same name is imported", ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
    useExistingFieldsCb.setSelected(true);
    // Create a panel to contain the overwrite check box
    JPanel checkBoxPnl = new JPanel(new GridBagLayout());
    checkBoxPnl.setBorder(emptyBorder);
    checkBoxPnl.add(overwriteChkBx, gbc);
    gbc.insets.top = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing();
    gbc.gridy++;
    checkBoxPnl.add(useExistingFieldsCb, gbc);
    // Allow the user to select the data file path + name to import from
    FileEnvVar[] dataFile = new CcddDialogHandler().choosePathFile(ccddMain, tableHandler.getOwner(), null, "export", new FileNameExtensionFilter[] { new FileNameExtensionFilter(FileExtension.CSV.getDescription(), FileExtension.CSV.getExtensionName()), new FileNameExtensionFilter(FileExtension.EDS.getDescription(), FileExtension.EDS.getExtensionName()), new FileNameExtensionFilter(FileExtension.JSON.getDescription(), FileExtension.JSON.getExtensionName()), new FileNameExtensionFilter(FileExtension.XTCE.getDescription(), FileExtension.XTCE.getExtensionName()) }, false, false, "Import Table Data", ccddMain.getProgPrefs().get(ModifiablePathInfo.TABLE_EXPORT_PATH.getPreferenceKey(), null), DialogOption.IMPORT_OPTION, checkBoxPnl);
    // Check if a file was chosen
    if (dataFile != null && dataFile[0] != null) {
        try {
            List<TableDefinition> tableDefinitions = null;
            CcddImportExportInterface ioHandler = null;
            // Check if the file to import is in CSV format based on the extension
            if (dataFile[0].getAbsolutePath().endsWith(FileExtension.CSV.getExtension())) {
                // Create a CSV handler
                ioHandler = new CcddCSVHandler(ccddMain, tableHandler.getFieldHandler(), tableHandler.getOwner());
            } else // Check if the file to import is in EDS XML format based on the extension
            if (dataFile[0].getAbsolutePath().endsWith(FileExtension.EDS.getExtension())) {
                // Create an EDS handler
                ioHandler = new CcddEDSHandler(ccddMain, tableHandler.getFieldHandler(), tableHandler.getOwner());
            } else // Check if the file to import is in JSON format based on the extension
            if (dataFile[0].getAbsolutePath().endsWith(FileExtension.JSON.getExtension())) {
                // Create a JSON handler
                ioHandler = new CcddJSONHandler(ccddMain, tableHandler.getFieldHandler(), tableHandler.getOwner());
            } else // Check if the file to import is in XTCE XML format based on the extension
            if (dataFile[0].getAbsolutePath().endsWith(FileExtension.XTCE.getExtension())) {
                // Create an XTCE handler
                ioHandler = new CcddXTCEHandler(ccddMain, tableHandler.getFieldHandler(), tableHandler.getOwner());
            } else // The file extension isn't recognized
            {
                throw new CCDDException("Cannot import file '" + dataFile[0].getAbsolutePath() + "' into table; unrecognized file type");
            }
            // Check that no error occurred creating the format conversion handler
            if (!ioHandler.getErrorStatus()) {
                // Store the current table type information so that it can be restored
                List<TypeDefinition> originalTableTypes = tableTypeHandler.getTypeDefinitions();
                // Import the data file into a table definition
                ioHandler.importFromFile(dataFile[0], ImportType.FIRST_DATA_ONLY);
                tableDefinitions = ioHandler.getTableDefinitions();
                // Check if a table definition was successfully created
                if (tableDefinitions != null && !tableDefinitions.isEmpty()) {
                    // Get a short-cut to the table definition to shorten subsequent calls
                    TableDefinition tableDefn = tableDefinitions.get(0);
                    // End any active edit sequence, then disable auto-ending so that the
                    // import operation can be handled as a single edit for undo/redo purposes
                    tableHandler.getTable().getUndoManager().endEditSequence();
                    tableHandler.getTable().getUndoHandler().setAutoEndEditSequence(false);
                    // Update the table description field in case the description changed
                    tableHandler.setDescription(tableDefn.getDescription());
                    // Add the imported data field(s) to the table
                    addImportedDataField(tableHandler.getFieldHandler(), tableDefn, tableHandler.getTableInformation().getTablePath(), useExistingFieldsCb.isSelected());
                    // Update the field information in case the field values changed
                    tableHandler.getFieldHandler().setFieldDefinitions(tableDefn.getDataFields());
                    tableHandler.getFieldHandler().buildFieldInformation(tableHandler.getTableInformation().getTablePath());
                    // Rebuild the table's editor panel which contains the data fields
                    tableHandler.createDataFieldPanel(true);
                    // Check if cell data is provided in the table definition
                    if (tableDefn.getData() != null && !tableDefn.getData().isEmpty()) {
                        // Get the original number of rows in the table
                        int numRows = tableHandler.getTableModel().getRowCount();
                        // importing the table following a cell validation error
                        if (!tableHandler.getTable().pasteData(tableDefn.getData().toArray(new String[0]), tableHandler.getTable().getColumnCount(), !overwriteChkBx.isSelected(), !overwriteChkBx.isSelected(), true, false)) {
                            // Let the user know how many rows were added
                            new CcddDialogHandler().showMessageDialog(tableHandler.getOwner(), "<html><b>" + (tableHandler.getTableModel().getRowCount() - numRows) + " row(s) added", "Paste Table Data", JOptionPane.INFORMATION_MESSAGE, DialogOption.OK_OPTION);
                        }
                    }
                    // Restore the table types to the values prior to the import operation
                    tableTypeHandler.setTypeDefinitions(originalTableTypes);
                    // Re-enable auto-ending of the edit sequence and end the sequence. The
                    // imported data can be removed with a single undo if desired
                    tableHandler.getTable().getUndoHandler().setAutoEndEditSequence(true);
                    tableHandler.getTable().getUndoManager().endEditSequence();
                    // Store the data file path in the program preferences backing store
                    storePath(ccddMain, dataFile[0].getAbsolutePathWithEnvVars(), true, ModifiablePathInfo.TABLE_EXPORT_PATH);
                }
            }
        } catch (IOException ioe) {
            // Inform the user that the data file cannot be read
            new CcddDialogHandler().showMessageDialog(tableHandler.getOwner(), "<html><b>Cannot read import file<br>'</b>" + dataFile[0].getAbsolutePath() + "<b>'", "File Error", JOptionPane.ERROR_MESSAGE, DialogOption.OK_OPTION);
        } catch (CCDDException ce) {
            // Check if an error message is provided
            if (!ce.getMessage().isEmpty()) {
                // Inform the user that an error occurred reading the import file
                new CcddDialogHandler().showMessageDialog(tableHandler.getOwner(), "<html><b>" + ce.getMessage(), "File Error", ce.getMessageType(), DialogOption.OK_OPTION);
            }
        } catch (Exception e) {
            // Display a dialog providing details on the unanticipated error
            CcddUtilities.displayException(e, tableHandler.getOwner());
        }
    }
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) CCDDException(CCDD.CcddClassesDataTable.CCDDException) GridBagLayout(java.awt.GridBagLayout) 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) TypeDefinition(CCDD.CcddTableTypeHandler.TypeDefinition) JCheckBox(javax.swing.JCheckBox) TableDefinition(CCDD.CcddClassesDataTable.TableDefinition) Border(javax.swing.border.Border)

Example 5 with FileEnvVar

use of CCDD.CcddClassesComponent.FileEnvVar in project CCDD by nasa.

the class CcddFileIOHandler method backupDatabaseToFile.

/**
 ********************************************************************************************
 * Backup the currently open project's database to a user-selected file using the pg_dump
 * utility. The backup data is stored in plain text format
 *
 * @param doInBackground
 *            true to perform the operation in a background process
 ********************************************************************************************
 */
protected void backupDatabaseToFile(boolean doInBackground) {
    // Get the name of the currently open database
    String databaseName = dbControl.getDatabaseName();
    String projectName = dbControl.getProjectName();
    // Set the initial layout manager characteristics
    GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing() / 2, 0, 0), 0, 0);
    // Create the backup file choice dialog
    final CcddDialogHandler dlg = new CcddDialogHandler();
    // Create a date and time stamp check box
    JCheckBox stampChkBx = new JCheckBox("Append date and time to file name");
    stampChkBx.setBorder(BorderFactory.createEmptyBorder());
    stampChkBx.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
    stampChkBx.setSelected(false);
    // Create a listener for check box selection actions
    stampChkBx.addActionListener(new ActionListener() {

        String timeStamp = "";

        /**
         ************************************************************************************
         * Handle check box selection actions
         ************************************************************************************
         */
        @Override
        public void actionPerformed(ActionEvent ae) {
            // Check if the data and time stamp check box is selected
            if (((JCheckBox) ae.getSource()).isSelected()) {
                // Get the current date and time stamp
                timeStamp = "_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
                // Append the date and time stamp to the file name
                dlg.getFileNameField().setText(dlg.getFileNameField().getText().replaceFirst(Pattern.quote(FileExtension.DBU.getExtension()), timeStamp + FileExtension.DBU.getExtension()));
            } else // The check box is not selected
            {
                // Remove the date and time stamp
                dlg.getFileNameField().setText(dlg.getFileNameField().getText().replaceFirst(timeStamp, ""));
            }
        }
    });
    // Create a panel to contain the date and time stamp check box
    JPanel stampPnl = new JPanel(new GridBagLayout());
    stampPnl.setBorder(BorderFactory.createEmptyBorder());
    stampPnl.add(stampChkBx, gbc);
    // Allow the user to select the backup file path + name
    FileEnvVar[] dataFile = dlg.choosePathFile(ccddMain, ccddMain.getMainFrame(), databaseName + FileExtension.DBU.getExtension(), null, new FileNameExtensionFilter[] { new FileNameExtensionFilter(FileExtension.DBU.getDescription(), FileExtension.DBU.getExtensionName()) }, false, false, "Backup Project " + projectName, ccddMain.getProgPrefs().get(ModifiablePathInfo.DATABASE_BACKUP_PATH.getPreferenceKey(), null), DialogOption.BACKUP_OPTION, stampPnl);
    // Check if a file was chosen
    if (dataFile != null && dataFile[0] != null) {
        boolean cancelBackup = false;
        // Check if the backup file exists
        if (dataFile[0].exists()) {
            // Check if the existing file should be overwritten
            if (new CcddDialogHandler().showMessageDialog(ccddMain.getMainFrame(), "<html><b>Overwrite existing backup file?", "Overwrite File", JOptionPane.QUESTION_MESSAGE, DialogOption.OK_CANCEL_OPTION) == OK_BUTTON) {
                // Check if the file can be deleted
                if (!dataFile[0].delete()) {
                    // Inform the user that the existing backup file cannot be replaced
                    new CcddDialogHandler().showMessageDialog(ccddMain.getMainFrame(), "<html><b>Cannot replace existing backup file<br>'</b>" + dataFile[0].getAbsolutePath() + "<b>'", "File Error", JOptionPane.ERROR_MESSAGE, DialogOption.OK_OPTION);
                    cancelBackup = true;
                }
            } else // File should not be overwritten
            {
                // Cancel backing up the database
                cancelBackup = true;
            }
        }
        // Check that no errors occurred and that the user didn't cancel the backup
        if (!cancelBackup) {
            // Check if the operation should be performed in the background
            if (doInBackground) {
                // Create a backup of the current database
                dbControl.backupDatabaseInBackground(projectName, dataFile[0]);
            } else // Perform the operation in the foreground
            {
                // Create a backup of the current database
                dbControl.backupDatabase(projectName, dataFile[0]);
            }
        }
    }
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) GridBagLayout(java.awt.GridBagLayout) ActionEvent(java.awt.event.ActionEvent) FileEnvVar(CCDD.CcddClassesComponent.FileEnvVar) FileNameExtensionFilter(javax.swing.filechooser.FileNameExtensionFilter) JCheckBox(javax.swing.JCheckBox) ActionListener(java.awt.event.ActionListener) SimpleDateFormat(java.text.SimpleDateFormat)

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