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
239 file = file.getAbsoluteFile();
243 // add this file from the save in progress stack
246 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
247 .getSavedBackupEntry();
248 this.suffix = bfpe.suffix;
249 this.noMax = bfpe.keepAll;
250 this.max = bfpe.rollMax;
251 this.digits = bfpe.digits;
252 this.reverseOrder = bfpe.reverse;
254 // create a temp file to save new data in
260 String tempfilename = file.getName();
261 File tempdir = file.getAbsoluteFile().getParentFile();
264 "BACKUPFILES [file!=null] attempting to create temp file for "
265 + tempfilename + " in dir " + tempdir);
266 temp = File.createTempFile(tempfilename,
267 TEMP_FILE_EXT + newTempFileSuffix, tempdir);
269 "BACKUPFILES using temp file " + temp.getAbsolutePath());
274 "BACKUPFILES [file==null] attempting to create default temp file "
275 + DEFAULT_TEMP_FILE + " with extension "
277 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
279 } catch (IOException e)
281 Console.error("Could not create temp file to save to (IOException)");
282 Console.error(e.getMessage());
283 Console.debug(Cache.getStackTraceString(e));
284 } catch (Exception e)
286 Console.error("Exception creating temp file for saving");
287 Console.debug(Cache.getStackTraceString(e));
289 this.setTempFile(temp);
292 private static void classInit()
294 Console.initLogger();
295 Console.trace("BACKUPFILES classInit");
296 boolean e = Cache.getDefault(ENABLED, !Platform.isJS());
298 Console.trace("BACKUPFILES " + (e ? "enabled" : "disabled"));
299 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
300 .getSavedBackupEntry();
301 Console.trace("BACKUPFILES preset scheme " + bfpe.toString());
302 setConfirmDelete(bfpe.confirmDelete);
303 Console.trace("BACKUPFILES confirm delete " + bfpe.confirmDelete);
306 public static void setEnabled(boolean flag)
311 public static boolean getEnabled()
317 public static void setConfirmDelete(boolean flag)
319 confirmDelete = flag;
322 public static boolean getConfirmDelete()
325 return confirmDelete;
328 // set, get and rename temp file into place
329 public void setTempFile(File temp)
331 this.tempFile = temp;
334 public File getTempFile()
339 public String getTempFilePath()
344 path = this.getTempFile().getCanonicalPath();
345 } catch (IOException e)
347 Console.error("IOException when getting Canonical Path of temp file '"
348 + this.getTempFile().getName() + "'");
349 Console.debug(Cache.getStackTraceString(e));
354 public boolean setWriteSuccess(boolean flag)
356 boolean old = this.tempFileWriteSuccess;
357 this.tempFileWriteSuccess = flag;
361 public boolean getWriteSuccess()
363 return this.tempFileWriteSuccess;
366 public boolean renameTempFile()
368 return moveFileToFile(tempFile, file);
371 // roll the backupfiles
372 public boolean rollBackupFiles()
374 return this.rollBackupFiles(true);
377 public boolean rollBackupFiles(boolean tidyUp)
379 // file doesn't yet exist or backups are not enabled or template is null or
381 if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
382 || suffix.length() == 0)
385 Console.debug("BACKUPFILES rollBackupFiles nothing to do." + ", "
386 + "filename: " + (file != null ? file.getName() : "null")
387 + ", " + "file exists: " + file.exists() + ", " + "enabled: "
388 + enabled + ", " + "max: " + max + ", " + "suffix: '" + suffix
393 Console.trace("BACKUPFILES rollBackupFiles starting");
399 dirFile = file.getParentFile();
400 dir = dirFile.getCanonicalPath();
401 Console.trace("BACKUPFILES dir: " + dir);
402 } catch (Exception e)
404 Console.error("Could not get canonical path for file '" + file + "'");
405 Console.error(e.getMessage());
406 Console.debug(Cache.getStackTraceString(e));
409 String filename = file.getName();
410 String basename = filename;
412 Console.trace("BACKUPFILES filename is " + filename);
414 // Create/move backups up one
418 // find existing backup files
419 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
421 File[] backupFiles = dirFile.listFiles(bff);
422 int nextIndexNum = 0;
424 Console.trace("BACKUPFILES backupFiles.length: " + backupFiles.length);
425 if (backupFiles.length == 0)
427 // No other backup files. Just need to move existing file to backupfile_1
429 "BACKUPFILES no existing backup files, setting index to 1");
434 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
435 backupFiles, basename);
436 // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
441 // backup style numbering
442 Console.trace("BACKUPFILES rolling files in reverse order");
444 int tempMax = noMax ? -1 : max;
445 // noMax == true means no limits
446 // look for first "gap" in backupFiles
447 // if tempMax is -1 at this stage just keep going until there's a gap,
448 // then hopefully tempMax gets set to the right index (a positive
449 // integer so the loop breaks)...
450 // why do I feel a little uneasy about this loop?..
451 for (int i = 1; tempMax < 0 || i <= max; i++)
453 if (!bfTreeMap.containsKey(i)) // first index without existent
460 File previousFile = null;
461 File fileToBeDeleted = null;
462 for (int n = tempMax; n > 0; n--)
464 String backupfilename = dir + File.separatorChar
465 + BackupFilenameParts.getBackupFilename(n, basename,
467 File backupfile_n = new File(backupfilename);
469 if (!backupfile_n.exists())
471 // no "oldest" file to delete
472 previousFile = backupfile_n;
473 fileToBeDeleted = null;
474 Console.trace("BACKUPFILES No oldest file to delete");
478 // check the modification time of this (backupfile_n) and the previous
479 // file (fileToBeDeleted) if the previous file is going to be deleted
480 if (fileToBeDeleted != null)
482 File replacementFile = backupfile_n;
483 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
484 long replacementFileLMT = replacementFile.lastModified();
485 Console.trace("BACKUPFILES fileToBeDeleted is "
486 + fileToBeDeleted.getAbsolutePath());
487 Console.trace("BACKUPFILES replacementFile is "
488 + backupfile_n.getAbsolutePath());
492 File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
495 if (fileToBeDeletedLMT > replacementFileLMT)
497 String fileToBeDeletedLMTString = sdf
498 .format(fileToBeDeletedLMT);
499 String replacementFileLMTString = sdf
500 .format(replacementFileLMT);
501 Console.warn("WARNING! I am set to delete backupfile "
502 + fileToBeDeleted.getName()
503 + " has modification time "
504 + fileToBeDeletedLMTString
505 + " which is newer than its replacement "
506 + replacementFile.getName()
507 + " with modification time "
508 + replacementFileLMTString);
510 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
511 replacementFile, true);
512 Console.trace("BACKUPFILES "
513 + (delete ? "confirmed" : "not") + " deleting file "
514 + fileToBeDeleted.getAbsolutePath()
515 + " which is newer than "
516 + replacementFile.getAbsolutePath());
520 // User has confirmed delete -- no need to add it to the list
521 fileToBeDeleted.delete();
525 Console.debug("BACKUPFILES moving "
526 + fileToBeDeleted.getAbsolutePath() + " to "
527 + oldestTempFile.getAbsolutePath());
528 moveFileToFile(fileToBeDeleted, oldestTempFile);
533 Console.debug("BACKUPFILES going to move "
534 + fileToBeDeleted.getAbsolutePath() + " to "
535 + oldestTempFile.getAbsolutePath());
536 moveFileToFile(fileToBeDeleted, oldestTempFile);
537 addDeleteFile(oldestTempFile);
540 } catch (Exception e)
543 "Error occurred, probably making new temp file for '"
544 + fileToBeDeleted.getName() + "'");
545 Console.error(Cache.getStackTraceString(e));
549 fileToBeDeleted = null;
552 if (!noMax && n == tempMax && backupfile_n.exists())
554 fileToBeDeleted = backupfile_n;
558 if (previousFile != null)
560 // using boolean '&' instead of '&&' as don't want moveFileToFile
561 // attempt to be conditional (short-circuit)
562 ret = ret & moveFileToFile(backupfile_n, previousFile);
566 previousFile = backupfile_n;
569 // index to use for the latest backup
572 else // not reverse numbering
574 // version style numbering (with earliest file deletion if max files
577 bfTreeMap.values().toArray(backupFiles);
578 StringBuilder bfsb = new StringBuilder();
579 for (int i = 0; i < backupFiles.length; i++)
581 if (bfsb.length() > 0)
585 bfsb.append(backupFiles[i].getName());
587 Console.trace("BACKUPFILES backupFiles: " + bfsb.toString());
589 // noMax == true means keep all backup files
590 if ((!noMax) && bfTreeMap.size() >= max)
592 Console.trace("BACKUPFILES noMax: " + noMax + ", " + "max: " + max
593 + ", " + "bfTreeMap.size(): " + bfTreeMap.size());
594 // need to delete some files to keep number of backups to designated
596 // Note that if the suffix is not numbered then do not delete any
597 // backup files later or we'll delete the new backup file (there can
599 int numToDelete = suffix.indexOf(NUM_PLACEHOLDER) > -1
600 ? bfTreeMap.size() - max + 1
602 Console.trace("BACKUPFILES numToDelete: " + numToDelete);
603 // the "replacement" file is the latest backup file being kept (it's
604 // not replacing though)
605 File replacementFile = numToDelete < backupFiles.length
606 ? backupFiles[numToDelete]
608 for (int i = 0; i < numToDelete; i++)
610 // check the deletion files for modification time of the last
611 // backupfile being saved
612 File fileToBeDeleted = backupFiles[i];
613 boolean delete = true;
616 "BACKUPFILES fileToBeDeleted: " + fileToBeDeleted);
618 boolean newer = false;
619 if (replacementFile != null)
621 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
622 long replacementFileLMT = replacementFile != null
623 ? replacementFile.lastModified()
625 if (fileToBeDeletedLMT > replacementFileLMT)
627 String fileToBeDeletedLMTString = sdf
628 .format(fileToBeDeletedLMT);
629 String replacementFileLMTString = sdf
630 .format(replacementFileLMT);
632 Console.warn("WARNING! I am set to delete backupfile '"
633 + fileToBeDeleted.getName()
634 + "' has modification time "
635 + fileToBeDeletedLMTString
636 + " which is newer than the oldest backupfile being kept '"
637 + replacementFile.getName()
638 + "' with modification time "
639 + replacementFileLMTString);
641 delete = confirmNewerDeleteFile(fileToBeDeleted,
642 replacementFile, false);
645 // User has confirmed delete -- no need to add it to the list
646 fileToBeDeleted.delete();
647 Console.debug("BACKUPFILES deleting fileToBeDeleted: "
653 // keeping file, nothing to do!
654 Console.debug("BACKUPFILES keeping fileToBeDeleted: "
661 addDeleteFile(fileToBeDeleted);
662 Console.debug("BACKUPFILES addDeleteFile(fileToBeDeleted): "
670 nextIndexNum = bfTreeMap.lastKey() + 1;
674 // Let's make the new backup file!! yay, got there at last!
675 String latestBackupFilename = dir + File.separatorChar
676 + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
678 Console.trace("BACKUPFILES Moving old file [" + file
679 + "] to latestBackupFilename [" + latestBackupFilename + "]");
680 // using boolean '&' instead of '&&' as don't want moveFileToFile attempt to
681 // be conditional (short-circuit)
682 ret = ret & moveFileToFile(file, new File(latestBackupFilename));
684 "BACKUPFILES moving " + file + " to " + latestBackupFilename
685 + " was " + (ret ? "" : "NOT ") + "successful");
688 Console.debug("BACKUPFILES tidying up files");
695 private static File nextTempFile(String filename, File dirFile)
699 COUNT: for (int i = 1; i < 1000; i++)
701 File trythis = new File(dirFile,
702 filename + '~' + Integer.toString(i));
703 if (!trythis.exists())
712 temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
717 private void tidyUpFiles()
722 private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
723 File replacementFile, boolean replace)
725 StringBuilder messageSB = new StringBuilder();
727 File ftbd = fileToBeDeleted;
728 String ftbdLMT = sdf.format(ftbd.lastModified());
729 String ftbdSize = Long.toString(ftbd.length());
731 File rf = replacementFile;
732 String rfLMT = sdf.format(rf.lastModified());
733 String rfSize = Long.toString(rf.length());
735 int confirmButton = JvOptionPane.NO_OPTION;
738 File saveFile = null;
741 saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
742 } catch (Exception e)
745 "Error when confirming to keep backup file newer than other backup files.");
748 messageSB.append(MessageManager.formatMessage(
749 "label.newerdelete_replacement_line", new String[]
750 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
752 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted and
753 // replaced by apparently older file \n''{1}''\t(modified {3}, size
755 messageSB.append("\n\n");
756 messageSB.append(MessageManager.formatMessage(
757 "label.confirm_deletion_or_rename", new String[]
758 { ftbd.getName(), saveFile.getName() }));
759 // "Confirm deletion of ''{0}'' or rename to ''{1}''?"
760 String[] options = new String[] {
761 MessageManager.getString("label.delete"),
762 MessageManager.getString("label.rename") };
764 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
765 : JvOptionPane.showOptionDialog(Desktop.desktop,
766 messageSB.toString(),
767 MessageManager.getString(
768 "label.backupfiles_confirm_delete"),
770 JvOptionPane.YES_NO_OPTION,
771 JvOptionPane.WARNING_MESSAGE, null, options,
776 messageSB.append(MessageManager
777 .formatMessage("label.newerdelete_line", new String[]
778 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
780 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted but
781 // is newer than the oldest remaining backup file \n''{1}''\t(modified
783 messageSB.append("\n\n");
784 messageSB.append(MessageManager
785 .formatMessage("label.confirm_deletion", new String[]
786 { ftbd.getName() }));
787 // "Confirm deletion of ''{0}''?"
788 String[] options = new String[] {
789 MessageManager.getString("label.delete"),
790 MessageManager.getString("label.keep") };
792 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
793 : JvOptionPane.showOptionDialog(Desktop.desktop,
794 messageSB.toString(),
795 MessageManager.getString(
796 "label.backupfiles_confirm_delete"),
798 JvOptionPane.YES_NO_OPTION,
799 JvOptionPane.WARNING_MESSAGE, null, options,
803 // return should be TRUE if file is to be deleted
804 return (confirmButton == JvOptionPane.YES_OPTION);
807 private void deleteOldFiles()
809 if (deleteFiles != null && !deleteFiles.isEmpty())
811 boolean doDelete = false;
812 StringBuilder messageSB = null;
813 if (confirmDelete && deleteFiles.size() > 0)
815 messageSB = new StringBuilder();
816 messageSB.append(MessageManager
817 .getString("label.backupfiles_confirm_delete_old_files"));
818 // "Delete the following older backup files? (see the Backups tab in
819 // Preferences for more options)"
820 for (int i = 0; i < deleteFiles.size(); i++)
822 File df = deleteFiles.get(i);
823 messageSB.append("\n");
824 messageSB.append(df.getName());
825 messageSB.append(" ");
826 messageSB.append(MessageManager.formatMessage("label.file_info",
828 { sdf.format(df.lastModified()),
829 Long.toString(df.length()) }));
830 // "(modified {0}, size {1})"
833 int confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
834 : JvOptionPane.showConfirmDialog(Desktop.desktop,
835 messageSB.toString(),
836 MessageManager.getString(
837 "label.backupfiles_confirm_delete"),
839 JvOptionPane.YES_NO_OPTION,
840 JvOptionPane.WARNING_MESSAGE);
842 doDelete = (confirmButton == JvOptionPane.YES_OPTION);
851 for (int i = 0; i < deleteFiles.size(); i++)
853 File fileToDelete = deleteFiles.get(i);
854 Console.trace("BACKUPFILES about to delete fileToDelete:"
856 fileToDelete.delete();
857 Console.warn("deleted '" + fileToDelete.getName() + "'");
866 private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
867 File[] backupFiles, String basename)
869 // sort the backup files (based on integer found in the suffix) using a
870 // precomputed Hashmap for speed
871 Map<Integer, File> bfHashMap = new HashMap<>();
872 for (int i = 0; i < backupFiles.length; i++)
874 File f = backupFiles[i];
875 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
877 bfHashMap.put(bfp.indexNum(), f);
879 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
880 bfTreeMap.putAll(bfHashMap);
884 public boolean rollBackupsAndRenameTempFile()
886 boolean write = this.getWriteSuccess();
888 boolean roll = false;
889 boolean rename = false;
892 roll = this.rollBackupFiles(false); // tidyUpFiles at the end
893 rename = this.renameTempFile();
897 * Not sure that this confirmation is desirable. By this stage the new file is
898 * already written successfully, but something (e.g. disk full) has happened while
899 * trying to roll the backup files, and most likely the filename needed will already
900 * be vacant so renaming the temp file is nearly always correct!
902 boolean okay = roll && rename;
905 StringBuilder messageSB = new StringBuilder();
906 messageSB.append(MessageManager.getString(
907 "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
908 // "Something possibly went wrong with the backups of this file."
911 if (messageSB.length() > 0)
913 messageSB.append("\n");
915 messageSB.append(MessageManager.getString(
916 "label.backupfiles_confirm_save_new_saved_file_ok"));
917 // "The new saved file seems okay."
921 if (messageSB.length() > 0)
923 messageSB.append("\n");
925 messageSB.append(MessageManager.getString(
926 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
927 // "The new saved file might not be okay."
929 if (messageSB.length() > 0)
931 messageSB.append("\n");
934 .append(MessageManager.getString("label.continue_operation"));
936 int confirmButton = Platform.isHeadless() ? JvOptionPane.OK_OPTION
937 : JvOptionPane.showConfirmDialog(Desktop.desktop,
938 messageSB.toString(),
939 MessageManager.getString(
940 "label.backupfiles_confirm_save_file"),
941 // "Confirm save file"
942 JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
943 okay = confirmButton == JvOptionPane.OK_OPTION;
950 // remove this file from the save in progress stack
951 removeSaveInProgress(rename);
956 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
957 String fileName, String suffix, int digits)
959 File[] backupFiles = null;
961 File file = new File(fileName);
966 dirFile = file.getParentFile();
967 } catch (Exception e)
969 Console.error("Could not get canonical path for file '" + file + "'");
970 return new TreeMap<>();
973 String filename = file.getName();
974 String basename = filename;
976 // find existing backup files
977 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
979 backupFiles = dirFile.listFiles(bff); // is clone needed?
981 // sort the backup files (based on integer found in the suffix) using a
982 // precomputed Hashmap for speed
983 Map<Integer, File> bfHashMap = new HashMap<>();
984 for (int i = 0; i < backupFiles.length; i++)
986 File f = backupFiles[i];
987 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
989 bfHashMap.put(bfp.indexNum(), f);
991 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
992 bfTreeMap.putAll(bfHashMap);
998 private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
999 boolean delete, boolean newer)
1001 return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
1004 private boolean addDeleteFile(File fileToBeDeleted)
1006 boolean ret = false;
1007 int pos = deleteFiles.indexOf(fileToBeDeleted);
1010 Console.debug("BACKUPFILES not adding file "
1011 + fileToBeDeleted.getAbsolutePath()
1012 + " to the delete list (already at index" + pos + ")");
1017 Console.debug("BACKUPFILES adding file "
1018 + fileToBeDeleted.getAbsolutePath() + " to the delete list");
1019 deleteFiles.add(fileToBeDeleted);
1024 public File getFile()
1029 public static boolean moveFileToFile(File oldFile, File newFile)
1031 Console.initLogger();
1032 boolean ret = false;
1033 Path oldPath = Paths.get(oldFile.getAbsolutePath());
1034 Path newPath = Paths.get(newFile.getAbsolutePath());
1037 // delete destination file - not usually necessary but Just In Case...
1038 Console.trace("BACKUPFILES deleting " + newFile.getAbsolutePath());
1040 Console.trace("BACKUPFILES moving " + oldFile.getAbsolutePath()
1041 + " to " + newFile.getAbsolutePath());
1042 Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
1044 Console.trace("BACKUPFILES move seems to have succeeded");
1045 } catch (IOException e)
1047 Console.warn("Could not move file '" + oldPath.toString() + "' to '"
1048 + newPath.toString() + "'");
1049 Console.error(e.getMessage());
1050 Console.debug(Cache.getStackTraceString(e));
1052 } catch (Exception e)
1054 Console.error(e.getMessage());
1055 Console.debug(Cache.getStackTraceString(e));