3 import jalview.bin.Cache;
4 import jalview.gui.Desktop;
5 import jalview.gui.JvOptionPane;
6 import jalview.util.MessageManager;
9 import java.io.IOException;
10 import java.util.Arrays;
12 import java.util.HashMap;
13 import java.util.TreeMap;
16 * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
17 * User configurable options are:
18 * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved.
19 * BACKUPFILES_SUFFIX - a template to insert after the file extension. Use '%n' to be replaced by a 0-led SUFFIX_DIGITS long integer.
20 * BACKUPFILES_NO_MAX - flag to turn off setting a maximum number of backup files to keep.
21 * BACKUPFILES_ROLL_MAX - the maximum number of backupfiles to keep for any one alignment or project file.
22 * BACKUPFILES_SUFFIX_DIGITS - the number of digits to insert replace %n with (e.g. BACKUPFILES_SUFFIX_DIGITS = 3 would make "001", "002", etc)
23 * 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.
24 * BACKUPFILES_CONFIRM_DELETE_OLD - if true then prompt/confirm with the user when deleting older backup/version files.
27 public class BackupFiles
30 // labels for saved params in Cache and .jalview_properties
31 public static final String NS = "BACKUPFILES";
33 public static final String ENABLED = NS + "_ENABLED";
35 public static final String SUFFIX = NS + "_SUFFIX";
37 public static final String NO_MAX = NS + "_NO_MAX";
39 public static final String ROLL_MAX = NS + "_ROLL_MAX";
41 public static final String SUFFIX_DIGITS = NS + "_SUFFIX_DIGITS";
43 public static final String NUM_PLACEHOLDER = "%n";
45 public static final String REVERSE_ORDER = NS + "_REVERSE_ORDER";
47 public static final String CONFIRM_DELETE_OLD = NS + "_CONFIRM_DELETE_OLD";
49 private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
51 private static final String TEMP_FILE_EXT = ".tmp";
53 // file - File object to be backed up and then updated (written over)
56 // enabled - default flag as to whether to do the backup file roll (if not
57 // defined in preferences)
58 private static boolean enabled;
60 // confirmDelete - default flag as to whether to confirm with the user before
61 // deleting old backup/version files
62 private static boolean confirmDelete;
64 // defaultSuffix - default template to use to append to basename of file
65 private String suffix;
67 // noMax - flag to turn off a maximum number of files
68 private boolean noMax;
70 // defaultMax - default max number of backup files
73 // defaultDigits - number of zero-led digits to use in the filename
76 // reverseOrder - set to true to make newest (latest) files lowest number
77 // (like rolled log files)
78 private boolean reverseOrder;
80 // temp saved file to become new saved file
81 private File tempFile;
83 // flag set to see if file save to temp file was successful
84 private boolean tempFileWriteSuccess;
86 public BackupFiles(String filename)
88 this(new File(filename));
91 // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
93 public BackupFiles(File file)
95 this(file, ".v" + NUM_PLACEHOLDER, false, 4, 3, false);
98 public BackupFiles(File file,
99 String defaultSuffix, boolean defaultNoMax, int defaultMax,
101 boolean defaultReverseOrder)
105 this.suffix = Cache.getDefault(SUFFIX, defaultSuffix);
106 this.noMax = Cache.getDefault(NO_MAX, defaultNoMax);
107 this.max = Cache.getDefault(ROLL_MAX, defaultMax);
108 this.digits = Cache.getDefault(SUFFIX_DIGITS, defaultDigits);
109 this.reverseOrder = Cache.getDefault(REVERSE_ORDER,
110 defaultReverseOrder);
112 // create a temp file to save new data in
118 String tempfilename = file.getName();
119 File tempdir = file.getParentFile();
120 temp = File.createTempFile(tempfilename, TEMP_FILE_EXT, tempdir);
124 temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
126 } catch (IOException e)
129 "Could not create temp file to save into (IOException)");
130 } catch (Exception e)
132 System.out.println("Exception ctreating temp file for saving");
134 this.setTempFile(temp);
137 public static void classInit()
139 setEnabled(Cache.getDefault(ENABLED, true));
140 setConfirmDelete(Cache.getDefault(CONFIRM_DELETE_OLD, true));
143 public static void setEnabled(boolean flag)
148 public static boolean getEnabled()
154 public static void setConfirmDelete(boolean flag)
156 confirmDelete = flag;
159 public static boolean getConfirmDelete()
162 return confirmDelete;
165 // set, get and rename temp file into place
166 public void setTempFile(File temp)
168 this.tempFile = temp;
171 public File getTempFile()
176 public String getTempFilePath()
181 path = this.getTempFile().getCanonicalPath();
182 } catch (IOException e)
185 "IOException when getting Canonical Path of temp file '"
186 + this.getTempFile().getName() + "'");
191 public boolean setWriteSuccess(boolean flag)
193 boolean old = this.tempFileWriteSuccess;
194 this.tempFileWriteSuccess = flag;
198 public boolean getWriteSuccess()
200 return this.tempFileWriteSuccess;
203 public boolean renameTempFile()
205 return tempFile.renameTo(file);
209 // roll the backupfiles
210 public boolean rollBackupFiles()
213 // file doesn't yet exist or backups are not enabled
214 if ((!file.exists()) || (!enabled) || (max < 0))
220 // split filename up to insert suffix template in the right place. template
221 // and backupMax can be set in .jalview_properties
226 dirFile = file.getParentFile();
227 dir = dirFile.getCanonicalPath();
228 } catch (Exception e)
231 "Could not get canonical path for file '" + file + "'");
234 String filename = file.getName();
235 String basename = filename;
238 // Create/move backups up one
240 File[] oldFilesToDelete = null;
242 // find existing backup files
243 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
245 File[] backupFiles = dirFile.listFiles(bff);
246 int nextIndexNum = 0;
247 String confirmDeleteExtraInfo = null;
249 if (backupFiles.length == 0)
251 // No other backup files. Just need to move existing file to backupfile_1
256 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(backupFiles, basename);
260 // backup style numbering
262 File lastfile = null;
263 int tempMax = noMax ? -1 : max;
264 // noMax == true means no limits
265 // look for first "gap" in backupFiles
266 // if tempMax is -1 at this stage just keep going until there's a gap,
267 // then hopefully tempMax gets set to the right index (a positive
268 // integer so the loop breaks)...
269 // why do I feel a little uneasy about this loop?..
270 for (int i = 1; tempMax < 0 || i <= max; i++)
272 if (!bfTreeMap.containsKey(i)) // first index without existent
279 // for (int m = 0; m < tempMax; m++)
280 for (int n = tempMax; n > 0; n--)
282 // int n = tempMax - m;
283 String backupfilename = dir + File.separatorChar
284 + BackupFilenameFilter.getBackupFilename(n, basename,
286 File backupfile_n = new File(backupfilename);
288 if (!backupfile_n.exists())
290 lastfile = backupfile_n;
294 // if (m == 0 && backupfile_n.exists())
295 if ((!noMax) && n == tempMax && backupfile_n.exists())
297 // move the largest (max) rolled file to a temp file and add to the delete list
300 File temp = File.createTempFile(backupfilename, TEMP_FILE_EXT,
302 backupfile_n.renameTo(temp);
304 oldFilesToDelete = new File[] { temp };
305 confirmDeleteExtraInfo = "(was " + backupfile_n.getName()
307 } catch (IOException e)
310 "IOException when creating temporary file for backupfilename");
316 if (lastfile != null)
318 ret = ret && backupfile_n.renameTo(lastfile);
322 lastfile = backupfile_n;
325 // index to use for the latest backup
330 // version style numbering (with earliest file deletion if max files
334 bfTreeMap.values().toArray(backupFiles);
336 // noMax == true means keep all backup files
337 if ((!noMax) && bfTreeMap.size() >= max)
339 // need to delete some files to keep number of backups to designated
341 int numToDelete = bfTreeMap.size() - max + 1;
342 oldFilesToDelete = Arrays.copyOfRange(backupFiles, 0,
347 nextIndexNum = bfTreeMap.lastKey() + 1;
352 deleteOldFiles(oldFilesToDelete, confirmDeleteExtraInfo);
354 // Let's make the new backup file!! yay, got there at last!
355 String latestBackupFilename = dir + File.separatorChar
356 + BackupFilenameFilter.getBackupFilename(nextIndexNum, basename,
358 File latestBackupFile = new File(latestBackupFilename);
359 ret = ret && file.renameTo(latestBackupFile);
364 private void deleteOldFiles(File[] oldFilesToDelete, String confirmDeleteExtraInfo) {
365 if (oldFilesToDelete != null && oldFilesToDelete.length > 0)
367 // delete old backup/version files
369 boolean delete = false;
372 // Object[] confirmMessageArray = {};
373 StringBuilder confirmMessage = new StringBuilder();
374 confirmMessage.append(MessageManager
375 .getString("label.backupfiles_confirm_delete_old_files"));
376 for (File f : oldFilesToDelete)
378 confirmMessage.append("\n");
379 confirmMessage.append(f.getName());
381 if (confirmDeleteExtraInfo != null
382 && confirmDeleteExtraInfo.length() > 0)
384 confirmMessage.append("\n");
385 confirmMessage.append(confirmDeleteExtraInfo);
387 int confirm = JvOptionPane.showConfirmDialog(Desktop.desktop,
388 confirmMessage.toString(),
390 .getString("label.backupfiles_confirm_delete"),
391 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
393 delete = (confirm == JvOptionPane.YES_OPTION);
402 for (int i = 0; i < oldFilesToDelete.length; i++)
404 File fileToDelete = oldFilesToDelete[i];
405 fileToDelete.delete();
406 // System.out.println("DELETING '" + fileToDelete.getName() +
414 private TreeMap sortBackupFilesAsTreeMap(File[] backupFiles, String basename) {
415 // sort the backup files (based on integer found in the suffix) using a
416 // precomputed Hashmap for speed
417 Map<Integer, File> bfHashMap = new HashMap<>();
418 for (int i = 0; i < backupFiles.length; i++)
420 File f = backupFiles[i];
421 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix, digits);
422 bfHashMap.put(bfp.indexNum(), f);
424 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
425 bfTreeMap.putAll(bfHashMap);
429 public boolean rollBackupsAndRenameTempFile()
431 boolean write = this.getWriteSuccess();
433 boolean roll = false;
435 roll = this.rollBackupFiles();
441 * Not sure that this confirmation is desirable. By this stage the new file is
442 * already written successfully, but something (e.g. disk full) has happened while
443 * trying to roll the backup files, and most likely the filename needed will already
444 * be vacant so renaming the temp file is nearly always correct!
448 int confirm = JvOptionPane.showConfirmDialog(Desktop.desktop,
449 MessageManager.getString(
450 "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"),
451 MessageManager.getString("label.backupfiles_confirm_save_file"),
452 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
454 if (confirm == JvOptionPane.YES_OPTION)
460 boolean rename = false;
463 rename = this.renameTempFile();
469 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
471 String suffix, int digits)
473 File[] backupFiles = null;
475 File file = new File(fileName);
481 dirFile = file.getParentFile();
482 dir = dirFile.getCanonicalPath();
483 } catch (Exception e)
486 "Could not get canonical path for file '" + file + "'");
487 return new TreeMap<>();
490 String filename = file.getName();
491 String basename = filename;
493 // find existing backup files
494 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix, digits);
495 backupFiles = dirFile.listFiles(bff); // is clone needed?
497 // sort the backup files (based on integer found in the suffix) using a
498 // precomputed Hashmap for speed
499 Map<Integer, File> bfHashMap = new HashMap<>();
500 for (int i = 0; i < backupFiles.length; i++)
502 File f = backupFiles[i];
503 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
505 bfHashMap.put(bfp.indexNum(), f);
507 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
508 bfTreeMap.putAll(bfHashMap);