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 private 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 System.out.println("RENAMING TEMP FILE '"+tempFile.getName() + "' TO '"+file.getName()+"'"); // DELETEME
206 return tempFile.renameTo(file);
210 // roll the backupfiles
211 public boolean rollBackupFiles()
214 // file doesn't yet exist or backups are not enabled
215 if ((!file.exists()) || (!enabled) || (max < 0))
221 // split filename up to insert suffix template in the right place. template
222 // and backupMax can be set in .jalview_properties
227 dirFile = file.getParentFile();
228 dir = dirFile.getCanonicalPath();
229 } catch (Exception e)
232 "Could not get canonical path for file '" + file + "'");
235 String filename = file.getName();
236 String basename = filename;
239 // Create/move backups up one
241 File[] oldFilesToDelete = null;
243 // find existing backup files
244 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
246 File[] backupFiles = dirFile.listFiles(bff);
247 int nextIndexNum = 0;
248 String confirmDeleteExtraInfo = null;
250 if (backupFiles.length == 0)
252 // No other backup files. Just need to move existing file to backupfile_1
257 TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(backupFiles, basename);
261 // backup style numbering
263 File lastfile = null;
264 int tempMax = noMax ? -1 : max;
265 // noMax == true means no limits
266 // look for first "gap" in backupFiles
267 // if tempMax is -1 at this stage just keep going until there's a gap,
268 // then hopefully tempMax gets set to the right index (a positive
269 // integer so the loop breaks)...
270 // why do I feel a little uneasy about this loop?..
271 for (int i = 1; tempMax < 0 || i <= max; i++)
273 if (!bfTreeMap.containsKey(i)) // first index without existent
280 // for (int m = 0; m < tempMax; m++)
281 for (int n = tempMax; n > 0; n--)
283 // int n = tempMax - m;
284 String backupfilename = dir + File.separatorChar
285 + BackupFilenameFilter.getBackupFilename(n, basename,
287 File backupfile_n = new File(backupfilename);
289 if (!backupfile_n.exists())
291 lastfile = backupfile_n;
295 // if (m == 0 && backupfile_n.exists())
296 if ((!noMax) && n == tempMax && backupfile_n.exists())
298 // move the largest (max) rolled file to a temp file and add to the delete list
301 File temp = File.createTempFile(backupfilename, TEMP_FILE_EXT,
303 backupfile_n.renameTo(temp);
305 oldFilesToDelete = new File[] { temp };
306 confirmDeleteExtraInfo = "(was " + backupfile_n.getName()
308 } catch (IOException e)
311 "IOException when creating temporary file for backupfilename");
317 if (lastfile != null)
319 ret = ret && backupfile_n.renameTo(lastfile);
323 lastfile = backupfile_n;
326 // index to use for the latest backup
331 // version style numbering (with earliest file deletion if max files
335 bfTreeMap.values().toArray(backupFiles);
337 // noMax == true means keep all backup files
338 if ((!noMax) && bfTreeMap.size() >= max)
340 // need to delete some files to keep number of backups to designated
342 int numToDelete = bfTreeMap.size() - max + 1;
343 oldFilesToDelete = Arrays.copyOfRange(backupFiles, 0,
348 nextIndexNum = bfTreeMap.lastKey() + 1;
353 deleteOldFiles(oldFilesToDelete, confirmDeleteExtraInfo);
355 // Let's make the new backup file!! yay, got there at last!
356 String latestBackupFilename = dir + File.separatorChar
357 + BackupFilenameFilter.getBackupFilename(nextIndexNum, basename,
359 File latestBackupFile = new File(latestBackupFilename);
360 ret = ret && file.renameTo(latestBackupFile);
365 private void deleteOldFiles(File[] oldFilesToDelete, String confirmDeleteExtraInfo) {
366 if (oldFilesToDelete != null && oldFilesToDelete.length > 0)
368 // delete old backup/version files
370 boolean delete = false;
373 // Object[] confirmMessageArray = {};
374 StringBuilder confirmMessage = new StringBuilder();
375 confirmMessage.append(MessageManager
376 .getString("label.backupfiles_confirm_delete_old_files"));
377 for (File f : oldFilesToDelete)
379 confirmMessage.append("\n");
380 confirmMessage.append(f.getName());
382 if (confirmDeleteExtraInfo != null
383 && confirmDeleteExtraInfo.length() > 0)
385 confirmMessage.append("\n");
386 confirmMessage.append(confirmDeleteExtraInfo);
388 int confirm = JvOptionPane.showConfirmDialog(Desktop.desktop,
389 confirmMessage.toString(),
391 .getString("label.backupfiles_confirm_delete"),
392 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
394 delete = (confirm == JvOptionPane.YES_OPTION);
403 for (int i = 0; i < oldFilesToDelete.length; i++)
405 File fileToDelete = oldFilesToDelete[i];
406 fileToDelete.delete();
407 // System.out.println("DELETING '" + fileToDelete.getName() +
415 private TreeMap sortBackupFilesAsTreeMap(File[] backupFiles, String basename) {
416 // sort the backup files (based on integer found in the suffix) using a
417 // precomputed Hashmap for speed
418 Map<Integer, File> bfHashMap = new HashMap<>();
419 for (int i = 0; i < backupFiles.length; i++)
421 File f = backupFiles[i];
422 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix, digits);
423 bfHashMap.put(bfp.indexNum(), f);
425 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
426 bfTreeMap.putAll(bfHashMap);
430 public boolean rollBackupsAndRenameTempFile()
432 boolean write = this.getWriteSuccess();
434 boolean roll = false;
436 roll = this.rollBackupFiles();
442 * Not sure that this confirmation is desirable. By this stage the new file is
443 * already written successfully, but something (e.g. disk full) has happened while
444 * trying to roll the backup files, and most likely the filename needed will already
445 * be vacant so renaming the temp file is nearly always correct!
449 int confirm = JvOptionPane.showConfirmDialog(Desktop.desktop,
450 MessageManager.getString(
451 "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"),
452 MessageManager.getString("label.backupfiles_confirm_save_file"),
453 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
455 if (confirm == JvOptionPane.YES_OPTION)
461 boolean rename = false;
464 rename = this.renameTempFile();
470 public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
472 String suffix, int digits)
474 File[] backupFiles = null;
476 File file = new File(fileName);
482 dirFile = file.getParentFile();
483 dir = dirFile.getCanonicalPath();
484 } catch (Exception e)
487 "Could not get canonical path for file '" + file + "'");
488 return new TreeMap<>();
491 String filename = file.getName();
492 String basename = filename;
494 // find existing backup files
495 BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix, digits);
496 backupFiles = dirFile.listFiles(bff); // is clone needed?
498 // sort the backup files (based on integer found in the suffix) using a
499 // precomputed Hashmap for speed
500 Map<Integer, File> bfHashMap = new HashMap<>();
501 for (int i = 0; i < backupFiles.length; i++)
503 File f = backupFiles[i];
504 BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
506 bfHashMap.put(bfp.indexNum(), f);
508 TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
509 bfTreeMap.putAll(bfHashMap);