JAL-3141 Changed suffix position to after the extension (removed extension detection...
[jalview.git] / src / jalview / io / BackupFiles.java
1 package jalview.io;
2
3 import jalview.bin.Cache;
4 import jalview.gui.Desktop;
5 import jalview.gui.JvOptionPane;
6 import jalview.util.MessageManager;
7
8 import java.io.File;
9 import java.io.IOException;
10 import java.util.Arrays;
11 import java.util.Map;
12 import java.util.HashMap;
13 import java.util.TreeMap;
14
15 /*
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.
25  */
26
27 public class BackupFiles
28 {
29
30   // labels for saved params in Cache and .jalview_properties
31   private static final String NS = "BACKUPFILES";
32
33   public static final String ENABLED = NS + "_ENABLED";
34
35   public static final String SUFFIX = NS + "_SUFFIX";
36
37   public static final String NO_MAX = NS + "_NO_MAX";
38
39   public static final String ROLL_MAX = NS + "_ROLL_MAX";
40
41   public static final String SUFFIX_DIGITS = NS + "_SUFFIX_DIGITS";
42
43   public static final String NUM_PLACEHOLDER = "%n";
44
45   public static final String REVERSE_ORDER = NS + "_REVERSE_ORDER";
46
47   public static final String CONFIRM_DELETE_OLD = NS + "_CONFIRM_DELETE_OLD";
48
49   private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
50
51   private static final String TEMP_FILE_EXT = ".tmp";
52
53   // file - File object to be backed up and then updated (written over)
54   private File file;
55
56   // enabled - default flag as to whether to do the backup file roll (if not
57   // defined in preferences)
58   private static boolean enabled;
59
60   // confirmDelete - default flag as to whether to confirm with the user before
61   // deleting old backup/version files
62   private static boolean confirmDelete;
63
64   // defaultSuffix - default template to use to append to basename of file
65   private String suffix;
66
67   // noMax - flag to turn off a maximum number of files
68   private boolean noMax;
69
70   // defaultMax - default max number of backup files
71   private int max;
72
73   // defaultDigits - number of zero-led digits to use in the filename
74   private int digits;
75
76   // reverseOrder - set to true to make newest (latest) files lowest number
77   // (like rolled log files)
78   private boolean reverseOrder;
79
80   // temp saved file to become new saved file
81   private File tempFile;
82
83   // flag set to see if file save to temp file was successful
84   private boolean tempFileWriteSuccess;
85
86   public BackupFiles(String filename)
87   {
88     this(new File(filename));
89   }
90
91   // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
92   // REVERSE_ORDER
93   public BackupFiles(File file)
94   {
95     this(file, ".v" + NUM_PLACEHOLDER, false, 4, 3, false);
96   }
97
98   public BackupFiles(File file,
99           String defaultSuffix, boolean defaultNoMax, int defaultMax,
100           int defaultDigits,
101           boolean defaultReverseOrder)
102   {
103     classInit();
104     this.file = file;
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);
111
112     // create a temp file to save new data in
113     File temp = null;
114     try
115     {
116       if (file != null)
117       {
118         String tempfilename = file.getName();
119         File tempdir = file.getParentFile();
120         temp = File.createTempFile(tempfilename, TEMP_FILE_EXT, tempdir);
121       }
122       else
123       {
124         temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
125       }
126     } catch (IOException e)
127     {
128       System.out.println(
129               "Could not create temp file to save into (IOException)");
130     } catch (Exception e)
131     {
132       System.out.println("Exception ctreating temp file for saving");
133     }
134     this.setTempFile(temp);
135   }
136
137   public static void classInit()
138   {
139     setEnabled(Cache.getDefault(ENABLED, true));
140     setConfirmDelete(Cache.getDefault(CONFIRM_DELETE_OLD, true));
141   }
142
143   public static void setEnabled(boolean flag)
144   {
145     enabled = flag;
146   }
147
148   public static boolean getEnabled()
149   {
150     classInit();
151     return enabled;
152   }
153
154   public static void setConfirmDelete(boolean flag)
155   {
156     confirmDelete = flag;
157   }
158
159   public static boolean getConfirmDelete()
160   {
161     classInit();
162     return confirmDelete;
163   }
164
165   // set, get and rename temp file into place
166   public void setTempFile(File temp)
167   {
168     this.tempFile = temp;
169   }
170
171   public File getTempFile()
172   {
173     return tempFile;
174   }
175
176   public String getTempFilePath()
177   {
178     String path = null;
179     try
180     {
181       path = this.getTempFile().getCanonicalPath();
182     } catch (IOException e)
183     {
184       System.out.println(
185               "IOException when getting Canonical Path of temp file '"
186                       + this.getTempFile().getName() + "'");
187     }
188     return path;
189   }
190
191   public boolean setWriteSuccess(boolean flag)
192   {
193     boolean old = this.tempFileWriteSuccess;
194     this.tempFileWriteSuccess = flag;
195     return old;
196   }
197
198   public boolean getWriteSuccess()
199   {
200     return this.tempFileWriteSuccess;
201   }
202
203   public boolean renameTempFile()
204   {
205     System.out.println("RENAMING TEMP FILE '"+tempFile.getName() + "' TO '"+file.getName()+"'"); // DELETEME
206     return tempFile.renameTo(file);
207   }
208
209
210   // roll the backupfiles
211   public boolean rollBackupFiles()
212   {
213
214     // file doesn't yet exist or backups are not enabled
215     if ((!file.exists()) || (!enabled) || (max < 0))
216     {
217       // nothing to do
218       return true;
219     }
220
221     // split filename up to insert suffix template in the right place. template
222     // and backupMax can be set in .jalview_properties
223     String dir = "";
224     File dirFile;
225     try
226     {
227       dirFile = file.getParentFile();
228       dir = dirFile.getCanonicalPath();
229     } catch (Exception e)
230     {
231       System.out.println(
232               "Could not get canonical path for file '" + file + "'");
233       return false;
234     }
235     String filename = file.getName();
236     String basename = filename;
237
238     boolean ret = true;
239     // Create/move backups up one
240
241     File[] oldFilesToDelete = null;
242     
243     // find existing backup files
244     BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
245             digits);
246     File[] backupFiles = dirFile.listFiles(bff);
247     int nextIndexNum = 0;
248     String confirmDeleteExtraInfo = null;
249     
250     if (backupFiles.length == 0)
251     {
252       // No other backup files. Just need to move existing file to backupfile_1
253       nextIndexNum = 1;
254     }
255     else
256     {
257       TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(backupFiles, basename);
258
259       if (reverseOrder)
260       {
261         // backup style numbering
262
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++)
272         {
273           if (!bfTreeMap.containsKey(i)) // first index without existent
274                                          // backupfile
275           {
276             tempMax = i;
277           }
278         }
279
280         // for (int m = 0; m < tempMax; m++)
281         for (int n = tempMax; n > 0; n--)
282         {
283           // int n = tempMax - m;
284           String backupfilename = dir + File.separatorChar
285                   + BackupFilenameFilter.getBackupFilename(n, basename,
286                           suffix, digits);
287           File backupfile_n = new File(backupfilename);
288
289           if (!backupfile_n.exists())
290           {
291             lastfile = backupfile_n;
292             continue;
293           }
294
295           // if (m == 0 && backupfile_n.exists())
296           if ((!noMax) && n == tempMax && backupfile_n.exists())
297           {
298             // move the largest (max) rolled file to a temp file and add to the delete list
299             try
300             {
301               File temp = File.createTempFile(backupfilename, TEMP_FILE_EXT,
302                     dirFile);
303               backupfile_n.renameTo(temp);
304
305               oldFilesToDelete = new File[] { temp };
306               confirmDeleteExtraInfo = "(was " + backupfile_n.getName()
307                       + ")";
308             } catch (IOException e)
309             {
310               System.out.println(
311                       "IOException when creating temporary file for backupfilename");
312             }
313           }
314           else
315           {
316             // Just In Case
317             if (lastfile != null)
318             {
319               ret = ret && backupfile_n.renameTo(lastfile);
320             }
321           }
322
323           lastfile = backupfile_n;
324         }
325
326         // index to use for the latest backup
327         nextIndexNum = 1;
328       }
329       else
330       {
331         // version style numbering (with earliest file deletion if max files
332         // reached)
333
334
335         bfTreeMap.values().toArray(backupFiles);
336
337         // noMax == true means keep all backup files
338         if ((!noMax) && bfTreeMap.size() >= max)
339         {
340           // need to delete some files to keep number of backups to designated
341           // max
342           int numToDelete = bfTreeMap.size() - max + 1;
343           oldFilesToDelete = Arrays.copyOfRange(backupFiles, 0,
344                   numToDelete);
345
346         }
347
348         nextIndexNum = bfTreeMap.lastKey() + 1;
349
350       }
351     }
352
353     deleteOldFiles(oldFilesToDelete, confirmDeleteExtraInfo);
354
355     // Let's make the new backup file!! yay, got there at last!
356     String latestBackupFilename = dir + File.separatorChar
357             + BackupFilenameFilter.getBackupFilename(nextIndexNum, basename,
358                     suffix, digits);
359     File latestBackupFile = new File(latestBackupFilename);
360     ret = ret && file.renameTo(latestBackupFile);
361
362     return ret;
363   }
364
365   private void deleteOldFiles(File[] oldFilesToDelete, String confirmDeleteExtraInfo) {
366     if (oldFilesToDelete != null && oldFilesToDelete.length > 0)
367     {
368       // delete old backup/version files
369
370       boolean delete = false;
371       if (confirmDelete)
372       {
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)
378         {
379           confirmMessage.append("\n");
380           confirmMessage.append(f.getName());
381         }
382         if (confirmDeleteExtraInfo != null
383                 && confirmDeleteExtraInfo.length() > 0)
384         {
385           confirmMessage.append("\n");
386           confirmMessage.append(confirmDeleteExtraInfo);
387         }
388         int confirm = JvOptionPane.showConfirmDialog(Desktop.desktop,
389                 confirmMessage.toString(),
390                 MessageManager
391                         .getString("label.backupfiles_confirm_delete"),
392                 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
393
394         delete = (confirm == JvOptionPane.YES_OPTION);
395       }
396       else
397       {
398         delete = true;
399       }
400
401       if (delete)
402       {
403         for (int i = 0; i < oldFilesToDelete.length; i++)
404         {
405           File fileToDelete = oldFilesToDelete[i];
406           fileToDelete.delete();
407           // System.out.println("DELETING '" + fileToDelete.getName() +
408           // "'");
409         }
410       }
411
412     }
413   }
414
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++)
420       {
421           File f = backupFiles[i];
422           BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix, digits);
423           bfHashMap.put(bfp.indexNum(), f);
424       }
425       TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
426       bfTreeMap.putAll(bfHashMap);
427       return bfTreeMap;
428   }
429
430   public boolean rollBackupsAndRenameTempFile()
431   {
432     boolean write = this.getWriteSuccess();
433     
434     boolean roll = false;
435     if (write) {
436       roll = this.rollBackupFiles();
437     } else {
438       return false;
439     }
440     
441     /*
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!
446      */
447     if (!roll)
448     {
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);
454
455       if (confirm == JvOptionPane.YES_OPTION)
456       {
457         roll = true;
458       }
459     }
460
461     boolean rename = false;
462     if (roll)
463     {
464       rename = this.renameTempFile();
465     }
466
467     return rename;
468   }
469
470   public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
471           String fileName,
472           String suffix, int digits)
473   {
474     File[] backupFiles = null;
475
476     File file = new File(fileName);
477
478     String dir = "";
479     File dirFile;
480     try
481     {
482       dirFile = file.getParentFile();
483       dir = dirFile.getCanonicalPath();
484     } catch (Exception e)
485     {
486       System.out.println(
487               "Could not get canonical path for file '" + file + "'");
488       return new TreeMap<>();
489     }
490
491     String filename = file.getName();
492     String basename = filename;
493     
494     // find existing backup files
495     BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix, digits);
496     backupFiles = dirFile.listFiles(bff); // is clone needed?
497     
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++)
502     {
503       File f = backupFiles[i];
504       BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
505               digits);
506       bfHashMap.put(bfp.indexNum(), f);
507     }
508     TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
509     bfTreeMap.putAll(bfHashMap);
510
511     return bfTreeMap;
512   }
513
514
515 }
516