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()
169 return savesInProgress.size() > 0;
172 public static List<File> savesInProgressFiles()
174 List<File> files = new ArrayList<>();
175 for (BackupFiles bfile : savesInProgress)
177 files.add(bfile.getFile());
182 public static List<CompletableFuture<Boolean>> savesInProgressCompletableFutures()
184 List<CompletableFuture<Boolean>> cfs = new ArrayList<>();
185 for (BackupFiles bfile : savesInProgress)
187 cfs.add(bfile.getMyFuture());
192 public static Future<Boolean> allSaved()
194 CompletableFuture<Boolean> f = new CompletableFuture<>();
196 executorService.submit(() -> {
197 for (BackupFiles buf : savesInProgress)
199 boolean allSaved = true;
202 allSaved &= buf.getMyFuture().get();
203 } catch (InterruptedException e)
205 Console.debug("InterruptedException waiting for files to save",
207 } catch (ExecutionException e)
209 Console.debug("ExecutionException waiting for files to save", e);
211 f.complete(allSaved);
217 public BackupFiles(String filename)
219 this(new File(filename));
222 // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
224 public BackupFiles(File file)
229 // add this file from the save in progress stack
232 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
233 .getSavedBackupEntry();
234 this.suffix = bfpe.suffix;
235 this.noMax = bfpe.keepAll;
236 this.max = bfpe.rollMax;
237 this.digits = bfpe.digits;
238 this.reverseOrder = bfpe.reverse;
240 // create a temp file to save new data in
246 String tempfilename = file.getName();
247 File tempdir = file.getParentFile();
249 "BACKUPFILES [file!=null] attempting to create temp file for "
250 + tempfilename + " in dir " + tempdir);
251 temp = File.createTempFile(tempfilename,
252 TEMP_FILE_EXT + newTempFileSuffix, tempdir);
254 "BACKUPFILES using temp file " + temp.getAbsolutePath());
259 "BACKUPFILES [file==null] attempting to create default temp file "
260 + DEFAULT_TEMP_FILE + " with extension "
262 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
264 } catch (IOException e)
266 Console.error("Could not create temp file to save to (IOException)");
267 Console.error(e.getMessage());
268 Console.debug(Cache.getStackTraceString(e));
269 } catch (Exception e)
271 Console.error("Exception creating temp file for saving");
272 Console.debug(Cache.getStackTraceString(e));
274 this.setTempFile(temp);
277 public static void classInit()
279 Console.initLogger();
280 Console.trace("BACKUPFILES classInit");
281 boolean e = Cache.getDefault(ENABLED, !Platform.isJS());
283 Console.trace("BACKUPFILES " + (e ? "enabled" : "disabled"));
284 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
285 .getSavedBackupEntry();
286 Console.trace("BACKUPFILES preset scheme " + bfpe.toString());
287 setConfirmDelete(bfpe.confirmDelete);
288 Console.trace("BACKUPFILES confirm delete " + bfpe.confirmDelete);
291 public static void setEnabled(boolean flag)
296 public static boolean getEnabled()
302 public static void setConfirmDelete(boolean flag)
304 confirmDelete = flag;
307 public static boolean getConfirmDelete()
310 return confirmDelete;
313 // set, get and rename temp file into place
314 public void setTempFile(File temp)
316 this.tempFile = temp;
319 public File getTempFile()
324 public String getTempFilePath()
329 path = this.getTempFile().getCanonicalPath();
330 } catch (IOException e)
332 Console.error("IOException when getting Canonical Path of temp file '"
333 + this.getTempFile().getName() + "'");
334 Console.debug(Cache.getStackTraceString(e));
339 public boolean setWriteSuccess(boolean flag)
341 boolean old = this.tempFileWriteSuccess;
342 this.tempFileWriteSuccess = flag;
346 public boolean getWriteSuccess()
348 return this.tempFileWriteSuccess;
351 public boolean renameTempFile()
353 return moveFileToFile(tempFile, file);
356 // roll the backupfiles
357 public boolean rollBackupFiles()
359 return this.rollBackupFiles(true);
362 public boolean rollBackupFiles(boolean tidyUp)
364 // file doesn't yet exist or backups are not enabled or template is null or
366 if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
367 || suffix.length() == 0)
370 Console.debug("BACKUPFILES rollBackupFiles nothing to do." + ", "
371 + "filename: " + (file != null ? file.getName() : "null")
372 + ", " + "file exists: " + file.exists() + ", " + "enabled: "
373 + enabled + ", " + "max: " + max + ", " + "suffix: '" + suffix
378 Console.trace("BACKUPFILES rollBackupFiles starting");
384 dirFile = file.getParentFile();
385 dir = dirFile.getCanonicalPath();
386 Console.trace("BACKUPFILES dir: " + dir);
387 } catch (Exception e)
389 Console.error("Could not get canonical path for file '" + file + "'");
390 Console.error(e.getMessage());
391 Console.debug(Cache.getStackTraceString(e));
394 String filename = file.getName();
395 String basename = filename;
397 Console.trace("BACKUPFILES filename is " + filename);
399 // Create/move backups up one
403 // find existing backup files
404 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
406 File[] backupFiles = dirFile.listFiles(bff);
407 int nextIndexNum = 0;
409 Console.trace("BACKUPFILES backupFiles.length: " + backupFiles.length);
410 if (backupFiles.length == 0)
412 // No other backup files. Just need to move existing file to backupfile_1
414 "BACKUPFILES no existing backup files, setting index to 1");
419 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
420 backupFiles, basename);
421 // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
426 // backup style numbering
427 Console.trace("BACKUPFILES rolling files in reverse order");
429 int tempMax = noMax ? -1 : max;
430 // noMax == true means no limits
431 // look for first "gap" in backupFiles
432 // if tempMax is -1 at this stage just keep going until there's a gap,
433 // then hopefully tempMax gets set to the right index (a positive
434 // integer so the loop breaks)...
435 // why do I feel a little uneasy about this loop?..
436 for (int i = 1; tempMax < 0 || i <= max; i++)
438 if (!bfTreeMap.containsKey(i)) // first index without existent
445 File previousFile = null;
446 File fileToBeDeleted = null;
447 for (int n = tempMax; n > 0; n--)
449 String backupfilename = dir + File.separatorChar
450 + BackupFilenameParts.getBackupFilename(n, basename,
452 File backupfile_n = new File(backupfilename);
454 if (!backupfile_n.exists())
456 // no "oldest" file to delete
457 previousFile = backupfile_n;
458 fileToBeDeleted = null;
459 Console.trace("BACKUPFILES No oldest file to delete");
463 // check the modification time of this (backupfile_n) and the previous
464 // file (fileToBeDeleted) if the previous file is going to be deleted
465 if (fileToBeDeleted != null)
467 File replacementFile = backupfile_n;
468 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
469 long replacementFileLMT = replacementFile.lastModified();
470 Console.trace("BACKUPFILES fileToBeDeleted is "
471 + fileToBeDeleted.getAbsolutePath());
472 Console.trace("BACKUPFILES replacementFile is "
473 + backupfile_n.getAbsolutePath());
477 File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
480 if (fileToBeDeletedLMT > replacementFileLMT)
482 String fileToBeDeletedLMTString = sdf
483 .format(fileToBeDeletedLMT);
484 String replacementFileLMTString = sdf
485 .format(replacementFileLMT);
486 Console.warn("WARNING! I am set to delete backupfile "
487 + fileToBeDeleted.getName()
488 + " has modification time "
489 + fileToBeDeletedLMTString
490 + " which is newer than its replacement "
491 + replacementFile.getName()
492 + " with modification time "
493 + replacementFileLMTString);
495 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
496 replacementFile, true);
497 Console.trace("BACKUPFILES "
498 + (delete ? "confirmed" : "not") + " deleting file "
499 + fileToBeDeleted.getAbsolutePath()
500 + " which is newer than "
501 + replacementFile.getAbsolutePath());
505 // User has confirmed delete -- no need to add it to the list
506 fileToBeDeleted.delete();
510 Console.debug("BACKUPFILES moving "
511 + fileToBeDeleted.getAbsolutePath() + " to "
512 + oldestTempFile.getAbsolutePath());
513 moveFileToFile(fileToBeDeleted, oldestTempFile);
518 Console.debug("BACKUPFILES going to move "
519 + fileToBeDeleted.getAbsolutePath() + " to "
520 + oldestTempFile.getAbsolutePath());
521 moveFileToFile(fileToBeDeleted, oldestTempFile);
522 addDeleteFile(oldestTempFile);
525 } catch (Exception e)
528 "Error occurred, probably making new temp file for '"
529 + fileToBeDeleted.getName() + "'");
530 Console.error(Cache.getStackTraceString(e));
534 fileToBeDeleted = null;
537 if (!noMax && n == tempMax && backupfile_n.exists())
539 fileToBeDeleted = backupfile_n;
543 if (previousFile != null)
545 // using boolean '&' instead of '&&' as don't want moveFileToFile
546 // attempt to be conditional (short-circuit)
547 ret = ret & moveFileToFile(backupfile_n, previousFile);
551 previousFile = backupfile_n;
554 // index to use for the latest backup
557 else // not reverse numbering
559 // version style numbering (with earliest file deletion if max files
562 bfTreeMap.values().toArray(backupFiles);
563 StringBuilder bfsb = new StringBuilder();
564 for (int i = 0; i < backupFiles.length; i++)
566 if (bfsb.length() > 0)
570 bfsb.append(backupFiles[i].getName());
572 Console.trace("BACKUPFILES backupFiles: " + bfsb.toString());
574 // noMax == true means keep all backup files
575 if ((!noMax) && bfTreeMap.size() >= max)
577 Console.trace("BACKUPFILES noMax: " + noMax + ", " + "max: " + max
578 + ", " + "bfTreeMap.size(): " + bfTreeMap.size());
579 // need to delete some files to keep number of backups to designated
581 // Note that if the suffix is not numbered then do not delete any
582 // backup files later or we'll delete the new backup file (there can
584 int numToDelete = suffix.indexOf(NUM_PLACEHOLDER) > -1
585 ? bfTreeMap.size() - max + 1
587 Console.trace("BACKUPFILES numToDelete: " + numToDelete);
588 // the "replacement" file is the latest backup file being kept (it's
589 // not replacing though)
590 File replacementFile = numToDelete < backupFiles.length
591 ? backupFiles[numToDelete]
593 for (int i = 0; i < numToDelete; i++)
595 // check the deletion files for modification time of the last
596 // backupfile being saved
597 File fileToBeDeleted = backupFiles[i];
598 boolean delete = true;
601 "BACKUPFILES fileToBeDeleted: " + fileToBeDeleted);
603 boolean newer = false;
604 if (replacementFile != null)
606 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
607 long replacementFileLMT = replacementFile != null
608 ? replacementFile.lastModified()
610 if (fileToBeDeletedLMT > replacementFileLMT)
612 String fileToBeDeletedLMTString = sdf
613 .format(fileToBeDeletedLMT);
614 String replacementFileLMTString = sdf
615 .format(replacementFileLMT);
617 Console.warn("WARNING! I am set to delete backupfile '"
618 + fileToBeDeleted.getName()
619 + "' has modification time "
620 + fileToBeDeletedLMTString
621 + " which is newer than the oldest backupfile being kept '"
622 + replacementFile.getName()
623 + "' with modification time "
624 + replacementFileLMTString);
626 delete = confirmNewerDeleteFile(fileToBeDeleted,
627 replacementFile, false);
630 // User has confirmed delete -- no need to add it to the list
631 fileToBeDeleted.delete();
632 Console.debug("BACKUPFILES deleting fileToBeDeleted: "
638 // keeping file, nothing to do!
639 Console.debug("BACKUPFILES keeping fileToBeDeleted: "
646 addDeleteFile(fileToBeDeleted);
647 Console.debug("BACKUPFILES addDeleteFile(fileToBeDeleted): "
655 nextIndexNum = bfTreeMap.lastKey() + 1;
659 // Let's make the new backup file!! yay, got there at last!
660 String latestBackupFilename = dir + File.separatorChar
661 + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
663 Console.trace("BACKUPFILES Moving old file [" + file
664 + "] to latestBackupFilename [" + latestBackupFilename + "]");
665 // using boolean '&' instead of '&&' as don't want moveFileToFile attempt to
666 // be conditional (short-circuit)
667 ret = ret & moveFileToFile(file, new File(latestBackupFilename));
669 "BACKUPFILES moving " + file + " to " + latestBackupFilename
670 + " was " + (ret ? "" : "NOT ") + "successful");
673 Console.debug("BACKUPFILES tidying up files");
680 private static File nextTempFile(String filename, File dirFile)
684 COUNT: for (int i = 1; i < 1000; i++)
686 File trythis = new File(dirFile,
687 filename + '~' + Integer.toString(i));
688 if (!trythis.exists())
697 temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
702 private void tidyUpFiles()
707 private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
708 File replacementFile, boolean replace)
710 StringBuilder messageSB = new StringBuilder();
712 File ftbd = fileToBeDeleted;
713 String ftbdLMT = sdf.format(ftbd.lastModified());
714 String ftbdSize = Long.toString(ftbd.length());
716 File rf = replacementFile;
717 String rfLMT = sdf.format(rf.lastModified());
718 String rfSize = Long.toString(rf.length());
720 int confirmButton = JvOptionPane.NO_OPTION;
723 File saveFile = null;
726 saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
727 } catch (Exception e)
730 "Error when confirming to keep backup file newer than other backup files.");
733 messageSB.append(MessageManager.formatMessage(
734 "label.newerdelete_replacement_line", new String[]
735 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
737 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted and
738 // replaced by apparently older file \n''{1}''\t(modified {3}, size
740 messageSB.append("\n\n");
741 messageSB.append(MessageManager.formatMessage(
742 "label.confirm_deletion_or_rename", new String[]
743 { ftbd.getName(), saveFile.getName() }));
744 // "Confirm deletion of ''{0}'' or rename to ''{1}''?"
745 String[] options = new String[] {
746 MessageManager.getString("label.delete"),
747 MessageManager.getString("label.rename") };
749 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
750 : JvOptionPane.showOptionDialog(Desktop.desktop,
751 messageSB.toString(),
752 MessageManager.getString(
753 "label.backupfiles_confirm_delete"),
755 JvOptionPane.YES_NO_OPTION,
756 JvOptionPane.WARNING_MESSAGE, null, options,
761 messageSB.append(MessageManager
762 .formatMessage("label.newerdelete_line", new String[]
763 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
765 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted but
766 // is newer than the oldest remaining backup file \n''{1}''\t(modified
768 messageSB.append("\n\n");
769 messageSB.append(MessageManager
770 .formatMessage("label.confirm_deletion", new String[]
771 { ftbd.getName() }));
772 // "Confirm deletion of ''{0}''?"
773 String[] options = new String[] {
774 MessageManager.getString("label.delete"),
775 MessageManager.getString("label.keep") };
777 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
778 : JvOptionPane.showOptionDialog(Desktop.desktop,
779 messageSB.toString(),
780 MessageManager.getString(
781 "label.backupfiles_confirm_delete"),
783 JvOptionPane.YES_NO_OPTION,
784 JvOptionPane.WARNING_MESSAGE, null, options,
788 // return should be TRUE if file is to be deleted
789 return (confirmButton == JvOptionPane.YES_OPTION);
792 private void deleteOldFiles()
794 if (deleteFiles != null && !deleteFiles.isEmpty())
796 boolean doDelete = false;
797 StringBuilder messageSB = null;
798 if (confirmDelete && deleteFiles.size() > 0)
800 messageSB = new StringBuilder();
801 messageSB.append(MessageManager
802 .getString("label.backupfiles_confirm_delete_old_files"));
803 // "Delete the following older backup files? (see the Backups tab in
804 // Preferences for more options)"
805 for (int i = 0; i < deleteFiles.size(); i++)
807 File df = deleteFiles.get(i);
808 messageSB.append("\n");
809 messageSB.append(df.getName());
810 messageSB.append(" ");
811 messageSB.append(MessageManager.formatMessage("label.file_info",
813 { sdf.format(df.lastModified()),
814 Long.toString(df.length()) }));
815 // "(modified {0}, size {1})"
818 int confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
819 : JvOptionPane.showConfirmDialog(Desktop.desktop,
820 messageSB.toString(),
821 MessageManager.getString(
822 "label.backupfiles_confirm_delete"),
824 JvOptionPane.YES_NO_OPTION,
825 JvOptionPane.WARNING_MESSAGE);
827 doDelete = (confirmButton == JvOptionPane.YES_OPTION);
836 for (int i = 0; i < deleteFiles.size(); i++)
838 File fileToDelete = deleteFiles.get(i);
839 Console.trace("BACKUPFILES about to delete fileToDelete:"
841 fileToDelete.delete();
842 Console.warn("deleted '" + fileToDelete.getName() + "'");
851 private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
852 File[] backupFiles, String basename)
854 // sort the backup files (based on integer found in the suffix) using a
855 // precomputed Hashmap for speed
856 Map<Integer, File> bfHashMap = new HashMap<>();
857 for (int i = 0; i < backupFiles.length; i++)
859 File f = backupFiles[i];
860 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
862 bfHashMap.put(bfp.indexNum(), f);
864 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
865 bfTreeMap.putAll(bfHashMap);
869 public boolean rollBackupsAndRenameTempFile()
871 boolean write = this.getWriteSuccess();
873 boolean roll = false;
874 boolean rename = false;
877 roll = this.rollBackupFiles(false); // tidyUpFiles at the end
878 rename = this.renameTempFile();
882 * Not sure that this confirmation is desirable. By this stage the new file is
883 * already written successfully, but something (e.g. disk full) has happened while
884 * trying to roll the backup files, and most likely the filename needed will already
885 * be vacant so renaming the temp file is nearly always correct!
887 boolean okay = roll && rename;
890 StringBuilder messageSB = new StringBuilder();
891 messageSB.append(MessageManager.getString(
892 "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
893 // "Something possibly went wrong with the backups of this file."
896 if (messageSB.length() > 0)
898 messageSB.append("\n");
900 messageSB.append(MessageManager.getString(
901 "label.backupfiles_confirm_save_new_saved_file_ok"));
902 // "The new saved file seems okay."
906 if (messageSB.length() > 0)
908 messageSB.append("\n");
910 messageSB.append(MessageManager.getString(
911 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
912 // "The new saved file might not be okay."
914 if (messageSB.length() > 0)
916 messageSB.append("\n");
919 .append(MessageManager.getString("label.continue_operation"));
921 int confirmButton = Platform.isHeadless() ? JvOptionPane.OK_OPTION
922 : JvOptionPane.showConfirmDialog(Desktop.desktop,
923 messageSB.toString(),
924 MessageManager.getString(
925 "label.backupfiles_confirm_save_file"),
926 // "Confirm save file"
927 JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
928 okay = confirmButton == JvOptionPane.OK_OPTION;
935 // remove this file from the save in progress stack
936 removeSaveInProgress(rename);
941 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
942 String fileName, String suffix, int digits)
944 File[] backupFiles = null;
946 File file = new File(fileName);
951 dirFile = file.getParentFile();
952 } catch (Exception e)
954 Console.error("Could not get canonical path for file '" + file + "'");
955 return new TreeMap<>();
958 String filename = file.getName();
959 String basename = filename;
961 // find existing backup files
962 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
964 backupFiles = dirFile.listFiles(bff); // is clone needed?
966 // sort the backup files (based on integer found in the suffix) using a
967 // precomputed Hashmap for speed
968 Map<Integer, File> bfHashMap = new HashMap<>();
969 for (int i = 0; i < backupFiles.length; i++)
971 File f = backupFiles[i];
972 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
974 bfHashMap.put(bfp.indexNum(), f);
976 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
977 bfTreeMap.putAll(bfHashMap);
983 private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
984 boolean delete, boolean newer)
986 return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
989 private boolean addDeleteFile(File fileToBeDeleted)
992 int pos = deleteFiles.indexOf(fileToBeDeleted);
995 Console.debug("BACKUPFILES not adding file "
996 + fileToBeDeleted.getAbsolutePath()
997 + " to the delete list (already at index" + pos + ")");
1002 Console.debug("BACKUPFILES adding file "
1003 + fileToBeDeleted.getAbsolutePath() + " to the delete list");
1004 deleteFiles.add(fileToBeDeleted);
1009 public File getFile()
1014 public static boolean moveFileToFile(File oldFile, File newFile)
1016 Console.initLogger();
1017 boolean ret = false;
1018 Path oldPath = Paths.get(oldFile.getAbsolutePath());
1019 Path newPath = Paths.get(newFile.getAbsolutePath());
1022 // delete destination file - not usually necessary but Just In Case...
1023 Console.trace("BACKUPFILES deleting " + newFile.getAbsolutePath());
1025 Console.trace("BACKUPFILES moving " + oldFile.getAbsolutePath()
1026 + " to " + newFile.getAbsolutePath());
1027 Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
1029 Console.trace("BACKUPFILES move seems to have succeeded");
1030 } catch (IOException e)
1032 Console.warn("Could not move file '" + oldPath.toString() + "' to '"
1033 + newPath.toString() + "'");
1034 Console.error(e.getMessage());
1035 Console.debug(Cache.getStackTraceString(e));
1037 } catch (Exception e)
1039 Console.error(e.getMessage());
1040 Console.debug(Cache.getStackTraceString(e));