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();
257 "BACKUPFILES [file!=null] attempting to create temp file for "
258 + tempfilename + " in dir " + tempdir);
259 temp = File.createTempFile(tempfilename,
260 TEMP_FILE_EXT + newTempFileSuffix, tempdir);
262 "BACKUPFILES using temp file " + temp.getAbsolutePath());
267 "BACKUPFILES [file==null] attempting to create default temp file "
268 + DEFAULT_TEMP_FILE + " with extension "
270 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
272 } catch (IOException e)
274 Console.error("Could not create temp file to save to (IOException)");
275 Console.error(e.getMessage());
276 Console.debug(Cache.getStackTraceString(e));
277 } catch (Exception e)
279 Console.error("Exception creating temp file for saving");
280 Console.debug(Cache.getStackTraceString(e));
282 this.setTempFile(temp);
285 public static void classInit()
287 Console.initLogger();
288 Console.trace("BACKUPFILES classInit");
289 boolean e = Cache.getDefault(ENABLED, !Platform.isJS());
291 Console.trace("BACKUPFILES " + (e ? "enabled" : "disabled"));
292 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
293 .getSavedBackupEntry();
294 Console.trace("BACKUPFILES preset scheme " + bfpe.toString());
295 setConfirmDelete(bfpe.confirmDelete);
296 Console.trace("BACKUPFILES confirm delete " + bfpe.confirmDelete);
299 public static void setEnabled(boolean flag)
304 public static boolean getEnabled()
310 public static void setConfirmDelete(boolean flag)
312 confirmDelete = flag;
315 public static boolean getConfirmDelete()
318 return confirmDelete;
321 // set, get and rename temp file into place
322 public void setTempFile(File temp)
324 this.tempFile = temp;
327 public File getTempFile()
332 public String getTempFilePath()
337 path = this.getTempFile().getCanonicalPath();
338 } catch (IOException e)
340 Console.error("IOException when getting Canonical Path of temp file '"
341 + this.getTempFile().getName() + "'");
342 Console.debug(Cache.getStackTraceString(e));
347 public boolean setWriteSuccess(boolean flag)
349 boolean old = this.tempFileWriteSuccess;
350 this.tempFileWriteSuccess = flag;
354 public boolean getWriteSuccess()
356 return this.tempFileWriteSuccess;
359 public boolean renameTempFile()
361 return moveFileToFile(tempFile, file);
364 // roll the backupfiles
365 public boolean rollBackupFiles()
367 return this.rollBackupFiles(true);
370 public boolean rollBackupFiles(boolean tidyUp)
372 // file doesn't yet exist or backups are not enabled or template is null or
374 if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
375 || suffix.length() == 0)
378 Console.debug("BACKUPFILES rollBackupFiles nothing to do." + ", "
379 + "filename: " + (file != null ? file.getName() : "null")
380 + ", " + "file exists: " + file.exists() + ", " + "enabled: "
381 + enabled + ", " + "max: " + max + ", " + "suffix: '" + suffix
386 Console.trace("BACKUPFILES rollBackupFiles starting");
392 dirFile = file.getParentFile();
393 dir = dirFile.getCanonicalPath();
394 Console.trace("BACKUPFILES dir: " + dir);
395 } catch (Exception e)
397 Console.error("Could not get canonical path for file '" + file + "'");
398 Console.error(e.getMessage());
399 Console.debug(Cache.getStackTraceString(e));
402 String filename = file.getName();
403 String basename = filename;
405 Console.trace("BACKUPFILES filename is " + filename);
407 // Create/move backups up one
411 // find existing backup files
412 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
414 File[] backupFiles = dirFile.listFiles(bff);
415 int nextIndexNum = 0;
417 Console.trace("BACKUPFILES backupFiles.length: " + backupFiles.length);
418 if (backupFiles.length == 0)
420 // No other backup files. Just need to move existing file to backupfile_1
422 "BACKUPFILES no existing backup files, setting index to 1");
427 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
428 backupFiles, basename);
429 // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
434 // backup style numbering
435 Console.trace("BACKUPFILES rolling files in reverse order");
437 int tempMax = noMax ? -1 : max;
438 // noMax == true means no limits
439 // look for first "gap" in backupFiles
440 // if tempMax is -1 at this stage just keep going until there's a gap,
441 // then hopefully tempMax gets set to the right index (a positive
442 // integer so the loop breaks)...
443 // why do I feel a little uneasy about this loop?..
444 for (int i = 1; tempMax < 0 || i <= max; i++)
446 if (!bfTreeMap.containsKey(i)) // first index without existent
453 File previousFile = null;
454 File fileToBeDeleted = null;
455 for (int n = tempMax; n > 0; n--)
457 String backupfilename = dir + File.separatorChar
458 + BackupFilenameParts.getBackupFilename(n, basename,
460 File backupfile_n = new File(backupfilename);
462 if (!backupfile_n.exists())
464 // no "oldest" file to delete
465 previousFile = backupfile_n;
466 fileToBeDeleted = null;
467 Console.trace("BACKUPFILES No oldest file to delete");
471 // check the modification time of this (backupfile_n) and the previous
472 // file (fileToBeDeleted) if the previous file is going to be deleted
473 if (fileToBeDeleted != null)
475 File replacementFile = backupfile_n;
476 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
477 long replacementFileLMT = replacementFile.lastModified();
478 Console.trace("BACKUPFILES fileToBeDeleted is "
479 + fileToBeDeleted.getAbsolutePath());
480 Console.trace("BACKUPFILES replacementFile is "
481 + backupfile_n.getAbsolutePath());
485 File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
488 if (fileToBeDeletedLMT > replacementFileLMT)
490 String fileToBeDeletedLMTString = sdf
491 .format(fileToBeDeletedLMT);
492 String replacementFileLMTString = sdf
493 .format(replacementFileLMT);
494 Console.warn("WARNING! I am set to delete backupfile "
495 + fileToBeDeleted.getName()
496 + " has modification time "
497 + fileToBeDeletedLMTString
498 + " which is newer than its replacement "
499 + replacementFile.getName()
500 + " with modification time "
501 + replacementFileLMTString);
503 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
504 replacementFile, true);
505 Console.trace("BACKUPFILES "
506 + (delete ? "confirmed" : "not") + " deleting file "
507 + fileToBeDeleted.getAbsolutePath()
508 + " which is newer than "
509 + replacementFile.getAbsolutePath());
513 // User has confirmed delete -- no need to add it to the list
514 fileToBeDeleted.delete();
518 Console.debug("BACKUPFILES moving "
519 + fileToBeDeleted.getAbsolutePath() + " to "
520 + oldestTempFile.getAbsolutePath());
521 moveFileToFile(fileToBeDeleted, oldestTempFile);
526 Console.debug("BACKUPFILES going to move "
527 + fileToBeDeleted.getAbsolutePath() + " to "
528 + oldestTempFile.getAbsolutePath());
529 moveFileToFile(fileToBeDeleted, oldestTempFile);
530 addDeleteFile(oldestTempFile);
533 } catch (Exception e)
536 "Error occurred, probably making new temp file for '"
537 + fileToBeDeleted.getName() + "'");
538 Console.error(Cache.getStackTraceString(e));
542 fileToBeDeleted = null;
545 if (!noMax && n == tempMax && backupfile_n.exists())
547 fileToBeDeleted = backupfile_n;
551 if (previousFile != null)
553 // using boolean '&' instead of '&&' as don't want moveFileToFile
554 // attempt to be conditional (short-circuit)
555 ret = ret & moveFileToFile(backupfile_n, previousFile);
559 previousFile = backupfile_n;
562 // index to use for the latest backup
565 else // not reverse numbering
567 // version style numbering (with earliest file deletion if max files
570 bfTreeMap.values().toArray(backupFiles);
571 StringBuilder bfsb = new StringBuilder();
572 for (int i = 0; i < backupFiles.length; i++)
574 if (bfsb.length() > 0)
578 bfsb.append(backupFiles[i].getName());
580 Console.trace("BACKUPFILES backupFiles: " + bfsb.toString());
582 // noMax == true means keep all backup files
583 if ((!noMax) && bfTreeMap.size() >= max)
585 Console.trace("BACKUPFILES noMax: " + noMax + ", " + "max: " + max
586 + ", " + "bfTreeMap.size(): " + bfTreeMap.size());
587 // need to delete some files to keep number of backups to designated
589 // Note that if the suffix is not numbered then do not delete any
590 // backup files later or we'll delete the new backup file (there can
592 int numToDelete = suffix.indexOf(NUM_PLACEHOLDER) > -1
593 ? bfTreeMap.size() - max + 1
595 Console.trace("BACKUPFILES numToDelete: " + numToDelete);
596 // the "replacement" file is the latest backup file being kept (it's
597 // not replacing though)
598 File replacementFile = numToDelete < backupFiles.length
599 ? backupFiles[numToDelete]
601 for (int i = 0; i < numToDelete; i++)
603 // check the deletion files for modification time of the last
604 // backupfile being saved
605 File fileToBeDeleted = backupFiles[i];
606 boolean delete = true;
609 "BACKUPFILES fileToBeDeleted: " + fileToBeDeleted);
611 boolean newer = false;
612 if (replacementFile != null)
614 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
615 long replacementFileLMT = replacementFile != null
616 ? replacementFile.lastModified()
618 if (fileToBeDeletedLMT > replacementFileLMT)
620 String fileToBeDeletedLMTString = sdf
621 .format(fileToBeDeletedLMT);
622 String replacementFileLMTString = sdf
623 .format(replacementFileLMT);
625 Console.warn("WARNING! I am set to delete backupfile '"
626 + fileToBeDeleted.getName()
627 + "' has modification time "
628 + fileToBeDeletedLMTString
629 + " which is newer than the oldest backupfile being kept '"
630 + replacementFile.getName()
631 + "' with modification time "
632 + replacementFileLMTString);
634 delete = confirmNewerDeleteFile(fileToBeDeleted,
635 replacementFile, false);
638 // User has confirmed delete -- no need to add it to the list
639 fileToBeDeleted.delete();
640 Console.debug("BACKUPFILES deleting fileToBeDeleted: "
646 // keeping file, nothing to do!
647 Console.debug("BACKUPFILES keeping fileToBeDeleted: "
654 addDeleteFile(fileToBeDeleted);
655 Console.debug("BACKUPFILES addDeleteFile(fileToBeDeleted): "
663 nextIndexNum = bfTreeMap.lastKey() + 1;
667 // Let's make the new backup file!! yay, got there at last!
668 String latestBackupFilename = dir + File.separatorChar
669 + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
671 Console.trace("BACKUPFILES Moving old file [" + file
672 + "] to latestBackupFilename [" + latestBackupFilename + "]");
673 // using boolean '&' instead of '&&' as don't want moveFileToFile attempt to
674 // be conditional (short-circuit)
675 ret = ret & moveFileToFile(file, new File(latestBackupFilename));
677 "BACKUPFILES moving " + file + " to " + latestBackupFilename
678 + " was " + (ret ? "" : "NOT ") + "successful");
681 Console.debug("BACKUPFILES tidying up files");
688 private static File nextTempFile(String filename, File dirFile)
692 COUNT: for (int i = 1; i < 1000; i++)
694 File trythis = new File(dirFile,
695 filename + '~' + Integer.toString(i));
696 if (!trythis.exists())
705 temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
710 private void tidyUpFiles()
715 private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
716 File replacementFile, boolean replace)
718 StringBuilder messageSB = new StringBuilder();
720 File ftbd = fileToBeDeleted;
721 String ftbdLMT = sdf.format(ftbd.lastModified());
722 String ftbdSize = Long.toString(ftbd.length());
724 File rf = replacementFile;
725 String rfLMT = sdf.format(rf.lastModified());
726 String rfSize = Long.toString(rf.length());
728 int confirmButton = JvOptionPane.NO_OPTION;
731 File saveFile = null;
734 saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
735 } catch (Exception e)
738 "Error when confirming to keep backup file newer than other backup files.");
741 messageSB.append(MessageManager.formatMessage(
742 "label.newerdelete_replacement_line", new String[]
743 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
745 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted and
746 // replaced by apparently older file \n''{1}''\t(modified {3}, size
748 messageSB.append("\n\n");
749 messageSB.append(MessageManager.formatMessage(
750 "label.confirm_deletion_or_rename", new String[]
751 { ftbd.getName(), saveFile.getName() }));
752 // "Confirm deletion of ''{0}'' or rename to ''{1}''?"
753 String[] options = new String[] {
754 MessageManager.getString("label.delete"),
755 MessageManager.getString("label.rename") };
757 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
758 : JvOptionPane.showOptionDialog(Desktop.desktop,
759 messageSB.toString(),
760 MessageManager.getString(
761 "label.backupfiles_confirm_delete"),
763 JvOptionPane.YES_NO_OPTION,
764 JvOptionPane.WARNING_MESSAGE, null, options,
769 messageSB.append(MessageManager
770 .formatMessage("label.newerdelete_line", new String[]
771 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
773 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted but
774 // is newer than the oldest remaining backup file \n''{1}''\t(modified
776 messageSB.append("\n\n");
777 messageSB.append(MessageManager
778 .formatMessage("label.confirm_deletion", new String[]
779 { ftbd.getName() }));
780 // "Confirm deletion of ''{0}''?"
781 String[] options = new String[] {
782 MessageManager.getString("label.delete"),
783 MessageManager.getString("label.keep") };
785 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
786 : JvOptionPane.showOptionDialog(Desktop.desktop,
787 messageSB.toString(),
788 MessageManager.getString(
789 "label.backupfiles_confirm_delete"),
791 JvOptionPane.YES_NO_OPTION,
792 JvOptionPane.WARNING_MESSAGE, null, options,
796 // return should be TRUE if file is to be deleted
797 return (confirmButton == JvOptionPane.YES_OPTION);
800 private void deleteOldFiles()
802 if (deleteFiles != null && !deleteFiles.isEmpty())
804 boolean doDelete = false;
805 StringBuilder messageSB = null;
806 if (confirmDelete && deleteFiles.size() > 0)
808 messageSB = new StringBuilder();
809 messageSB.append(MessageManager
810 .getString("label.backupfiles_confirm_delete_old_files"));
811 // "Delete the following older backup files? (see the Backups tab in
812 // Preferences for more options)"
813 for (int i = 0; i < deleteFiles.size(); i++)
815 File df = deleteFiles.get(i);
816 messageSB.append("\n");
817 messageSB.append(df.getName());
818 messageSB.append(" ");
819 messageSB.append(MessageManager.formatMessage("label.file_info",
821 { sdf.format(df.lastModified()),
822 Long.toString(df.length()) }));
823 // "(modified {0}, size {1})"
826 int confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
827 : JvOptionPane.showConfirmDialog(Desktop.desktop,
828 messageSB.toString(),
829 MessageManager.getString(
830 "label.backupfiles_confirm_delete"),
832 JvOptionPane.YES_NO_OPTION,
833 JvOptionPane.WARNING_MESSAGE);
835 doDelete = (confirmButton == JvOptionPane.YES_OPTION);
844 for (int i = 0; i < deleteFiles.size(); i++)
846 File fileToDelete = deleteFiles.get(i);
847 Console.trace("BACKUPFILES about to delete fileToDelete:"
849 fileToDelete.delete();
850 Console.warn("deleted '" + fileToDelete.getName() + "'");
859 private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
860 File[] backupFiles, String basename)
862 // sort the backup files (based on integer found in the suffix) using a
863 // precomputed Hashmap for speed
864 Map<Integer, File> bfHashMap = new HashMap<>();
865 for (int i = 0; i < backupFiles.length; i++)
867 File f = backupFiles[i];
868 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
870 bfHashMap.put(bfp.indexNum(), f);
872 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
873 bfTreeMap.putAll(bfHashMap);
877 public boolean rollBackupsAndRenameTempFile()
879 boolean write = this.getWriteSuccess();
881 boolean roll = false;
882 boolean rename = false;
885 roll = this.rollBackupFiles(false); // tidyUpFiles at the end
886 rename = this.renameTempFile();
890 * Not sure that this confirmation is desirable. By this stage the new file is
891 * already written successfully, but something (e.g. disk full) has happened while
892 * trying to roll the backup files, and most likely the filename needed will already
893 * be vacant so renaming the temp file is nearly always correct!
895 boolean okay = roll && rename;
898 StringBuilder messageSB = new StringBuilder();
899 messageSB.append(MessageManager.getString(
900 "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
901 // "Something possibly went wrong with the backups of this file."
904 if (messageSB.length() > 0)
906 messageSB.append("\n");
908 messageSB.append(MessageManager.getString(
909 "label.backupfiles_confirm_save_new_saved_file_ok"));
910 // "The new saved file seems okay."
914 if (messageSB.length() > 0)
916 messageSB.append("\n");
918 messageSB.append(MessageManager.getString(
919 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
920 // "The new saved file might not be okay."
922 if (messageSB.length() > 0)
924 messageSB.append("\n");
927 .append(MessageManager.getString("label.continue_operation"));
929 int confirmButton = Platform.isHeadless() ? JvOptionPane.OK_OPTION
930 : JvOptionPane.showConfirmDialog(Desktop.desktop,
931 messageSB.toString(),
932 MessageManager.getString(
933 "label.backupfiles_confirm_save_file"),
934 // "Confirm save file"
935 JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
936 okay = confirmButton == JvOptionPane.OK_OPTION;
943 // remove this file from the save in progress stack
944 removeSaveInProgress(rename);
949 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
950 String fileName, String suffix, int digits)
952 File[] backupFiles = null;
954 File file = new File(fileName);
959 dirFile = file.getParentFile();
960 } catch (Exception e)
962 Console.error("Could not get canonical path for file '" + file + "'");
963 return new TreeMap<>();
966 String filename = file.getName();
967 String basename = filename;
969 // find existing backup files
970 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
972 backupFiles = dirFile.listFiles(bff); // is clone needed?
974 // sort the backup files (based on integer found in the suffix) using a
975 // precomputed Hashmap for speed
976 Map<Integer, File> bfHashMap = new HashMap<>();
977 for (int i = 0; i < backupFiles.length; i++)
979 File f = backupFiles[i];
980 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
982 bfHashMap.put(bfp.indexNum(), f);
984 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
985 bfTreeMap.putAll(bfHashMap);
991 private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
992 boolean delete, boolean newer)
994 return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
997 private boolean addDeleteFile(File fileToBeDeleted)
1000 int pos = deleteFiles.indexOf(fileToBeDeleted);
1003 Console.debug("BACKUPFILES not adding file "
1004 + fileToBeDeleted.getAbsolutePath()
1005 + " to the delete list (already at index" + pos + ")");
1010 Console.debug("BACKUPFILES adding file "
1011 + fileToBeDeleted.getAbsolutePath() + " to the delete list");
1012 deleteFiles.add(fileToBeDeleted);
1017 public File getFile()
1022 public static boolean moveFileToFile(File oldFile, File newFile)
1024 Console.initLogger();
1025 boolean ret = false;
1026 Path oldPath = Paths.get(oldFile.getAbsolutePath());
1027 Path newPath = Paths.get(newFile.getAbsolutePath());
1030 // delete destination file - not usually necessary but Just In Case...
1031 Console.trace("BACKUPFILES deleting " + newFile.getAbsolutePath());
1033 Console.trace("BACKUPFILES moving " + oldFile.getAbsolutePath()
1034 + " to " + newFile.getAbsolutePath());
1035 Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
1037 Console.trace("BACKUPFILES move seems to have succeeded");
1038 } catch (IOException e)
1040 Console.warn("Could not move file '" + oldPath.toString() + "' to '"
1041 + newPath.toString() + "'");
1042 Console.error(e.getMessage());
1043 Console.debug(Cache.getStackTraceString(e));
1045 } catch (Exception e)
1047 Console.error(e.getMessage());
1048 Console.debug(Cache.getStackTraceString(e));