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 just before 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 private static String NS = "BACKUPFILES";
33 public static String ENABLED = NS + "_ENABLED";
35 public static String SUFFIX = NS + "_SUFFIX";
37 public static String NO_MAX = NS + "_NO_MAX";
39 public static String ROLL_MAX = NS + "_ROLL_MAX";
41 public static String SUFFIX_DIGITS = NS + "_SUFFIX_DIGITS";
43 public static final String NUM_PLACEHOLDER = "%n";
45 public static String REVERSE_ORDER = NS + "_REVERSE_ORDER";
47 public static String CONFIRM_DELETE_OLD = NS + "_CONFIRM_DELETE_OLD";
49 private static String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
51 // file - File object to be backed up and then updated (written over)
54 // enabled - default flag as to whether to do the backup file roll (if not
55 // defined in preferences)
56 private static boolean enabled;
58 // confirmDelete - default flag as to whether to confirm with the user before
59 // deleting old backup/version files
60 private static boolean confirmDelete;
62 // defaultSuffix - default template to use to append to basename of file
63 private String suffix;
65 // noMax - flag to turn off a maximum number of files
66 private boolean noMax;
68 // defaultMax - default max number of backup files
71 // defaultDigits - number of zero-led digits to use in the filename
74 // reverseOrder - set to true to make newest (latest) files lowest number
75 // (like rolled log files)
76 private boolean reverseOrder;
78 // temp saved file to become new saved file
79 private File tempFile;
81 // flag set to see if file save to temp file was successful
82 private boolean tempFileWriteSuccess;
84 public BackupFiles(String filename)
86 this(new File(filename));
89 // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
91 public BackupFiles(File file)
93 this(file, "-v" + NUM_PLACEHOLDER, false, 4, 3, false);
96 public BackupFiles(File file,
97 String defaultSuffix, boolean defaultNoMax, int defaultMax,
99 boolean defaultReverseOrder)
103 this.suffix = Cache.getDefault(SUFFIX, defaultSuffix);
104 this.noMax = Cache.getDefault(NO_MAX, defaultNoMax);
105 this.max = Cache.getDefault(ROLL_MAX, defaultMax);
106 this.digits = Cache.getDefault(SUFFIX_DIGITS, defaultDigits);
107 this.reverseOrder = Cache.getDefault(REVERSE_ORDER,
108 defaultReverseOrder);
110 // create a temp file to save new data in
116 String tempfilename = file.getName();
117 File tempdir = file.getParentFile();
118 temp = File.createTempFile(tempfilename, ".tmp", tempdir);
122 temp = File.createTempFile(DEFAULT_TEMP_FILE, ".tmp");
124 } catch (IOException e)
127 "Could not create temp file to save into (IOException)");
128 } catch (Exception e)
130 System.out.println("Exception ctreating temp file for saving");
132 this.setTempFile(temp);
135 public static void classInit()
137 setEnabled(Cache.getDefault(ENABLED, true));
138 setConfirmDelete(Cache.getDefault(CONFIRM_DELETE_OLD, true));
141 public static void setEnabled(boolean flag)
146 public static boolean getEnabled()
152 public static void setConfirmDelete(boolean flag)
154 confirmDelete = flag;
157 public static boolean getConfirmDelete()
160 return confirmDelete;
163 // set, get and rename temp file into place
164 public void setTempFile(File temp)
166 this.tempFile = temp;
169 public File getTempFile()
174 public String getTempFilePath()
179 path = this.getTempFile().getCanonicalPath();
180 } catch (IOException e)
183 "IOException when getting Canonical Path of temp file '"
184 + this.getTempFile().getName() + "'");
189 public boolean setWriteSuccess(boolean flag)
191 boolean old = this.tempFileWriteSuccess;
192 this.tempFileWriteSuccess = flag;
196 public boolean getWriteSuccess()
198 return this.tempFileWriteSuccess;
201 public boolean renameTempFile()
203 return tempFile.renameTo(file);
207 // roll the backupfiles
208 public boolean rollBackupFiles()
211 // file doesn't yet exist or backups are not enabled
212 if ((!file.exists()) || (!enabled) || (max < 0))
218 // split filename up to insert suffix template in the right place. template
219 // and backupMax can be set in .jalview_properties
224 dirFile = file.getParentFile();
225 dir = dirFile.getCanonicalPath();
226 } catch (Exception e)
229 "Could not get canonical path for file '" + file + "'");
232 String filename = file.getName();
233 String basename = filename;
234 String extension = "";
235 int dotcharpos = filename.lastIndexOf('.');
236 // don't split filenames with the last '.' at the very beginning or
237 // very end of the filename
238 if ((dotcharpos > 0) && (dotcharpos < filename.length() - 1))
240 basename = filename.substring(0, dotcharpos);
241 extension = filename.substring(dotcharpos); // NOTE this includes the '.'
245 // Create/move backups up one
247 File[] oldFilesToDelete = null;
249 // find existing backup files
250 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
253 File[] backupFiles = dirFile.listFiles(bff);
254 int nextIndexNum = 0;
255 String confirmDeleteExtraInfo = null;
257 if (backupFiles.length == 0)
259 // No other backup files. Just need to move existing file to backupfile_1
264 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(backupFiles, basename, extension);
268 // backup style numbering
270 File lastfile = null;
271 int tempMax = noMax ? -1 : max;
272 // noMax == true means no limits
273 // look for first "gap" in backupFiles
274 // if tempMax is -1 at this stage just keep going until there's a gap,
275 // then hopefully tempMax gets set to the right index (a positive
276 // integer so the loop breaks)...
277 // why do I feel a little uneasy about this loop?..
278 for (int i = 1; tempMax < 0 || i <= max; i++)
280 if (!bfTreeMap.containsKey(i)) // first index without existent
287 // for (int m = 0; m < tempMax; m++)
288 for (int n = tempMax; n > 0; n--)
290 // int n = tempMax - m;
291 String backupfilename = dir + File.separatorChar
292 + BackupFilenameFilter.getBackupFilename(n, basename,
293 suffix, digits, extension);
294 File backupfile_n = new File(backupfilename);
296 if (!backupfile_n.exists())
298 lastfile = backupfile_n;
302 // if (m == 0 && backupfile_n.exists())
303 if ((!noMax) && n == tempMax && backupfile_n.exists())
305 // move the largest (max) rolled file to a temp file and add to the delete list
308 File temp = File.createTempFile(backupfilename, ".tmp",
310 backupfile_n.renameTo(temp);
312 oldFilesToDelete = new File[] { temp };
313 confirmDeleteExtraInfo = "(was " + backupfile_n.getName()
315 } catch (IOException e)
318 "IOException when creating temporary file for backupfilename");
324 if (lastfile != null)
326 ret = ret && backupfile_n.renameTo(lastfile);
330 lastfile = backupfile_n;
333 // index to use for the latest backup
338 // version style numbering (with earliest file deletion if max files
342 bfTreeMap.values().toArray(backupFiles);
344 // noMax == true means keep all backup files
345 if ((!noMax) && bfTreeMap.size() >= max)
347 // need to delete some files to keep number of backups to designated
349 int numToDelete = bfTreeMap.size() - max + 1;
350 oldFilesToDelete = Arrays.copyOfRange(backupFiles, 0,
355 nextIndexNum = bfTreeMap.lastKey() + 1;
360 deleteOldFiles(oldFilesToDelete, confirmDeleteExtraInfo);
362 // Let's make the new backup file!! yay, got there at last!
363 String latestBackupFilename = dir + File.separatorChar
364 + BackupFilenameFilter.getBackupFilename(nextIndexNum, basename,
365 suffix, digits, extension);
366 File latestBackupFile = new File(latestBackupFilename);
367 ret = ret && file.renameTo(latestBackupFile);
372 private void deleteOldFiles(File[] oldFilesToDelete, String confirmDeleteExtraInfo) {
373 if (oldFilesToDelete != null && oldFilesToDelete.length > 0)
375 // delete old backup/version files
377 boolean delete = false;
380 // Object[] confirmMessageArray = {};
381 StringBuilder confirmMessage = new StringBuilder();
382 confirmMessage.append(MessageManager
383 .getString("label.backupfiles_confirm_delete_old_files"));
384 for (File f : oldFilesToDelete)
386 confirmMessage.append("\n");
387 confirmMessage.append(f.getName());
389 if (confirmDeleteExtraInfo != null
390 && confirmDeleteExtraInfo.length() > 0)
392 confirmMessage.append("\n");
393 confirmMessage.append(confirmDeleteExtraInfo);
395 int confirm = JvOptionPane.showConfirmDialog(Desktop.desktop,
396 confirmMessage.toString(),
398 .getString("label.backupfiles_confirm_delete"),
399 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
401 delete = (confirm == JvOptionPane.YES_OPTION);
410 for (int i = 0; i < oldFilesToDelete.length; i++)
412 File fileToDelete = oldFilesToDelete[i];
413 fileToDelete.delete();
414 // System.out.println("DELETING '" + fileToDelete.getName() +
422 private TreeMap sortBackupFilesAsTreeMap(File[] backupFiles, String basename, String extension) {
423 // sort the backup files (based on integer found in the suffix) using a
424 // precomputed Hashmap for speed
425 Map<Integer, File> bfHashMap = new HashMap<>();
426 for (int i = 0; i < backupFiles.length; i++)
428 File f = backupFiles[i];
429 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix, digits, extension);
430 bfHashMap.put(bfp.indexNum(), f);
432 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
433 bfTreeMap.putAll(bfHashMap);
437 public boolean rollBackupsAndRenameTempFile()
439 boolean write = this.getWriteSuccess();
441 boolean roll = false;
443 roll = this.rollBackupFiles();
449 * Not sure that this confirmation is desirable. By this stage the new file is
450 * already written successfully, but something (e.g. disk full) has happened while
451 * trying to roll the backup files, and most likely the filename needed will already
452 * be vacant so renaming the temp file is nearly always correct!
456 int confirm = JvOptionPane.showConfirmDialog(Desktop.desktop,
457 MessageManager.getString(
458 "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"),
459 MessageManager.getString("label.backupfiles_confirm_save_file"),
460 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
462 if (confirm == JvOptionPane.YES_OPTION)
468 boolean rename = false;
471 rename = this.renameTempFile();
477 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
479 String suffix, int digits)
481 File[] backupFiles = null;
483 File file = new File(fileName);
489 dirFile = file.getParentFile();
490 dir = dirFile.getCanonicalPath();
491 } catch (Exception e)
494 "Could not get canonical path for file '" + file + "'");
495 return new TreeMap<>();
498 String filename = file.getName();
499 String basename = filename;
500 String extension = "";
501 int dotcharpos = filename.lastIndexOf('.');
502 // don't split of filenames with the last '.' at the very beginning or
503 // very end of the filename
504 if ((dotcharpos > 0) && (dotcharpos < filename.length() - 1))
506 basename = filename.substring(0, dotcharpos);
507 extension = filename.substring(dotcharpos); // NOTE this includes the '.'
510 // find existing backup files
511 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix, digits, extension);
512 backupFiles = dirFile.listFiles(bff); // is clone needed?
514 // sort the backup files (based on integer found in the suffix) using a
515 // precomputed Hashmap for speed
516 Map<Integer, File> bfHashMap = new HashMap<>();
517 for (int i = 0; i < backupFiles.length; i++)
519 File f = backupFiles[i];
520 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
522 bfHashMap.put(bfp.indexNum(), f);
524 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
525 bfTreeMap.putAll(bfHashMap);
530 public static File[] getBackupFiles(String fileName, String suffix,
533 TreeMap<Integer, File> bfTreeMap = getBackupFilesAsTreeMap(fileName,
535 File[] backupFiles = new File[bfTreeMap.size()];
536 bfTreeMap.values().toArray(backupFiles);