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;
33 import java.util.TreeMap;
35 import jalview.bin.Cache;
36 import jalview.gui.Desktop;
37 import jalview.gui.JvOptionPane;
38 import jalview.util.MessageManager;
39 import jalview.util.Platform;
42 * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
43 * User configurable options are:
44 * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved.
45 * The rest of the options are now saved as BACKUPFILES_PRESET, BACKUPFILES_SAVED and BACKUPFILES_CUSTOM
46 * (see BackupFilesPresetEntry)
49 public class BackupFiles
52 // labels for saved params in Cache and .jalview_properties
53 public static final String NS = "BACKUPFILES";
55 public static final String ENABLED = NS + "_ENABLED";
57 public static final String NUM_PLACEHOLDER = "%n";
59 private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
61 private static final String TEMP_FILE_EXT = ".tmp";
63 // file - File object to be backed up and then updated (written over)
66 // enabled - default flag as to whether to do the backup file roll (if not
67 // defined in preferences)
68 private static boolean enabled;
70 // confirmDelete - default flag as to whether to confirm with the user before
71 // deleting old backup/version files
72 private static boolean confirmDelete;
74 // defaultSuffix - default template to use to append to basename of file
75 private String suffix;
77 // noMax - flag to turn off a maximum number of files
78 private boolean noMax;
80 // defaultMax - default max number of backup files
83 // defaultDigits - number of zero-led digits to use in the filename
86 // reverseOrder - set to true to make newest (latest) files lowest number
87 // (like rolled log files)
88 private boolean reverseOrder;
90 // temp saved file to become new saved file
91 private File tempFile;
93 // flag set to see if file save to temp file was successful
94 private boolean tempFileWriteSuccess;
96 // array of files to be deleted, with extra information
97 private ArrayList<File> deleteFiles = new ArrayList<>();
99 // date formatting for modification times
100 private static final SimpleDateFormat sdf = new SimpleDateFormat(
101 "yyyy-MM-dd HH:mm:ss");
103 private static final String newTempFileSuffix = "_newfile";
105 private static final String oldTempFileSuffix = "_oldfile_tobedeleted";
107 public BackupFiles(String filename)
109 this(new File(filename));
112 // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
114 public BackupFiles(File file)
118 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
119 .getSavedBackupEntry();
120 this.suffix = bfpe.suffix;
121 this.noMax = bfpe.keepAll;
122 this.max = bfpe.rollMax;
123 this.digits = bfpe.digits;
124 this.reverseOrder = bfpe.reverse;
126 // create a temp file to save new data in
132 String tempfilename = file.getName();
133 File tempdir = file.getParentFile();
134 temp = File.createTempFile(tempfilename,
135 TEMP_FILE_EXT + newTempFileSuffix, tempdir);
139 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
141 } catch (IOException e)
144 "Could not create temp file to save into (IOException)");
145 } catch (Exception e)
147 Cache.log.error("Exception ctreating temp file for saving");
149 this.setTempFile(temp);
152 public static void classInit()
154 setEnabled(Cache.getDefault(ENABLED, true));
155 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
156 .getSavedBackupEntry();
157 setConfirmDelete(bfpe.confirmDelete);
160 public static void setEnabled(boolean flag)
165 public static boolean getEnabled()
171 public static void setConfirmDelete(boolean flag)
173 confirmDelete = flag;
176 public static boolean getConfirmDelete()
179 return confirmDelete;
182 // set, get and rename temp file into place
183 public void setTempFile(File temp)
185 this.tempFile = temp;
188 public File getTempFile()
193 public String getTempFilePath()
198 path = this.getTempFile().getCanonicalPath();
199 } catch (IOException e)
202 "IOException when getting Canonical Path of temp file '"
203 + this.getTempFile().getName() + "'");
208 public boolean setWriteSuccess(boolean flag)
210 boolean old = this.tempFileWriteSuccess;
211 this.tempFileWriteSuccess = flag;
215 public boolean getWriteSuccess()
217 return this.tempFileWriteSuccess;
220 public boolean renameTempFile()
222 return moveFileToFile(tempFile, file);
225 // roll the backupfiles
226 public boolean rollBackupFiles()
228 return this.rollBackupFiles(true);
231 public boolean rollBackupFiles(boolean tidyUp)
233 // file doesn't yet exist or backups are not enabled or template is null or
235 if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
236 || suffix.length() == 0)
239 Cache.log.debug("BACKUPFILES rollBackupFiles nothing to do." + ", "
240 + "filename: " + (file != null ? file.getName() : "null")
241 + ", " + "file exists: " + file.exists() + ", " + "enabled: "
242 + enabled + ", " + "max: " + max + ", " + "suffix: '" + suffix
251 dirFile = file.getParentFile();
252 dir = dirFile.getCanonicalPath();
253 Cache.log.debug("BACKUPFILES: dir: " + dir);
254 } catch (Exception e)
257 "Could not get canonical path for file '" + file + "'");
260 String filename = file.getName();
261 String basename = filename;
264 // Create/move backups up one
268 // find existing backup files
269 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
271 File[] backupFiles = dirFile.listFiles(bff);
272 int nextIndexNum = 0;
275 .debug("BACKUPFILES backupFiles.length: " + backupFiles.length);
276 if (backupFiles.length == 0)
278 // No other backup files. Just need to move existing file to backupfile_1
283 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
284 backupFiles, basename);
285 // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
290 // backup style numbering
292 int tempMax = noMax ? -1 : max;
293 // noMax == true means no limits
294 // look for first "gap" in backupFiles
295 // if tempMax is -1 at this stage just keep going until there's a gap,
296 // then hopefully tempMax gets set to the right index (a positive
297 // integer so the loop breaks)...
298 // why do I feel a little uneasy about this loop?..
299 for (int i = 1; tempMax < 0 || i <= max; i++)
301 if (!bfTreeMap.containsKey(i)) // first index without existent
308 File previousFile = null;
309 File fileToBeDeleted = null;
310 for (int n = tempMax; n > 0; n--)
312 String backupfilename = dir + File.separatorChar
313 + BackupFilenameParts.getBackupFilename(n, basename,
315 File backupfile_n = new File(backupfilename);
317 if (!backupfile_n.exists())
319 // no "oldest" file to delete
320 previousFile = backupfile_n;
321 fileToBeDeleted = null;
325 // check the modification time of this (backupfile_n) and the previous
326 // file (fileToBeDeleted) if the previous file is going to be deleted
327 if (fileToBeDeleted != null)
329 File replacementFile = backupfile_n;
330 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
331 long replacementFileLMT = replacementFile.lastModified();
335 File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
338 if (fileToBeDeletedLMT > replacementFileLMT)
340 String fileToBeDeletedLMTString = sdf
341 .format(fileToBeDeletedLMT);
342 String replacementFileLMTString = sdf
343 .format(replacementFileLMT);
344 Cache.log.warn("WARNING! I am set to delete backupfile "
345 + fileToBeDeleted.getName()
346 + " has modification time "
347 + fileToBeDeletedLMTString
348 + " which is newer than its replacement "
349 + replacementFile.getName()
350 + " with modification time "
351 + replacementFileLMTString);
353 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
354 replacementFile, true);
358 // User has confirmed delete -- no need to add it to the list
359 fileToBeDeleted.delete();
363 moveFileToFile(fileToBeDeleted, oldestTempFile);
368 moveFileToFile(fileToBeDeleted, oldestTempFile);
369 addDeleteFile(oldestTempFile);
372 } catch (Exception e)
375 "Error occurred, probably making new temp file for '"
376 + fileToBeDeleted.getName() + "'");
377 Cache.log.error(e.getStackTrace());
381 fileToBeDeleted = null;
384 if (!noMax && n == tempMax && backupfile_n.exists())
386 fileToBeDeleted = backupfile_n;
390 if (previousFile != null)
392 ret = ret && moveFileToFile(backupfile_n, previousFile);
396 previousFile = backupfile_n;
399 // index to use for the latest backup
402 else // not reverse numbering
404 // version style numbering (with earliest file deletion if max files
407 bfTreeMap.values().toArray(backupFiles);
408 StringBuilder bfsb = new StringBuilder();
409 for (int i = 0; i < backupFiles.length; i++)
411 if (bfsb.length() > 0)
415 bfsb.append(backupFiles[i].getName());
417 Cache.log.debug("BACKUPFILES backupFiles: " + bfsb.toString());
419 // noMax == true means keep all backup files
420 if ((!noMax) && bfTreeMap.size() >= max)
422 Cache.log.debug("BACKUPFILES noMax: " + noMax + ", " + "max: "
423 + max + ", " + "bfTreeMap.size(): " + bfTreeMap.size());
424 // need to delete some files to keep number of backups to designated
426 // Note that if the suffix is not numbered then do not delete any
427 // backup files later or we'll delete the new backup file (there can
429 int numToDelete = suffix.indexOf(NUM_PLACEHOLDER) > -1
430 ? bfTreeMap.size() - max + 1
432 Cache.log.debug("BACKUPFILES numToDelete: " + numToDelete);
433 // the "replacement" file is the latest backup file being kept (it's
434 // not replacing though)
435 File replacementFile = numToDelete < backupFiles.length
436 ? backupFiles[numToDelete]
438 for (int i = 0; i < numToDelete; i++)
440 // check the deletion files for modification time of the last
441 // backupfile being saved
442 File fileToBeDeleted = backupFiles[i];
443 boolean delete = true;
446 "BACKUPFILES fileToBeDeleted: " + fileToBeDeleted);
448 boolean newer = false;
449 if (replacementFile != null)
451 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
452 long replacementFileLMT = replacementFile != null
453 ? replacementFile.lastModified()
455 if (fileToBeDeletedLMT > replacementFileLMT)
457 String fileToBeDeletedLMTString = sdf
458 .format(fileToBeDeletedLMT);
459 String replacementFileLMTString = sdf
460 .format(replacementFileLMT);
462 Cache.log.warn("WARNING! I am set to delete backupfile '"
463 + fileToBeDeleted.getName()
464 + "' has modification time "
465 + fileToBeDeletedLMTString
466 + " which is newer than the oldest backupfile being kept '"
467 + replacementFile.getName()
468 + "' with modification time "
469 + replacementFileLMTString);
471 delete = confirmNewerDeleteFile(fileToBeDeleted,
472 replacementFile, false);
475 // User has confirmed delete -- no need to add it to the list
476 fileToBeDeleted.delete();
477 Cache.log.debug("BACKUPFILES deleting fileToBeDeleted: "
483 // keeping file, nothing to do!
484 Cache.log.debug("BACKUPFILES keeping fileToBeDeleted: "
491 addDeleteFile(fileToBeDeleted);
492 Cache.log.debug("BACKUPFILES addDeleteFile(fileToBeDelted): "
500 nextIndexNum = bfTreeMap.lastKey() + 1;
504 // Let's make the new backup file!! yay, got there at last!
505 String latestBackupFilename = dir + File.separatorChar
506 + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
508 Cache.log.debug("BACKUPFILES Moving old file [" + file
509 + "] to latestBackupFilename [" + latestBackupFilename + "]");
510 ret |= moveFileToFile(file, new File(latestBackupFilename));
511 Cache.log.debug("BACKUPFILES moving " + latestBackupFilename + " to "
512 + file + " was " + (ret ? "" : "NOT ") + "successful");
516 Cache.log.debug("BACKUPFILES tidying up files");
523 private static File nextTempFile(String filename, File dirFile)
527 COUNT: for (int i = 1; i < 1000; i++)
529 File trythis = new File(dirFile,
530 filename + '~' + Integer.toString(i));
531 if (!trythis.exists())
540 temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
545 private void tidyUpFiles()
550 private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
551 File replacementFile, boolean replace)
553 StringBuilder messageSB = new StringBuilder();
555 File ftbd = fileToBeDeleted;
556 String ftbdLMT = sdf.format(ftbd.lastModified());
557 String ftbdSize = Long.toString(ftbd.length());
559 File rf = replacementFile;
560 String rfLMT = sdf.format(rf.lastModified());
561 String rfSize = Long.toString(rf.length());
563 int confirmButton = JvOptionPane.NO_OPTION;
566 File saveFile = null;
569 saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
570 } catch (Exception e)
573 "Error when confirming to keep backup file newer than other backup files.");
576 messageSB.append(MessageManager.formatMessage(
577 "label.newerdelete_replacement_line", new String[]
578 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
580 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted and
581 // replaced by apparently older file \n''{1}''\t(modified {3}, size
583 messageSB.append("\n\n");
584 messageSB.append(MessageManager.formatMessage(
585 "label.confirm_deletion_or_rename", new String[]
586 { ftbd.getName(), saveFile.getName() }));
587 // "Confirm deletion of ''{0}'' or rename to ''{1}''?"
588 String[] options = new String[] {
589 MessageManager.getString("label.delete"),
590 MessageManager.getString("label.rename") };
592 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
593 : JvOptionPane.showOptionDialog(Desktop.desktop,
594 messageSB.toString(),
595 MessageManager.getString(
596 "label.backupfiles_confirm_delete"),
598 JvOptionPane.YES_NO_OPTION,
599 JvOptionPane.WARNING_MESSAGE, null, options,
604 messageSB.append(MessageManager
605 .formatMessage("label.newerdelete_line", new String[]
606 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
608 // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted but
609 // is newer than the oldest remaining backup file \n''{1}''\t(modified
611 messageSB.append("\n\n");
612 messageSB.append(MessageManager
613 .formatMessage("label.confirm_deletion", new String[]
614 { ftbd.getName() }));
615 // "Confirm deletion of ''{0}''?"
616 String[] options = new String[] {
617 MessageManager.getString("label.delete"),
618 MessageManager.getString("label.keep") };
620 confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
621 : JvOptionPane.showOptionDialog(Desktop.desktop,
622 messageSB.toString(),
623 MessageManager.getString(
624 "label.backupfiles_confirm_delete"),
626 JvOptionPane.YES_NO_OPTION,
627 JvOptionPane.WARNING_MESSAGE, null, options,
631 // return should be TRUE if file is to be deleted
632 return (confirmButton == JvOptionPane.YES_OPTION);
635 private void deleteOldFiles()
637 if (deleteFiles != null && !deleteFiles.isEmpty())
639 boolean doDelete = false;
640 StringBuilder messageSB = null;
641 if (confirmDelete && deleteFiles.size() > 0)
643 messageSB = new StringBuilder();
644 messageSB.append(MessageManager
645 .getString("label.backupfiles_confirm_delete_old_files"));
646 // "Delete the following older backup files? (see the Backups tab in
647 // Preferences for more options)"
648 for (int i = 0; i < deleteFiles.size(); i++)
650 File df = deleteFiles.get(i);
651 messageSB.append("\n");
652 messageSB.append(df.getName());
653 messageSB.append(" ");
654 messageSB.append(MessageManager.formatMessage("label.file_info",
656 { sdf.format(df.lastModified()),
657 Long.toString(df.length()) }));
658 // "(modified {0}, size {1})"
661 int confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
662 : JvOptionPane.showConfirmDialog(Desktop.desktop,
663 messageSB.toString(),
664 MessageManager.getString(
665 "label.backupfiles_confirm_delete"),
667 JvOptionPane.YES_NO_OPTION,
668 JvOptionPane.WARNING_MESSAGE);
670 doDelete = (confirmButton == JvOptionPane.YES_OPTION);
679 for (int i = 0; i < deleteFiles.size(); i++)
681 File fileToDelete = deleteFiles.get(i);
683 "BACKUPFILES deleting fileToDelete:" + fileToDelete);
684 fileToDelete.delete();
685 Cache.log.warn("deleting '" + fileToDelete.getName() + "'");
694 private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
695 File[] backupFiles, String basename)
697 // sort the backup files (based on integer found in the suffix) using a
698 // precomputed Hashmap for speed
699 Map<Integer, File> bfHashMap = new HashMap<>();
700 for (int i = 0; i < backupFiles.length; i++)
702 File f = backupFiles[i];
703 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
705 bfHashMap.put(bfp.indexNum(), f);
707 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
708 bfTreeMap.putAll(bfHashMap);
712 public boolean rollBackupsAndRenameTempFile()
714 boolean write = this.getWriteSuccess();
716 boolean roll = false;
717 boolean rename = false;
720 roll = this.rollBackupFiles(false); // tidyUpFiles at the end
721 rename = this.renameTempFile();
725 * Not sure that this confirmation is desirable. By this stage the new file is
726 * already written successfully, but something (e.g. disk full) has happened while
727 * trying to roll the backup files, and most likely the filename needed will already
728 * be vacant so renaming the temp file is nearly always correct!
730 boolean okay = roll && rename;
733 boolean yesno = false;
734 StringBuilder messageSB = new StringBuilder();
735 messageSB.append(MessageManager.getString(
736 "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
737 // "Something possibly went wrong with the backups of this file."
740 if (messageSB.length() > 0)
742 messageSB.append("\n");
744 messageSB.append(MessageManager.getString(
745 "label.backupfiles_confirm_save_new_saved_file_ok"));
746 // "The new saved file seems okay."
750 if (messageSB.length() > 0)
752 messageSB.append("\n");
754 messageSB.append(MessageManager.getString(
755 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
756 // "The new saved file might not be okay."
759 int confirmButton = Platform.isHeadless() ? JvOptionPane.OK_OPTION
760 : JvOptionPane.showConfirmDialog(Desktop.desktop,
761 messageSB.toString(),
762 MessageManager.getString(
763 "label.backupfiles_confirm_save_file"),
764 // "Confirm save file"
765 JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
766 okay = confirmButton == JvOptionPane.OK_OPTION;
776 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
777 String fileName, String suffix, int digits)
779 File[] backupFiles = null;
781 File file = new File(fileName);
786 dirFile = file.getParentFile();
787 } catch (Exception e)
790 "Could not get canonical path for file '" + file + "'");
791 return new TreeMap<>();
794 String filename = file.getName();
795 String basename = filename;
797 // find existing backup files
798 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
800 backupFiles = dirFile.listFiles(bff); // is clone needed?
802 // sort the backup files (based on integer found in the suffix) using a
803 // precomputed Hashmap for speed
804 Map<Integer, File> bfHashMap = new HashMap<>();
805 for (int i = 0; i < backupFiles.length; i++)
807 File f = backupFiles[i];
808 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
810 bfHashMap.put(bfp.indexNum(), f);
812 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
813 bfTreeMap.putAll(bfHashMap);
819 private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
820 boolean delete, boolean newer)
822 return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
825 private boolean addDeleteFile(File fileToBeDeleted)
828 int pos = deleteFiles.indexOf(fileToBeDeleted);
835 deleteFiles.add(fileToBeDeleted);
840 public static boolean moveFileToFile(File oldFile, File newFile)
843 Path oldPath = Paths.get(oldFile.getAbsolutePath());
844 Path newPath = Paths.get(newFile.getAbsolutePath());
847 // delete destination file - not usually necessary but Just In Case...
849 Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
851 } catch (IOException e)
853 Cache.log.warn("Could not move file '" + oldPath.toString() + "' to '"
854 + newPath.toString() + "'");
855 Cache.log.error(e.getStackTrace());
857 } catch (Exception e)
859 Cache.log.error(e.getMessage());
860 Cache.log.error(e.getStackTrace());