Search in sources :

Example 16 with BackgroundCommand

use of CCDD.CcddBackgroundCommand.BackgroundCommand in project CCDD by nasa.

the class CcddDbTableCommandHandler method renameTableType.

/**
 ********************************************************************************************
 * Change the name of a table type and update the existing tables of the specified type. This
 * command 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 command completes execution
 *
 * @param typeName
 *            current name of the table type
 *
 * @param newName
 *            new name for this table type
 *
 * @param typeDialog
 *            reference to the type manager dialog
 ********************************************************************************************
 */
protected void renameTableType(final String typeName, final String newName, final CcddTableTypeManagerDialog typeDialog) {
    // Execute the command in the background
    CcddBackgroundCommand.executeInBackground(ccddMain, new BackgroundCommand() {

        boolean errorFlag = false;

        String tableName;

        /**
         ************************************************************************************
         * Rename table type command
         ************************************************************************************
         */
        @Override
        protected void execute() {
            try {
                // Create the command to update the table definitions table
                StringBuilder command = new StringBuilder(storeTableTypesInfoTableCommand());
                // Get an array containing tables of the specified type
                String[] tableNames = queryTablesOfTypeList(typeName, typeDialog);
                // For each table of the specified type
                for (String table : tableNames) {
                    tableName = table;
                    // Get the table's comment so that it can be rebuilt with the new type name
                    String[] comment = queryDataTableComment(table, typeDialog);
                    // Update the table comment to reflect the new type name
                    command.append(buildDataTableComment(comment[TableCommentIndex.NAME.ordinal()], newName));
                }
                // Add the command to rename any default data fields for this table type
                command.append("UPDATE " + InternalTable.FIELDS.getTableName() + " SET " + FieldsColumn.OWNER_NAME.getColumnName() + " = " + delimitText(CcddFieldHandler.getFieldTypeName(newName)) + " WHERE " + FieldsColumn.OWNER_NAME.getColumnName() + " = " + delimitText(CcddFieldHandler.getFieldTypeName(typeName)) + "; ");
                // Execute the command to change the table's type name
                dbCommand.executeDbCommand(command.toString(), typeDialog);
                // Log that renaming the table succeeded
                eventLog.logEvent(SUCCESS_MSG, "Table '" + tableName + "' type renamed to '" + newName + "'");
            } catch (SQLException se) {
                // Inform the user that renaming the table type failed
                eventLog.logFailEvent(typeDialog, "Cannot rename type for table '" + tableName + "'; cause '" + se.getMessage() + "'", "<html><b>Cannot rename type for table '</b>" + tableName + "<b>'");
                errorFlag = true;
            }
        }

        /**
         ************************************************************************************
         * Rename table type command complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            typeDialog.doTypeOperationComplete(errorFlag, null, null);
        }
    });
}
Also used : SQLException(java.sql.SQLException) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand)

Example 17 with BackgroundCommand

use of CCDD.CcddBackgroundCommand.BackgroundCommand in project CCDD by nasa.

the class CcddScriptHandler method getDataAndExecuteScriptInBackground.

/**
 ********************************************************************************************
 * Get the table information array from the table data used by the script script
 * association(s), then execute the script(s). This command 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 script execution command, however, is disabled
 * until the this command completes execution
 *
 * @param tree
 *            table tree of the table instances (parent tables with their child tables); null
 *            if the tree should be loaded
 *
 * @param associations
 *            list of script association to execute
 *
 * @param dialog
 *            reference to the script dialog (manager or executive) calling this method
 ********************************************************************************************
 */
private void getDataAndExecuteScriptInBackground(final CcddTableTreeHandler tree, final List<Object[]> associations, final CcddFrameHandler dialog) {
    final CcddDialogHandler cancelDialog = new CcddDialogHandler();
    // Create a thread to execute the script in the background
    final Thread scriptThread = new Thread(new Runnable() {

        /**
         ************************************************************************************
         * Execute script association(s)
         ************************************************************************************
         */
        @Override
        public void run() {
            // Disable the calling dialog's controls
            dialog.setControlsEnabled(false);
            // Execute the script association(s) and obtain the completion status(es)
            isBad = getDataAndExecuteScript(tree, associations, dialog);
            // Remove the converted variable name list(s) other than the one created using the
            // separators stored in the program preferences
            variableHandler.removeUnusedLists();
            // Close the script cancellation dialog. This also logs the association completion
            // status and re-enables the calling dialog's- controls
            cancelDialog.closeDialog(CANCEL_BUTTON);
        }
    });
    // Display the script cancellation dialog in a background thread
    CcddBackgroundCommand.executeInBackground(ccddMain, dialog, new BackgroundCommand() {

        /**
         ************************************************************************************
         * Display the cancellation dialog
         ************************************************************************************
         */
        @SuppressWarnings("deprecation")
        @Override
        protected void execute() {
            // Display the dialog and wait for the close action (the user selects the Okay
            // button or the script execution completes and a Cancel button is issued)
            int option = cancelDialog.showMessageDialog(dialog, "<html><b>Script execution in progress...<br><br>" + CcddUtilities.colorHTMLText("*** Press </i>Halt<i> " + "to terminate script execution ***", Color.RED), "Script Executing", JOptionPane.ERROR_MESSAGE, DialogOption.HALT_OPTION);
            // still executing
            if (option == OK_BUTTON && scriptThread.isAlive()) {
                // Forcibly stop script execution. Note: this method is deprecated due to
                // inherent issues that can occur when a thread is abruptly stopped. However,
                // the stop method is the only manner in which the script can be terminated
                // (without additional code within the script itself, which cannot be assumed
                // since the scripts are user-generated). There shouldn't be a potential for
                // object corruption in the application since it doesn't reference any objects
                // created by a script
                scriptThread.stop();
                // Set the execution status(es) to indicate the scripts didn't complete
                isBad = new boolean[associations.size()];
                Arrays.fill(isBad, true);
            }
        }

        /**
         ************************************************************************************
         * Perform cancellation dialog complete steps
         ************************************************************************************
         */
        @Override
        protected void complete() {
            // Log the result of the script execution(s)
            logScriptCompletionStatus(associations, isBad);
            // Enable the calling dialog's controls
            dialog.setControlsEnabled(true);
        }
    });
    // Execute the script in a background thread
    scriptThread.start();
}
Also used : BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand)

Example 18 with BackgroundCommand

use of CCDD.CcddBackgroundCommand.BackgroundCommand in project CCDD by nasa.

the class CcddTableManagerDialog method initialize.

/**
 ********************************************************************************************
 * Create the table manager dialog. This 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 telemetry
 * scheduler initialization completes execution
 ********************************************************************************************
 */
private void initialize() {
    // Build the table manager dialog in the background
    CcddBackgroundCommand.executeInBackground(ccddMain, new BackgroundCommand() {

        boolean errorFlag = false;

        JPanel dialogPnl;

        FileExtension fileExtn;

        // 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);

        /**
         ************************************************************************************
         * Build the table manager dialog
         ************************************************************************************
         */
        @Override
        protected void execute() {
            isNodeSelectionChanging = false;
            // Create an empty border
            emptyBorder = BorderFactory.createEmptyBorder();
            // Create a border for the input fields
            border = BorderFactory.createCompoundBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, Color.GRAY), BorderFactory.createEmptyBorder(ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing(), ModifiableSpacingInfo.INPUT_FIELD_PADDING.getSpacing()));
            // Create dialog based on supplied dialog type
            switch(dialogType) {
                case NEW:
                    // Create a panel to contain the dialog components
                    dialogPnl = new JPanel(new GridBagLayout());
                    dialogPnl.setBorder(emptyBorder);
                    // types from which to choose
                    if (addRadioButtons(null, false, tableTypeHandler.getTypeInformation(), null, "Select table type", dialogPnl, gbc)) {
                        // Create the table creation dialog label and field, and add them to
                        // the dialog panel
                        addTableInputFields("Table name(s)", dialogPnl, true, gbc);
                        nameFld.setToolTipText(CcddUtilities.wrapText("Delimit multiple names using commas", ModifiableSizeInfo.MAX_TOOL_TIP_LENGTH.getSize()));
                    } else // There are no table type available from which to choose
                    {
                        // Inform the user that no table type exists in the database
                        new CcddDialogHandler().showMessageDialog(caller, "<html><b>Project '" + dbControl.getDatabaseName() + "' has no table type defined", "New Table", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                        errorFlag = true;
                    }
                    break;
                case EDIT:
                    // Create a panel to contain the dialog components
                    dialogPnl = createSelectionPanel("Select table(s) to edit", gbc, TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION, TableTreeType.TABLES);
                    // for editing
                    if (dialogPnl != null) {
                        // Add a listener to the table tree for mouse events
                        tableTree.addMouseListener(new MouseAdapter() {

                            /**
                             ****************************************************************
                             * Handle mouse press events
                             ****************************************************************
                             */
                            @Override
                            public void mousePressed(MouseEvent me) {
                                // Check if the right mouse button is double clicked
                                if (me.getClickCount() == 2 && SwingUtilities.isRightMouseButton(me)) {
                                    // Get the selected row in the tree
                                    int rowIndex = tableTree.getClosestRowForLocation(me.getX(), me.getY());
                                    // Check if a valid row was selected
                                    if (rowIndex != -1) {
                                        // Get the path for the selected row
                                        TreePath path = tableTree.getPathForRow(rowIndex);
                                        // Check if a table was selected
                                        if (path.getPathCount() > tableTree.getHeaderNodeLevel()) {
                                            // Load the selected table's data into a table
                                            // editor and close this dialog
                                            dbTable.loadTableDataInBackground(tableTree.getFullVariablePath(path.getPath()), callingEditorDialog);
                                            closeDialog();
                                        }
                                    }
                                }
                            }
                        });
                    } else // There are no tables available for editing
                    {
                        errorFlag = true;
                    }
                    break;
                case RENAME:
                    // Create a panel to contain the dialog components
                    dialogPnl = createSelectionPanel("Select a table to rename", gbc, TreeSelectionModel.SINGLE_TREE_SELECTION, TableTreeType.PROTOTYPE_TABLES);
                    // for renaming
                    if (dialogPnl != null) {
                        // Create the table renaming dialog label and field
                        addTableInputFields("New name", dialogPnl, false, gbc);
                    } else // There are no tables available for renaming
                    {
                        errorFlag = true;
                    }
                    break;
                case COPY:
                    // Create a panel to contain the dialog components
                    dialogPnl = createSelectionPanel("Select a table to copy", gbc, TreeSelectionModel.SINGLE_TREE_SELECTION, TableTreeType.PROTOTYPE_TABLES);
                    // for copying
                    if (dialogPnl != null) {
                        // Create the table copying dialog label and field
                        addTableInputFields("Copy name", dialogPnl, false, gbc);
                    } else // There are no tables available for copying
                    {
                        errorFlag = true;
                    }
                    break;
                case DELETE:
                    // Create a panel to contain the dialog components
                    dialogPnl = createSelectionPanel("Select table(s) to delete", gbc, TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION, TableTreeType.PROTOTYPE_TABLES);
                    // available for deleting
                    if (dialogPnl == null) {
                        errorFlag = true;
                    }
                    break;
                case IMPORT:
                    break;
                case EXPORT_CSV:
                case EXPORT_XTCE:
                case EXPORT_EDS:
                case EXPORT_JSON:
                    switch(dialogType) {
                        // Set the file extension based on the dialog type
                        case EXPORT_CSV:
                            fileExtn = FileExtension.CSV;
                            break;
                        case EXPORT_EDS:
                            fileExtn = FileExtension.EDS;
                            break;
                        case EXPORT_XTCE:
                            fileExtn = FileExtension.XTCE;
                            break;
                        case EXPORT_JSON:
                            fileExtn = FileExtension.JSON;
                            break;
                        default:
                            break;
                    }
                    // Create the export dialog
                    dialogPnl = createExportPanel(fileExtn, gbc);
                    // Check if the export panel doesn't exist
                    if (dialogPnl == null) {
                        errorFlag = true;
                    }
                    break;
            }
        }

        /**
         ************************************************************************************
         * Table manager dialog creation complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            // Check that no error occurred creating the dialog
            if (!errorFlag) {
                // Display the dialog based on supplied dialog type
                switch(dialogType) {
                    case NEW:
                        // Check if the Okay button was selected
                        if (showOptionsDialog(caller, dialogPnl, "New Table", DialogOption.CREATE_OPTION, true) == OK_BUTTON) {
                            // Create the table(s)
                            dbTable.createTableInBackground(tableNames, descriptionFld.getText(), getRadioButtonSelected(), CcddTableManagerDialog.this);
                        }
                        break;
                    case EDIT:
                        // Display the table selection dialog
                        if (showOptionsDialog(caller, dialogPnl, "Edit Table", DialogOption.OPEN_OPTION, true) == OK_BUTTON) {
                            // Get the list of selected tables, including children
                            List<String> tablePaths = tableTree.getSelectedTablesWithChildren();
                            // Load the selected table's data into a table editor
                            dbTable.loadTableDataInBackground(tablePaths.toArray(new String[0]), callingEditorDialog);
                        }
                        break;
                    case RENAME:
                        // Display the table renaming dialog
                        if (showOptionsDialog(caller, dialogPnl, "Rename Table", DialogOption.RENAME_OPTION, true) == OK_BUTTON) {
                            // Rename the table
                            dbTable.renameTable(tableTree.getSelectionPath().getLastPathComponent().toString(), nameFld.getText(), descriptionFld.getText(), CcddTableManagerDialog.this);
                        }
                        break;
                    case COPY:
                        // Display the table copying dialog
                        if (showOptionsDialog(caller, dialogPnl, "Copy Table", DialogOption.COPY_OPTION, true) == OK_BUTTON) {
                            // Copy the table
                            dbTable.copyTable(tableTree.getSelectionPath().getLastPathComponent().toString(), nameFld.getText(), descriptionFld.getText(), CcddTableManagerDialog.this);
                        }
                        break;
                    case DELETE:
                        // deletion dialog
                        if (showOptionsDialog(caller, dialogPnl, "Delete Table", DialogOption.DELETE_OPTION, true) == OK_BUTTON) {
                            // Create storage for the list of table names
                            List<String> tableNames = new ArrayList<String>();
                            invalidatedEditors = new ArrayList<String[]>();
                            // Step through each selected table in the tree
                            for (String path : tableTree.getSelectedTablesWithChildren()) {
                                // Add the table name to the list
                                tableNames.add(path);
                                // Add the pattern for the data type path of tables matching
                                // the deleted prototype table
                                invalidatedEditors.add(new String[] { path, null });
                            }
                            // Check if a table is selected
                            if (!tableNames.isEmpty()) {
                                // Delete the table(s)
                                dbTable.deleteTableInBackground(tableNames.toArray(new String[0]), CcddTableManagerDialog.this, caller);
                            }
                        }
                        break;
                    case IMPORT:
                        // Allow the user to select the data file path + name(s) from which to
                        // import, and the import options
                        FileEnvVar[] filePath = choosePathFile(ccddMain, caller, 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, true, "Import Table(s)", ccddMain.getProgPrefs().get(ModifiablePathInfo.TABLE_EXPORT_PATH.getPreferenceKey(), null), DialogOption.IMPORT_OPTION, createImportPanel(gbc));
                        // Check if a file was chosen
                        if (filePath != null) {
                            // Export the contents of the selected table(s) in the specified
                            // format
                            fileIOHandler.importFile(filePath, backupFirstCb.isSelected(), replaceExistingTablesCb.isSelected(), appendExistingFieldsCb.isSelected(), useExistingFieldsCb.isSelected(), CcddTableManagerDialog.this);
                        }
                        break;
                    case EXPORT_CSV:
                    case EXPORT_XTCE:
                    case EXPORT_EDS:
                    case EXPORT_JSON:
                        // Check if the export panel exists; if so display the dialog
                        if (showOptionsDialog(caller, dialogPnl, "Export Table(s) in " + fileExtn.getExtensionName().toUpperCase() + " Format", DialogOption.EXPORT_OPTION, true) == OK_BUTTON) {
                            // Create storage for the list of table paths
                            List<String> tablePaths = new ArrayList<String>();
                            // Check if the export command originated from the main menu
                            if (callingEditorDialog == null) {
                                // Get the list of selected tables, including children
                                tablePaths = tableTree.getSelectedTablesWithChildren();
                                // Add the ancestors of the selected tables to the list
                                tableTree.addTableAncestors(tablePaths, false);
                            } else // The export command originated from a table editor dialog menu
                            {
                                // Add the table editor's table variable path to the list
                                tablePaths.add(callingEditorDialog.getTableEditor().getTableInformation().getTablePath());
                            }
                            // Export the contents of the selected table(s) in the specified
                            // format
                            fileIOHandler.exportSelectedTables(pathFld.getText(), tablePaths.toArray(new String[0]), overwriteFileCb.isSelected(), singleFileRBtn.isSelected(), (replaceMacrosCb != null ? replaceMacrosCb.isSelected() : true), (includeReservedMsgIDsCb != null ? includeReservedMsgIDsCb.isSelected() : false), (includeVariablePaths != null ? includeVariablePaths.isSelected() : false), (includeVariablePaths != null && includeVariablePaths.isSelected() ? ccddMain.getVariableHandler() : null), (varPathSepFld != null ? new String[] { varPathSepFld.getText(), Boolean.toString(hideDataTypeCb.isSelected()), typeNameSepFld.getText() } : null), fileExtn, (bigRBtn.isSelected() ? EndianType.BIG_ENDIAN : EndianType.LITTLE_ENDIAN), versionFld.getText(), validStatFld.getText(), class1Fld.getText(), class2Fld.getText(), class3Fld.getText(), CcddTableManagerDialog.this);
                        }
                        break;
                }
            }
        }
    });
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) MouseEvent(java.awt.event.MouseEvent) GridBagLayout(java.awt.GridBagLayout) MouseAdapter(java.awt.event.MouseAdapter) ArrayList(java.util.ArrayList) FileNameExtensionFilter(javax.swing.filechooser.FileNameExtensionFilter) TreePath(javax.swing.tree.TreePath) FileExtension(CCDD.CcddConstants.FileExtension) List(java.util.List) ArrayList(java.util.ArrayList) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand)

Example 19 with BackgroundCommand

use of CCDD.CcddBackgroundCommand.BackgroundCommand 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 20 with BackgroundCommand

use of CCDD.CcddBackgroundCommand.BackgroundCommand in project CCDD by nasa.

the class CcddFieldTableEditorDialog method selectDataFields.

/**
 ********************************************************************************************
 * Display a dialog for the user to select the data fields to display in the editor table. This
 * 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 telemetry scheduler initialization completes execution
 ********************************************************************************************
 */
private void selectDataFields() {
    // Build the data field selection dialog in the background
    CcddBackgroundCommand.executeInBackground(ccddMain, new BackgroundCommand() {

        // Create panels to hold the components of the dialog
        JPanel selectPnl = new JPanel(new GridBagLayout());

        /**
         ************************************************************************************
         * Build the data field selection dialog
         ************************************************************************************
         */
        @Override
        protected void execute() {
            // Set the initial layout manager characteristics
            GridBagConstraints gbc = new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.BOTH, new Insets(ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing() / 2, ModifiableSpacingInfo.LABEL_HORIZONTAL_SPACING.getSpacing(), 0, 0), 0, 0);
            // Load the data field information from the database
            getDataFieldInformation();
            // Create a selection dialog, a panel for the table selection tree, and a panel to
            // contain a check box for each unique data field name
            selectDlg = new CcddDialogHandler() {

                /**
                 ****************************************************************************
                 * Verify input fields
                 *
                 * @return true if the dialog input is valid
                 ****************************************************************************
                 */
                @Override
                protected boolean verifySelection() {
                    // Assume the dialog input is valid
                    boolean isValid = true;
                    // Check if no data field check box is selected
                    if (selectDlg.getCheckBoxSelected().length == 0) {
                        // Inform the user that a field must be selected
                        new CcddDialogHandler().showMessageDialog(this, "<html><b>Must select at least one data field", "No Data Field Selected", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
                        isValid = false;
                    }
                    return isValid;
                }
            };
            JPanel fieldPnl = new JPanel(new GridBagLayout());
            selectPnl.setBorder(emptyBorder);
            fieldPnl.setBorder(emptyBorder);
            // from which to choose
            if (selectDlg.addCheckBoxes(null, getDataFieldNames(), null, "Select data fields to display/edit", fieldPnl)) {
                // Check if more than one data field name check box exists
                if (selectDlg.getCheckBoxes().length > 2) {
                    // Create a Select All check box
                    final JCheckBox selectAllCb = new JCheckBox("Select all data fields", false);
                    selectAllCb.setFont(ModifiableFontInfo.LABEL_BOLD.getFont());
                    selectAllCb.setBorder(emptyBorder);
                    // Create a listener for changes to the Select All check box selection
                    // status
                    selectAllCb.addActionListener(new ActionListener() {

                        /**
                         ********************************************************************
                         * Handle a change to the Select All check box selection status
                         ********************************************************************
                         */
                        @Override
                        public void actionPerformed(ActionEvent ae) {
                            // Step through each data field name check box
                            for (JCheckBox fieldCb : selectDlg.getCheckBoxes()) {
                                // Set the check box selection status to match the Select All
                                // check box selection status
                                fieldCb.setSelected(selectAllCb.isSelected());
                            }
                        }
                    });
                    // Add the Select All checkbox to the field name panel
                    gbc.gridy++;
                    fieldPnl.add(selectAllCb, gbc);
                }
                // the Select button)
                if (columnNames != null) {
                    // Step through the list of check boxes representing the data fields
                    for (JCheckBox cb : selectDlg.getCheckBoxes()) {
                        // Select the data field check box if the field was displayed when the
                        // Select button was pressed
                        cb.setSelected(Arrays.asList(columnNames).contains(cb.getText()));
                    }
                }
                // Add the field panel to the selection panel
                gbc.insets.top = 0;
                gbc.insets.left = 0;
                gbc.weighty = 0.0;
                gbc.gridy = 0;
                selectPnl.add(fieldPnl, gbc);
                // Build the table tree showing both table prototypes and table instances;
                // i.e., parent tables with their child tables (i.e., parents with children)
                tableTree = new CcddTableTreeHandler(ccddMain, new CcddGroupHandler(ccddMain, null, CcddFieldTableEditorDialog.this), TableTreeType.TABLES, true, false, CcddFieldTableEditorDialog.this);
                // Add the tree to the selection panel
                gbc.insets.top = ModifiableSpacingInfo.LABEL_VERTICAL_SPACING.getSpacing();
                gbc.weightx = 1.0;
                gbc.weighty = 1.0;
                gbc.gridx++;
                selectPnl.add(tableTree.createTreePanel("Tables", TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION, ccddMain.getMainFrame()), gbc);
            } else // No data field exists to choose
            {
                // Inform the user that no data field is defined
                new CcddDialogHandler().showMessageDialog((isVisible() ? CcddFieldTableEditorDialog.this : ccddMain.getMainFrame()), "<html><b>No data field exists", "No Data Field", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
            }
        }

        /**
         ************************************************************************************
         * Data field selection dialog creation complete
         ************************************************************************************
         */
        @Override
        protected void complete() {
            // Display the data field selection dialog if any fields are available for display
            if (!dataFields.isEmpty() && selectDlg.showOptionsDialog((isVisible() ? CcddFieldTableEditorDialog.this : ccddMain.getMainFrame()), selectPnl, "Select Data Field(s)", DialogOption.OK_CANCEL_OPTION, true) == OK_BUTTON) {
                // Create a list for the column names. Add the default columns (table name and
                // path)
                List<String> columnNamesList = new ArrayList<String>();
                columnNamesList.add(FieldTableEditorColumnInfo.OWNER.getColumnName());
                columnNamesList.add(FieldTableEditorColumnInfo.PATH.getColumnName());
                // Step through each selected data field name
                for (String name : selectDlg.getCheckBoxSelected()) {
                    // Add the data field name to the column name list
                    columnNamesList.add(name);
                }
                // Convert the list of column names to an array
                columnNames = columnNamesList.toArray(new String[0]);
                // Create the cell selection container
                selectedCells = new CellSelectionHandler();
                // Clear any removal selections
                selectedCells.clear();
                // Check if this is the initial display of the selection dialog
                if (dataFieldTable == null) {
                    // Create the data field editor dialog
                    displayDataFieldTableEditor();
                } else // The selection dialog is spawned from the data field table editor
                {
                    // Reload the data field table
                    dataFieldTable.loadAndFormatData();
                    // Check if the field table editor dialog is already open
                    if (CcddFieldTableEditorDialog.this.isVisible()) {
                        // Reposition the field table editor dialog
                        positionFieldEditorDialog();
                    }
                }
            }
        }
    });
}
Also used : JPanel(javax.swing.JPanel) GridBagConstraints(java.awt.GridBagConstraints) Insets(java.awt.Insets) GridBagLayout(java.awt.GridBagLayout) ActionEvent(java.awt.event.ActionEvent) CellSelectionHandler(CCDD.CcddClassesComponent.CellSelectionHandler) JCheckBox(javax.swing.JCheckBox) ActionListener(java.awt.event.ActionListener) ValidateCellActionListener(CCDD.CcddClassesComponent.ValidateCellActionListener) List(java.util.List) ArrayList(java.util.ArrayList) BackgroundCommand(CCDD.CcddBackgroundCommand.BackgroundCommand)

Aggregations

BackgroundCommand (CCDD.CcddBackgroundCommand.BackgroundCommand)26 JPanel (javax.swing.JPanel)16 GridBagConstraints (java.awt.GridBagConstraints)14 GridBagLayout (java.awt.GridBagLayout)14 Insets (java.awt.Insets)14 ActionEvent (java.awt.event.ActionEvent)13 ArrayList (java.util.ArrayList)11 ActionListener (java.awt.event.ActionListener)10 SQLException (java.sql.SQLException)10 JButton (javax.swing.JButton)9 JLabel (javax.swing.JLabel)8 ValidateCellActionListener (CCDD.CcddClassesComponent.ValidateCellActionListener)7 TypeDefinition (CCDD.CcddTableTypeHandler.TypeDefinition)4 List (java.util.List)4 BoxLayout (javax.swing.BoxLayout)4 JCheckBox (javax.swing.JCheckBox)4 DnDTabbedPane (CCDD.CcddClassesComponent.DnDTabbedPane)3 Border (javax.swing.border.Border)3 CustomSplitPane (CCDD.CcddClassesComponent.CustomSplitPane)2 CCDDException (CCDD.CcddClassesDataTable.CCDDException)2