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.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.nio.file.StandardCopyOption;
35 import java.text.SimpleDateFormat;
36 import java.util.ArrayList;
37 import java.util.HashMap;
39 import java.util.TreeMap;
41 import jalview.bin.Cache;
42 import jalview.gui.Desktop;
43 import jalview.gui.JvOptionPane;
44 import jalview.util.MessageManager;
47 * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
48 * User configurable options are:
49 * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved.
50 * The rest of the options are now saved as BACKUPFILES_PRESET, BACKUPFILES_SAVED and BACKUPFILES_CUSTOM
51 * (see BackupFilesPresetEntry)
54 public class BackupFiles
57 // labels for saved params in Cache and .jalview_properties
58 public static final String NS = "BACKUPFILES";
60 public static final String ENABLED = NS + "_ENABLED";
62 public static final String NUM_PLACEHOLDER = "%n";
64 private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
66 private static final String TEMP_FILE_EXT = ".tmp";
68 // file - File object to be backed up and then updated (written over)
71 // enabled - default flag as to whether to do the backup file roll (if not
72 // defined in preferences)
73 private static boolean enabled;
75 // confirmDelete - default flag as to whether to confirm with the user before
76 // deleting old backup/version files
77 private static boolean confirmDelete;
79 // defaultSuffix - default template to use to append to basename of file
80 private String suffix;
82 // noMax - flag to turn off a maximum number of files
83 private boolean noMax;
85 // defaultMax - default max number of backup files
88 // defaultDigits - number of zero-led digits to use in the filename
91 // reverseOrder - set to true to make newest (latest) files lowest number
92 // (like rolled log files)
93 private boolean reverseOrder;
95 // temp saved file to become new saved file
96 private File tempFile;
98 // flag set to see if file save to temp file was successful
99 private boolean tempFileWriteSuccess;
101 // array of files to be deleted, with extra information
102 private ArrayList<File> deleteFiles = new ArrayList<>();
104 // date formatting for modification times
105 private static final SimpleDateFormat sdf = new SimpleDateFormat(
106 "yyyy-MM-dd HH:mm:ss");
108 private static final String newTempFileSuffix = "_newfile";
110 private static final String oldTempFileSuffix = "_oldfile_tobedeleted";
112 public BackupFiles(String filename)
114 this(new File(filename));
117 // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
119 public BackupFiles(File file)
123 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
124 .getSavedBackupEntry();
125 this.suffix = bfpe.suffix;
126 this.noMax = bfpe.keepAll;
127 this.max = bfpe.rollMax;
128 this.digits = bfpe.digits;
129 this.reverseOrder = bfpe.reverse;
131 // create a temp file to save new data in
137 String tempfilename = file.getName();
138 File tempdir = file.getParentFile();
139 temp = File.createTempFile(tempfilename,
140 TEMP_FILE_EXT + newTempFileSuffix, tempdir);
144 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
146 } catch (IOException e)
149 "Could not create temp file to save into (IOException)");
150 } catch (Exception e)
152 System.out.println("Exception ctreating temp file for saving");
154 this.setTempFile(temp);
157 public static void classInit()
159 setEnabled(Cache.getDefault(ENABLED, !Platform.isJS()));
160 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
161 .getSavedBackupEntry();
162 setConfirmDelete(bfpe.confirmDelete);
165 public static void setEnabled(boolean flag)
170 public static boolean getEnabled()
176 public static void setConfirmDelete(boolean flag)
178 confirmDelete = flag;
181 public static boolean getConfirmDelete()
184 return confirmDelete;
187 // set, get and rename temp file into place
188 public void setTempFile(File temp)
190 this.tempFile = temp;
193 public File getTempFile()
198 public String getTempFilePath()
203 path = this.getTempFile().getCanonicalPath();
204 } catch (IOException e)
207 "IOException when getting Canonical Path of temp file '"
208 + this.getTempFile().getName() + "'");
213 public boolean setWriteSuccess(boolean flag)
215 boolean old = this.tempFileWriteSuccess;
216 this.tempFileWriteSuccess = flag;
220 public boolean getWriteSuccess()
222 return this.tempFileWriteSuccess;
225 public boolean renameTempFile()
227 return moveFileToFile(tempFile, file);
230 // roll the backupfiles
231 public boolean rollBackupFiles()
233 return this.rollBackupFiles(true);
236 public boolean rollBackupFiles(boolean tidyUp)
238 // file doesn't yet exist or backups are not enabled or template is null or
240 if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
241 || suffix.length() == 0)
251 dirFile = file.getParentFile();
252 dir = dirFile.getCanonicalPath();
253 } catch (Exception e)
256 "Could not get canonical path for file '" + file + "'");
259 String filename = file.getName();
260 String basename = filename;
263 // Create/move backups up one
267 // find existing backup files
268 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
270 File[] backupFiles = dirFile.listFiles(bff);
271 int nextIndexNum = 0;
273 if (backupFiles.length == 0)
275 // No other backup files. Just need to move existing file to backupfile_1
280 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
281 backupFiles, basename);
282 // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
287 // backup style numbering
289 int tempMax = noMax ? -1 : max;
290 // noMax == true means no limits
291 // look for first "gap" in backupFiles
292 // if tempMax is -1 at this stage just keep going until there's a gap,
293 // then hopefully tempMax gets set to the right index (a positive
294 // integer so the loop breaks)...
295 // why do I feel a little uneasy about this loop?..
296 for (int i = 1; tempMax < 0 || i <= max; i++)
298 if (!bfTreeMap.containsKey(i)) // first index without existent
305 File previousFile = null;
306 File fileToBeDeleted = null;
307 for (int n = tempMax; n > 0; n--)
309 String backupfilename = dir + File.separatorChar
310 + BackupFilenameParts.getBackupFilename(n, basename,
312 File backupfile_n = new File(backupfilename);
314 if (!backupfile_n.exists())
316 // no "oldest" file to delete
317 previousFile = backupfile_n;
318 fileToBeDeleted = null;
322 // check the modification time of this (backupfile_n) and the previous
323 // file (fileToBeDeleted) if the previous file is going to be deleted
324 if (fileToBeDeleted != null)
326 File replacementFile = backupfile_n;
327 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
328 long replacementFileLMT = replacementFile.lastModified();
332 File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
335 if (fileToBeDeletedLMT > replacementFileLMT)
337 String fileToBeDeletedLMTString = sdf
338 .format(fileToBeDeletedLMT);
339 String replacementFileLMTString = sdf
340 .format(replacementFileLMT);
341 System.out.println("WARNING! I am set to delete backupfile "
342 + fileToBeDeleted.getName()
343 + " has modification time "
344 + fileToBeDeletedLMTString
345 + " which is newer than its replacement "
346 + replacementFile.getName()
347 + " with modification time "
348 + replacementFileLMTString);
350 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
351 replacementFile, true);
355 // User has confirmed delete -- no need to add it to the list
356 fileToBeDeleted.delete();
360 moveFileToFile(fileToBeDeleted, oldestTempFile);
365 moveFileToFile(fileToBeDeleted, oldestTempFile);
366 addDeleteFile(oldestTempFile);
369 } catch (Exception e)
372 "Error occurred, probably making new temp file for '"
373 + fileToBeDeleted.getName() + "'");
378 fileToBeDeleted = null;
381 if (!noMax && n == tempMax && backupfile_n.exists())
383 fileToBeDeleted = backupfile_n;
387 if (previousFile != null)
389 ret = ret && moveFileToFile(backupfile_n, previousFile);
393 previousFile = backupfile_n;
396 // index to use for the latest backup
401 // version style numbering (with earliest file deletion if max files
404 bfTreeMap.values().toArray(backupFiles);
406 // noMax == true means keep all backup files
407 if ((!noMax) && bfTreeMap.size() >= max)
409 // need to delete some files to keep number of backups to designated
411 int numToDelete = bfTreeMap.size() - max + 1;
412 // the "replacement" file is the latest backup file being kept (it's
413 // not replacing though)
414 File replacementFile = numToDelete < backupFiles.length
415 ? backupFiles[numToDelete]
417 for (int i = 0; i < numToDelete; i++)
419 // check the deletion files for modification time of the last
420 // backupfile being saved
421 File fileToBeDeleted = backupFiles[i];
422 boolean delete = true;
424 boolean newer = false;
425 if (replacementFile != null)
427 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
428 long replacementFileLMT = replacementFile != null
429 ? replacementFile.lastModified()
431 if (fileToBeDeletedLMT > replacementFileLMT)
433 String fileToBeDeletedLMTString = sdf
434 .format(fileToBeDeletedLMT);
435 String replacementFileLMTString = sdf
436 .format(replacementFileLMT);
439 .println("WARNING! I am set to delete backupfile '"
440 + fileToBeDeleted.getName()
441 + "' has modification time "
442 + fileToBeDeletedLMTString
443 + " which is newer than the oldest backupfile being kept '"
444 + replacementFile.getName()
445 + "' with modification time "
446 + replacementFileLMTString);
448 delete = confirmNewerDeleteFile(fileToBeDeleted,
449 replacementFile, false);
452 // User has confirmed delete -- no need to add it to the list
453 fileToBeDeleted.delete();
458 // keeping file, nothing to do!
464 addDeleteFile(fileToBeDeleted);
471 nextIndexNum = bfTreeMap.lastKey() + 1;
475 // Let's make the new backup file!! yay, got there at last!
476 String latestBackupFilename = dir + File.separatorChar
477 + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
479 ret |= moveFileToFile(file, new File(latestBackupFilename));
489 private static File nextTempFile(String filename, File dirFile)
493 COUNT: for (int i = 1; i < 1000; i++)
495 File trythis = new File(dirFile,
496 filename + '~' + Integer.toString(i));
497 if (!trythis.exists())
506 temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
511 private void tidyUpFiles()
516 private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
517 File replacementFile, boolean replace)
519 StringBuilder messageSB = new StringBuilder();
521 File ftbd = fileToBeDeleted;
522 String ftbdLMT = sdf.format(ftbd.lastModified());
523 String ftbdSize = Long.toString(ftbd.length());
525 File rf = replacementFile;
526 String rfLMT = sdf.format(rf.lastModified());
527 String rfSize = Long.toString(rf.length());
529 int confirmButton = JvOptionPane.NO_OPTION;
532 File saveFile = null;
535 saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
536 } catch (Exception e)
539 "Error when confirming to keep backup file newer than other backup files.");
542 messageSB.append(MessageManager.formatMessage(
543 "label.newerdelete_replacement_line", new String[]
544 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
546 messageSB.append("\n\n");
547 messageSB.append(MessageManager.formatMessage(
548 "label.confirm_deletion_or_rename", new String[]
549 { ftbd.getName(), saveFile.getName() }));
550 String[] options = new String[] {
551 MessageManager.getString("label.delete"),
552 MessageManager.getString("label.rename") };
554 confirmButton = JvOptionPane.showOptionDialog(Desktop.desktop,
555 messageSB.toString(),
556 MessageManager.getString("label.backupfiles_confirm_delete"),
557 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
558 null, options, options[0]);
562 messageSB.append(MessageManager
563 .formatMessage("label.newerdelete_line", new String[]
564 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
566 messageSB.append("\n\n");
567 messageSB.append(MessageManager
568 .formatMessage("label.confirm_deletion", new String[]
569 { ftbd.getName() }));
570 String[] options = new String[] {
571 MessageManager.getString("label.delete"),
572 MessageManager.getString("label.keep") };
574 confirmButton = JvOptionPane.showOptionDialog(Desktop.desktop,
575 messageSB.toString(),
576 MessageManager.getString("label.backupfiles_confirm_delete"),
577 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
578 null, options, options[0]);
581 // return should be TRUE if file is to be deleted
582 return (confirmButton == JvOptionPane.YES_OPTION);
585 private void deleteOldFiles()
587 if (deleteFiles != null && !deleteFiles.isEmpty())
589 boolean doDelete = false;
590 StringBuilder messageSB = null;
591 if (confirmDelete && deleteFiles.size() > 0)
593 messageSB = new StringBuilder();
594 messageSB.append(MessageManager
595 .getString("label.backupfiles_confirm_delete_old_files"));
596 for (int i = 0; i < deleteFiles.size(); i++)
598 File df = deleteFiles.get(i);
599 messageSB.append("\n");
600 messageSB.append(df.getName());
601 messageSB.append(" ");
602 messageSB.append(MessageManager.formatMessage("label.file_info",
604 { sdf.format(df.lastModified()),
605 Long.toString(df.length()) }));
608 int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop,
609 messageSB.toString(),
611 .getString("label.backupfiles_confirm_delete"),
612 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
614 doDelete = (confirmButton == JvOptionPane.YES_OPTION);
623 for (int i = 0; i < deleteFiles.size(); i++)
625 File fileToDelete = deleteFiles.get(i);
626 fileToDelete.delete();
627 System.out.println("DELETING '" + fileToDelete.getName() + "'");
636 private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
637 File[] backupFiles, String basename)
639 // sort the backup files (based on integer found in the suffix) using a
640 // precomputed Hashmap for speed
641 Map<Integer, File> bfHashMap = new HashMap<>();
642 for (int i = 0; i < backupFiles.length; i++)
644 File f = backupFiles[i];
645 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
647 bfHashMap.put(bfp.indexNum(), f);
649 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
650 bfTreeMap.putAll(bfHashMap);
654 public boolean rollBackupsAndRenameTempFile()
656 boolean write = this.getWriteSuccess();
658 boolean roll = false;
659 boolean rename = false;
662 roll = this.rollBackupFiles(false);
663 rename = this.renameTempFile();
667 * Not sure that this confirmation is desirable. By this stage the new file is
668 * already written successfully, but something (e.g. disk full) has happened while
669 * trying to roll the backup files, and most likely the filename needed will already
670 * be vacant so renaming the temp file is nearly always correct!
672 boolean okay = roll && rename;
675 StringBuilder messageSB = new StringBuilder();
676 messageSB.append(MessageManager.getString(
677 "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
680 if (messageSB.length() > 0)
682 messageSB.append("\n");
684 messageSB.append(MessageManager.getString(
685 "label.backupfiles_confirm_save_new_saved_file_ok"));
689 if (messageSB.length() > 0)
691 messageSB.append("\n");
693 messageSB.append(MessageManager.getString(
694 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
697 int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop,
698 messageSB.toString(),
700 .getString("label.backupfiles_confirm_save_file"),
701 JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
702 okay = confirmButton == JvOptionPane.OK_OPTION;
712 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
713 String fileName, String suffix, int digits)
715 File[] backupFiles = null;
717 File file = new File(fileName);
722 dirFile = file.getParentFile();
723 } catch (Exception e)
726 "Could not get canonical path for file '" + file + "'");
727 return new TreeMap<>();
730 String filename = file.getName();
731 String basename = filename;
733 // find existing backup files
734 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
736 backupFiles = dirFile.listFiles(bff); // is clone needed?
738 // sort the backup files (based on integer found in the suffix) using a
739 // precomputed Hashmap for speed
740 Map<Integer, File> bfHashMap = new HashMap<>();
741 for (int i = 0; i < backupFiles.length; i++)
743 File f = backupFiles[i];
744 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
746 bfHashMap.put(bfp.indexNum(), f);
748 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
749 bfTreeMap.putAll(bfHashMap);
755 private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
756 boolean delete, boolean newer)
758 return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
761 private boolean addDeleteFile(File fileToBeDeleted)
764 int pos = deleteFiles.indexOf(fileToBeDeleted);
771 deleteFiles.add(fileToBeDeleted);
776 public static boolean moveFileToFile(File oldFile, File newFile)
779 Path oldPath = Paths.get(oldFile.getAbsolutePath());
780 Path newPath = Paths.get(newFile.getAbsolutePath());
783 Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
785 } catch (IOException e)
787 Cache.log.warn("Could not move file '" + oldPath.toString() + "' to '"
788 + newPath.toString() + "'");