aafe8f29de6eac2fc3b40da1c11d7f6fcfa507f3
[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   public 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     return tempFile.renameTo(file);
206   }
207
208
209   // roll the backupfiles
210   public boolean rollBackupFiles()
211   {
212
213     // file doesn't yet exist or backups are not enabled
214     if ((!file.exists()) || (!enabled) || (max < 0))
215     {
216       // nothing to do
217       return true;
218     }
219
220     // split filename up to insert suffix template in the right place. template
221     // and backupMax can be set in .jalview_properties
222     String dir = "";
223     File dirFile;
224     try
225     {
226       dirFile = file.getParentFile();
227       dir = dirFile.getCanonicalPath();
228     } catch (Exception e)
229     {
230       System.out.println(
231               "Could not get canonical path for file '" + file + "'");
232       return false;
233     }
234     String filename = file.getName();
235     String basename = filename;
236
237     boolean ret = true;
238     // Create/move backups up one
239
240     File[] oldFilesToDelete = null;
241     
242     // find existing backup files
243     BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
244             digits);
245     File[] backupFiles = dirFile.listFiles(bff);
246     int nextIndexNum = 0;
247     String confirmDeleteExtraInfo = null;
248     
249     if (backupFiles.length == 0)
250     {
251       // No other backup files. Just need to move existing file to backupfile_1
252       nextIndexNum = 1;
253     }
254     else
255     {
256       TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(backupFiles, basename);
257
258       if (reverseOrder)
259       {
260         // backup style numbering
261
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++)
271         {
272           if (!bfTreeMap.containsKey(i)) // first index without existent
273                                          // backupfile
274           {
275             tempMax = i;
276           }
277         }
278
279         // for (int m = 0; m < tempMax; m++)
280         for (int n = tempMax; n > 0; n--)
281         {
282           // int n = tempMax - m;
283           String backupfilename = dir + File.separatorChar
284                   + BackupFilenameFilter.getBackupFilename(n, basename,
285                           suffix, digits);
286           File backupfile_n = new File(backupfilename);
287
288           if (!backupfile_n.exists())
289           {
290             lastfile = backupfile_n;
291             continue;
292           }
293
294           // if (m == 0 && backupfile_n.exists())
295           if ((!noMax) && n == tempMax && backupfile_n.exists())
296           {
297             // move the largest (max) rolled file to a temp file and add to the delete list
298             try
299             {
300               File temp = File.createTempFile(backupfilename, TEMP_FILE_EXT,
301                     dirFile);
302               backupfile_n.renameTo(temp);
303
304               oldFilesToDelete = new File[] { temp };
305               confirmDeleteExtraInfo = "(was " + backupfile_n.getName()
306                       + ")";
307             } catch (IOException e)
308             {
309               System.out.println(
310                       "IOException when creating temporary file for backupfilename");
311             }
312           }
313           else
314           {
315             // Just In Case
316             if (lastfile != null)
317             {
318               ret = ret && backupfile_n.renameTo(lastfile);
319             }
320           }
321
322           lastfile = backupfile_n;
323         }
324
325         // index to use for the latest backup
326         nextIndexNum = 1;
327       }
328       else
329       {
330         // version style numbering (with earliest file deletion if max files
331         // reached)
332
333
334         bfTreeMap.values().toArray(backupFiles);
335
336         // noMax == true means keep all backup files
337         if ((!noMax) && bfTreeMap.size() >= max)
338         {
339           // need to delete some files to keep number of backups to designated
340           // max
341           int numToDelete = bfTreeMap.size() - max + 1;
342           oldFilesToDelete = Arrays.copyOfRange(backupFiles, 0,
343                   numToDelete);
344
345         }
346
347         nextIndexNum = bfTreeMap.lastKey() + 1;
348
349       }
350     }
351
352     deleteOldFiles(oldFilesToDelete, confirmDeleteExtraInfo);
353
354     // Let's make the new backup file!! yay, got there at last!
355     String latestBackupFilename = dir + File.separatorChar
356             + BackupFilenameFilter.getBackupFilename(nextIndexNum, basename,
357                     suffix, digits);
358     File latestBackupFile = new File(latestBackupFilename);
359     ret = ret && file.renameTo(latestBackupFile);
360
361     return ret;
362   }
363
364   private void deleteOldFiles(File[] oldFilesToDelete, String confirmDeleteExtraInfo) {
365     if (oldFilesToDelete != null && oldFilesToDelete.length > 0)
366     {
367       // delete old backup/version files
368
369       boolean delete = false;
370       if (confirmDelete)
371       {
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)
377         {
378           confirmMessage.append("\n");
379           confirmMessage.append(f.getName());
380         }
381         if (confirmDeleteExtraInfo != null
382                 && confirmDeleteExtraInfo.length() > 0)
383         {
384           confirmMessage.append("\n");
385           confirmMessage.append(confirmDeleteExtraInfo);
386         }
387         int confirm = JvOptionPane.showConfirmDialog(Desktop.desktop,
388                 confirmMessage.toString(),
389                 MessageManager
390                         .getString("label.backupfiles_confirm_delete"),
391                 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
392
393         delete = (confirm == JvOptionPane.YES_OPTION);
394       }
395       else
396       {
397         delete = true;
398       }
399
400       if (delete)
401       {
402         for (int i = 0; i < oldFilesToDelete.length; i++)
403         {
404           File fileToDelete = oldFilesToDelete[i];
405           fileToDelete.delete();
406           // System.out.println("DELETING '" + fileToDelete.getName() +
407           // "'");
408         }
409       }
410
411     }
412   }
413
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++)
419       {
420           File f = backupFiles[i];
421           BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix, digits);
422           bfHashMap.put(bfp.indexNum(), f);
423       }
424       TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
425       bfTreeMap.putAll(bfHashMap);
426       return bfTreeMap;
427   }
428
429   public boolean rollBackupsAndRenameTempFile()
430   {
431     boolean write = this.getWriteSuccess();
432     
433     boolean roll = false;
434     if (write) {
435       roll = this.rollBackupFiles();
436     } else {
437       return false;
438     }
439     
440     /*
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!
445      */
446     if (!roll)
447     {
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);
453
454       if (confirm == JvOptionPane.YES_OPTION)
455       {
456         roll = true;
457       }
458     }
459
460     boolean rename = false;
461     if (roll)
462     {
463       rename = this.renameTempFile();
464     }
465
466     return rename;
467   }
468
469   public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
470           String fileName,
471           String suffix, int digits)
472   {
473     File[] backupFiles = null;
474
475     File file = new File(fileName);
476
477     String dir = "";
478     File dirFile;
479     try
480     {
481       dirFile = file.getParentFile();
482       dir = dirFile.getCanonicalPath();
483     } catch (Exception e)
484     {
485       System.out.println(
486               "Could not get canonical path for file '" + file + "'");
487       return new TreeMap<>();
488     }
489
490     String filename = file.getName();
491     String basename = filename;
492     
493     // find existing backup files
494     BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix, digits);
495     backupFiles = dirFile.listFiles(bff); // is clone needed?
496     
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++)
501     {
502       File f = backupFiles[i];
503       BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
504               digits);
505       bfHashMap.put(bfp.indexNum(), f);
506     }
507     TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
508     bfTreeMap.putAll(bfHashMap);
509
510     return bfTreeMap;
511   }
512
513
514 }
515