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.
24 import java.io.IOException;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28 import java.nio.file.StandardCopyOption;
29 import java.text.SimpleDateFormat;
30 import java.util.ArrayList;
31 import java.util.HashMap;
33 import java.util.TreeMap;
35 import jalview.bin.Cache;
36 import jalview.gui.Desktop;
37 import jalview.gui.JvOptionPane;
38 import jalview.util.MessageManager;
41 * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
42 * User configurable options are:
43 * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved.
44 * The rest of the options are now saved as BACKUPFILES_PRESET, BACKUPFILES_SAVED and BACKUPFILES_CUSTOM
45 * (see BackupFilesPresetEntry)
48 public class BackupFiles
51 // labels for saved params in Cache and .jalview_properties
52 public static final String NS = "BACKUPFILES";
54 public static final String ENABLED = NS + "_ENABLED";
56 public static final String NUM_PLACEHOLDER = "%n";
58 private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
60 private static final String TEMP_FILE_EXT = ".tmp";
62 // file - File object to be backed up and then updated (written over)
65 // enabled - default flag as to whether to do the backup file roll (if not
66 // defined in preferences)
67 private static boolean enabled;
69 // confirmDelete - default flag as to whether to confirm with the user before
70 // deleting old backup/version files
71 private static boolean confirmDelete;
73 // defaultSuffix - default template to use to append to basename of file
74 private String suffix;
76 // noMax - flag to turn off a maximum number of files
77 private boolean noMax;
79 // defaultMax - default max number of backup files
82 // defaultDigits - number of zero-led digits to use in the filename
85 // reverseOrder - set to true to make newest (latest) files lowest number
86 // (like rolled log files)
87 private boolean reverseOrder;
89 // temp saved file to become new saved file
90 private File tempFile;
92 // flag set to see if file save to temp file was successful
93 private boolean tempFileWriteSuccess;
95 // array of files to be deleted, with extra information
96 private ArrayList<File> deleteFiles = new ArrayList<>();
98 // date formatting for modification times
99 private static final SimpleDateFormat sdf = new SimpleDateFormat(
100 "yyyy-MM-dd HH:mm:ss");
102 private static final String newTempFileSuffix = "_newfile";
104 private static final String oldTempFileSuffix = "_oldfile_tobedeleted";
106 public BackupFiles(String filename)
108 this(new File(filename));
111 // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
113 public BackupFiles(File file)
117 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
118 .getSavedBackupEntry();
119 this.suffix = bfpe.suffix;
120 this.noMax = bfpe.keepAll;
121 this.max = bfpe.rollMax;
122 this.digits = bfpe.digits;
123 this.reverseOrder = bfpe.reverse;
125 // create a temp file to save new data in
131 String tempfilename = file.getName();
132 File tempdir = file.getParentFile();
133 temp = File.createTempFile(tempfilename,
134 TEMP_FILE_EXT + newTempFileSuffix, tempdir);
138 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
140 } catch (IOException e)
143 "Could not create temp file to save into (IOException)");
144 } catch (Exception e)
146 System.out.println("Exception ctreating temp file for saving");
148 this.setTempFile(temp);
151 public static void classInit()
153 setEnabled(Cache.getDefault(ENABLED, true));
154 BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
155 .getSavedBackupEntry();
156 setConfirmDelete(bfpe.confirmDelete);
159 public static void setEnabled(boolean flag)
164 public static boolean getEnabled()
170 public static void setConfirmDelete(boolean flag)
172 confirmDelete = flag;
175 public static boolean getConfirmDelete()
178 return confirmDelete;
181 // set, get and rename temp file into place
182 public void setTempFile(File temp)
184 this.tempFile = temp;
187 public File getTempFile()
192 public String getTempFilePath()
197 path = this.getTempFile().getCanonicalPath();
198 } catch (IOException e)
201 "IOException when getting Canonical Path of temp file '"
202 + this.getTempFile().getName() + "'");
207 public boolean setWriteSuccess(boolean flag)
209 boolean old = this.tempFileWriteSuccess;
210 this.tempFileWriteSuccess = flag;
214 public boolean getWriteSuccess()
216 return this.tempFileWriteSuccess;
219 public boolean renameTempFile()
221 return moveFileToFile(tempFile, file);
224 // roll the backupfiles
225 public boolean rollBackupFiles()
227 return this.rollBackupFiles(true);
230 public boolean rollBackupFiles(boolean tidyUp)
232 // file doesn't yet exist or backups are not enabled or template is null or
234 if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
235 || suffix.length() == 0)
245 dirFile = file.getParentFile();
246 dir = dirFile.getCanonicalPath();
247 } catch (Exception e)
250 "Could not get canonical path for file '" + file + "'");
253 String filename = file.getName();
254 String basename = filename;
257 // Create/move backups up one
261 // find existing backup files
262 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
264 File[] backupFiles = dirFile.listFiles(bff);
265 int nextIndexNum = 0;
267 if (backupFiles.length == 0)
269 // No other backup files. Just need to move existing file to backupfile_1
274 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
275 backupFiles, basename);
276 // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
281 // backup style numbering
283 int tempMax = noMax ? -1 : max;
284 // noMax == true means no limits
285 // look for first "gap" in backupFiles
286 // if tempMax is -1 at this stage just keep going until there's a gap,
287 // then hopefully tempMax gets set to the right index (a positive
288 // integer so the loop breaks)...
289 // why do I feel a little uneasy about this loop?..
290 for (int i = 1; tempMax < 0 || i <= max; i++)
292 if (!bfTreeMap.containsKey(i)) // first index without existent
299 File previousFile = null;
300 File fileToBeDeleted = null;
301 for (int n = tempMax; n > 0; n--)
303 String backupfilename = dir + File.separatorChar
304 + BackupFilenameParts.getBackupFilename(n, basename,
306 File backupfile_n = new File(backupfilename);
308 if (!backupfile_n.exists())
310 // no "oldest" file to delete
311 previousFile = backupfile_n;
312 fileToBeDeleted = null;
316 // check the modification time of this (backupfile_n) and the previous
317 // file (fileToBeDeleted) if the previous file is going to be deleted
318 if (fileToBeDeleted != null)
320 File replacementFile = backupfile_n;
321 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
322 long replacementFileLMT = replacementFile.lastModified();
326 File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
329 if (fileToBeDeletedLMT > replacementFileLMT)
331 String fileToBeDeletedLMTString = sdf
332 .format(fileToBeDeletedLMT);
333 String replacementFileLMTString = sdf
334 .format(replacementFileLMT);
335 System.out.println("WARNING! I am set to delete backupfile "
336 + fileToBeDeleted.getName()
337 + " has modification time "
338 + fileToBeDeletedLMTString
339 + " which is newer than its replacement "
340 + replacementFile.getName()
341 + " with modification time "
342 + replacementFileLMTString);
344 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
345 replacementFile, true);
349 // User has confirmed delete -- no need to add it to the list
350 fileToBeDeleted.delete();
354 moveFileToFile(fileToBeDeleted, oldestTempFile);
359 moveFileToFile(fileToBeDeleted, oldestTempFile);
360 addDeleteFile(oldestTempFile);
363 } catch (Exception e)
366 "Error occurred, probably making new temp file for '"
367 + fileToBeDeleted.getName() + "'");
372 fileToBeDeleted = null;
375 if (!noMax && n == tempMax && backupfile_n.exists())
377 fileToBeDeleted = backupfile_n;
381 if (previousFile != null)
383 ret = ret && moveFileToFile(backupfile_n, previousFile);
387 previousFile = backupfile_n;
390 // index to use for the latest backup
395 // version style numbering (with earliest file deletion if max files
398 bfTreeMap.values().toArray(backupFiles);
400 // noMax == true means keep all backup files
401 if ((!noMax) && bfTreeMap.size() >= max)
403 // need to delete some files to keep number of backups to designated
405 int numToDelete = bfTreeMap.size() - max + 1;
406 // the "replacement" file is the latest backup file being kept (it's
407 // not replacing though)
408 File replacementFile = numToDelete < backupFiles.length
409 ? backupFiles[numToDelete]
411 for (int i = 0; i < numToDelete; i++)
413 // check the deletion files for modification time of the last
414 // backupfile being saved
415 File fileToBeDeleted = backupFiles[i];
416 boolean delete = true;
418 boolean newer = false;
419 if (replacementFile != null)
421 long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
422 long replacementFileLMT = replacementFile != null
423 ? replacementFile.lastModified()
425 if (fileToBeDeletedLMT > replacementFileLMT)
427 String fileToBeDeletedLMTString = sdf
428 .format(fileToBeDeletedLMT);
429 String replacementFileLMTString = sdf
430 .format(replacementFileLMT);
433 .println("WARNING! I am set to delete backupfile '"
434 + fileToBeDeleted.getName()
435 + "' has modification time "
436 + fileToBeDeletedLMTString
437 + " which is newer than the oldest backupfile being kept '"
438 + replacementFile.getName()
439 + "' with modification time "
440 + replacementFileLMTString);
442 delete = confirmNewerDeleteFile(fileToBeDeleted,
443 replacementFile, false);
446 // User has confirmed delete -- no need to add it to the list
447 fileToBeDeleted.delete();
452 // keeping file, nothing to do!
458 addDeleteFile(fileToBeDeleted);
465 nextIndexNum = bfTreeMap.lastKey() + 1;
469 // Let's make the new backup file!! yay, got there at last!
470 String latestBackupFilename = dir + File.separatorChar
471 + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
473 ret |= moveFileToFile(file, new File(latestBackupFilename));
483 private static File nextTempFile(String filename, File dirFile)
487 COUNT: for (int i = 1; i < 1000; i++)
489 File trythis = new File(dirFile,
490 filename + '~' + Integer.toString(i));
491 if (!trythis.exists())
500 temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
505 private void tidyUpFiles()
510 private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
511 File replacementFile, boolean replace)
513 StringBuilder messageSB = new StringBuilder();
515 File ftbd = fileToBeDeleted;
516 String ftbdLMT = sdf.format(ftbd.lastModified());
517 String ftbdSize = Long.toString(ftbd.length());
519 File rf = replacementFile;
520 String rfLMT = sdf.format(rf.lastModified());
521 String rfSize = Long.toString(rf.length());
523 int confirmButton = JvOptionPane.NO_OPTION;
526 File saveFile = null;
529 saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
530 } catch (Exception e)
533 "Error when confirming to keep backup file newer than other backup files.");
536 messageSB.append(MessageManager.formatMessage(
537 "label.newerdelete_replacement_line", new String[]
538 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
540 messageSB.append("\n\n");
541 messageSB.append(MessageManager.formatMessage(
542 "label.confirm_deletion_or_rename", new String[]
543 { ftbd.getName(), saveFile.getName() }));
544 String[] options = new String[] {
545 MessageManager.getString("label.delete"),
546 MessageManager.getString("label.rename") };
548 confirmButton = JvOptionPane.showOptionDialog(Desktop.desktop,
549 messageSB.toString(),
550 MessageManager.getString("label.backupfiles_confirm_delete"),
551 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
552 null, options, options[0]);
556 messageSB.append(MessageManager
557 .formatMessage("label.newerdelete_line", new String[]
558 { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
560 messageSB.append("\n\n");
561 messageSB.append(MessageManager
562 .formatMessage("label.confirm_deletion", new String[]
563 { ftbd.getName() }));
564 String[] options = new String[] {
565 MessageManager.getString("label.delete"),
566 MessageManager.getString("label.keep") };
568 confirmButton = JvOptionPane.showOptionDialog(Desktop.desktop,
569 messageSB.toString(),
570 MessageManager.getString("label.backupfiles_confirm_delete"),
571 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
572 null, options, options[0]);
575 // return should be TRUE if file is to be deleted
576 return (confirmButton == JvOptionPane.YES_OPTION);
579 private void deleteOldFiles()
581 if (deleteFiles != null && !deleteFiles.isEmpty())
583 boolean doDelete = false;
584 StringBuilder messageSB = null;
585 if (confirmDelete && deleteFiles.size() > 0)
587 messageSB = new StringBuilder();
588 messageSB.append(MessageManager
589 .getString("label.backupfiles_confirm_delete_old_files"));
590 for (int i = 0; i < deleteFiles.size(); i++)
592 File df = deleteFiles.get(i);
593 messageSB.append("\n");
594 messageSB.append(df.getName());
595 messageSB.append(" ");
596 messageSB.append(MessageManager.formatMessage("label.file_info",
598 { sdf.format(df.lastModified()),
599 Long.toString(df.length()) }));
602 int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop,
603 messageSB.toString(),
605 .getString("label.backupfiles_confirm_delete"),
606 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
608 doDelete = (confirmButton == JvOptionPane.YES_OPTION);
617 for (int i = 0; i < deleteFiles.size(); i++)
619 File fileToDelete = deleteFiles.get(i);
620 fileToDelete.delete();
621 System.out.println("DELETING '" + fileToDelete.getName() + "'");
630 private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
631 File[] backupFiles, String basename)
633 // sort the backup files (based on integer found in the suffix) using a
634 // precomputed Hashmap for speed
635 Map<Integer, File> bfHashMap = new HashMap<>();
636 for (int i = 0; i < backupFiles.length; i++)
638 File f = backupFiles[i];
639 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
641 bfHashMap.put(bfp.indexNum(), f);
643 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
644 bfTreeMap.putAll(bfHashMap);
648 public boolean rollBackupsAndRenameTempFile()
650 boolean write = this.getWriteSuccess();
652 boolean roll = false;
653 boolean rename = false;
656 roll = this.rollBackupFiles(false);
657 rename = this.renameTempFile();
661 * Not sure that this confirmation is desirable. By this stage the new file is
662 * already written successfully, but something (e.g. disk full) has happened while
663 * trying to roll the backup files, and most likely the filename needed will already
664 * be vacant so renaming the temp file is nearly always correct!
666 boolean okay = roll && rename;
669 StringBuilder messageSB = new StringBuilder();
670 messageSB.append(MessageManager.getString(
671 "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
674 if (messageSB.length() > 0)
676 messageSB.append("\n");
678 messageSB.append(MessageManager.getString(
679 "label.backupfiles_confirm_save_new_saved_file_ok"));
683 if (messageSB.length() > 0)
685 messageSB.append("\n");
687 messageSB.append(MessageManager.getString(
688 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
691 int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop,
692 messageSB.toString(),
694 .getString("label.backupfiles_confirm_save_file"),
695 JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
696 okay = confirmButton == JvOptionPane.OK_OPTION;
706 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
707 String fileName, String suffix, int digits)
709 File[] backupFiles = null;
711 File file = new File(fileName);
716 dirFile = file.getParentFile();
717 } catch (Exception e)
720 "Could not get canonical path for file '" + file + "'");
721 return new TreeMap<>();
724 String filename = file.getName();
725 String basename = filename;
727 // find existing backup files
728 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
730 backupFiles = dirFile.listFiles(bff); // is clone needed?
732 // sort the backup files (based on integer found in the suffix) using a
733 // precomputed Hashmap for speed
734 Map<Integer, File> bfHashMap = new HashMap<>();
735 for (int i = 0; i < backupFiles.length; i++)
737 File f = backupFiles[i];
738 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
740 bfHashMap.put(bfp.indexNum(), f);
742 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
743 bfTreeMap.putAll(bfHashMap);
749 private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
750 boolean delete, boolean newer)
752 return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
755 private boolean addDeleteFile(File fileToBeDeleted)
758 int pos = deleteFiles.indexOf(fileToBeDeleted);
765 deleteFiles.add(fileToBeDeleted);
770 public static boolean moveFileToFile(File oldFile, File newFile)
773 Path oldPath = Paths.get(oldFile.getAbsolutePath());
774 Path newPath = Paths.get(newFile.getAbsolutePath());
777 Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
779 } catch (IOException e)
781 Cache.log.warn("Could not move file '" + oldPath.toString() + "' to '"
782 + newPath.toString() + "'");