2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
24 import java.io.IOException;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28 import java.nio.file.StandardCopyOption;
29 import java.text.SimpleDateFormat;
30 import java.util.ArrayList;
31 import java.util.HashMap;
32 import java.util.List;
34 import java.util.TreeMap;
35 import java.util.concurrent.CompletableFuture;
36 import java.util.concurrent.ExecutionException;
37 import java.util.concurrent.ExecutorService;
38 import java.util.concurrent.Executors;
39 import java.util.concurrent.Future;
41 import jalview.bin.Cache;
42 import jalview.bin.Console;
43 import jalview.gui.Desktop;
44 import jalview.gui.JvOptionPane;
45 import jalview.util.MessageManager;
46 import jalview.util.Platform;
49 * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
50 * User configurable options are:
51 * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved.
52 * The rest of the options are now saved as BACKUPFILES_PRESET, BACKUPFILES_SAVED and BACKUPFILES_CUSTOM
53 * (see BackupFilesPresetEntry)
56 public class BackupFiles
59 // labels for saved params in Cache and .jalview_properties
60 public static final String NS = "BACKUPFILES";
62 public static final String ENABLED = NS + "_ENABLED";
64 public static final String NUM_PLACEHOLDER = "%n";
66 private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
68 private static final String TEMP_FILE_EXT = ".tmp";
70 // file - File object to be backed up and then updated (written over)
73 // enabled - default flag as to whether to do the backup file roll (if not
74 // defined in preferences)
75 private static boolean enabled;
77 // confirmDelete - default flag as to whether to confirm with the user before
78 // deleting old backup/version files
79 private static boolean confirmDelete;
81 // defaultSuffix - default template to use to append to basename of file
82 private String suffix;
84 // noMax - flag to turn off a maximum number of files
85 private boolean noMax;
87 // defaultMax - default max number of backup files
90 // defaultDigits - number of zero-led digits to use in the filename
93 // reverseOrder - set to true to make newest (latest) files lowest number
94 // (like rolled log files)
95 private boolean reverseOrder;
97 // temp saved file to become new saved file
98 private File tempFile;
100 // flag set to see if file save to temp file was successful
101 private boolean tempFileWriteSuccess;
103 // array of files to be deleted, with extra information
104 private ArrayList<File> deleteFiles = new ArrayList<>();
106 // date formatting for modification times
107 private static final SimpleDateFormat sdf = new SimpleDateFormat(
108 "yyyy-MM-dd HH:mm:ss");
110 private static final String newTempFileSuffix = "_newfile";
112 private static final String oldTempFileSuffix = "_oldfile_tobedeleted";
114 // thread pool used for completablefutures
115 private static final ExecutorService executorService = Executors
116 .newFixedThreadPool(3);
118 private static List<BackupFiles> savesInProgress = new ArrayList<>();
120 private CompletableFuture<Boolean> myFuture = null;
122 private boolean addSaveInProgress()
124 if (savesInProgress.contains(this))
131 savesInProgress.add(this);
136 private boolean removeSaveInProgress(boolean ret)
138 if (savesInProgress.contains(this))
140 this.getMyFuture().complete(ret);
141 // remove all occurrences
142 while (savesInProgress.remove(this))
150 private static CompletableFuture<Boolean> getNewFuture()
152 return new CompletableFuture<Boolean>()
157 private CompletableFuture<Boolean> getMyFuture()
159 return this.myFuture;
162 private void setMyFuture()
164 this.myFuture = getNewFuture();
167 public static boolean hasSavesInProgress()
170 for (CompletableFuture cf : savesInProgressCompletableFutures(true))
177 public static List<File> savesInProgressFiles(boolean all)
179 List<File> files = new ArrayList<>();
180 for (BackupFiles bfile : savesInProgress)
182 if (all || !bfile.getMyFuture().isDone())
183 files.add(bfile.getFile());
188 public static List<CompletableFuture<Boolean>> savesInProgressCompletableFutures(
191 List<CompletableFuture<Boolean>> cfs = new ArrayList<>();
192 for (BackupFiles bfile : savesInProgress)
194 if (all || !bfile.getMyFuture().isDone())
195 cfs.add(bfile.getMyFuture());
200 public static Future<Boolean> allSaved()
202 CompletableFuture<Boolean> f = new CompletableFuture<>();
204 executorService.submit(() -> {
205 for (BackupFiles buf : savesInProgress)
207 boolean allSaved = true;
210 allSaved &= buf.getMyFuture().get();
211 } catch (InterruptedException e)
213 Console.debug("InterruptedException waiting for files to save",
215 } catch (ExecutionException e)
217 Console.debug("ExecutionException waiting for files to save", e);
219 f.complete(allSaved);
225 public BackupFiles(String filename)
227 this(new File(filename));
230 // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
232 public BackupFiles(File file)
235 if (file.getParentFile() == null)
237 // filename probably in pwd represented with no parent -- fix it before it's a problem
238 file = file.getAbsoluteFile();
242 // add this file from the save in progress stack
245 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
246 .getSavedBackupEntry();
247 this.suffix = bfpe.suffix;
248 this.noMax = bfpe.keepAll;
249 this.max = bfpe.rollMax;
250 this.digits = bfpe.digits;
251 this.reverseOrder = bfpe.reverse;
253 // create a temp file to save new data in
259 String tempfilename = file.getName();
260 File tempdir = file.getAbsoluteFile().getParentFile();
263 "BACKUPFILES [file!=null] attempting to create temp file for "
264 + tempfilename + " in dir " + tempdir);
265 temp = File.createTempFile(tempfilename,
266 TEMP_FILE_EXT + newTempFileSuffix, tempdir);
268 "BACKUPFILES using temp file " + temp.getAbsolutePath());
273 "BACKUPFILES [file==null] attempting to create default temp file "
274 + DEFAULT_TEMP_FILE + " with extension "
276 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
278 } catch (IOException e)
280 Console.error("Could not create temp file to save to (IOException)");
281 Console.error(e.getMessage());
282 Console.debug(Cache.getStackTraceString(e));
283 } catch (Exception e)
285 Console.error("Exception creating temp file for saving");
286 Console.debug(Cache.getStackTraceString(e));
288 this.setTempFile(temp);
291 private static void classInit()
293 Console.initLogger();
294 Console.trace("BACKUPFILES classInit");
295 boolean e = Cache.getDefault(ENABLED, !Platform.isJS());
297 Console.trace("BACKUPFILES " + (e ? "enabled" : "disabled"));
298 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
299 .getSavedBackupEntry();
300 Console.trace("BACKUPFILES preset scheme " + bfpe.toString());
301 setConfirmDelete(bfpe.confirmDelete);
302 Console.trace("BACKUPFILES confirm delete " + bfpe.confirmDelete);
305 public static void setEnabled(boolean flag)
310 public static boolean getEnabled()
316 public static void setConfirmDelete(boolean flag)
318 confirmDelete = flag;
321 public static boolean getConfirmDelete()
324 return confirmDelete;
327 // set, get and rename temp file into place
328 public void setTempFile(File temp)
330 this.tempFile = temp;
333 public File getTempFile()
338 public String getTempFilePath()
343 path = this.getTempFile().getCanonicalPath();
344 } catch (IOException e)
346 Console.error("IOException when getting Canonical Path of temp file '"
347 + this.getTempFile().getName() + "'");
348 Console.debug(Cache.getStackTraceString(e));
353 public boolean setWriteSuccess(boolean flag)
355 boolean old = this.tempFileWriteSuccess;
356 this.tempFileWriteSuccess = flag;
360 public boolean getWriteSuccess()
362 return this.tempFileWriteSuccess;
365 public boolean renameTempFile()
367 return moveFileToFile(tempFile, file);
370 // roll the backupfiles
371 public boolean rollBackupFiles()
373 return this.rollBackupFiles(true);
376 public boolean rollBackupFiles(boolean tidyUp)
378 // file doesn't yet exist or backups are not enabled or template is null or
380 if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
381 || suffix.length() == 0)
384 Console.debug("BACKUPFILES rollBackupFiles nothing to do." + ", "
385 + "filename: " + (file != null ? file.getName() : "null")
386 + ", " + "file exists: " + file.exists() + ", " + "enabled: "
387 + enabled + ", " + "max: " + max + ", " + "suffix: '" + suffix
392 Console.trace("BACKUPFILES rollBackupFiles starting");
398 dirFile = file.getParentFile();
399 dir = dirFile.getCanonicalPath();
400 Console.trace("BACKUPFILES dir: " + dir);
401 } catch (Exception e)
403 Console.error("Could not get canonical path for file '" + file + "'");
404 Console.error(e.getMessage());
405 Console.debug(Cache.getStackTraceString(e));
408 String filename = file.getName();
409 String basename = filename;
411 Console.trace("BACKUPFILES filename is " + filename);
413 // Create/move backups up one
417 // find existing backup files
418 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
420 File[] backupFiles = dirFile.listFiles(bff);
421 int nextIndexNum = 0;
423 Console.trace("BACKUPFILES backupFiles.length: " + backupFiles.length);
424 if (backupFiles.length == 0)
426 // No other backup files. Just need to move existing file to backupfile_1
428 "BACKUPFILES no existing backup files, setting index to 1");
433 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
434 backupFiles, basename);
435 // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
440 // backup style numbering
441 Console.trace("BACKUPFILES rolling files in reverse order");
443 int tempMax = noMax ? -1 : max;
444 // noMax == true means no limits
445 // look for first "gap" in backupFiles
446 // if tempMax is -1 at this stage just keep going until there's a gap,
447 // then hopefully tempMax gets set to the right index (a positive
448 // integer so the loop breaks)...
449 // why do I feel a little uneasy about this loop?..
450 for (int i = 1; tempMax < 0 || i <= max; i++)
452 if (!bfTreeMap.containsKey(i)) // first index without existent
459 File previousFile = null;
460 File fileToBeDeleted = null;
461 for (int n = tempMax; n > 0; n--)
463 String backupfilename = dir + File.separatorChar
464 + BackupFilenameParts.getBackupFilename(n, basename,
466 File backupfile_n = new File(backupfilename);
468 if (!backupfile_n.exists())
470 // no "oldest" file to delete
471 previousFile = backupfile_n;
472 fileToBeDeleted = null;
473 Console.trace("BACKUPFILES No oldest file to delete");
477 // check the modification time of this (backupfile_n) and the previous
478 // file (fileToBeDeleted) if the previous file is going to be deleted
479 if (fileToBeDeleted != null)
481 File replacementFile = backupfile_n;
482 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
483 long replacementFileLMT = replacementFile.lastModified();
484 Console.trace("BACKUPFILES fileToBeDeleted is "
485 + fileToBeDeleted.getAbsolutePath());
486 Console.trace("BACKUPFILES replacementFile is "
487 + backupfile_n.getAbsolutePath());
491 File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
494 if (fileToBeDeletedLMT > replacementFileLMT)
496 String fileToBeDeletedLMTString = sdf
497 .format(fileToBeDeletedLMT);
498 String replacementFileLMTString = sdf
499 .format(replacementFileLMT);
500 Console.warn("WARNING! I am set to delete backupfile "
501 + fileToBeDeleted.getName()
502 + " has modification time "
503 + fileToBeDeletedLMTString
504 + " which is newer than its replacement "
505 + replacementFile.getName()
506 + " with modification time "
507 + replacementFileLMTString);
509 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
510 replacementFile, true);
511 Console.trace("BACKUPFILES "
512 + (delete ? "confirmed" : "not") + " deleting file "
513 + fileToBeDeleted.getAbsolutePath()
514 + " which is newer than "
515 + replacementFile.getAbsolutePath());
519 // User has confirmed delete -- no need to add it to the list
520 fileToBeDeleted.delete();
524 Console.debug("BACKUPFILES moving "
525 + fileToBeDeleted.getAbsolutePath() + " to "
526 + oldestTempFile.getAbsolutePath());
527 moveFileToFile(fileToBeDeleted, oldestTempFile);
532 Console.debug("BACKUPFILES going to move "
533 + fileToBeDeleted.getAbsolutePath() + " to "
534 + oldestTempFile.getAbsolutePath());
535 moveFileToFile(fileToBeDeleted, oldestTempFile);
536 addDeleteFile(oldestTempFile);
539 } catch (Exception e)
542 "Error occurred, probably making new temp file for '"
543 + fileToBeDeleted.getName() + "'");
544 Console.error(Cache.getStackTraceString(e));
548 fileToBeDeleted = null;
551 if (!noMax && n == tempMax && backupfile_n.exists())
553 fileToBeDeleted = backupfile_n;
557 if (previousFile != null)
559 // using boolean '&' instead of '&&' as don't want moveFileToFile
560 // attempt to be conditional (short-circuit)
561 ret = ret & moveFileToFile(backupfile_n, previousFile);
565 previousFile = backupfile_n;
568 // index to use for the latest backup
571 else // not reverse numbering
573 // version style numbering (with earliest file deletion if max files
576 bfTreeMap.values().toArray(backupFiles);
577 StringBuilder bfsb = new StringBuilder();
578 for (int i = 0; i < backupFiles.length; i++)
580 if (bfsb.length() > 0)
584 bfsb.append(backupFiles[i].getName());
586 Console.trace("BACKUPFILES backupFiles: " + bfsb.toString());
588 // noMax == true means keep all backup files
589 if ((!noMax) && bfTreeMap.size() >= max)
591 Console.trace("BACKUPFILES noMax: " + noMax + ", " + "max: " + max
592 + ", " + "bfTreeMap.size(): " + bfTreeMap.size());
593 // need to delete some files to keep number of backups to designated
595 // Note that if the suffix is not numbered then do not delete any
596 // backup files later or we'll delete the new backup file (there can
598 int numToDelete = suffix.indexOf(NUM_PLACEHOLDER) > -1
599 ? bfTreeMap.size() - max + 1
601 Console.trace("BACKUPFILES numToDelete: " + numToDelete);
602 // the "replacement" file is the latest backup file being kept (it's
603 // not replacing though)
604 File replacementFile = numToDelete < backupFiles.length
605 ? backupFiles[numToDelete]
607 for (int i = 0; i < numToDelete; i++)
609 // check the deletion files for modification time of the last
610 // backupfile being saved
611 File fileToBeDeleted = backupFiles[i];
612 boolean delete = true;
615 "BACKUPFILES fileToBeDeleted: " + fileToBeDeleted);
617 boolean newer = false;
618 if (replacementFile != null)
620 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
621 long replacementFileLMT = replacementFile != null
622 ? replacementFile.lastModified()
624 if (fileToBeDeletedLMT > replacementFileLMT)
626 String fileToBeDeletedLMTString = sdf
627 .format(fileToBeDeletedLMT);
628 String replacementFileLMTString = sdf
629 .format(replacementFileLMT);
631 Console.warn("WARNING! I am set to delete backupfile '"
632 + fileToBeDeleted.getName()
633 + "' has modification time "
634 + fileToBeDeletedLMTString
635 + " which is newer than the oldest backupfile being kept '"
636 + replacementFile.getName()
637 + "' with modification time "
638 + replacementFileLMTString);
640 delete = confirmNewerDeleteFile(fileToBeDeleted,
641 replacementFile, false);
644 // User has confirmed delete -- no need to add it to the list
645 fileToBeDeleted.delete();
646 Console.debug("BACKUPFILES deleting fileToBeDeleted: "
652 // keeping file, nothing to do!
653 Console.debug("BACKUPFILES keeping fileToBeDeleted: "
660 addDeleteFile(fileToBeDeleted);
661 Console.debug("BACKUPFILES addDeleteFile(fileToBeDeleted): "
669 nextIndexNum = bfTreeMap.lastKey() + 1;
673 // Let's make the new backup file!! yay, got there at last!
674 String latestBackupFilename = dir + File.separatorChar
675 + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
677 Console.trace("BACKUPFILES Moving old file [" + file
678 + "] to latestBackupFilename [" + latestBackupFilename + "]");
679 // using boolean '&' instead of '&&' as don't want moveFileToFile attempt to
680 // be conditional (short-circuit)
681 ret = ret & moveFileToFile(file, new File(latestBackupFilename));
683 "BACKUPFILES moving " + file + " to " + latestBackupFilename
684 + " was " + (ret ? "" : "NOT ") + "successful");
687 Console.debug("BACKUPFILES tidying up files");
694 private static File nextTempFile(String filename, File dirFile)
698 COUNT: for (int i = 1; i < 1000; i++)
700 File trythis = new File(dirFile,
701 filename + '~' + Integer.toString(i));
702 if (!trythis.exists())
711 temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
716 private void tidyUpFiles()
721 private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
722 File replacementFile, boolean replace)
724 StringBuilder messageSB = new StringBuilder();
726 File ftbd = fileToBeDeleted;
727 String ftbdLMT = sdf.format(ftbd.lastModified());
728 String ftbdSize = Long.toString(ftbd.length());
730 File rf = replacementFile;
731 String rfLMT = sdf.format(rf.lastModified());
732 String rfSize = Long.toString(rf.length());
734 int confirmButton = JvOptionPane.NO_OPTION;
737 File saveFile = null;
740 saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
741 } catch (Exception e)
744 "Error when confirming to keep backup file newer than other backup files.");
747 messageSB.append(MessageManager.formatMessage(
748 "label.newerdelete_replacement_line", new String[]
749 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
751 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted and
752 // replaced by apparently older file \n''{1}''\t(modified {3}, size
754 messageSB.append("\n\n");
755 messageSB.append(MessageManager.formatMessage(
756 "label.confirm_deletion_or_rename", new String[]
757 { ftbd.getName(), saveFile.getName() }));
758 // "Confirm deletion of ''{0}'' or rename to ''{1}''?"
759 String[] options = new String[] {
760 MessageManager.getString("label.delete"),
761 MessageManager.getString("label.rename") };
763 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
764 : JvOptionPane.showOptionDialog(Desktop.desktop,
765 messageSB.toString(),
766 MessageManager.getString(
767 "label.backupfiles_confirm_delete"),
769 JvOptionPane.YES_NO_OPTION,
770 JvOptionPane.WARNING_MESSAGE, null, options,
775 messageSB.append(MessageManager
776 .formatMessage("label.newerdelete_line", new String[]
777 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
779 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted but
780 // is newer than the oldest remaining backup file \n''{1}''\t(modified
782 messageSB.append("\n\n");
783 messageSB.append(MessageManager
784 .formatMessage("label.confirm_deletion", new String[]
785 { ftbd.getName() }));
786 // "Confirm deletion of ''{0}''?"
787 String[] options = new String[] {
788 MessageManager.getString("label.delete"),
789 MessageManager.getString("label.keep") };
791 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
792 : JvOptionPane.showOptionDialog(Desktop.desktop,
793 messageSB.toString(),
794 MessageManager.getString(
795 "label.backupfiles_confirm_delete"),
797 JvOptionPane.YES_NO_OPTION,
798 JvOptionPane.WARNING_MESSAGE, null, options,
802 // return should be TRUE if file is to be deleted
803 return (confirmButton == JvOptionPane.YES_OPTION);
806 private void deleteOldFiles()
808 if (deleteFiles != null && !deleteFiles.isEmpty())
810 boolean doDelete = false;
811 StringBuilder messageSB = null;
812 if (confirmDelete && deleteFiles.size() > 0)
814 messageSB = new StringBuilder();
815 messageSB.append(MessageManager
816 .getString("label.backupfiles_confirm_delete_old_files"));
817 // "Delete the following older backup files? (see the Backups tab in
818 // Preferences for more options)"
819 for (int i = 0; i < deleteFiles.size(); i++)
821 File df = deleteFiles.get(i);
822 messageSB.append("\n");
823 messageSB.append(df.getName());
824 messageSB.append(" ");
825 messageSB.append(MessageManager.formatMessage("label.file_info",
827 { sdf.format(df.lastModified()),
828 Long.toString(df.length()) }));
829 // "(modified {0}, size {1})"
832 int confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
833 : JvOptionPane.showConfirmDialog(Desktop.desktop,
834 messageSB.toString(),
835 MessageManager.getString(
836 "label.backupfiles_confirm_delete"),
838 JvOptionPane.YES_NO_OPTION,
839 JvOptionPane.WARNING_MESSAGE);
841 doDelete = (confirmButton == JvOptionPane.YES_OPTION);
850 for (int i = 0; i < deleteFiles.size(); i++)
852 File fileToDelete = deleteFiles.get(i);
853 Console.trace("BACKUPFILES about to delete fileToDelete:"
855 fileToDelete.delete();
856 Console.warn("deleted '" + fileToDelete.getName() + "'");
865 private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
866 File[] backupFiles, String basename)
868 // sort the backup files (based on integer found in the suffix) using a
869 // precomputed Hashmap for speed
870 Map<Integer, File> bfHashMap = new HashMap<>();
871 for (int i = 0; i < backupFiles.length; i++)
873 File f = backupFiles[i];
874 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
876 bfHashMap.put(bfp.indexNum(), f);
878 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
879 bfTreeMap.putAll(bfHashMap);
883 public boolean rollBackupsAndRenameTempFile()
885 boolean write = this.getWriteSuccess();
887 boolean roll = false;
888 boolean rename = false;
891 roll = this.rollBackupFiles(false); // tidyUpFiles at the end
892 rename = this.renameTempFile();
896 * Not sure that this confirmation is desirable. By this stage the new file is
897 * already written successfully, but something (e.g. disk full) has happened while
898 * trying to roll the backup files, and most likely the filename needed will already
899 * be vacant so renaming the temp file is nearly always correct!
901 boolean okay = roll && rename;
904 StringBuilder messageSB = new StringBuilder();
905 messageSB.append(MessageManager.getString(
906 "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
907 // "Something possibly went wrong with the backups of this file."
910 if (messageSB.length() > 0)
912 messageSB.append("\n");
914 messageSB.append(MessageManager.getString(
915 "label.backupfiles_confirm_save_new_saved_file_ok"));
916 // "The new saved file seems okay."
920 if (messageSB.length() > 0)
922 messageSB.append("\n");
924 messageSB.append(MessageManager.getString(
925 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
926 // "The new saved file might not be okay."
928 if (messageSB.length() > 0)
930 messageSB.append("\n");
933 .append(MessageManager.getString("label.continue_operation"));
935 int confirmButton = Platform.isHeadless() ? JvOptionPane.OK_OPTION
936 : JvOptionPane.showConfirmDialog(Desktop.desktop,
937 messageSB.toString(),
938 MessageManager.getString(
939 "label.backupfiles_confirm_save_file"),
940 // "Confirm save file"
941 JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
942 okay = confirmButton == JvOptionPane.OK_OPTION;
949 // remove this file from the save in progress stack
950 removeSaveInProgress(rename);
955 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
956 String fileName, String suffix, int digits)
958 File[] backupFiles = null;
960 File file = new File(fileName);
965 dirFile = file.getParentFile();
966 } catch (Exception e)
968 Console.error("Could not get canonical path for file '" + file + "'");
969 return new TreeMap<>();
972 String filename = file.getName();
973 String basename = filename;
975 // find existing backup files
976 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
978 backupFiles = dirFile.listFiles(bff); // is clone needed?
980 // sort the backup files (based on integer found in the suffix) using a
981 // precomputed Hashmap for speed
982 Map<Integer, File> bfHashMap = new HashMap<>();
983 for (int i = 0; i < backupFiles.length; i++)
985 File f = backupFiles[i];
986 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
988 bfHashMap.put(bfp.indexNum(), f);
990 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
991 bfTreeMap.putAll(bfHashMap);
997 private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
998 boolean delete, boolean newer)
1000 return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
1003 private boolean addDeleteFile(File fileToBeDeleted)
1005 boolean ret = false;
1006 int pos = deleteFiles.indexOf(fileToBeDeleted);
1009 Console.debug("BACKUPFILES not adding file "
1010 + fileToBeDeleted.getAbsolutePath()
1011 + " to the delete list (already at index" + pos + ")");
1016 Console.debug("BACKUPFILES adding file "
1017 + fileToBeDeleted.getAbsolutePath() + " to the delete list");
1018 deleteFiles.add(fileToBeDeleted);
1023 public File getFile()
1028 public static boolean moveFileToFile(File oldFile, File newFile)
1030 Console.initLogger();
1031 boolean ret = false;
1032 Path oldPath = Paths.get(oldFile.getAbsolutePath());
1033 Path newPath = Paths.get(newFile.getAbsolutePath());
1036 // delete destination file - not usually necessary but Just In Case...
1037 Console.trace("BACKUPFILES deleting " + newFile.getAbsolutePath());
1039 Console.trace("BACKUPFILES moving " + oldFile.getAbsolutePath()
1040 + " to " + newFile.getAbsolutePath());
1041 Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
1043 Console.trace("BACKUPFILES move seems to have succeeded");
1044 } catch (IOException e)
1046 Console.warn("Could not move file '" + oldPath.toString() + "' to '"
1047 + newPath.toString() + "'");
1048 Console.error(e.getMessage());
1049 Console.debug(Cache.getStackTraceString(e));
1051 } catch (Exception e)
1053 Console.error(e.getMessage());
1054 Console.debug(Cache.getStackTraceString(e));