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.
23 import jalview.bin.Cache;
24 import jalview.gui.Desktop;
25 import jalview.gui.JvOptionPane;
26 import jalview.util.MessageManager;
27 import jalview.util.Platform;
30 import java.io.IOException;
31 import java.text.SimpleDateFormat;
32 import java.util.ArrayList;
33 import java.util.HashMap;
35 import java.util.TreeMap;
38 * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
39 * User configurable options are:
40 * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved.
41 * The rest of the options are now saved as BACKUPFILES_PRESET, BACKUPFILES_SAVED and BACKUPFILES_CUSTOM
42 * (see BackupFilesPresetEntry)
45 public class BackupFiles
48 // labels for saved params in Cache and .jalview_properties
49 public static final String NS = "BACKUPFILES";
51 public static final String ENABLED = NS + "_ENABLED";
53 public static final String NUM_PLACEHOLDER = "%n";
55 private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
57 private static final String TEMP_FILE_EXT = ".tmp";
59 // file - File object to be backed up and then updated (written over)
62 // enabled - default flag as to whether to do the backup file roll (if not
63 // defined in preferences)
64 private static boolean enabled;
66 // confirmDelete - default flag as to whether to confirm with the user before
67 // deleting old backup/version files
68 private static boolean confirmDelete;
70 // defaultSuffix - default template to use to append to basename of file
71 private String suffix;
73 // noMax - flag to turn off a maximum number of files
74 private boolean noMax;
76 // defaultMax - default max number of backup files
79 // defaultDigits - number of zero-led digits to use in the filename
82 // reverseOrder - set to true to make newest (latest) files lowest number
83 // (like rolled log files)
84 private boolean reverseOrder;
86 // temp saved file to become new saved file
87 private File tempFile;
89 // flag set to see if file save to temp file was successful
90 private boolean tempFileWriteSuccess;
92 // array of files to be deleted, with extra information
93 private ArrayList<File> deleteFiles = new ArrayList<>();
95 // date formatting for modification times
96 private static final SimpleDateFormat sdf = new SimpleDateFormat(
97 "yyyy-MM-dd HH:mm:ss");
99 public BackupFiles(String filename)
101 this(new File(filename));
104 // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
106 public BackupFiles(File file)
110 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry.getSavedBackupEntry();
111 this.suffix = bfpe.suffix;
112 this.noMax = bfpe.keepAll;
113 this.max = bfpe.rollMax;
114 this.digits = bfpe.digits;
115 this.reverseOrder = bfpe.reverse;
117 // create a temp file to save new data in
123 String tempfilename = file.getName();
124 File tempdir = file.getParentFile();
125 temp = File.createTempFile(tempfilename, TEMP_FILE_EXT + "_newfile",
130 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
132 } catch (IOException e)
135 "Could not create temp file to save into (IOException)");
136 } catch (Exception e)
138 System.out.println("Exception ctreating temp file for saving");
140 this.setTempFile(temp);
143 public static void classInit()
145 setEnabled(Cache.getDefault(ENABLED, !Platform.isJS()));
146 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
147 .getSavedBackupEntry();
148 setConfirmDelete(bfpe.confirmDelete);
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.getDesktopPane(),
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.getDesktopPane(),
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.getDesktopPane(),
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.getDesktopPane(),
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);