3 import jalview.bin.Cache;
4 import jalview.gui.Desktop;
5 import jalview.gui.JvOptionPane;
6 import jalview.util.MessageManager;
9 import java.io.IOException;
10 import java.text.SimpleDateFormat;
11 import java.util.ArrayList;
12 import java.util.HashMap;
14 import java.util.TreeMap;
17 * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
18 * User configurable options are:
19 * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved.
20 * BACKUPFILES_SUFFIX - a template to insert after the file extension. Use '%n' to be replaced by a 0-led SUFFIX_DIGITS long integer.
21 * BACKUPFILES_NO_MAX - flag to turn off setting a maximum number of backup files to keep.
22 * BACKUPFILES_ROLL_MAX - the maximum number of backupfiles to keep for any one alignment or project file.
23 * BACKUPFILES_SUFFIX_DIGITS - the number of digits to insert replace %n with (e.g. BACKUPFILES_SUFFIX_DIGITS = 3 would make "001", "002", etc)
24 * BACKUPFILES_REVERSE_ORDER - if true then "logfile" style numbering and file rolling will occur. If false then ever-increasing version numbering will occur, but old files will still be deleted if there are more than ROLL_MAX backup files.
25 * BACKUPFILES_CONFIRM_DELETE_OLD - if true then prompt/confirm with the user when deleting older backup/version files.
28 public class BackupFiles
31 // labels for saved params in Cache and .jalview_properties
32 public static final String NS = "BACKUPFILES";
34 public static final String ENABLED = NS + "_ENABLED";
36 public static final String SUFFIX = NS + "_SUFFIX";
38 public static final String NO_MAX = NS + "_NO_MAX";
40 public static final String ROLL_MAX = NS + "_ROLL_MAX";
42 public static final String SUFFIX_DIGITS = NS + "_SUFFIX_DIGITS";
44 public static final String NUM_PLACEHOLDER = "%n";
46 public static final String REVERSE_ORDER = NS + "_REVERSE_ORDER";
48 public static final String CONFIRM_DELETE_OLD = NS
49 + "_CONFIRM_DELETE_OLD";
51 private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
53 private static final String TEMP_FILE_EXT = ".tmp";
55 // file - File object to be backed up and then updated (written over)
58 // enabled - default flag as to whether to do the backup file roll (if not
59 // defined in preferences)
60 private static boolean enabled;
62 // confirmDelete - default flag as to whether to confirm with the user before
63 // deleting old backup/version files
64 private static boolean confirmDelete;
66 // defaultSuffix - default template to use to append to basename of file
67 private String suffix;
69 // noMax - flag to turn off a maximum number of files
70 private boolean noMax;
72 // defaultMax - default max number of backup files
75 // defaultDigits - number of zero-led digits to use in the filename
78 // reverseOrder - set to true to make newest (latest) files lowest number
79 // (like rolled log files)
80 private boolean reverseOrder;
82 // temp saved file to become new saved file
83 private File tempFile;
85 // flag set to see if file save to temp file was successful
86 private boolean tempFileWriteSuccess;
88 // array of files to be deleted, with extra information
89 private ArrayList<File> deleteFiles = new ArrayList<>();
91 // date formatting for modification times
92 private static final SimpleDateFormat sdf = new SimpleDateFormat(
93 "yyyy-MM-dd HH:mm:ss");
95 public BackupFiles(String filename)
97 this(new File(filename));
100 // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
102 public BackupFiles(File file)
104 this(file, ".bak" + NUM_PLACEHOLDER, false, 3, 3, false);
107 public BackupFiles(File file, String defaultSuffix, boolean defaultNoMax,
108 int defaultMax, int defaultDigits, boolean defaultReverseOrder)
112 this.suffix = Cache.getDefault(SUFFIX, defaultSuffix);
113 this.noMax = Cache.getDefault(NO_MAX, defaultNoMax);
114 this.max = Cache.getDefault(ROLL_MAX, defaultMax);
115 this.digits = Cache.getDefault(SUFFIX_DIGITS, defaultDigits);
116 this.reverseOrder = Cache.getDefault(REVERSE_ORDER,
117 defaultReverseOrder);
119 // create a temp file to save new data in
125 String tempfilename = file.getName();
126 File tempdir = file.getParentFile();
127 temp = File.createTempFile(tempfilename, TEMP_FILE_EXT + "_newfile",
132 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
134 } catch (IOException e)
137 "Could not create temp file to save into (IOException)");
138 } catch (Exception e)
140 System.out.println("Exception ctreating temp file for saving");
142 this.setTempFile(temp);
145 public static void classInit()
147 setEnabled(Cache.getDefault(ENABLED, true));
148 setConfirmDelete(Cache.getDefault(CONFIRM_DELETE_OLD, true));
151 public static void setEnabled(boolean flag)
156 public static boolean getEnabled()
162 public static void setConfirmDelete(boolean flag)
164 confirmDelete = flag;
167 public static boolean getConfirmDelete()
170 return confirmDelete;
173 // set, get and rename temp file into place
174 public void setTempFile(File temp)
176 this.tempFile = temp;
179 public File getTempFile()
184 public String getTempFilePath()
189 path = this.getTempFile().getCanonicalPath();
190 } catch (IOException e)
193 "IOException when getting Canonical Path of temp file '"
194 + this.getTempFile().getName() + "'");
199 public boolean setWriteSuccess(boolean flag)
201 boolean old = this.tempFileWriteSuccess;
202 this.tempFileWriteSuccess = flag;
206 public boolean getWriteSuccess()
208 return this.tempFileWriteSuccess;
211 public boolean renameTempFile()
213 return tempFile.renameTo(file);
216 // roll the backupfiles
217 public boolean rollBackupFiles()
219 return this.rollBackupFiles(true);
222 public boolean rollBackupFiles(boolean tidyUp)
224 // file doesn't yet exist or backups are not enabled or template is null or
226 if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
227 || suffix.length() == 0)
237 dirFile = file.getParentFile();
238 dir = dirFile.getCanonicalPath();
239 } catch (Exception e)
242 "Could not get canonical path for file '" + file + "'");
245 String filename = file.getName();
246 String basename = filename;
249 // Create/move backups up one
253 // find existing backup files
254 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
256 File[] backupFiles = dirFile.listFiles(bff);
257 int nextIndexNum = 0;
259 if (backupFiles.length == 0)
261 // No other backup files. Just need to move existing file to backupfile_1
266 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
267 backupFiles, basename);
268 // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
273 // backup style numbering
276 int tempMax = noMax ? -1 : max;
277 // noMax == true means no limits
278 // look for first "gap" in backupFiles
279 // if tempMax is -1 at this stage just keep going until there's a gap,
280 // then hopefully tempMax gets set to the right index (a positive
281 // integer so the loop breaks)...
282 // why do I feel a little uneasy about this loop?..
283 for (int i = 1; tempMax < 0 || i <= max; i++)
285 if (!bfTreeMap.containsKey(i)) // first index without existent
292 File previousFile = null;
293 File fileToBeDeleted = null;
294 for (int n = tempMax; n > 0; n--)
296 String backupfilename = dir + File.separatorChar
297 + BackupFilenameParts.getBackupFilename(n, basename,
299 File backupfile_n = new File(backupfilename);
301 if (!backupfile_n.exists())
303 // no "oldest" file to delete
304 previousFile = backupfile_n;
305 fileToBeDeleted = null;
309 // check the modification time of this (backupfile_n) and the previous
310 // file (fileToBeDeleted) if the previous file is going to be deleted
311 if (fileToBeDeleted != null)
313 File replacementFile = backupfile_n;
314 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
315 long replacementFileLMT = replacementFile.lastModified();
319 File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
322 if (fileToBeDeletedLMT > replacementFileLMT)
324 String fileToBeDeletedLMTString = sdf
325 .format(fileToBeDeletedLMT);
326 String replacementFileLMTString = sdf
327 .format(replacementFileLMT);
328 System.out.println("WARNING! I am set to delete backupfile "
329 + fileToBeDeleted.getName()
330 + " has modification time "
331 + fileToBeDeletedLMTString
332 + " which is newer than its replacement "
333 + replacementFile.getName()
334 + " with modification time "
335 + replacementFileLMTString);
337 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
338 replacementFile, true);
342 // User has confirmed delete -- no need to add it to the list
343 fileToBeDeleted.delete();
347 fileToBeDeleted.renameTo(oldestTempFile);
352 fileToBeDeleted.renameTo(oldestTempFile);
353 addDeleteFile(oldestTempFile);
356 } catch (Exception e)
359 "Error occurred, probably making new temp file for '"
360 + fileToBeDeleted.getName() + "'");
365 fileToBeDeleted = null;
368 if (!noMax && n == tempMax && backupfile_n.exists())
370 fileToBeDeleted = backupfile_n;
374 if (previousFile != null)
376 ret = ret && backupfile_n.renameTo(previousFile);
380 previousFile = backupfile_n;
383 // index to use for the latest backup
388 // version style numbering (with earliest file deletion if max files
391 bfTreeMap.values().toArray(backupFiles);
393 // noMax == true means keep all backup files
394 if ((!noMax) && bfTreeMap.size() >= max)
396 // need to delete some files to keep number of backups to designated
398 int numToDelete = bfTreeMap.size() - max + 1;
399 // the "replacement" file is the latest backup file being kept (it's
400 // not replacing though)
401 File replacementFile = numToDelete < backupFiles.length
402 ? backupFiles[numToDelete]
404 for (int i = 0; i < numToDelete; i++)
406 // check the deletion files for modification time of the last
407 // backupfile being saved
408 File fileToBeDeleted = backupFiles[i];
409 boolean delete = true;
411 boolean newer = false;
412 if (replacementFile != null)
414 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
415 long replacementFileLMT = replacementFile != null
416 ? replacementFile.lastModified()
418 if (fileToBeDeletedLMT > replacementFileLMT)
420 String fileToBeDeletedLMTString = sdf
421 .format(fileToBeDeletedLMT);
422 String replacementFileLMTString = sdf
423 .format(replacementFileLMT);
426 .println("WARNING! I am set to delete backupfile '"
427 + fileToBeDeleted.getName()
428 + "' has modification time "
429 + fileToBeDeletedLMTString
430 + " which is newer than the oldest backupfile being kept '"
431 + replacementFile.getName()
432 + "' with modification time "
433 + replacementFileLMTString);
435 delete = confirmNewerDeleteFile(fileToBeDeleted,
436 replacementFile, false);
439 // User has confirmed delete -- no need to add it to the list
440 fileToBeDeleted.delete();
445 // keeping file, nothing to do!
451 addDeleteFile(fileToBeDeleted);
458 nextIndexNum = bfTreeMap.lastKey() + 1;
462 // Let's make the new backup file!! yay, got there at last!
463 String latestBackupFilename = dir + File.separatorChar
464 + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
466 ret |= file.renameTo(new File(latestBackupFilename));
476 private static File nextTempFile(String filename, File dirFile)
480 COUNT: for (int i = 1; i < 1000; i++)
482 File trythis = new File(dirFile,
483 filename + '~' + Integer.toString(i));
484 if (!trythis.exists())
493 temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
498 private void tidyUpFiles()
503 private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
504 File replacementFile, boolean replace)
506 StringBuilder messageSB = new StringBuilder();
508 File ftbd = fileToBeDeleted;
509 String ftbdLMT = sdf.format(ftbd.lastModified());
510 String ftbdSize = Long.toString(ftbd.length());
512 File rf = replacementFile;
513 String rfLMT = sdf.format(rf.lastModified());
514 String rfSize = Long.toString(rf.length());
516 int confirmButton = JvOptionPane.NO_OPTION;
519 File saveFile = null;
522 saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
523 } catch (Exception e)
526 "Error when confirming to keep backup file newer than other backup files.");
529 messageSB.append(MessageManager.formatMessage(
530 "label.newerdelete_replacement_line", new String[]
531 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
533 messageSB.append("\n\n");
534 messageSB.append(MessageManager.formatMessage(
535 "label.confirm_deletion_or_rename", new String[]
536 { ftbd.getName(), saveFile.getName() }));
537 String[] options = new String[] {
538 MessageManager.getString("label.delete"),
539 MessageManager.getString("label.rename") };
541 confirmButton = JvOptionPane.showOptionDialog(Desktop.desktop,
542 messageSB.toString(),
543 MessageManager.getString("label.backupfiles_confirm_delete"),
544 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
545 null, options, options[0]);
549 messageSB.append(MessageManager
550 .formatMessage("label.newerdelete_line", new String[]
551 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
553 messageSB.append("\n\n");
554 messageSB.append(MessageManager
555 .formatMessage("label.confirm_deletion", new String[]
556 { ftbd.getName() }));
557 String[] options = new String[] {
558 MessageManager.getString("label.delete"),
559 MessageManager.getString("label.keep") };
561 confirmButton = JvOptionPane.showOptionDialog(Desktop.desktop,
562 messageSB.toString(),
563 MessageManager.getString("label.backupfiles_confirm_delete"),
564 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
565 null, options, options[0]);
569 // return should be TRUE if file is to be deleted
570 return (confirmButton == JvOptionPane.YES_OPTION);
573 private void deleteOldFiles()
575 if (deleteFiles != null && !deleteFiles.isEmpty())
577 boolean doDelete = false;
578 StringBuilder messageSB = null;
579 if (confirmDelete && deleteFiles.size() > 0)
581 messageSB = new StringBuilder();
582 messageSB.append(MessageManager
583 .getString("label.backupfiles_confirm_delete_old_files"));
584 for (int i = 0; i < deleteFiles.size(); i++)
586 File df = deleteFiles.get(i);
587 messageSB.append("\n");
588 messageSB.append(df.getName());
589 messageSB.append(" ");
590 messageSB.append(MessageManager.formatMessage("label.file_info",
592 { sdf.format(df.lastModified()),
593 Long.toString(df.length()) }));
596 int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop,
597 messageSB.toString(),
599 .getString("label.backupfiles_confirm_delete"),
600 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
602 doDelete = (confirmButton == JvOptionPane.YES_OPTION);
611 for (int i = 0; i < deleteFiles.size(); i++)
613 File fileToDelete = deleteFiles.get(i);
614 fileToDelete.delete();
615 System.out.println("DELETING '" + fileToDelete.getName() + "'");
624 private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
628 // sort the backup files (based on integer found in the suffix) using a
629 // precomputed Hashmap for speed
630 Map<Integer, File> bfHashMap = new HashMap<>();
631 for (int i = 0; i < backupFiles.length; i++)
633 File f = backupFiles[i];
634 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
636 bfHashMap.put(bfp.indexNum(), f);
638 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
639 bfTreeMap.putAll(bfHashMap);
643 public boolean rollBackupsAndRenameTempFile()
645 boolean write = this.getWriteSuccess();
647 boolean roll = false;
648 boolean rename = false;
651 roll = this.rollBackupFiles(false);
652 rename = this.renameTempFile();
656 * Not sure that this confirmation is desirable. By this stage the new file is
657 * already written successfully, but something (e.g. disk full) has happened while
658 * trying to roll the backup files, and most likely the filename needed will already
659 * be vacant so renaming the temp file is nearly always correct!
661 boolean okay = roll && rename;
664 StringBuilder messageSB = new StringBuilder();
665 messageSB.append(MessageManager.getString( "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
668 if (messageSB.length() > 0)
670 messageSB.append("\n");
672 messageSB.append(MessageManager.getString(
673 "label.backupfiles_confirm_save_new_saved_file_ok"));
677 if (messageSB.length() > 0)
679 messageSB.append("\n");
681 messageSB.append(MessageManager.getString(
682 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
685 int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop,
686 messageSB.toString(),
688 .getString("label.backupfiles_confirm_save_file"),
689 JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
690 okay = confirmButton == JvOptionPane.OK_OPTION;
700 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
701 String fileName, String suffix, int digits)
703 File[] backupFiles = null;
705 File file = new File(fileName);
710 dirFile = file.getParentFile();
711 } catch (Exception e)
714 "Could not get canonical path for file '" + file + "'");
715 return new TreeMap<>();
718 String filename = file.getName();
719 String basename = filename;
721 // find existing backup files
722 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
724 backupFiles = dirFile.listFiles(bff); // is clone needed?
726 // sort the backup files (based on integer found in the suffix) using a
727 // precomputed Hashmap for speed
728 Map<Integer, File> bfHashMap = new HashMap<>();
729 for (int i = 0; i < backupFiles.length; i++)
731 File f = backupFiles[i];
732 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
734 bfHashMap.put(bfp.indexNum(), f);
736 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
737 bfTreeMap.putAll(bfHashMap);
743 private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
744 boolean delete, boolean newer)
746 return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
749 private boolean addDeleteFile(File fileToBeDeleted)
752 int pos = deleteFiles.indexOf(fileToBeDeleted);
759 deleteFiles.add(fileToBeDeleted);