+/*
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
+ *
+ * This file is part of Jalview.
+ *
+ * Jalview is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
+ * Jalview is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty
+ * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
+ */
package jalview.io;
-import jalview.bin.Cache;
-
import java.io.File;
import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.TreeMap;
+
+import jalview.bin.Cache;
+import jalview.gui.Desktop;
+import jalview.gui.JvOptionPane;
+import jalview.util.MessageManager;
+
+/*
+ * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
+ * User configurable options are:
+ * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved.
+ * The rest of the options are now saved as BACKUPFILES_PRESET, BACKUPFILES_SAVED and BACKUPFILES_CUSTOM
+ * (see BackupFilesPresetEntry)
+ */
public class BackupFiles
{
// labels for saved params in Cache and .jalview_properties
- private static String NS = "BACKUPFILES";
+ public static final String NS = "BACKUPFILES";
- public static String ENABLED = NS + "_ENABLED";
+ public static final String ENABLED = NS + "_ENABLED";
- public static String SUFFIX = NS + "_SUFFIX";
+ public static final String NUM_PLACEHOLDER = "%n";
- public static String ROLL_MAX = NS + "_ROLL_MAX";
+ private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
- public static String SUFFIX_DIGITS = NS + "_SUFFIX_DIGITS";
-
- public static String REVERSE_ORDER = NS + "_REVERSE_ORDER";
-
- private static String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
+ private static final String TEMP_FILE_EXT = ".tmp";
// file - File object to be backed up and then updated (written over)
private File file;
// enabled - default flag as to whether to do the backup file roll (if not
// defined in preferences)
- private boolean enabled = true;
+ private static boolean enabled;
+
+ // confirmDelete - default flag as to whether to confirm with the user before
+ // deleting old backup/version files
+ private static boolean confirmDelete;
// defaultSuffix - default template to use to append to basename of file
- private String suffix = "-v%n";
+ private String suffix;
+
+ // noMax - flag to turn off a maximum number of files
+ private boolean noMax;
// defaultMax - default max number of backup files
- private int max = 4;
+ private int max;
// defaultDigits - number of zero-led digits to use in the filename
- private int digits = 2;
+ private int digits;
// reverseOrder - set to true to make newest (latest) files lowest number
// (like rolled log files)
- private boolean reverseOrder = false;
+ private boolean reverseOrder;
// temp saved file to become new saved file
private File tempFile;
- public BackupFiles(String filename)
- {
- this(new File(filename));
- }
+ // flag set to see if file save to temp file was successful
+ private boolean tempFileWriteSuccess;
- // first time defaults for ENABLED, SUFFIX, ROLL_MAX, SUFFIX_DIGITS and
- // REVERSE_ORDER
- public BackupFiles(File file)
- {
- this(file, true, "-v%n", 4, 2, false);
- }
+ // array of files to be deleted, with extra information
+ private ArrayList<File> deleteFiles = new ArrayList<>();
- // set, get and rename temp file into place
- public void setTempFile(File temp)
- {
- this.tempFile = temp;
- }
+ // date formatting for modification times
+ private static final SimpleDateFormat sdf = new SimpleDateFormat(
+ "yyyy-MM-dd HH:mm:ss");
- public File getTempFile()
- {
- return tempFile;
- }
+ private static final String newTempFileSuffix = "_newfile";
- public boolean renameTempFile()
+ private static final String oldTempFileSuffix = "_oldfile_tobedeleted";
+
+ public BackupFiles(String filename)
{
- return tempFile.renameTo(file);
+ this(new File(filename));
}
- protected BackupFiles(File file, boolean defaultEnabled,
- String defaultSuffix,
- int defaultMax, int defaultDigits, boolean defaultReverseOrder)
+ // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
+ // REVERSE_ORDER
+ public BackupFiles(File file)
{
+ classInit();
this.file = file;
- this.enabled = Cache.getDefault(ENABLED, defaultEnabled);
- this.suffix = Cache.getDefault(SUFFIX, defaultSuffix);
- this.max = Cache.getDefault(ROLL_MAX, defaultMax);
- this.digits = Cache.getDefault(SUFFIX_DIGITS, defaultDigits);
- this.reverseOrder = Cache.getDefault(REVERSE_ORDER,
- defaultReverseOrder);
-
+ BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
+ .getSavedBackupEntry();
+ this.suffix = bfpe.suffix;
+ this.noMax = bfpe.keepAll;
+ this.max = bfpe.rollMax;
+ this.digits = bfpe.digits;
+ this.reverseOrder = bfpe.reverse;
+
// create a temp file to save new data in
- File temp;
+ File temp = null;
try
{
if (file != null)
{
String tempfilename = file.getName();
File tempdir = file.getParentFile();
- temp = File.createTempFile(tempfilename, ".tmp", tempdir);
+ temp = File.createTempFile(tempfilename,
+ TEMP_FILE_EXT + newTempFileSuffix, tempdir);
}
else
{
- temp = File.createTempFile(DEFAULT_TEMP_FILE, ".tmp");
- setTempFile(temp);
+ temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
}
} catch (IOException e)
{
{
System.out.println("Exception ctreating temp file for saving");
}
+ this.setTempFile(temp);
+ }
+
+ public static void classInit()
+ {
+ setEnabled(Cache.getDefault(ENABLED, true));
+ BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
+ .getSavedBackupEntry();
+ setConfirmDelete(bfpe.confirmDelete);
+ }
+
+ public static void setEnabled(boolean flag)
+ {
+ enabled = flag;
+ }
+
+ public static boolean getEnabled()
+ {
+ classInit();
+ return enabled;
+ }
+
+ public static void setConfirmDelete(boolean flag)
+ {
+ confirmDelete = flag;
+ }
+
+ public static boolean getConfirmDelete()
+ {
+ classInit();
+ return confirmDelete;
+ }
+
+ // set, get and rename temp file into place
+ public void setTempFile(File temp)
+ {
+ this.tempFile = temp;
+ }
+
+ public File getTempFile()
+ {
+ return tempFile;
+ }
+
+ public String getTempFilePath()
+ {
+ String path = null;
+ try
+ {
+ path = this.getTempFile().getCanonicalPath();
+ } catch (IOException e)
+ {
+ System.out.println(
+ "IOException when getting Canonical Path of temp file '"
+ + this.getTempFile().getName() + "'");
+ }
+ return path;
+ }
+ public boolean setWriteSuccess(boolean flag)
+ {
+ boolean old = this.tempFileWriteSuccess;
+ this.tempFileWriteSuccess = flag;
+ return old;
+ }
+
+ public boolean getWriteSuccess()
+ {
+ return this.tempFileWriteSuccess;
+ }
+
+ public boolean renameTempFile()
+ {
+ return moveFileToFile(tempFile, file);
}
// roll the backupfiles
public boolean rollBackupFiles()
{
+ return this.rollBackupFiles(true);
+ }
- // file doesn't yet exist or backups are not enabled
- if ((!file.exists()) || (!enabled) || (max < 1))
+ public boolean rollBackupFiles(boolean tidyUp)
+ {
+ // file doesn't yet exist or backups are not enabled or template is null or
+ // empty
+ if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
+ || suffix.length() == 0)
{
// nothing to do
return true;
}
- // split filename up to insert suffix template in the right place. template
- // and backupMax can be set in .jalview_properties
String dir = "";
+ File dirFile;
try
{
- File dirFile = file.getParentFile();
+ dirFile = file.getParentFile();
dir = dirFile.getCanonicalPath();
} catch (Exception e)
{
}
String filename = file.getName();
String basename = filename;
- String extension = "";
- int dotcharpos = filename.lastIndexOf('.');
- // don't split of filenames with the last '.' at the very beginning or
- // very end of the filename
- if ((dotcharpos > 0) && (dotcharpos < filename.length() - 1))
- {
- basename = filename.substring(0, dotcharpos);
- extension = filename.substring(dotcharpos); // NOTE this includes the '.'
- }
boolean ret = true;
// Create/move backups up one
- String numString = null;
- File lastfile = null;
- if (reverseOrder)
+ deleteFiles.clear();
+
+ // find existing backup files
+ BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
+ digits);
+ File[] backupFiles = dirFile.listFiles(bff);
+ int nextIndexNum = 0;
+
+ if (backupFiles.length == 0)
+ {
+ // No other backup files. Just need to move existing file to backupfile_1
+ nextIndexNum = 1;
+ }
+ else
{
- // backup style numbering
- for (int m = 0; m < max; m++)
+ TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
+ backupFiles, basename);
+ // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
+ // mappings
+
+ if (reverseOrder)
{
- int n = max - m;
- numString = String.format("%0" + digits + "d", n);
- String backupSuffix = suffix.replaceAll("%n", numString);
- String backupfilename = dir + File.separatorChar + basename
- + backupSuffix + extension;
- File backupfile_n = new File(backupfilename);
-
- if (!backupfile_n.exists())
+ // backup style numbering
+
+ int tempMax = noMax ? -1 : max;
+ // noMax == true means no limits
+ // look for first "gap" in backupFiles
+ // if tempMax is -1 at this stage just keep going until there's a gap,
+ // then hopefully tempMax gets set to the right index (a positive
+ // integer so the loop breaks)...
+ // why do I feel a little uneasy about this loop?..
+ for (int i = 1; tempMax < 0 || i <= max; i++)
{
- lastfile = backupfile_n;
- continue;
+ if (!bfTreeMap.containsKey(i)) // first index without existent
+ // backupfile
+ {
+ tempMax = i;
+ }
}
- if (m == 0)
- { // Move the max backup to /tmp instead of deleting (Just In
- // Case)
- String tmpfile = "tmp-" + backupfile_n.getName();
- try
+ File previousFile = null;
+ File fileToBeDeleted = null;
+ for (int n = tempMax; n > 0; n--)
+ {
+ String backupfilename = dir + File.separatorChar
+ + BackupFilenameParts.getBackupFilename(n, basename,
+ suffix, digits);
+ File backupfile_n = new File(backupfilename);
+
+ if (!backupfile_n.exists())
{
- File tmpFile = File.createTempFile(tmpfile, ".tmp");
- ret = ret && backupfile_n.renameTo(tmpFile);
- } catch (IOException e)
+ // no "oldest" file to delete
+ previousFile = backupfile_n;
+ fileToBeDeleted = null;
+ continue;
+ }
+
+ // check the modification time of this (backupfile_n) and the previous
+ // file (fileToBeDeleted) if the previous file is going to be deleted
+ if (fileToBeDeleted != null)
+ {
+ File replacementFile = backupfile_n;
+ long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
+ long replacementFileLMT = replacementFile.lastModified();
+
+ try
+ {
+ File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
+ dirFile);
+
+ if (fileToBeDeletedLMT > replacementFileLMT)
+ {
+ String fileToBeDeletedLMTString = sdf
+ .format(fileToBeDeletedLMT);
+ String replacementFileLMTString = sdf
+ .format(replacementFileLMT);
+ System.out.println("WARNING! I am set to delete backupfile "
+ + fileToBeDeleted.getName()
+ + " has modification time "
+ + fileToBeDeletedLMTString
+ + " which is newer than its replacement "
+ + replacementFile.getName()
+ + " with modification time "
+ + replacementFileLMTString);
+
+ boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
+ replacementFile, true);
+
+ if (delete)
+ {
+ // User has confirmed delete -- no need to add it to the list
+ fileToBeDeleted.delete();
+ }
+ else
+ {
+ moveFileToFile(fileToBeDeleted, oldestTempFile);
+ }
+ }
+ else
+ {
+ moveFileToFile(fileToBeDeleted, oldestTempFile);
+ addDeleteFile(oldestTempFile);
+ }
+
+ } catch (Exception e)
+ {
+ System.out.println(
+ "Error occurred, probably making new temp file for '"
+ + fileToBeDeleted.getName() + "'");
+ e.printStackTrace();
+ }
+
+ // reset
+ fileToBeDeleted = null;
+ }
+
+ if (!noMax && n == tempMax && backupfile_n.exists())
{
- System.out.println(
- "Could not create temp file '" + tmpfile + ".tmp'");
+ fileToBeDeleted = backupfile_n;
}
+ else
+ {
+ if (previousFile != null)
+ {
+ ret = ret && moveFileToFile(backupfile_n, previousFile);
+ }
+ }
+
+ previousFile = backupfile_n;
}
- else
+
+ // index to use for the latest backup
+ nextIndexNum = 1;
+ }
+ else
+ {
+ // version style numbering (with earliest file deletion if max files
+ // reached)
+
+ bfTreeMap.values().toArray(backupFiles);
+
+ // noMax == true means keep all backup files
+ if ((!noMax) && bfTreeMap.size() >= max)
{
- // Just In Case
- if (lastfile != null)
+ // need to delete some files to keep number of backups to designated
+ // max
+ int numToDelete = bfTreeMap.size() - max + 1;
+ // the "replacement" file is the latest backup file being kept (it's
+ // not replacing though)
+ File replacementFile = numToDelete < backupFiles.length
+ ? backupFiles[numToDelete]
+ : null;
+ for (int i = 0; i < numToDelete; i++)
{
- ret = ret && backupfile_n.renameTo(lastfile);
+ // check the deletion files for modification time of the last
+ // backupfile being saved
+ File fileToBeDeleted = backupFiles[i];
+ boolean delete = true;
+
+ boolean newer = false;
+ if (replacementFile != null)
+ {
+ long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
+ long replacementFileLMT = replacementFile != null
+ ? replacementFile.lastModified()
+ : Long.MAX_VALUE;
+ if (fileToBeDeletedLMT > replacementFileLMT)
+ {
+ String fileToBeDeletedLMTString = sdf
+ .format(fileToBeDeletedLMT);
+ String replacementFileLMTString = sdf
+ .format(replacementFileLMT);
+
+ System.out
+ .println("WARNING! I am set to delete backupfile '"
+ + fileToBeDeleted.getName()
+ + "' has modification time "
+ + fileToBeDeletedLMTString
+ + " which is newer than the oldest backupfile being kept '"
+ + replacementFile.getName()
+ + "' with modification time "
+ + replacementFileLMTString);
+
+ delete = confirmNewerDeleteFile(fileToBeDeleted,
+ replacementFile, false);
+ if (delete)
+ {
+ // User has confirmed delete -- no need to add it to the list
+ fileToBeDeleted.delete();
+ delete = false;
+ }
+ else
+ {
+ // keeping file, nothing to do!
+ }
+ }
+ }
+ if (delete)
+ {
+ addDeleteFile(fileToBeDeleted);
+ }
+
}
+
}
- lastfile = backupfile_n;
+ nextIndexNum = bfTreeMap.lastKey() + 1;
+ }
+ }
+
+ // Let's make the new backup file!! yay, got there at last!
+ String latestBackupFilename = dir + File.separatorChar
+ + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
+ suffix, digits);
+ ret |= moveFileToFile(file, new File(latestBackupFilename));
+
+ if (tidyUp)
+ {
+ tidyUpFiles();
+ }
+
+ return ret;
+ }
+
+ private static File nextTempFile(String filename, File dirFile)
+ throws IOException
+ {
+ File temp = null;
+ COUNT: for (int i = 1; i < 1000; i++)
+ {
+ File trythis = new File(dirFile,
+ filename + '~' + Integer.toString(i));
+ if (!trythis.exists())
+ {
+ temp = trythis;
+ break COUNT;
}
}
+ if (temp == null)
+ {
+ temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
+ }
+ return temp;
+ }
+
+ private void tidyUpFiles()
+ {
+ deleteOldFiles();
+ }
+
+ private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
+ File replacementFile, boolean replace)
+ {
+ StringBuilder messageSB = new StringBuilder();
+
+ File ftbd = fileToBeDeleted;
+ String ftbdLMT = sdf.format(ftbd.lastModified());
+ String ftbdSize = Long.toString(ftbd.length());
+
+ File rf = replacementFile;
+ String rfLMT = sdf.format(rf.lastModified());
+ String rfSize = Long.toString(rf.length());
+
+ int confirmButton = JvOptionPane.NO_OPTION;
+ if (replace)
+ {
+ File saveFile = null;
+ try
+ {
+ saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
+ } catch (Exception e)
+ {
+ System.out.println(
+ "Error when confirming to keep backup file newer than other backup files.");
+ e.printStackTrace();
+ }
+ messageSB.append(MessageManager.formatMessage(
+ "label.newerdelete_replacement_line", new String[]
+ { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
+ rfSize }));
+ messageSB.append("\n\n");
+ messageSB.append(MessageManager.formatMessage(
+ "label.confirm_deletion_or_rename", new String[]
+ { ftbd.getName(), saveFile.getName() }));
+ String[] options = new String[] {
+ MessageManager.getString("label.delete"),
+ MessageManager.getString("label.rename") };
+
+ confirmButton = JvOptionPane.showOptionDialog(Desktop.desktop,
+ messageSB.toString(),
+ MessageManager.getString("label.backupfiles_confirm_delete"),
+ JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
+ null, options, options[0]);
+ }
else
{
- // version style numbering (with file rolling though)
+ messageSB.append(MessageManager
+ .formatMessage("label.newerdelete_line", new String[]
+ { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
+ rfSize }));
+ messageSB.append("\n\n");
+ messageSB.append(MessageManager
+ .formatMessage("label.confirm_deletion", new String[]
+ { ftbd.getName() }));
+ String[] options = new String[] {
+ MessageManager.getString("label.delete"),
+ MessageManager.getString("label.keep") };
+
+ confirmButton = JvOptionPane.showOptionDialog(Desktop.desktop,
+ messageSB.toString(),
+ MessageManager.getString("label.backupfiles_confirm_delete"),
+ JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
+ null, options, options[0]);
+ }
+
+ // return should be TRUE if file is to be deleted
+ return (confirmButton == JvOptionPane.YES_OPTION);
+ }
+
+ private void deleteOldFiles()
+ {
+ if (deleteFiles != null && !deleteFiles.isEmpty())
+ {
+ boolean doDelete = false;
+ StringBuilder messageSB = null;
+ if (confirmDelete && deleteFiles.size() > 0)
+ {
+ messageSB = new StringBuilder();
+ messageSB.append(MessageManager
+ .getString("label.backupfiles_confirm_delete_old_files"));
+ for (int i = 0; i < deleteFiles.size(); i++)
+ {
+ File df = deleteFiles.get(i);
+ messageSB.append("\n");
+ messageSB.append(df.getName());
+ messageSB.append(" ");
+ messageSB.append(MessageManager.formatMessage("label.file_info",
+ new String[]
+ { sdf.format(df.lastModified()),
+ Long.toString(df.length()) }));
+ }
+
+ int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop,
+ messageSB.toString(),
+ MessageManager
+ .getString("label.backupfiles_confirm_delete"),
+ JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
+
+ doDelete = (confirmButton == JvOptionPane.YES_OPTION);
+ }
+ else
+ {
+ doDelete = true;
+ }
+
+ if (doDelete)
+ {
+ for (int i = 0; i < deleteFiles.size(); i++)
+ {
+ File fileToDelete = deleteFiles.get(i);
+ fileToDelete.delete();
+ System.out.println("DELETING '" + fileToDelete.getName() + "'");
+ }
+ }
+
+ }
+
+ deleteFiles.clear();
+ }
+
+ private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
+ File[] backupFiles, String basename)
+ {
+ // sort the backup files (based on integer found in the suffix) using a
+ // precomputed Hashmap for speed
+ Map<Integer, File> bfHashMap = new HashMap<>();
+ for (int i = 0; i < backupFiles.length; i++)
+ {
+ File f = backupFiles[i];
+ BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
+ digits);
+ bfHashMap.put(bfp.indexNum(), f);
+ }
+ TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
+ bfTreeMap.putAll(bfHashMap);
+ return bfTreeMap;
+ }
+
+ public boolean rollBackupsAndRenameTempFile()
+ {
+ boolean write = this.getWriteSuccess();
+
+ boolean roll = false;
+ boolean rename = false;
+ if (write)
+ {
+ roll = this.rollBackupFiles(false);
+ rename = this.renameTempFile();
+ }
- // check if all backup files exist
- int largest = 0;
- for (int m = 0; m < max; m++)
+ /*
+ * Not sure that this confirmation is desirable. By this stage the new file is
+ * already written successfully, but something (e.g. disk full) has happened while
+ * trying to roll the backup files, and most likely the filename needed will already
+ * be vacant so renaming the temp file is nearly always correct!
+ */
+ boolean okay = roll && rename;
+ if (!okay)
+ {
+ StringBuilder messageSB = new StringBuilder();
+ messageSB.append(MessageManager.getString(
+ "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
+ if (rename)
{
- int n = m + 1;
- numString = String.format("%0" + digits + "d", n);
- String backupSuffix = suffix.replaceAll("%n", numString);
- String backupfilename = dir + File.separatorChar + basename
- + backupSuffix + extension;
- File backupfile_n = new File(backupfilename);
- if (backupfile_n.exists())
+ if (messageSB.length() > 0)
{
- largest = n;
+ messageSB.append("\n");
}
+ messageSB.append(MessageManager.getString(
+ "label.backupfiles_confirm_save_new_saved_file_ok"));
}
- // MORE CODE HERE BEN!
+ else
+ {
+ if (messageSB.length() > 0)
+ {
+ messageSB.append("\n");
+ }
+ messageSB.append(MessageManager.getString(
+ "label.backupfiles_confirm_save_new_saved_file_not_ok"));
+ }
+
+ int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop,
+ messageSB.toString(),
+ MessageManager
+ .getString("label.backupfiles_confirm_save_file"),
+ JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
+ okay = confirmButton == JvOptionPane.OK_OPTION;
+ }
+ if (okay)
+ {
+ tidyUpFiles();
+ }
+
+ return rename;
+ }
+
+ public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
+ String fileName, String suffix, int digits)
+ {
+ File[] backupFiles = null;
+
+ File file = new File(fileName);
+
+ File dirFile;
+ try
+ {
+ dirFile = file.getParentFile();
+ } catch (Exception e)
+ {
+ System.out.println(
+ "Could not get canonical path for file '" + file + "'");
+ return new TreeMap<>();
+ }
+
+ String filename = file.getName();
+ String basename = filename;
+
+ // find existing backup files
+ BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
+ digits);
+ backupFiles = dirFile.listFiles(bff); // is clone needed?
+
+ // sort the backup files (based on integer found in the suffix) using a
+ // precomputed Hashmap for speed
+ Map<Integer, File> bfHashMap = new HashMap<>();
+ for (int i = 0; i < backupFiles.length; i++)
+ {
+ File f = backupFiles[i];
+ BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
+ digits);
+ bfHashMap.put(bfp.indexNum(), f);
}
+ TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
+ bfTreeMap.putAll(bfHashMap);
- // now actually backup the important file!
- ret = ret && file.renameTo(lastfile);
+ return bfTreeMap;
+ }
+ /*
+ private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
+ boolean delete, boolean newer)
+ {
+ return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
+ }
+ */
+ private boolean addDeleteFile(File fileToBeDeleted)
+ {
+ boolean ret = false;
+ int pos = deleteFiles.indexOf(fileToBeDeleted);
+ if (pos > -1)
+ {
+ return true;
+ }
+ else
+ {
+ deleteFiles.add(fileToBeDeleted);
+ }
return ret;
}
+ private boolean moveFileToFile(File oldFile, File newFile)
+ {
+ boolean ret = false;
+ Path oldPath = Paths.get(oldFile.getAbsolutePath());
+ Path newPath = Paths.get(newFile.getAbsolutePath());
+ try
+ {
+ Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
+ ret = true;
+ } catch (IOException e)
+ {
+ Cache.log.warn("Could not move file '" + oldPath.toString() + "' to '"
+ + newPath.toString() + "'");
+ ret = false;
+ }
+ return ret;
+ }
}