3 import jalview.bin.Cache;
4 import jalview.gui.Desktop;
5 import jalview.gui.JvOptionPane;
6 import jalview.util.MessageManager;
7 import jalview.util.Platform;
10 import java.io.IOException;
11 import java.text.SimpleDateFormat;
12 import java.util.ArrayList;
13 import java.util.HashMap;
15 import java.util.TreeMap;
18 * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
19 * User configurable options are:
20 * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved.
21 * BACKUPFILES_SUFFIX - a template to insert after the file extension. Use '%n' to be replaced by a 0-led SUFFIX_DIGITS long integer.
22 * BACKUPFILES_NO_MAX - flag to turn off setting a maximum number of backup files to keep.
23 * BACKUPFILES_ROLL_MAX - the maximum number of backupfiles to keep for any one alignment or project file.
24 * BACKUPFILES_SUFFIX_DIGITS - the number of digits to insert replace %n with (e.g. BACKUPFILES_SUFFIX_DIGITS = 3 would make "001", "002", etc)
25 * 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.
26 * BACKUPFILES_CONFIRM_DELETE_OLD - if true then prompt/confirm with the user when deleting older backup/version files.
29 public class BackupFiles
32 // labels for saved params in Cache and .jalview_properties
33 public static final String NS = "BACKUPFILES";
35 public static final String ENABLED = NS + "_ENABLED";
37 public static final String SUFFIX = NS + "_SUFFIX";
39 public static final String NO_MAX = NS + "_NO_MAX";
41 public static final String ROLL_MAX = NS + "_ROLL_MAX";
43 public static final String SUFFIX_DIGITS = NS + "_SUFFIX_DIGITS";
45 public static final String NUM_PLACEHOLDER = "%n";
47 public static final String REVERSE_ORDER = NS + "_REVERSE_ORDER";
49 public static final String CONFIRM_DELETE_OLD = NS
50 + "_CONFIRM_DELETE_OLD";
52 private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
54 private static final String TEMP_FILE_EXT = ".tmp";
56 // file - File object to be backed up and then updated (written over)
59 // enabled - default flag as to whether to do the backup file roll (if not
60 // defined in preferences)
61 private static boolean enabled;
63 // confirmDelete - default flag as to whether to confirm with the user before
64 // deleting old backup/version files
65 private static boolean confirmDelete;
67 // defaultSuffix - default template to use to append to basename of file
68 private String suffix;
70 // noMax - flag to turn off a maximum number of files
71 private boolean noMax;
73 // defaultMax - default max number of backup files
76 // defaultDigits - number of zero-led digits to use in the filename
79 // reverseOrder - set to true to make newest (latest) files lowest number
80 // (like rolled log files)
81 private boolean reverseOrder;
83 // temp saved file to become new saved file
84 private File tempFile;
86 // flag set to see if file save to temp file was successful
87 private boolean tempFileWriteSuccess;
89 // array of files to be deleted, with extra information
90 private ArrayList<File> deleteFiles = new ArrayList<>();
92 // date formatting for modification times
93 private static final SimpleDateFormat sdf = new SimpleDateFormat(
94 "yyyy-MM-dd HH:mm:ss");
96 public BackupFiles(String filename)
98 this(new File(filename));
101 // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
103 public BackupFiles(File file)
105 this(file, ".bak" + NUM_PLACEHOLDER, false, 3, 3, false);
108 public BackupFiles(File file, String defaultSuffix, boolean defaultNoMax,
109 int defaultMax, int defaultDigits, boolean defaultReverseOrder)
113 this.suffix = Cache.getDefault(SUFFIX, defaultSuffix);
114 this.noMax = Cache.getDefault(NO_MAX, defaultNoMax);
115 this.max = Cache.getDefault(ROLL_MAX, defaultMax);
116 this.digits = Cache.getDefault(SUFFIX_DIGITS, defaultDigits);
117 this.reverseOrder = Cache.getDefault(REVERSE_ORDER,
118 defaultReverseOrder);
120 // create a temp file to save new data in
126 String tempfilename = file.getName();
127 File tempdir = file.getParentFile();
128 temp = File.createTempFile(tempfilename, TEMP_FILE_EXT + "_newfile",
133 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
135 } catch (IOException e)
138 "Could not create temp file to save into (IOException)");
139 } catch (Exception e)
141 System.out.println("Exception ctreating temp file for saving");
143 this.setTempFile(temp);
146 public static void classInit()
148 setEnabled(Cache.getDefault(ENABLED, !Platform.isJS()));
149 setConfirmDelete(Cache.getDefault(CONFIRM_DELETE_OLD, true));
152 public static void setEnabled(boolean flag)
157 public static boolean getEnabled()
163 public static void setConfirmDelete(boolean flag)
165 confirmDelete = flag;
168 public static boolean getConfirmDelete()
171 return confirmDelete;
174 // set, get and rename temp file into place
175 public void setTempFile(File temp)
177 this.tempFile = temp;
180 public File getTempFile()
185 public String getTempFilePath()
190 path = this.getTempFile().getCanonicalPath();
191 } catch (IOException e)
194 "IOException when getting Canonical Path of temp file '"
195 + this.getTempFile().getName() + "'");
200 public boolean setWriteSuccess(boolean flag)
202 boolean old = this.tempFileWriteSuccess;
203 this.tempFileWriteSuccess = flag;
207 public boolean getWriteSuccess()
209 return this.tempFileWriteSuccess;
212 public boolean renameTempFile()
214 return tempFile.renameTo(file);
217 // roll the backupfiles
218 public boolean rollBackupFiles()
220 return this.rollBackupFiles(true);
223 public boolean rollBackupFiles(boolean tidyUp)
225 // file doesn't yet exist or backups are not enabled or template is null or
227 if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
228 || suffix.length() == 0)
238 dirFile = file.getParentFile();
239 dir = dirFile.getCanonicalPath();
240 } catch (Exception e)
243 "Could not get canonical path for file '" + file + "'");
246 String filename = file.getName();
247 String basename = filename;
250 // Create/move backups up one
254 // find existing backup files
255 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
257 File[] backupFiles = dirFile.listFiles(bff);
258 int nextIndexNum = 0;
260 if (backupFiles.length == 0)
262 // No other backup files. Just need to move existing file to backupfile_1
267 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
268 backupFiles, basename);
269 // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
274 // backup style numbering
277 int tempMax = noMax ? -1 : max;
278 // noMax == true means no limits
279 // look for first "gap" in backupFiles
280 // if tempMax is -1 at this stage just keep going until there's a gap,
281 // then hopefully tempMax gets set to the right index (a positive
282 // integer so the loop breaks)...
283 // why do I feel a little uneasy about this loop?..
284 for (int i = 1; tempMax < 0 || i <= max; i++)
286 if (!bfTreeMap.containsKey(i)) // first index without existent
293 File previousFile = null;
294 File fileToBeDeleted = null;
295 for (int n = tempMax; n > 0; n--)
297 String backupfilename = dir + File.separatorChar
298 + BackupFilenameParts.getBackupFilename(n, basename,
300 File backupfile_n = new File(backupfilename);
302 if (!backupfile_n.exists())
304 // no "oldest" file to delete
305 previousFile = backupfile_n;
306 fileToBeDeleted = null;
310 // check the modification time of this (backupfile_n) and the previous
311 // file (fileToBeDeleted) if the previous file is going to be deleted
312 if (fileToBeDeleted != null)
314 File replacementFile = backupfile_n;
315 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
316 long replacementFileLMT = replacementFile.lastModified();
320 File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
323 if (fileToBeDeletedLMT > replacementFileLMT)
325 String fileToBeDeletedLMTString = sdf
326 .format(fileToBeDeletedLMT);
327 String replacementFileLMTString = sdf
328 .format(replacementFileLMT);
329 System.out.println("WARNING! I am set to delete backupfile "
330 + fileToBeDeleted.getName()
331 + " has modification time "
332 + fileToBeDeletedLMTString
333 + " which is newer than its replacement "
334 + replacementFile.getName()
335 + " with modification time "
336 + replacementFileLMTString);
338 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
339 replacementFile, true);
343 // User has confirmed delete -- no need to add it to the list
344 fileToBeDeleted.delete();
348 fileToBeDeleted.renameTo(oldestTempFile);
353 fileToBeDeleted.renameTo(oldestTempFile);
354 addDeleteFile(oldestTempFile);
357 } catch (Exception e)
360 "Error occurred, probably making new temp file for '"
361 + fileToBeDeleted.getName() + "'");
366 fileToBeDeleted = null;
369 if (!noMax && n == tempMax && backupfile_n.exists())
371 fileToBeDeleted = backupfile_n;
375 if (previousFile != null)
377 ret = ret && backupfile_n.renameTo(previousFile);
381 previousFile = backupfile_n;
384 // index to use for the latest backup
389 // version style numbering (with earliest file deletion if max files
392 bfTreeMap.values().toArray(backupFiles);
394 // noMax == true means keep all backup files
395 if ((!noMax) && bfTreeMap.size() >= max)
397 // need to delete some files to keep number of backups to designated
399 int numToDelete = bfTreeMap.size() - max + 1;
400 // the "replacement" file is the latest backup file being kept (it's
401 // not replacing though)
402 File replacementFile = numToDelete < backupFiles.length
403 ? backupFiles[numToDelete]
405 for (int i = 0; i < numToDelete; i++)
407 // check the deletion files for modification time of the last
408 // backupfile being saved
409 File fileToBeDeleted = backupFiles[i];
410 boolean delete = true;
412 boolean newer = false;
413 if (replacementFile != null)
415 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
416 long replacementFileLMT = replacementFile != null
417 ? replacementFile.lastModified()
419 if (fileToBeDeletedLMT > replacementFileLMT)
421 String fileToBeDeletedLMTString = sdf
422 .format(fileToBeDeletedLMT);
423 String replacementFileLMTString = sdf
424 .format(replacementFileLMT);
427 .println("WARNING! I am set to delete backupfile '"
428 + fileToBeDeleted.getName()
429 + "' has modification time "
430 + fileToBeDeletedLMTString
431 + " which is newer than the oldest backupfile being kept '"
432 + replacementFile.getName()
433 + "' with modification time "
434 + replacementFileLMTString);
436 delete = confirmNewerDeleteFile(fileToBeDeleted,
437 replacementFile, false);
440 // User has confirmed delete -- no need to add it to the list
441 fileToBeDeleted.delete();
446 // keeping file, nothing to do!
452 addDeleteFile(fileToBeDeleted);
459 nextIndexNum = bfTreeMap.lastKey() + 1;
463 // Let's make the new backup file!! yay, got there at last!
464 String latestBackupFilename = dir + File.separatorChar
465 + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
467 ret |= file.renameTo(new File(latestBackupFilename));
477 private static File nextTempFile(String filename, File dirFile)
481 COUNT: for (int i = 1; i < 1000; i++)
483 File trythis = new File(dirFile,
484 filename + '~' + Integer.toString(i));
485 if (!trythis.exists())
494 temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
499 private void tidyUpFiles()
504 private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
505 File replacementFile, boolean replace)
507 StringBuilder messageSB = new StringBuilder();
509 File ftbd = fileToBeDeleted;
510 String ftbdLMT = sdf.format(ftbd.lastModified());
511 String ftbdSize = Long.toString(ftbd.length());
513 File rf = replacementFile;
514 String rfLMT = sdf.format(rf.lastModified());
515 String rfSize = Long.toString(rf.length());
517 int confirmButton = JvOptionPane.NO_OPTION;
520 File saveFile = null;
523 saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
524 } catch (Exception e)
527 "Error when confirming to keep backup file newer than other backup files.");
530 messageSB.append(MessageManager.formatMessage(
531 "label.newerdelete_replacement_line", new String[]
532 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
534 messageSB.append("\n\n");
535 messageSB.append(MessageManager.formatMessage(
536 "label.confirm_deletion_or_rename", new String[]
537 { ftbd.getName(), saveFile.getName() }));
538 String[] options = new String[] {
539 MessageManager.getString("label.delete"),
540 MessageManager.getString("label.rename") };
542 confirmButton = JvOptionPane.showOptionDialog(Desktop.getDesktopPane(),
543 messageSB.toString(),
544 MessageManager.getString("label.backupfiles_confirm_delete"),
545 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
546 null, options, options[0]);
550 messageSB.append(MessageManager
551 .formatMessage("label.newerdelete_line", new String[]
552 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
554 messageSB.append("\n\n");
555 messageSB.append(MessageManager
556 .formatMessage("label.confirm_deletion", new String[]
557 { ftbd.getName() }));
558 String[] options = new String[] {
559 MessageManager.getString("label.delete"),
560 MessageManager.getString("label.keep") };
562 confirmButton = JvOptionPane.showOptionDialog(Desktop.getDesktopPane(),
563 messageSB.toString(),
564 MessageManager.getString("label.backupfiles_confirm_delete"),
565 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
566 null, options, options[0]);
570 // return should be TRUE if file is to be deleted
571 return (confirmButton == JvOptionPane.YES_OPTION);
574 private void deleteOldFiles()
576 if (deleteFiles != null && !deleteFiles.isEmpty())
578 boolean doDelete = false;
579 StringBuilder messageSB = null;
580 if (confirmDelete && deleteFiles.size() > 0)
582 messageSB = new StringBuilder();
583 messageSB.append(MessageManager
584 .getString("label.backupfiles_confirm_delete_old_files"));
585 for (int i = 0; i < deleteFiles.size(); i++)
587 File df = deleteFiles.get(i);
588 messageSB.append("\n");
589 messageSB.append(df.getName());
590 messageSB.append(" ");
591 messageSB.append(MessageManager.formatMessage("label.file_info",
593 { sdf.format(df.lastModified()),
594 Long.toString(df.length()) }));
597 int confirmButton = JvOptionPane.showConfirmDialog(Desktop.getDesktopPane(),
598 messageSB.toString(),
600 .getString("label.backupfiles_confirm_delete"),
601 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
603 doDelete = (confirmButton == JvOptionPane.YES_OPTION);
612 for (int i = 0; i < deleteFiles.size(); i++)
614 File fileToDelete = deleteFiles.get(i);
615 fileToDelete.delete();
616 System.out.println("DELETING '" + fileToDelete.getName() + "'");
625 private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
629 // sort the backup files (based on integer found in the suffix) using a
630 // precomputed Hashmap for speed
631 Map<Integer, File> bfHashMap = new HashMap<>();
632 for (int i = 0; i < backupFiles.length; i++)
634 File f = backupFiles[i];
635 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
637 bfHashMap.put(bfp.indexNum(), f);
639 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
640 bfTreeMap.putAll(bfHashMap);
644 public boolean rollBackupsAndRenameTempFile()
646 boolean write = this.getWriteSuccess();
648 boolean roll = false;
649 boolean rename = false;
652 roll = this.rollBackupFiles(false);
653 rename = this.renameTempFile();
657 * Not sure that this confirmation is desirable. By this stage the new file is
658 * already written successfully, but something (e.g. disk full) has happened while
659 * trying to roll the backup files, and most likely the filename needed will already
660 * be vacant so renaming the temp file is nearly always correct!
662 boolean okay = roll && rename;
665 StringBuilder messageSB = new StringBuilder();
666 messageSB.append(MessageManager.getString( "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
669 if (messageSB.length() > 0)
671 messageSB.append("\n");
673 messageSB.append(MessageManager.getString(
674 "label.backupfiles_confirm_save_new_saved_file_ok"));
678 if (messageSB.length() > 0)
680 messageSB.append("\n");
682 messageSB.append(MessageManager.getString(
683 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
686 int confirmButton = JvOptionPane.showConfirmDialog(Desktop.getDesktopPane(),
687 messageSB.toString(),
689 .getString("label.backupfiles_confirm_save_file"),
690 JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
691 okay = confirmButton == JvOptionPane.OK_OPTION;
701 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
702 String fileName, String suffix, int digits)
704 File[] backupFiles = null;
706 File file = new File(fileName);
711 dirFile = file.getParentFile();
712 } catch (Exception e)
715 "Could not get canonical path for file '" + file + "'");
716 return new TreeMap<>();
719 String filename = file.getName();
720 String basename = filename;
722 // find existing backup files
723 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
725 backupFiles = dirFile.listFiles(bff); // is clone needed?
727 // sort the backup files (based on integer found in the suffix) using a
728 // precomputed Hashmap for speed
729 Map<Integer, File> bfHashMap = new HashMap<>();
730 for (int i = 0; i < backupFiles.length; i++)
732 File f = backupFiles[i];
733 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
735 bfHashMap.put(bfp.indexNum(), f);
737 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
738 bfTreeMap.putAll(bfHashMap);
744 private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
745 boolean delete, boolean newer)
747 return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
750 private boolean addDeleteFile(File fileToBeDeleted)
753 int pos = deleteFiles.indexOf(fileToBeDeleted);
760 deleteFiles.add(fileToBeDeleted);