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 * The rest of the options are now saved as BACKUPFILES_PRESET, BACKUPFILES_SAVED and BACKUPFILES_CUSTOM
22 * (see BackupFilesPresetEntry)
25 public class BackupFiles
28 // labels for saved params in Cache and .jalview_properties
29 public static final String NS = "BACKUPFILES";
31 public static final String ENABLED = NS + "_ENABLED";
33 public static final String NUM_PLACEHOLDER = "%n";
35 private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
37 private static final String TEMP_FILE_EXT = ".tmp";
39 // file - File object to be backed up and then updated (written over)
42 // enabled - default flag as to whether to do the backup file roll (if not
43 // defined in preferences)
44 private static boolean enabled;
46 // confirmDelete - default flag as to whether to confirm with the user before
47 // deleting old backup/version files
48 private static boolean confirmDelete;
50 // defaultSuffix - default template to use to append to basename of file
51 private String suffix;
53 // noMax - flag to turn off a maximum number of files
54 private boolean noMax;
56 // defaultMax - default max number of backup files
59 // defaultDigits - number of zero-led digits to use in the filename
62 // reverseOrder - set to true to make newest (latest) files lowest number
63 // (like rolled log files)
64 private boolean reverseOrder;
66 // temp saved file to become new saved file
67 private File tempFile;
69 // flag set to see if file save to temp file was successful
70 private boolean tempFileWriteSuccess;
72 // array of files to be deleted, with extra information
73 private ArrayList<File> deleteFiles = new ArrayList<>();
75 // date formatting for modification times
76 private static final SimpleDateFormat sdf = new SimpleDateFormat(
77 "yyyy-MM-dd HH:mm:ss");
79 public BackupFiles(String filename)
81 this(new File(filename));
84 // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
86 public BackupFiles(File file)
90 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry.getSavedBackupEntry();
91 this.suffix = bfpe.suffix;
92 this.noMax = bfpe.keepAll;
93 this.max = bfpe.rollMax;
94 this.digits = bfpe.digits;
95 this.reverseOrder = bfpe.reverse;
97 // create a temp file to save new data in
103 String tempfilename = file.getName();
104 File tempdir = file.getParentFile();
105 temp = File.createTempFile(tempfilename, TEMP_FILE_EXT + "_newfile",
110 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
112 } catch (IOException e)
115 "Could not create temp file to save into (IOException)");
116 } catch (Exception e)
118 System.out.println("Exception ctreating temp file for saving");
120 this.setTempFile(temp);
123 public static void classInit()
125 setEnabled(Cache.getDefault(ENABLED, !Platform.isJS()));
126 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
127 .getSavedBackupEntry();
128 setConfirmDelete(bfpe.confirmDelete);
131 public static void setEnabled(boolean flag)
136 public static boolean getEnabled()
142 public static void setConfirmDelete(boolean flag)
144 confirmDelete = flag;
147 public static boolean getConfirmDelete()
150 return confirmDelete;
153 // set, get and rename temp file into place
154 public void setTempFile(File temp)
156 this.tempFile = temp;
159 public File getTempFile()
164 public String getTempFilePath()
169 path = this.getTempFile().getCanonicalPath();
170 } catch (IOException e)
173 "IOException when getting Canonical Path of temp file '"
174 + this.getTempFile().getName() + "'");
179 public boolean setWriteSuccess(boolean flag)
181 boolean old = this.tempFileWriteSuccess;
182 this.tempFileWriteSuccess = flag;
186 public boolean getWriteSuccess()
188 return this.tempFileWriteSuccess;
191 public boolean renameTempFile()
193 return tempFile.renameTo(file);
196 // roll the backupfiles
197 public boolean rollBackupFiles()
199 return this.rollBackupFiles(true);
202 public boolean rollBackupFiles(boolean tidyUp)
204 // file doesn't yet exist or backups are not enabled or template is null or
206 if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
207 || suffix.length() == 0)
217 dirFile = file.getParentFile();
218 dir = dirFile.getCanonicalPath();
219 } catch (Exception e)
222 "Could not get canonical path for file '" + file + "'");
225 String filename = file.getName();
226 String basename = filename;
229 // Create/move backups up one
233 // find existing backup files
234 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
236 File[] backupFiles = dirFile.listFiles(bff);
237 int nextIndexNum = 0;
239 if (backupFiles.length == 0)
241 // No other backup files. Just need to move existing file to backupfile_1
246 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
247 backupFiles, basename);
248 // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
253 // backup style numbering
256 int tempMax = noMax ? -1 : max;
257 // noMax == true means no limits
258 // look for first "gap" in backupFiles
259 // if tempMax is -1 at this stage just keep going until there's a gap,
260 // then hopefully tempMax gets set to the right index (a positive
261 // integer so the loop breaks)...
262 // why do I feel a little uneasy about this loop?..
263 for (int i = 1; tempMax < 0 || i <= max; i++)
265 if (!bfTreeMap.containsKey(i)) // first index without existent
272 File previousFile = null;
273 File fileToBeDeleted = null;
274 for (int n = tempMax; n > 0; n--)
276 String backupfilename = dir + File.separatorChar
277 + BackupFilenameParts.getBackupFilename(n, basename,
279 File backupfile_n = new File(backupfilename);
281 if (!backupfile_n.exists())
283 // no "oldest" file to delete
284 previousFile = backupfile_n;
285 fileToBeDeleted = null;
289 // check the modification time of this (backupfile_n) and the previous
290 // file (fileToBeDeleted) if the previous file is going to be deleted
291 if (fileToBeDeleted != null)
293 File replacementFile = backupfile_n;
294 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
295 long replacementFileLMT = replacementFile.lastModified();
299 File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
302 if (fileToBeDeletedLMT > replacementFileLMT)
304 String fileToBeDeletedLMTString = sdf
305 .format(fileToBeDeletedLMT);
306 String replacementFileLMTString = sdf
307 .format(replacementFileLMT);
308 System.out.println("WARNING! I am set to delete backupfile "
309 + fileToBeDeleted.getName()
310 + " has modification time "
311 + fileToBeDeletedLMTString
312 + " which is newer than its replacement "
313 + replacementFile.getName()
314 + " with modification time "
315 + replacementFileLMTString);
317 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
318 replacementFile, true);
322 // User has confirmed delete -- no need to add it to the list
323 fileToBeDeleted.delete();
327 fileToBeDeleted.renameTo(oldestTempFile);
332 fileToBeDeleted.renameTo(oldestTempFile);
333 addDeleteFile(oldestTempFile);
336 } catch (Exception e)
339 "Error occurred, probably making new temp file for '"
340 + fileToBeDeleted.getName() + "'");
345 fileToBeDeleted = null;
348 if (!noMax && n == tempMax && backupfile_n.exists())
350 fileToBeDeleted = backupfile_n;
354 if (previousFile != null)
356 ret = ret && backupfile_n.renameTo(previousFile);
360 previousFile = backupfile_n;
363 // index to use for the latest backup
368 // version style numbering (with earliest file deletion if max files
371 bfTreeMap.values().toArray(backupFiles);
373 // noMax == true means keep all backup files
374 if ((!noMax) && bfTreeMap.size() >= max)
376 // need to delete some files to keep number of backups to designated
378 int numToDelete = bfTreeMap.size() - max + 1;
379 // the "replacement" file is the latest backup file being kept (it's
380 // not replacing though)
381 File replacementFile = numToDelete < backupFiles.length
382 ? backupFiles[numToDelete]
384 for (int i = 0; i < numToDelete; i++)
386 // check the deletion files for modification time of the last
387 // backupfile being saved
388 File fileToBeDeleted = backupFiles[i];
389 boolean delete = true;
391 boolean newer = false;
392 if (replacementFile != null)
394 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
395 long replacementFileLMT = replacementFile != null
396 ? replacementFile.lastModified()
398 if (fileToBeDeletedLMT > replacementFileLMT)
400 String fileToBeDeletedLMTString = sdf
401 .format(fileToBeDeletedLMT);
402 String replacementFileLMTString = sdf
403 .format(replacementFileLMT);
406 .println("WARNING! I am set to delete backupfile '"
407 + fileToBeDeleted.getName()
408 + "' has modification time "
409 + fileToBeDeletedLMTString
410 + " which is newer than the oldest backupfile being kept '"
411 + replacementFile.getName()
412 + "' with modification time "
413 + replacementFileLMTString);
415 delete = confirmNewerDeleteFile(fileToBeDeleted,
416 replacementFile, false);
419 // User has confirmed delete -- no need to add it to the list
420 fileToBeDeleted.delete();
425 // keeping file, nothing to do!
431 addDeleteFile(fileToBeDeleted);
438 nextIndexNum = bfTreeMap.lastKey() + 1;
442 // Let's make the new backup file!! yay, got there at last!
443 String latestBackupFilename = dir + File.separatorChar
444 + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
446 ret |= file.renameTo(new File(latestBackupFilename));
456 private static File nextTempFile(String filename, File dirFile)
460 COUNT: for (int i = 1; i < 1000; i++)
462 File trythis = new File(dirFile,
463 filename + '~' + Integer.toString(i));
464 if (!trythis.exists())
473 temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
478 private void tidyUpFiles()
483 private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
484 File replacementFile, boolean replace)
486 StringBuilder messageSB = new StringBuilder();
488 File ftbd = fileToBeDeleted;
489 String ftbdLMT = sdf.format(ftbd.lastModified());
490 String ftbdSize = Long.toString(ftbd.length());
492 File rf = replacementFile;
493 String rfLMT = sdf.format(rf.lastModified());
494 String rfSize = Long.toString(rf.length());
496 int confirmButton = JvOptionPane.NO_OPTION;
499 File saveFile = null;
502 saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
503 } catch (Exception e)
506 "Error when confirming to keep backup file newer than other backup files.");
509 messageSB.append(MessageManager.formatMessage(
510 "label.newerdelete_replacement_line", new String[]
511 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
513 messageSB.append("\n\n");
514 messageSB.append(MessageManager.formatMessage(
515 "label.confirm_deletion_or_rename", new String[]
516 { ftbd.getName(), saveFile.getName() }));
517 String[] options = new String[] {
518 MessageManager.getString("label.delete"),
519 MessageManager.getString("label.rename") };
521 confirmButton = JvOptionPane.showOptionDialog(Desktop.desktop,
522 messageSB.toString(),
523 MessageManager.getString("label.backupfiles_confirm_delete"),
524 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
525 null, options, options[0]);
529 messageSB.append(MessageManager
530 .formatMessage("label.newerdelete_line", new String[]
531 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
533 messageSB.append("\n\n");
534 messageSB.append(MessageManager
535 .formatMessage("label.confirm_deletion", new String[]
536 { ftbd.getName() }));
537 String[] options = new String[] {
538 MessageManager.getString("label.delete"),
539 MessageManager.getString("label.keep") };
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 // return should be TRUE if file is to be deleted
550 return (confirmButton == JvOptionPane.YES_OPTION);
553 private void deleteOldFiles()
555 if (deleteFiles != null && !deleteFiles.isEmpty())
557 boolean doDelete = false;
558 StringBuilder messageSB = null;
559 if (confirmDelete && deleteFiles.size() > 0)
561 messageSB = new StringBuilder();
562 messageSB.append(MessageManager
563 .getString("label.backupfiles_confirm_delete_old_files"));
564 for (int i = 0; i < deleteFiles.size(); i++)
566 File df = deleteFiles.get(i);
567 messageSB.append("\n");
568 messageSB.append(df.getName());
569 messageSB.append(" ");
570 messageSB.append(MessageManager.formatMessage("label.file_info",
572 { sdf.format(df.lastModified()),
573 Long.toString(df.length()) }));
576 int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop,
577 messageSB.toString(),
579 .getString("label.backupfiles_confirm_delete"),
580 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
582 doDelete = (confirmButton == JvOptionPane.YES_OPTION);
591 for (int i = 0; i < deleteFiles.size(); i++)
593 File fileToDelete = deleteFiles.get(i);
594 fileToDelete.delete();
595 System.out.println("DELETING '" + fileToDelete.getName() + "'");
604 private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
608 // sort the backup files (based on integer found in the suffix) using a
609 // precomputed Hashmap for speed
610 Map<Integer, File> bfHashMap = new HashMap<>();
611 for (int i = 0; i < backupFiles.length; i++)
613 File f = backupFiles[i];
614 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
616 bfHashMap.put(bfp.indexNum(), f);
618 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
619 bfTreeMap.putAll(bfHashMap);
623 public boolean rollBackupsAndRenameTempFile()
625 boolean write = this.getWriteSuccess();
627 boolean roll = false;
628 boolean rename = false;
631 roll = this.rollBackupFiles(false);
632 rename = this.renameTempFile();
636 * Not sure that this confirmation is desirable. By this stage the new file is
637 * already written successfully, but something (e.g. disk full) has happened while
638 * trying to roll the backup files, and most likely the filename needed will already
639 * be vacant so renaming the temp file is nearly always correct!
641 boolean okay = roll && rename;
644 StringBuilder messageSB = new StringBuilder();
645 messageSB.append(MessageManager.getString( "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
648 if (messageSB.length() > 0)
650 messageSB.append("\n");
652 messageSB.append(MessageManager.getString(
653 "label.backupfiles_confirm_save_new_saved_file_ok"));
657 if (messageSB.length() > 0)
659 messageSB.append("\n");
661 messageSB.append(MessageManager.getString(
662 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
665 int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop,
666 messageSB.toString(),
668 .getString("label.backupfiles_confirm_save_file"),
669 JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
670 okay = confirmButton == JvOptionPane.OK_OPTION;
680 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
681 String fileName, String suffix, int digits)
683 File[] backupFiles = null;
685 File file = new File(fileName);
690 dirFile = file.getParentFile();
691 } catch (Exception e)
694 "Could not get canonical path for file '" + file + "'");
695 return new TreeMap<>();
698 String filename = file.getName();
699 String basename = filename;
701 // find existing backup files
702 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
704 backupFiles = dirFile.listFiles(bff); // is clone needed?
706 // sort the backup files (based on integer found in the suffix) using a
707 // precomputed Hashmap for speed
708 Map<Integer, File> bfHashMap = new HashMap<>();
709 for (int i = 0; i < backupFiles.length; i++)
711 File f = backupFiles[i];
712 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
714 bfHashMap.put(bfp.indexNum(), f);
716 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
717 bfTreeMap.putAll(bfHashMap);
723 private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
724 boolean delete, boolean newer)
726 return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
729 private boolean addDeleteFile(File fileToBeDeleted)
732 int pos = deleteFiles.indexOf(fileToBeDeleted);
739 deleteFiles.add(fileToBeDeleted);