use of CCDD.CcddClassesComponent.FileEnvVar in project CCDD by nasa.
the class CcddEventLogDialog method openEventLogFile.
/**
********************************************************************************************
* Open the event log file. If this is the current session's event log then create the file; if
* this is an existing log then open the user-selected file
*
* @return true if the log is opened
********************************************************************************************
*/
private boolean openEventLogFile() {
boolean isOpen = false;
// Check if this the log for the current session
if (isSessionLog) {
try {
// The session log is considered open even if the file cannot be opened
isOpen = true;
// Create the session log file using the date and time stamp as part of the name,
// and the log file path if set by command line command
logFile = new FileEnvVar((!ModifiablePathInfo.SESSION_LOG_FILE_PATH.getPath().isEmpty() ? ModifiablePathInfo.SESSION_LOG_FILE_PATH.getPath() + File.separator : "") + "CCDD-" + getDateTimeStamp("yyyyMMdd_HHmmss") + ".log");
// Attempt to create the log file and check if it can be written to
if (logFile.createNewFile() && logFile.canWrite()) {
// Create a writer to the log
logWriter = new PrintWriter(logFile);
// Indicate that the log was created
isLogWrite = true;
} else // File cannot be created or written to
{
// Indicate that the log wasn't created
isLogWrite = false;
}
} catch (Exception e) {
// Indicate that the log wasn't created
isLogWrite = false;
}
// Check if the log couldn't be created
if (!isLogWrite) {
// Inform the user that an error occurred creating the log file
new CcddDialogHandler().showMessageDialog(ccddMain.getMainFrame(), "<html><b>Cannot create event log file", "Log Error", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
}
} else // Open an existing log file
{
// Allow the user to select the event log file path + name to read from
FileEnvVar[] file = new CcddDialogHandler().choosePathFile(ccddMain, ccddMain.getMainFrame(), null, null, new FileNameExtensionFilter[] { new FileNameExtensionFilter(FileExtension.LOG.getDescription(), FileExtension.LOG.getExtensionName()) }, false, "Open Event Log", ccddMain.getProgPrefs().get(ModifiablePathInfo.READ_LOG_FILE_PATH.getPreferenceKey(), null), DialogOption.OPEN_OPTION);
// Check if a file was chosen
if (file != null && file[0] != null) {
// Check if the file doesn't exist
if (!file[0].exists()) {
// Inform the user that the event log file cannot be located
new CcddDialogHandler().showMessageDialog(ccddMain.getMainFrame(), "<html><b>Cannot locate event log file<br>'</b>" + file[0].getAbsolutePath() + "<b>'", "File Error", JOptionPane.ERROR_MESSAGE, DialogOption.OK_OPTION);
} else // The event log file exists
{
// Set the event log status flag to false since this log won't be added to.
// Save the log file object and store the selected log in the preferences
// backing store
isOpen = true;
isLogWrite = false;
logFile = file[0];
// Store the log path path in the program preferences backing store
CcddFileIOHandler.storePath(ccddMain, logFile.getAbsolutePathWithEnvVars(), true, ModifiablePathInfo.READ_LOG_FILE_PATH);
}
}
}
return isOpen;
}
use of CCDD.CcddClassesComponent.FileEnvVar in project CCDD by nasa.
the class CcddScriptManagerDialog method addAssociation.
/**
********************************************************************************************
* Add an association to the script associations list based on the script and table selections
*
* @param insertPoint
* insertion point for the added row into the associations table:
* TableInsertionPoint.START to insert as the first row in the table,
* TableInsertionPoint.SELECTION to insert below the currently selected row, or
* TableInsertionPoint.END to insert as the last row in the table
*
* @return true if the association inputs are valid and the association is successfully added
********************************************************************************************
*/
private boolean addAssociation(TableInsertionPoint insertPoint) {
boolean isAdded = false;
try {
List<String> members = new ArrayList<>();
// Check if the tree is filtered by group
if (tableTree.isFilteredByGroup()) {
// Step through each selected group
for (String group : tableTree.getSelectedGroups()) {
// Add the group to the list. Any table belonging to the group is deselected
members.add(GROUP_DATA_FIELD_IDENT + group);
}
}
// Remove any excess white space
nameFld.setText(nameFld.getText().trim());
descriptionFld.setText(descriptionFld.getText().trim());
// Check if the name field isn't blank
if (!nameFld.getText().isEmpty()) {
// Check if the association name does not match the alphanumeric input type
if (!nameFld.getText().matches(InputDataType.ALPHANUMERIC.getInputMatch())) {
throw new CCDDException("Illegal character(s) in association name");
}
// creating a duplicate
for (int row = 0; row < assnsTable.getRowCount(); row++) {
// matches the one being added (case insensitive)
if (nameFld.getText().equalsIgnoreCase(assnsTable.getValueAt(row, AssociationsTableColumnInfo.NAME.ordinal()).toString())) {
throw new CCDDException("Association name already in use");
}
}
}
// Add the selected table names, skipping child tables if an ancestor of the table is
// selected
members.addAll(tableTree.getSelectedTablesWithoutChildren());
// Get a file descriptor for the script file name
FileEnvVar scriptFile = new FileEnvVar(scriptFld.getText());
// Check that the script association already exists in the list
if (isAssociationExists(scriptFile.getAbsolutePathWithEnvVars(), members.toArray(new String[0]))) {
throw new CCDDException("An association with this script and table(s) " + "already exists in the script associations table");
}
// Create the script association strings
String assn = "";
// Step through each selected table/group in the tree
for (String member : members) {
// Add the table/group name to the script association
assn += member + ASSN_TABLE_SEPARATOR;
}
// Remove the trailing table separator
assn = CcddUtilities.removeTrailer(assn, ASSN_TABLE_SEPARATOR);
// Insert the new script association at the end of the associations table, then select
// it and scroll to it
assnsTable.insertRow(true, insertPoint, new Object[] { nameFld.getText(), descriptionFld.getText(), scriptFile.getAbsolutePathWithEnvVars(), CcddUtilities.highlightDataType(assn), (scriptFile.exists() ? AvailabilityType.AVAILABLE : AvailabilityType.SCRIPT_MISSING) });
isAdded = true;
} catch (CCDDException ce) {
// Inform the user that an input value is invalid
new CcddDialogHandler().showMessageDialog(ccddMain.getMainFrame(), "<html><b>" + ce.getMessage(), "Invalid Input", JOptionPane.WARNING_MESSAGE, DialogOption.OK_OPTION);
}
return isAdded;
}
use of CCDD.CcddClassesComponent.FileEnvVar in project CCDD by nasa.
the class CcddDialogHandler method choosePathFile.
/**
********************************************************************************************
* Display a dialog that allows the user to select one or more files or a folder. Optionally
* allow a panel containing other components to be displayed beneath the file chooser portion
*
* @param main
* main class
*
* @param parent
* window to center the dialog over
*
* @param fileName
* file name to display in the input field chosen; null if no file name is initially
* displayed. Ignored if folderOnly is true (may be null)
*
* @param fileType
* describes the type of files when more than one file extension is supplied; null
* if only one (or no) file extension is provided. Ignored if folderOnly is true
* (may be null)
*
* @param fileExtensions
* valid file extensions with description. Use null to allow any extension. Ignored
* if folderOnly is true (may be null)
*
* @param folderOnly
* true to allow only folders to be selected
*
* @param multipleFiles
* true to allow selection of more than one file. Unused if folderOnly is true
*
* @param dialogTitle
* title to display in the dialog window frame
*
* @param folder
* file path to use as the initial folder to display
*
* @param optionType
* dialog type: LOAD_OPTION, SAVE_OPTION, SEARCH_OPTION, READ_OPTION, PRINT_OPTION,
* CLOSE_OPTION, OK_OPTION, or OK_CANCEL_OPTION
*
* @param lowerPanel
* JPanel containing other components to display below the JChooser component; null
* if no lower components are to be displayed
*
* @return Array containing the selected file handle(s). null if the Cancel button is selected.
* The first file reference is null if Okay is selected and the file name list is empty
********************************************************************************************
*/
protected FileEnvVar[] choosePathFile(CcddMain main, Component parent, String fileName, String fileType, FileNameExtensionFilter[] fileExtensions, boolean folderOnly, boolean multipleFiles, String dialogTitle, String folder, DialogOption optionType, JPanel lowerPanel) {
FileEnvVar[] file = new FileEnvVar[1];
// Get the environment variables within the folder path
Map<String, String> envVars = FileEnvVar.getEnvVars(folder);
// Create the file chooser. Set the path to the one from the back store per the provided
// key; if no entry exists for the key then use the default path (the default location is
// operating system dependent)
final JFileChooser chooser = new JFileChooser(FileEnvVar.expandEnvVars(folder, envVars) + File.separator + ".");
// True to allow multiple files to be selected
chooser.setMultiSelectionEnabled(multipleFiles);
// Locate the file name input field in the file chooser dialog. In order to use custom
// buttons in the file chooser dialog, the file name input field must be located and the
// inputs to it listened for so that the selected file can be updated. Otherwise, changes
// made to the file name are ignored and when the Okay button is pressed the file name used
// is the highlighted one in the file list box
nameField = getFileChooserTextField(chooser);
// Check if only a folder is allowed to be chosen
if (folderOnly) {
// Allow only the selection of a folder (not a file)
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
// Get the path to initially display
fileName = FileEnvVar.restoreEnvVars(chooser.getCurrentDirectory().getAbsolutePath(), envVars);
} else // Not folder-only
{
// Check if no name is specified
if (fileName == null) {
// Set the file name to blank
fileName = "";
} else // Check if the file name is present
if (!fileName.isEmpty()) {
// Bound the file name with quotes
fileName = "\"" + fileName + "\"";
}
// Allow only the selection of files
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
// Check if one or more file extensions are specified
if (fileExtensions != null) {
// Check if more than one file extension is provided
if (fileExtensions.length > 1) {
String extensions = "";
List<String> extensionList = new ArrayList<String>();
// Step through each file extension
for (FileNameExtensionFilter fileExtension : fileExtensions) {
// Build the extension names string and append the extension(s) to the list
extensions += "*." + CcddUtilities.convertArrayToString(fileExtension.getExtensions()) + ", ";
extensionList.addAll(Arrays.asList(fileExtension.getExtensions()));
}
// Set the filter to the list of all applicable extensions so that initially
// all files of the acceptable types are displayed
chooser.setFileFilter(new FileNameExtensionFilter("All " + fileType + " files (" + CcddUtilities.removeTrailer(extensions, ", ") + ")", extensionList.toArray(new String[0])));
}
// Step through each file extension
for (FileNameExtensionFilter fileExtension : fileExtensions) {
// Convert the extension list into a string
String extensions = CcddUtilities.convertArrayToString(fileExtension.getExtensions());
// Add the extension to the file chooser
chooser.addChoosableFileFilter(new ExtensionFilter(extensions, fileExtension.getDescription() + " (*." + extensions + ")"));
}
// Check if only a single file extension is applicable
if (fileExtensions.length == 1) {
// Set the file filter to show only files with the desired extension
chooser.setFileFilter(chooser.getChoosableFileFilters()[1]);
}
}
// Add a listener for changes to the selected file(s)
chooser.addPropertyChangeListener(new PropertyChangeListener() {
/**
********************************************************************************
* Handle changes to the file(s) selected. Whenever a file selection change strip
* the path name from the file(s) and build a list of just the names. Insert this
* list into the file chooser's file name text field. This is done automatically
* for most look & feels, but not all (e.g., GTK+)
********************************************************************************
*/
@Override
public void propertyChange(PropertyChangeEvent pce) {
// Check if the file selection has changed
if (pce.getPropertyName().equals("SelectedFilesChangedProperty")) {
String nameList = "";
// Step through the selected files
for (int index = 0; index < chooser.getSelectedFiles().length; index++) {
// Append the file name without the path, surrounded by quotes, to the
// name list
nameList += "\"" + chooser.getSelectedFiles()[index].getName() + "\" ";
}
// Insert the file name list into the file chooser's file name text field
nameField.setText(nameList);
}
}
});
}
// Insert the file name into the file chooser's file name text field. Most look & feels do
// this automatically, but not all (e.g., GTK+)
nameField.setText(fileName);
// Hide the file chooser's default buttons
chooser.setControlButtonsAreShown(false);
// Create the dialog panel and add the file chooser to it
JPanel dialogPanel = new JPanel();
dialogPanel.setLayout(new BoxLayout(dialogPanel, BoxLayout.Y_AXIS));
dialogPanel.add(chooser);
// Check if a lower panel is provided
if (lowerPanel != null) {
// Add the lower panel to the dialog panel
dialogPanel.add(lowerPanel);
}
// Open the file chooser dialog and wait for a button click
if (createDialog(parent, dialogPanel, null, null, dialogTitle, optionType, null, true, true) == OK_BUTTON) {
// Extract the file name(s) from the file chooser name field. Spaces may appear in the
// names only if the name is within double quotes. The names are split on spaces
// outside of quotes, at every second quote, or at commas. First any leading or
// trailing white space characters are removed
String names = nameField.getText().trim();
// Check if only a folder is allowed to be chosen
if (folderOnly) {
// Surround the names with quotes, if not already, in order to preserve any spaces
// in the path
names = names.replaceFirst("^\"?([^\"]*)\"?$", "\"$1\"");
}
// Create a flag to keep track of whether or not the character being checked is inside
// or outside a pair of quotes
boolean isQuoted = false;
// Step through the string containing the file name(s)
for (int index = 0; index < names.length(); index++) {
// Get the current character
char c = names.charAt(index);
// Check if the character is a quote
if (c == '"') {
// Invert the quote on/off flag
isQuoted = !isQuoted;
}
// quote of a pair of quotes
if ((c == ' ' || c == '"') && !isQuoted) {
// Replace the character with a comma. Occurrences of double commas can result
// from this operation; these are accounted for later
names = names.substring(0, index) + "," + names.substring(index + 1);
}
}
// Replace every instance of back-to-back commas that may have resulted in the
// replacement steps above with a single comma, remove every remaining quote, then
// split the string at the commas, which now delineate the separate file names
String[] fileNames = names.replaceAll(",,+", ",").replaceAll("\"+", "").split(",");
// Check if the file name text field isn't empty
if (!fileNames[0].isEmpty()) {
// Create a file array
file = new FileEnvVar[fileNames.length];
// Step through the file names/paths
for (int i = 0; i < fileNames.length; i++) {
// Check if a file type was specified and the file name has no extension
if (fileExtensions != null && !fileNames[i].contains(".")) {
// Add the extension to the file name. If more than one extension is
// provided then use the first one
fileNames[i] = fileNames[i] + "." + ((ExtensionFilter) chooser.getFileFilter()).getExtension();
}
// Create a file handle for each file name or the path name. If this is not a
// folder, prepend the file path to the name
file[i] = new FileEnvVar(FileEnvVar.restoreEnvVars((folderOnly ? "" : chooser.getCurrentDirectory().getAbsolutePath() + File.separator) + fileNames[i], envVars));
}
}
} else // The Cancel button was pressed
{
// Set the return file reference to null
file = null;
}
return file;
}
use of CCDD.CcddClassesComponent.FileEnvVar in project CCDD by nasa.
the class CcddPatchHandler method updateAssociationsTable2.
/**
********************************************************************************************
* Update the associations table to include a name 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 updateAssociationsTable2() 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() == 3) {
// 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 name 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 #11132017", JOptionPane.QUESTION_MESSAGE, DialogOption.OK_CANCEL_OPTION) != OK_BUTTON) {
assnsData.close();
throw new CCDDException("user elected to not install patch (#1113017)");
}
// Step through each of the query results
while (assnsData.next()) {
// Create an array to contain the column values
String[] columnValues = new String[4];
// Step through each column in the row
for (int column = 0; column < 3; 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 name
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");
}
// 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();
}
}
use of CCDD.CcddClassesComponent.FileEnvVar in project CCDD by nasa.
the class CcddPatchHandler method updateDataBaseComment.
/**
********************************************************************************************
* Update the project database comments to include the database name with capitalization and
* special characters intact. The project database is first backed up to the file
* <projectName>_<timeStamp>.dbu. The new format for the comment is <CCDD project identifier
* string><lock status, 0 or 1>;<project name with capitalization intact>;<project
* description>. Older versions of CCDD are compatible with the project database after applying
* this patch
*
* @throws CCDDException
* If an error occurs while applying the patch
********************************************************************************************
*/
private void updateDataBaseComment() {
CcddEventLogDialog eventLog = ccddMain.getSessionEventLog();
CcddDbControlHandler dbControl = ccddMain.getDbControlHandler();
try {
CcddDbCommandHandler dbCommand = ccddMain.getDbCommandHandler();
// Get the comment for the currently open database
String comment = dbControl.getDatabaseComment(dbControl.getDatabaseName());
// Divide the comment into the lock status, visible name, and description
String[] nameAndDesc = comment.split(DATABASE_COMMENT_SEPARATOR, 3);
// Check if the comment isn't in the new format
if (nameAndDesc.length < 3 || !dbControl.getProjectName().equalsIgnoreCase(nameAndDesc[DatabaseComment.PROJECT_NAME.ordinal()])) {
// 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()));
// Update the project database comment to the new format
dbCommand.executeDbCommand("COMMENT ON DATABASE " + dbControl.getDatabaseName() + " IS " + CcddDbTableCommandHandler.delimitText(CCDD_PROJECT_IDENTIFIER + comment.substring(0, 1) + DATABASE_COMMENT_SEPARATOR + dbControl.getProjectName() + DATABASE_COMMENT_SEPARATOR + nameAndDesc[0].substring(1)) + "; ", ccddMain.getMainFrame());
// Inform the user that updating the database comment completed
eventLog.logEvent(EventLogMessageType.SUCCESS_MSG, "Project '" + dbControl.getProjectName() + "' comment conversion complete");
}
} catch (Exception e) {
// Inform the user that converting the database comments failed
eventLog.logFailEvent(ccddMain.getMainFrame(), "Cannot convert project '" + dbControl.getProjectName() + "' comment to new format; cause '" + e.getMessage() + "'", "<html><b>Cannot convert project '" + dbControl.getProjectName() + "' comment to new format");
}
}
Aggregations