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())
177 public static List<File> savesInProgressFiles()
179 List<File> files = new ArrayList<>();
180 for (BackupFiles bfile : savesInProgress)
182 files.add(bfile.getFile());
187 public static List<CompletableFuture<Boolean>> savesInProgressCompletableFutures()
189 List<CompletableFuture<Boolean>> cfs = new ArrayList<>();
190 for (BackupFiles bfile : savesInProgress)
192 cfs.add(bfile.getMyFuture());
197 public static Future<Boolean> allSaved()
199 CompletableFuture<Boolean> f = new CompletableFuture<>();
201 executorService.submit(() -> {
202 for (BackupFiles buf : savesInProgress)
204 boolean allSaved = true;
207 allSaved &= buf.getMyFuture().get();
208 } catch (InterruptedException e)
210 Console.debug("InterruptedException waiting for files to save",
212 } catch (ExecutionException e)
214 Console.debug("ExecutionException waiting for files to save", e);
216 f.complete(allSaved);
222 public BackupFiles(String filename)
224 this(new File(filename));
227 // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
229 public BackupFiles(File file)
234 // add this file from the save in progress stack
237 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
238 .getSavedBackupEntry();
239 this.suffix = bfpe.suffix;
240 this.noMax = bfpe.keepAll;
241 this.max = bfpe.rollMax;
242 this.digits = bfpe.digits;
243 this.reverseOrder = bfpe.reverse;
245 // create a temp file to save new data in
251 String tempfilename = file.getName();
252 File tempdir = file.getParentFile();
254 "BACKUPFILES [file!=null] attempting to create temp file for "
255 + tempfilename + " in dir " + tempdir);
256 temp = File.createTempFile(tempfilename,
257 TEMP_FILE_EXT + newTempFileSuffix, tempdir);
259 "BACKUPFILES using temp file " + temp.getAbsolutePath());
264 "BACKUPFILES [file==null] attempting to create default temp file "
265 + DEFAULT_TEMP_FILE + " with extension "
267 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
269 } catch (IOException e)
271 Console.error("Could not create temp file to save to (IOException)");
272 Console.error(e.getMessage());
273 Console.debug(Cache.getStackTraceString(e));
274 } catch (Exception e)
276 Console.error("Exception creating temp file for saving");
277 Console.debug(Cache.getStackTraceString(e));
279 this.setTempFile(temp);
282 public static void classInit()
284 Console.initLogger();
285 Console.trace("BACKUPFILES classInit");
286 boolean e = Cache.getDefault(ENABLED, !Platform.isJS());
288 Console.trace("BACKUPFILES " + (e ? "enabled" : "disabled"));
289 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
290 .getSavedBackupEntry();
291 Console.trace("BACKUPFILES preset scheme " + bfpe.toString());
292 setConfirmDelete(bfpe.confirmDelete);
293 Console.trace("BACKUPFILES confirm delete " + bfpe.confirmDelete);
296 public static void setEnabled(boolean flag)
301 public static boolean getEnabled()
307 public static void setConfirmDelete(boolean flag)
309 confirmDelete = flag;
312 public static boolean getConfirmDelete()
315 return confirmDelete;
318 // set, get and rename temp file into place
319 public void setTempFile(File temp)
321 this.tempFile = temp;
324 public File getTempFile()
329 public String getTempFilePath()
334 path = this.getTempFile().getCanonicalPath();
335 } catch (IOException e)
337 Console.error("IOException when getting Canonical Path of temp file '"
338 + this.getTempFile().getName() + "'");
339 Console.debug(Cache.getStackTraceString(e));
344 public boolean setWriteSuccess(boolean flag)
346 boolean old = this.tempFileWriteSuccess;
347 this.tempFileWriteSuccess = flag;
351 public boolean getWriteSuccess()
353 return this.tempFileWriteSuccess;
356 public boolean renameTempFile()
358 return moveFileToFile(tempFile, file);
361 // roll the backupfiles
362 public boolean rollBackupFiles()
364 return this.rollBackupFiles(true);
367 public boolean rollBackupFiles(boolean tidyUp)
369 // file doesn't yet exist or backups are not enabled or template is null or
371 if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
372 || suffix.length() == 0)
375 Console.debug("BACKUPFILES rollBackupFiles nothing to do." + ", "
376 + "filename: " + (file != null ? file.getName() : "null")
377 + ", " + "file exists: " + file.exists() + ", " + "enabled: "
378 + enabled + ", " + "max: " + max + ", " + "suffix: '" + suffix
383 Console.trace("BACKUPFILES rollBackupFiles starting");
389 dirFile = file.getParentFile();
390 dir = dirFile.getCanonicalPath();
391 Console.trace("BACKUPFILES dir: " + dir);
392 } catch (Exception e)
394 Console.error("Could not get canonical path for file '" + file + "'");
395 Console.error(e.getMessage());
396 Console.debug(Cache.getStackTraceString(e));
399 String filename = file.getName();
400 String basename = filename;
402 Console.trace("BACKUPFILES filename is " + filename);
404 // Create/move backups up one
408 // find existing backup files
409 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
411 File[] backupFiles = dirFile.listFiles(bff);
412 int nextIndexNum = 0;
414 Console.trace("BACKUPFILES backupFiles.length: " + backupFiles.length);
415 if (backupFiles.length == 0)
417 // No other backup files. Just need to move existing file to backupfile_1
419 "BACKUPFILES no existing backup files, setting index to 1");
424 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
425 backupFiles, basename);
426 // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
431 // backup style numbering
432 Console.trace("BACKUPFILES rolling files in reverse order");
434 int tempMax = noMax ? -1 : max;
435 // noMax == true means no limits
436 // look for first "gap" in backupFiles
437 // if tempMax is -1 at this stage just keep going until there's a gap,
438 // then hopefully tempMax gets set to the right index (a positive
439 // integer so the loop breaks)...
440 // why do I feel a little uneasy about this loop?..
441 for (int i = 1; tempMax < 0 || i <= max; i++)
443 if (!bfTreeMap.containsKey(i)) // first index without existent
450 File previousFile = null;
451 File fileToBeDeleted = null;
452 for (int n = tempMax; n > 0; n--)
454 String backupfilename = dir + File.separatorChar
455 + BackupFilenameParts.getBackupFilename(n, basename,
457 File backupfile_n = new File(backupfilename);
459 if (!backupfile_n.exists())
461 // no "oldest" file to delete
462 previousFile = backupfile_n;
463 fileToBeDeleted = null;
464 Console.trace("BACKUPFILES No oldest file to delete");
468 // check the modification time of this (backupfile_n) and the previous
469 // file (fileToBeDeleted) if the previous file is going to be deleted
470 if (fileToBeDeleted != null)
472 File replacementFile = backupfile_n;
473 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
474 long replacementFileLMT = replacementFile.lastModified();
475 Console.trace("BACKUPFILES fileToBeDeleted is "
476 + fileToBeDeleted.getAbsolutePath());
477 Console.trace("BACKUPFILES replacementFile is "
478 + backupfile_n.getAbsolutePath());
482 File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
485 if (fileToBeDeletedLMT > replacementFileLMT)
487 String fileToBeDeletedLMTString = sdf
488 .format(fileToBeDeletedLMT);
489 String replacementFileLMTString = sdf
490 .format(replacementFileLMT);
491 Console.warn("WARNING! I am set to delete backupfile "
492 + fileToBeDeleted.getName()
493 + " has modification time "
494 + fileToBeDeletedLMTString
495 + " which is newer than its replacement "
496 + replacementFile.getName()
497 + " with modification time "
498 + replacementFileLMTString);
500 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
501 replacementFile, true);
502 Console.trace("BACKUPFILES "
503 + (delete ? "confirmed" : "not") + " deleting file "
504 + fileToBeDeleted.getAbsolutePath()
505 + " which is newer than "
506 + replacementFile.getAbsolutePath());
510 // User has confirmed delete -- no need to add it to the list
511 fileToBeDeleted.delete();
515 Console.debug("BACKUPFILES moving "
516 + fileToBeDeleted.getAbsolutePath() + " to "
517 + oldestTempFile.getAbsolutePath());
518 moveFileToFile(fileToBeDeleted, oldestTempFile);
523 Console.debug("BACKUPFILES going to move "
524 + fileToBeDeleted.getAbsolutePath() + " to "
525 + oldestTempFile.getAbsolutePath());
526 moveFileToFile(fileToBeDeleted, oldestTempFile);
527 addDeleteFile(oldestTempFile);
530 } catch (Exception e)
533 "Error occurred, probably making new temp file for '"
534 + fileToBeDeleted.getName() + "'");
535 Console.error(Cache.getStackTraceString(e));
539 fileToBeDeleted = null;
542 if (!noMax && n == tempMax && backupfile_n.exists())
544 fileToBeDeleted = backupfile_n;
548 if (previousFile != null)
550 // using boolean '&' instead of '&&' as don't want moveFileToFile
551 // attempt to be conditional (short-circuit)
552 ret = ret & moveFileToFile(backupfile_n, previousFile);
556 previousFile = backupfile_n;
559 // index to use for the latest backup
562 else // not reverse numbering
564 // version style numbering (with earliest file deletion if max files
567 bfTreeMap.values().toArray(backupFiles);
568 StringBuilder bfsb = new StringBuilder();
569 for (int i = 0; i < backupFiles.length; i++)
571 if (bfsb.length() > 0)
575 bfsb.append(backupFiles[i].getName());
577 Console.trace("BACKUPFILES backupFiles: " + bfsb.toString());
579 // noMax == true means keep all backup files
580 if ((!noMax) && bfTreeMap.size() >= max)
582 Console.trace("BACKUPFILES noMax: " + noMax + ", " + "max: " + max
583 + ", " + "bfTreeMap.size(): " + bfTreeMap.size());
584 // need to delete some files to keep number of backups to designated
586 // Note that if the suffix is not numbered then do not delete any
587 // backup files later or we'll delete the new backup file (there can
589 int numToDelete = suffix.indexOf(NUM_PLACEHOLDER) > -1
590 ? bfTreeMap.size() - max + 1
592 Console.trace("BACKUPFILES numToDelete: " + numToDelete);
593 // the "replacement" file is the latest backup file being kept (it's
594 // not replacing though)
595 File replacementFile = numToDelete < backupFiles.length
596 ? backupFiles[numToDelete]
598 for (int i = 0; i < numToDelete; i++)
600 // check the deletion files for modification time of the last
601 // backupfile being saved
602 File fileToBeDeleted = backupFiles[i];
603 boolean delete = true;
606 "BACKUPFILES fileToBeDeleted: " + fileToBeDeleted);
608 boolean newer = false;
609 if (replacementFile != null)
611 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
612 long replacementFileLMT = replacementFile != null
613 ? replacementFile.lastModified()
615 if (fileToBeDeletedLMT > replacementFileLMT)
617 String fileToBeDeletedLMTString = sdf
618 .format(fileToBeDeletedLMT);
619 String replacementFileLMTString = sdf
620 .format(replacementFileLMT);
622 Console.warn("WARNING! I am set to delete backupfile '"
623 + fileToBeDeleted.getName()
624 + "' has modification time "
625 + fileToBeDeletedLMTString
626 + " which is newer than the oldest backupfile being kept '"
627 + replacementFile.getName()
628 + "' with modification time "
629 + replacementFileLMTString);
631 delete = confirmNewerDeleteFile(fileToBeDeleted,
632 replacementFile, false);
635 // User has confirmed delete -- no need to add it to the list
636 fileToBeDeleted.delete();
637 Console.debug("BACKUPFILES deleting fileToBeDeleted: "
643 // keeping file, nothing to do!
644 Console.debug("BACKUPFILES keeping fileToBeDeleted: "
651 addDeleteFile(fileToBeDeleted);
652 Console.debug("BACKUPFILES addDeleteFile(fileToBeDeleted): "
660 nextIndexNum = bfTreeMap.lastKey() + 1;
664 // Let's make the new backup file!! yay, got there at last!
665 String latestBackupFilename = dir + File.separatorChar
666 + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
668 Console.trace("BACKUPFILES Moving old file [" + file
669 + "] to latestBackupFilename [" + latestBackupFilename + "]");
670 // using boolean '&' instead of '&&' as don't want moveFileToFile attempt to
671 // be conditional (short-circuit)
672 ret = ret & moveFileToFile(file, new File(latestBackupFilename));
674 "BACKUPFILES moving " + file + " to " + latestBackupFilename
675 + " was " + (ret ? "" : "NOT ") + "successful");
678 Console.debug("BACKUPFILES tidying up files");
685 private static File nextTempFile(String filename, File dirFile)
689 COUNT: for (int i = 1; i < 1000; i++)
691 File trythis = new File(dirFile,
692 filename + '~' + Integer.toString(i));
693 if (!trythis.exists())
702 temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
707 private void tidyUpFiles()
712 private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
713 File replacementFile, boolean replace)
715 StringBuilder messageSB = new StringBuilder();
717 File ftbd = fileToBeDeleted;
718 String ftbdLMT = sdf.format(ftbd.lastModified());
719 String ftbdSize = Long.toString(ftbd.length());
721 File rf = replacementFile;
722 String rfLMT = sdf.format(rf.lastModified());
723 String rfSize = Long.toString(rf.length());
725 int confirmButton = JvOptionPane.NO_OPTION;
728 File saveFile = null;
731 saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
732 } catch (Exception e)
735 "Error when confirming to keep backup file newer than other backup files.");
738 messageSB.append(MessageManager.formatMessage(
739 "label.newerdelete_replacement_line", new String[]
740 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
742 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted and
743 // replaced by apparently older file \n''{1}''\t(modified {3}, size
745 messageSB.append("\n\n");
746 messageSB.append(MessageManager.formatMessage(
747 "label.confirm_deletion_or_rename", new String[]
748 { ftbd.getName(), saveFile.getName() }));
749 // "Confirm deletion of ''{0}'' or rename to ''{1}''?"
750 String[] options = new String[] {
751 MessageManager.getString("label.delete"),
752 MessageManager.getString("label.rename") };
754 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
755 : JvOptionPane.showOptionDialog(Desktop.desktop,
756 messageSB.toString(),
757 MessageManager.getString(
758 "label.backupfiles_confirm_delete"),
760 JvOptionPane.YES_NO_OPTION,
761 JvOptionPane.WARNING_MESSAGE, null, options,
766 messageSB.append(MessageManager
767 .formatMessage("label.newerdelete_line", new String[]
768 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
770 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted but
771 // is newer than the oldest remaining backup file \n''{1}''\t(modified
773 messageSB.append("\n\n");
774 messageSB.append(MessageManager
775 .formatMessage("label.confirm_deletion", new String[]
776 { ftbd.getName() }));
777 // "Confirm deletion of ''{0}''?"
778 String[] options = new String[] {
779 MessageManager.getString("label.delete"),
780 MessageManager.getString("label.keep") };
782 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
783 : JvOptionPane.showOptionDialog(Desktop.desktop,
784 messageSB.toString(),
785 MessageManager.getString(
786 "label.backupfiles_confirm_delete"),
788 JvOptionPane.YES_NO_OPTION,
789 JvOptionPane.WARNING_MESSAGE, null, options,
793 // return should be TRUE if file is to be deleted
794 return (confirmButton == JvOptionPane.YES_OPTION);
797 private void deleteOldFiles()
799 if (deleteFiles != null && !deleteFiles.isEmpty())
801 boolean doDelete = false;
802 StringBuilder messageSB = null;
803 if (confirmDelete && deleteFiles.size() > 0)
805 messageSB = new StringBuilder();
806 messageSB.append(MessageManager
807 .getString("label.backupfiles_confirm_delete_old_files"));
808 // "Delete the following older backup files? (see the Backups tab in
809 // Preferences for more options)"
810 for (int i = 0; i < deleteFiles.size(); i++)
812 File df = deleteFiles.get(i);
813 messageSB.append("\n");
814 messageSB.append(df.getName());
815 messageSB.append(" ");
816 messageSB.append(MessageManager.formatMessage("label.file_info",
818 { sdf.format(df.lastModified()),
819 Long.toString(df.length()) }));
820 // "(modified {0}, size {1})"
823 int confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
824 : JvOptionPane.showConfirmDialog(Desktop.desktop,
825 messageSB.toString(),
826 MessageManager.getString(
827 "label.backupfiles_confirm_delete"),
829 JvOptionPane.YES_NO_OPTION,
830 JvOptionPane.WARNING_MESSAGE);
832 doDelete = (confirmButton == JvOptionPane.YES_OPTION);
841 for (int i = 0; i < deleteFiles.size(); i++)
843 File fileToDelete = deleteFiles.get(i);
844 Console.trace("BACKUPFILES about to delete fileToDelete:"
846 fileToDelete.delete();
847 Console.warn("deleted '" + fileToDelete.getName() + "'");
856 private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
857 File[] backupFiles, String basename)
859 // sort the backup files (based on integer found in the suffix) using a
860 // precomputed Hashmap for speed
861 Map<Integer, File> bfHashMap = new HashMap<>();
862 for (int i = 0; i < backupFiles.length; i++)
864 File f = backupFiles[i];
865 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
867 bfHashMap.put(bfp.indexNum(), f);
869 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
870 bfTreeMap.putAll(bfHashMap);
874 public boolean rollBackupsAndRenameTempFile()
876 boolean write = this.getWriteSuccess();
878 boolean roll = false;
879 boolean rename = false;
882 roll = this.rollBackupFiles(false); // tidyUpFiles at the end
883 rename = this.renameTempFile();
887 * Not sure that this confirmation is desirable. By this stage the new file is
888 * already written successfully, but something (e.g. disk full) has happened while
889 * trying to roll the backup files, and most likely the filename needed will already
890 * be vacant so renaming the temp file is nearly always correct!
892 boolean okay = roll && rename;
895 StringBuilder messageSB = new StringBuilder();
896 messageSB.append(MessageManager.getString(
897 "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
898 // "Something possibly went wrong with the backups of this file."
901 if (messageSB.length() > 0)
903 messageSB.append("\n");
905 messageSB.append(MessageManager.getString(
906 "label.backupfiles_confirm_save_new_saved_file_ok"));
907 // "The new saved file seems okay."
911 if (messageSB.length() > 0)
913 messageSB.append("\n");
915 messageSB.append(MessageManager.getString(
916 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
917 // "The new saved file might not be okay."
919 if (messageSB.length() > 0)
921 messageSB.append("\n");
924 .append(MessageManager.getString("label.continue_operation"));
926 int confirmButton = Platform.isHeadless() ? JvOptionPane.OK_OPTION
927 : JvOptionPane.showConfirmDialog(Desktop.desktop,
928 messageSB.toString(),
929 MessageManager.getString(
930 "label.backupfiles_confirm_save_file"),
931 // "Confirm save file"
932 JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
933 okay = confirmButton == JvOptionPane.OK_OPTION;
940 // remove this file from the save in progress stack
941 removeSaveInProgress(rename);
946 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
947 String fileName, String suffix, int digits)
949 File[] backupFiles = null;
951 File file = new File(fileName);
956 dirFile = file.getParentFile();
957 } catch (Exception e)
959 Console.error("Could not get canonical path for file '" + file + "'");
960 return new TreeMap<>();
963 String filename = file.getName();
964 String basename = filename;
966 // find existing backup files
967 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
969 backupFiles = dirFile.listFiles(bff); // is clone needed?
971 // sort the backup files (based on integer found in the suffix) using a
972 // precomputed Hashmap for speed
973 Map<Integer, File> bfHashMap = new HashMap<>();
974 for (int i = 0; i < backupFiles.length; i++)
976 File f = backupFiles[i];
977 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
979 bfHashMap.put(bfp.indexNum(), f);
981 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
982 bfTreeMap.putAll(bfHashMap);
988 private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
989 boolean delete, boolean newer)
991 return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
994 private boolean addDeleteFile(File fileToBeDeleted)
997 int pos = deleteFiles.indexOf(fileToBeDeleted);
1000 Console.debug("BACKUPFILES not adding file "
1001 + fileToBeDeleted.getAbsolutePath()
1002 + " to the delete list (already at index" + pos + ")");
1007 Console.debug("BACKUPFILES adding file "
1008 + fileToBeDeleted.getAbsolutePath() + " to the delete list");
1009 deleteFiles.add(fileToBeDeleted);
1014 public File getFile()
1019 public static boolean moveFileToFile(File oldFile, File newFile)
1021 Console.initLogger();
1022 boolean ret = false;
1023 Path oldPath = Paths.get(oldFile.getAbsolutePath());
1024 Path newPath = Paths.get(newFile.getAbsolutePath());
1027 // delete destination file - not usually necessary but Just In Case...
1028 Console.trace("BACKUPFILES deleting " + newFile.getAbsolutePath());
1030 Console.trace("BACKUPFILES moving " + oldFile.getAbsolutePath()
1031 + " to " + newFile.getAbsolutePath());
1032 Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
1034 Console.trace("BACKUPFILES move seems to have succeeded");
1035 } catch (IOException e)
1037 Console.warn("Could not move file '" + oldPath.toString() + "' to '"
1038 + newPath.toString() + "'");
1039 Console.error(e.getMessage());
1040 Console.debug(Cache.getStackTraceString(e));
1042 } catch (Exception e)
1044 Console.error(e.getMessage());
1045 Console.debug(Cache.getStackTraceString(e));