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)
237 // add this file from the save in progress stack
240 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
241 .getSavedBackupEntry();
242 this.suffix = bfpe.suffix;
243 this.noMax = bfpe.keepAll;
244 this.max = bfpe.rollMax;
245 this.digits = bfpe.digits;
246 this.reverseOrder = bfpe.reverse;
248 // create a temp file to save new data in
254 String tempfilename = file.getName();
255 File tempdir = file.getParentFile();
258 "BACKUPFILES [file!=null] attempting to create temp file for "
259 + tempfilename + " in dir " + tempdir);
260 temp = File.createTempFile(tempfilename,
261 TEMP_FILE_EXT + newTempFileSuffix, tempdir);
263 "BACKUPFILES using temp file " + temp.getAbsolutePath());
268 "BACKUPFILES [file==null] attempting to create default temp file "
269 + DEFAULT_TEMP_FILE + " with extension "
271 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
273 } catch (IOException e)
275 Console.error("Could not create temp file to save to (IOException)");
276 Console.error(e.getMessage());
277 Console.debug(Cache.getStackTraceString(e));
278 } catch (Exception e)
280 Console.error("Exception creating temp file for saving");
281 Console.debug(Cache.getStackTraceString(e));
283 this.setTempFile(temp);
286 public static void classInit()
288 Console.initLogger();
289 Console.trace("BACKUPFILES classInit");
290 boolean e = Cache.getDefault(ENABLED, !Platform.isJS());
292 Console.trace("BACKUPFILES " + (e ? "enabled" : "disabled"));
293 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
294 .getSavedBackupEntry();
295 Console.trace("BACKUPFILES preset scheme " + bfpe.toString());
296 setConfirmDelete(bfpe.confirmDelete);
297 Console.trace("BACKUPFILES confirm delete " + bfpe.confirmDelete);
300 public static void setEnabled(boolean flag)
305 public static boolean getEnabled()
311 public static void setConfirmDelete(boolean flag)
313 confirmDelete = flag;
316 public static boolean getConfirmDelete()
319 return confirmDelete;
322 // set, get and rename temp file into place
323 public void setTempFile(File temp)
325 this.tempFile = temp;
328 public File getTempFile()
333 public String getTempFilePath()
338 path = this.getTempFile().getCanonicalPath();
339 } catch (IOException e)
341 Console.error("IOException when getting Canonical Path of temp file '"
342 + this.getTempFile().getName() + "'");
343 Console.debug(Cache.getStackTraceString(e));
348 public boolean setWriteSuccess(boolean flag)
350 boolean old = this.tempFileWriteSuccess;
351 this.tempFileWriteSuccess = flag;
355 public boolean getWriteSuccess()
357 return this.tempFileWriteSuccess;
360 public boolean renameTempFile()
362 return moveFileToFile(tempFile, file);
365 // roll the backupfiles
366 public boolean rollBackupFiles()
368 return this.rollBackupFiles(true);
371 public boolean rollBackupFiles(boolean tidyUp)
373 // file doesn't yet exist or backups are not enabled or template is null or
375 if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
376 || suffix.length() == 0)
379 Console.debug("BACKUPFILES rollBackupFiles nothing to do." + ", "
380 + "filename: " + (file != null ? file.getName() : "null")
381 + ", " + "file exists: " + file.exists() + ", " + "enabled: "
382 + enabled + ", " + "max: " + max + ", " + "suffix: '" + suffix
387 Console.trace("BACKUPFILES rollBackupFiles starting");
393 dirFile = file.getParentFile();
394 dir = dirFile.getCanonicalPath();
395 Console.trace("BACKUPFILES dir: " + dir);
396 } catch (Exception e)
398 Console.error("Could not get canonical path for file '" + file + "'");
399 Console.error(e.getMessage());
400 Console.debug(Cache.getStackTraceString(e));
403 String filename = file.getName();
404 String basename = filename;
406 Console.trace("BACKUPFILES filename is " + filename);
408 // Create/move backups up one
412 // find existing backup files
413 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
415 File[] backupFiles = dirFile.listFiles(bff);
416 int nextIndexNum = 0;
418 Console.trace("BACKUPFILES backupFiles.length: " + backupFiles.length);
419 if (backupFiles.length == 0)
421 // No other backup files. Just need to move existing file to backupfile_1
423 "BACKUPFILES no existing backup files, setting index to 1");
428 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
429 backupFiles, basename);
430 // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
435 // backup style numbering
436 Console.trace("BACKUPFILES rolling files in reverse order");
438 int tempMax = noMax ? -1 : max;
439 // noMax == true means no limits
440 // look for first "gap" in backupFiles
441 // if tempMax is -1 at this stage just keep going until there's a gap,
442 // then hopefully tempMax gets set to the right index (a positive
443 // integer so the loop breaks)...
444 // why do I feel a little uneasy about this loop?..
445 for (int i = 1; tempMax < 0 || i <= max; i++)
447 if (!bfTreeMap.containsKey(i)) // first index without existent
454 File previousFile = null;
455 File fileToBeDeleted = null;
456 for (int n = tempMax; n > 0; n--)
458 String backupfilename = dir + File.separatorChar
459 + BackupFilenameParts.getBackupFilename(n, basename,
461 File backupfile_n = new File(backupfilename);
463 if (!backupfile_n.exists())
465 // no "oldest" file to delete
466 previousFile = backupfile_n;
467 fileToBeDeleted = null;
468 Console.trace("BACKUPFILES No oldest file to delete");
472 // check the modification time of this (backupfile_n) and the previous
473 // file (fileToBeDeleted) if the previous file is going to be deleted
474 if (fileToBeDeleted != null)
476 File replacementFile = backupfile_n;
477 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
478 long replacementFileLMT = replacementFile.lastModified();
479 Console.trace("BACKUPFILES fileToBeDeleted is "
480 + fileToBeDeleted.getAbsolutePath());
481 Console.trace("BACKUPFILES replacementFile is "
482 + backupfile_n.getAbsolutePath());
486 File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
489 if (fileToBeDeletedLMT > replacementFileLMT)
491 String fileToBeDeletedLMTString = sdf
492 .format(fileToBeDeletedLMT);
493 String replacementFileLMTString = sdf
494 .format(replacementFileLMT);
495 Console.warn("WARNING! I am set to delete backupfile "
496 + fileToBeDeleted.getName()
497 + " has modification time "
498 + fileToBeDeletedLMTString
499 + " which is newer than its replacement "
500 + replacementFile.getName()
501 + " with modification time "
502 + replacementFileLMTString);
504 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
505 replacementFile, true);
506 Console.trace("BACKUPFILES "
507 + (delete ? "confirmed" : "not") + " deleting file "
508 + fileToBeDeleted.getAbsolutePath()
509 + " which is newer than "
510 + replacementFile.getAbsolutePath());
514 // User has confirmed delete -- no need to add it to the list
515 fileToBeDeleted.delete();
519 Console.debug("BACKUPFILES moving "
520 + fileToBeDeleted.getAbsolutePath() + " to "
521 + oldestTempFile.getAbsolutePath());
522 moveFileToFile(fileToBeDeleted, oldestTempFile);
527 Console.debug("BACKUPFILES going to move "
528 + fileToBeDeleted.getAbsolutePath() + " to "
529 + oldestTempFile.getAbsolutePath());
530 moveFileToFile(fileToBeDeleted, oldestTempFile);
531 addDeleteFile(oldestTempFile);
534 } catch (Exception e)
537 "Error occurred, probably making new temp file for '"
538 + fileToBeDeleted.getName() + "'");
539 Console.error(Cache.getStackTraceString(e));
543 fileToBeDeleted = null;
546 if (!noMax && n == tempMax && backupfile_n.exists())
548 fileToBeDeleted = backupfile_n;
552 if (previousFile != null)
554 // using boolean '&' instead of '&&' as don't want moveFileToFile
555 // attempt to be conditional (short-circuit)
556 ret = ret & moveFileToFile(backupfile_n, previousFile);
560 previousFile = backupfile_n;
563 // index to use for the latest backup
566 else // not reverse numbering
568 // version style numbering (with earliest file deletion if max files
571 bfTreeMap.values().toArray(backupFiles);
572 StringBuilder bfsb = new StringBuilder();
573 for (int i = 0; i < backupFiles.length; i++)
575 if (bfsb.length() > 0)
579 bfsb.append(backupFiles[i].getName());
581 Console.trace("BACKUPFILES backupFiles: " + bfsb.toString());
583 // noMax == true means keep all backup files
584 if ((!noMax) && bfTreeMap.size() >= max)
586 Console.trace("BACKUPFILES noMax: " + noMax + ", " + "max: " + max
587 + ", " + "bfTreeMap.size(): " + bfTreeMap.size());
588 // need to delete some files to keep number of backups to designated
590 // Note that if the suffix is not numbered then do not delete any
591 // backup files later or we'll delete the new backup file (there can
593 int numToDelete = suffix.indexOf(NUM_PLACEHOLDER) > -1
594 ? bfTreeMap.size() - max + 1
596 Console.trace("BACKUPFILES numToDelete: " + numToDelete);
597 // the "replacement" file is the latest backup file being kept (it's
598 // not replacing though)
599 File replacementFile = numToDelete < backupFiles.length
600 ? backupFiles[numToDelete]
602 for (int i = 0; i < numToDelete; i++)
604 // check the deletion files for modification time of the last
605 // backupfile being saved
606 File fileToBeDeleted = backupFiles[i];
607 boolean delete = true;
610 "BACKUPFILES fileToBeDeleted: " + fileToBeDeleted);
612 boolean newer = false;
613 if (replacementFile != null)
615 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
616 long replacementFileLMT = replacementFile != null
617 ? replacementFile.lastModified()
619 if (fileToBeDeletedLMT > replacementFileLMT)
621 String fileToBeDeletedLMTString = sdf
622 .format(fileToBeDeletedLMT);
623 String replacementFileLMTString = sdf
624 .format(replacementFileLMT);
626 Console.warn("WARNING! I am set to delete backupfile '"
627 + fileToBeDeleted.getName()
628 + "' has modification time "
629 + fileToBeDeletedLMTString
630 + " which is newer than the oldest backupfile being kept '"
631 + replacementFile.getName()
632 + "' with modification time "
633 + replacementFileLMTString);
635 delete = confirmNewerDeleteFile(fileToBeDeleted,
636 replacementFile, false);
639 // User has confirmed delete -- no need to add it to the list
640 fileToBeDeleted.delete();
641 Console.debug("BACKUPFILES deleting fileToBeDeleted: "
647 // keeping file, nothing to do!
648 Console.debug("BACKUPFILES keeping fileToBeDeleted: "
655 addDeleteFile(fileToBeDeleted);
656 Console.debug("BACKUPFILES addDeleteFile(fileToBeDeleted): "
664 nextIndexNum = bfTreeMap.lastKey() + 1;
668 // Let's make the new backup file!! yay, got there at last!
669 String latestBackupFilename = dir + File.separatorChar
670 + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
672 Console.trace("BACKUPFILES Moving old file [" + file
673 + "] to latestBackupFilename [" + latestBackupFilename + "]");
674 // using boolean '&' instead of '&&' as don't want moveFileToFile attempt to
675 // be conditional (short-circuit)
676 ret = ret & moveFileToFile(file, new File(latestBackupFilename));
678 "BACKUPFILES moving " + file + " to " + latestBackupFilename
679 + " was " + (ret ? "" : "NOT ") + "successful");
682 Console.debug("BACKUPFILES tidying up files");
689 private static File nextTempFile(String filename, File dirFile)
693 COUNT: for (int i = 1; i < 1000; i++)
695 File trythis = new File(dirFile,
696 filename + '~' + Integer.toString(i));
697 if (!trythis.exists())
706 temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
711 private void tidyUpFiles()
716 private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
717 File replacementFile, boolean replace)
719 StringBuilder messageSB = new StringBuilder();
721 File ftbd = fileToBeDeleted;
722 String ftbdLMT = sdf.format(ftbd.lastModified());
723 String ftbdSize = Long.toString(ftbd.length());
725 File rf = replacementFile;
726 String rfLMT = sdf.format(rf.lastModified());
727 String rfSize = Long.toString(rf.length());
729 int confirmButton = JvOptionPane.NO_OPTION;
732 File saveFile = null;
735 saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
736 } catch (Exception e)
739 "Error when confirming to keep backup file newer than other backup files.");
742 messageSB.append(MessageManager.formatMessage(
743 "label.newerdelete_replacement_line", new String[]
744 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
746 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted and
747 // replaced by apparently older file \n''{1}''\t(modified {3}, size
749 messageSB.append("\n\n");
750 messageSB.append(MessageManager.formatMessage(
751 "label.confirm_deletion_or_rename", new String[]
752 { ftbd.getName(), saveFile.getName() }));
753 // "Confirm deletion of ''{0}'' or rename to ''{1}''?"
754 String[] options = new String[] {
755 MessageManager.getString("label.delete"),
756 MessageManager.getString("label.rename") };
758 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
759 : JvOptionPane.showOptionDialog(Desktop.desktop,
760 messageSB.toString(),
761 MessageManager.getString(
762 "label.backupfiles_confirm_delete"),
764 JvOptionPane.YES_NO_OPTION,
765 JvOptionPane.WARNING_MESSAGE, null, options,
770 messageSB.append(MessageManager
771 .formatMessage("label.newerdelete_line", new String[]
772 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
774 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted but
775 // is newer than the oldest remaining backup file \n''{1}''\t(modified
777 messageSB.append("\n\n");
778 messageSB.append(MessageManager
779 .formatMessage("label.confirm_deletion", new String[]
780 { ftbd.getName() }));
781 // "Confirm deletion of ''{0}''?"
782 String[] options = new String[] {
783 MessageManager.getString("label.delete"),
784 MessageManager.getString("label.keep") };
786 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
787 : JvOptionPane.showOptionDialog(Desktop.desktop,
788 messageSB.toString(),
789 MessageManager.getString(
790 "label.backupfiles_confirm_delete"),
792 JvOptionPane.YES_NO_OPTION,
793 JvOptionPane.WARNING_MESSAGE, null, options,
797 // return should be TRUE if file is to be deleted
798 return (confirmButton == JvOptionPane.YES_OPTION);
801 private void deleteOldFiles()
803 if (deleteFiles != null && !deleteFiles.isEmpty())
805 boolean doDelete = false;
806 StringBuilder messageSB = null;
807 if (confirmDelete && deleteFiles.size() > 0)
809 messageSB = new StringBuilder();
810 messageSB.append(MessageManager
811 .getString("label.backupfiles_confirm_delete_old_files"));
812 // "Delete the following older backup files? (see the Backups tab in
813 // Preferences for more options)"
814 for (int i = 0; i < deleteFiles.size(); i++)
816 File df = deleteFiles.get(i);
817 messageSB.append("\n");
818 messageSB.append(df.getName());
819 messageSB.append(" ");
820 messageSB.append(MessageManager.formatMessage("label.file_info",
822 { sdf.format(df.lastModified()),
823 Long.toString(df.length()) }));
824 // "(modified {0}, size {1})"
827 int confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
828 : JvOptionPane.showConfirmDialog(Desktop.desktop,
829 messageSB.toString(),
830 MessageManager.getString(
831 "label.backupfiles_confirm_delete"),
833 JvOptionPane.YES_NO_OPTION,
834 JvOptionPane.WARNING_MESSAGE);
836 doDelete = (confirmButton == JvOptionPane.YES_OPTION);
845 for (int i = 0; i < deleteFiles.size(); i++)
847 File fileToDelete = deleteFiles.get(i);
848 Console.trace("BACKUPFILES about to delete fileToDelete:"
850 fileToDelete.delete();
851 Console.warn("deleted '" + fileToDelete.getName() + "'");
860 private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
861 File[] backupFiles, String basename)
863 // sort the backup files (based on integer found in the suffix) using a
864 // precomputed Hashmap for speed
865 Map<Integer, File> bfHashMap = new HashMap<>();
866 for (int i = 0; i < backupFiles.length; i++)
868 File f = backupFiles[i];
869 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
871 bfHashMap.put(bfp.indexNum(), f);
873 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
874 bfTreeMap.putAll(bfHashMap);
878 public boolean rollBackupsAndRenameTempFile()
880 boolean write = this.getWriteSuccess();
882 boolean roll = false;
883 boolean rename = false;
886 roll = this.rollBackupFiles(false); // tidyUpFiles at the end
887 rename = this.renameTempFile();
891 * Not sure that this confirmation is desirable. By this stage the new file is
892 * already written successfully, but something (e.g. disk full) has happened while
893 * trying to roll the backup files, and most likely the filename needed will already
894 * be vacant so renaming the temp file is nearly always correct!
896 boolean okay = roll && rename;
899 StringBuilder messageSB = new StringBuilder();
900 messageSB.append(MessageManager.getString(
901 "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
902 // "Something possibly went wrong with the backups of this file."
905 if (messageSB.length() > 0)
907 messageSB.append("\n");
909 messageSB.append(MessageManager.getString(
910 "label.backupfiles_confirm_save_new_saved_file_ok"));
911 // "The new saved file seems okay."
915 if (messageSB.length() > 0)
917 messageSB.append("\n");
919 messageSB.append(MessageManager.getString(
920 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
921 // "The new saved file might not be okay."
923 if (messageSB.length() > 0)
925 messageSB.append("\n");
928 .append(MessageManager.getString("label.continue_operation"));
930 int confirmButton = Platform.isHeadless() ? JvOptionPane.OK_OPTION
931 : JvOptionPane.showConfirmDialog(Desktop.desktop,
932 messageSB.toString(),
933 MessageManager.getString(
934 "label.backupfiles_confirm_save_file"),
935 // "Confirm save file"
936 JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
937 okay = confirmButton == JvOptionPane.OK_OPTION;
944 // remove this file from the save in progress stack
945 removeSaveInProgress(rename);
950 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
951 String fileName, String suffix, int digits)
953 File[] backupFiles = null;
955 File file = new File(fileName);
960 dirFile = file.getParentFile();
961 } catch (Exception e)
963 Console.error("Could not get canonical path for file '" + file + "'");
964 return new TreeMap<>();
967 String filename = file.getName();
968 String basename = filename;
970 // find existing backup files
971 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
973 backupFiles = dirFile.listFiles(bff); // is clone needed?
975 // sort the backup files (based on integer found in the suffix) using a
976 // precomputed Hashmap for speed
977 Map<Integer, File> bfHashMap = new HashMap<>();
978 for (int i = 0; i < backupFiles.length; i++)
980 File f = backupFiles[i];
981 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
983 bfHashMap.put(bfp.indexNum(), f);
985 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
986 bfTreeMap.putAll(bfHashMap);
992 private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
993 boolean delete, boolean newer)
995 return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
998 private boolean addDeleteFile(File fileToBeDeleted)
1000 boolean ret = false;
1001 int pos = deleteFiles.indexOf(fileToBeDeleted);
1004 Console.debug("BACKUPFILES not adding file "
1005 + fileToBeDeleted.getAbsolutePath()
1006 + " to the delete list (already at index" + pos + ")");
1011 Console.debug("BACKUPFILES adding file "
1012 + fileToBeDeleted.getAbsolutePath() + " to the delete list");
1013 deleteFiles.add(fileToBeDeleted);
1018 public File getFile()
1023 public static boolean moveFileToFile(File oldFile, File newFile)
1025 Console.initLogger();
1026 boolean ret = false;
1027 Path oldPath = Paths.get(oldFile.getAbsolutePath());
1028 Path newPath = Paths.get(newFile.getAbsolutePath());
1031 // delete destination file - not usually necessary but Just In Case...
1032 Console.trace("BACKUPFILES deleting " + newFile.getAbsolutePath());
1034 Console.trace("BACKUPFILES moving " + oldFile.getAbsolutePath()
1035 + " to " + newFile.getAbsolutePath());
1036 Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
1038 Console.trace("BACKUPFILES move seems to have succeeded");
1039 } catch (IOException e)
1041 Console.warn("Could not move file '" + oldPath.toString() + "' to '"
1042 + newPath.toString() + "'");
1043 Console.error(e.getMessage());
1044 Console.debug(Cache.getStackTraceString(e));
1046 } catch (Exception e)
1048 Console.error(e.getMessage());
1049 Console.debug(Cache.getStackTraceString(e));