Update to match develop to allow merge
[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 import jalview.util.Platform;
8
9 import java.io.File;
10 import java.io.IOException;
11 import java.text.SimpleDateFormat;
12 import java.util.ArrayList;
13 import java.util.HashMap;
14 import java.util.Map;
15 import java.util.TreeMap;
16
17 /*
18  * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
19  * User configurable options are:
20  * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved.
21  * BACKUPFILES_SUFFIX - a template to insert after the file extension.  Use '%n' to be replaced by a 0-led SUFFIX_DIGITS long integer.
22  * BACKUPFILES_NO_MAX - flag to turn off setting a maximum number of backup files to keep.
23  * BACKUPFILES_ROLL_MAX - the maximum number of backupfiles to keep for any one alignment or project file.
24  * BACKUPFILES_SUFFIX_DIGITS - the number of digits to insert replace %n with (e.g. BACKUPFILES_SUFFIX_DIGITS = 3 would make "001", "002", etc)
25  * 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. 
26  * BACKUPFILES_CONFIRM_DELETE_OLD - if true then prompt/confirm with the user when deleting older backup/version files.
27  */
28
29 public class BackupFiles
30 {
31
32   // labels for saved params in Cache and .jalview_properties
33   public static final String NS = "BACKUPFILES";
34
35   public static final String ENABLED = NS + "_ENABLED";
36
37   public static final String SUFFIX = NS + "_SUFFIX";
38
39   public static final String NO_MAX = NS + "_NO_MAX";
40
41   public static final String ROLL_MAX = NS + "_ROLL_MAX";
42
43   public static final String SUFFIX_DIGITS = NS + "_SUFFIX_DIGITS";
44
45   public static final String NUM_PLACEHOLDER = "%n";
46
47   public static final String REVERSE_ORDER = NS + "_REVERSE_ORDER";
48
49   public static final String CONFIRM_DELETE_OLD = NS
50           + "_CONFIRM_DELETE_OLD";
51
52   private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
53
54   private static final String TEMP_FILE_EXT = ".tmp";
55
56   // file - File object to be backed up and then updated (written over)
57   private File file;
58
59   // enabled - default flag as to whether to do the backup file roll (if not
60   // defined in preferences)
61   private static boolean enabled;
62
63   // confirmDelete - default flag as to whether to confirm with the user before
64   // deleting old backup/version files
65   private static boolean confirmDelete;
66
67   // defaultSuffix - default template to use to append to basename of file
68   private String suffix;
69
70   // noMax - flag to turn off a maximum number of files
71   private boolean noMax;
72
73   // defaultMax - default max number of backup files
74   private int max;
75
76   // defaultDigits - number of zero-led digits to use in the filename
77   private int digits;
78
79   // reverseOrder - set to true to make newest (latest) files lowest number
80   // (like rolled log files)
81   private boolean reverseOrder;
82
83   // temp saved file to become new saved file
84   private File tempFile;
85
86   // flag set to see if file save to temp file was successful
87   private boolean tempFileWriteSuccess;
88
89   // array of files to be deleted, with extra information
90   private ArrayList<File> deleteFiles = new ArrayList<>();
91
92   // date formatting for modification times
93   private static final SimpleDateFormat sdf = new SimpleDateFormat(
94           "yyyy-MM-dd HH:mm:ss");
95
96   public BackupFiles(String filename)
97   {
98     this(new File(filename));
99   }
100
101   // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
102   // REVERSE_ORDER
103   public BackupFiles(File file)
104   {
105     this(file, ".bak" + NUM_PLACEHOLDER, false, 3, 3, false);
106   }
107
108   public BackupFiles(File file, String defaultSuffix, boolean defaultNoMax,
109           int defaultMax, int defaultDigits, boolean defaultReverseOrder)
110   {
111     classInit();
112     this.file = file;
113     this.suffix = Cache.getDefault(SUFFIX, defaultSuffix);
114     this.noMax = Cache.getDefault(NO_MAX, defaultNoMax);
115     this.max = Cache.getDefault(ROLL_MAX, defaultMax);
116     this.digits = Cache.getDefault(SUFFIX_DIGITS, defaultDigits);
117     this.reverseOrder = Cache.getDefault(REVERSE_ORDER,
118             defaultReverseOrder);
119
120     // create a temp file to save new data in
121     File temp = null;
122     try
123     {
124       if (file != null)
125       {
126         String tempfilename = file.getName();
127         File tempdir = file.getParentFile();
128         temp = File.createTempFile(tempfilename, TEMP_FILE_EXT + "_newfile",
129                 tempdir);
130       }
131       else
132       {
133         temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
134       }
135     } catch (IOException e)
136     {
137       System.out.println(
138               "Could not create temp file to save into (IOException)");
139     } catch (Exception e)
140     {
141       System.out.println("Exception ctreating temp file for saving");
142     }
143     this.setTempFile(temp);
144   }
145
146   public static void classInit()
147   {
148     setEnabled(Cache.getDefault(ENABLED, !Platform.isJS()));
149     setConfirmDelete(Cache.getDefault(CONFIRM_DELETE_OLD, true));
150   }
151
152   public static void setEnabled(boolean flag)
153   {
154     enabled = flag;
155   }
156
157   public static boolean getEnabled()
158   {
159     classInit();
160     return enabled;
161   }
162
163   public static void setConfirmDelete(boolean flag)
164   {
165     confirmDelete = flag;
166   }
167
168   public static boolean getConfirmDelete()
169   {
170     classInit();
171     return confirmDelete;
172   }
173
174   // set, get and rename temp file into place
175   public void setTempFile(File temp)
176   {
177     this.tempFile = temp;
178   }
179
180   public File getTempFile()
181   {
182     return tempFile;
183   }
184
185   public String getTempFilePath()
186   {
187     String path = null;
188     try
189     {
190       path = this.getTempFile().getCanonicalPath();
191     } catch (IOException e)
192     {
193       System.out.println(
194               "IOException when getting Canonical Path of temp file '"
195                       + this.getTempFile().getName() + "'");
196     }
197     return path;
198   }
199
200   public boolean setWriteSuccess(boolean flag)
201   {
202     boolean old = this.tempFileWriteSuccess;
203     this.tempFileWriteSuccess = flag;
204     return old;
205   }
206
207   public boolean getWriteSuccess()
208   {
209     return this.tempFileWriteSuccess;
210   }
211
212   public boolean renameTempFile()
213   {
214     return tempFile.renameTo(file);
215   }
216
217   // roll the backupfiles
218   public boolean rollBackupFiles()
219   {
220     return this.rollBackupFiles(true);
221   }
222
223   public boolean rollBackupFiles(boolean tidyUp)
224   {
225     // file doesn't yet exist or backups are not enabled or template is null or
226     // empty
227     if ((!file.exists()) || (!enabled) || max < 0 || suffix == null
228             || suffix.length() == 0)
229     {
230       // nothing to do
231       return true;
232     }
233
234     String dir = "";
235     File dirFile;
236     try
237     {
238       dirFile = file.getParentFile();
239       dir = dirFile.getCanonicalPath();
240     } catch (Exception e)
241     {
242       System.out.println(
243               "Could not get canonical path for file '" + file + "'");
244       return false;
245     }
246     String filename = file.getName();
247     String basename = filename;
248
249     boolean ret = true;
250     // Create/move backups up one
251
252     deleteFiles.clear();
253
254     // find existing backup files
255     BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
256             digits);
257     File[] backupFiles = dirFile.listFiles(bff);
258     int nextIndexNum = 0;
259
260     if (backupFiles.length == 0)
261     {
262       // No other backup files. Just need to move existing file to backupfile_1
263       nextIndexNum = 1;
264     }
265     else
266     {
267       TreeMap<Integer, File> bfTreeMap = sortBackupFilesAsTreeMap(
268               backupFiles, basename);
269       // bfTreeMap now a sorted list of <Integer index>,<File backupfile>
270       // mappings
271
272       if (reverseOrder)
273       {
274         // backup style numbering
275
276
277         int tempMax = noMax ? -1 : max;
278         // noMax == true means no limits
279         // look for first "gap" in backupFiles
280         // if tempMax is -1 at this stage just keep going until there's a gap,
281         // then hopefully tempMax gets set to the right index (a positive
282         // integer so the loop breaks)...
283         // why do I feel a little uneasy about this loop?..
284         for (int i = 1; tempMax < 0 || i <= max; i++)
285         {
286           if (!bfTreeMap.containsKey(i)) // first index without existent
287                                          // backupfile
288           {
289             tempMax = i;
290           }
291         }
292         
293         File previousFile = null;
294         File fileToBeDeleted = null;
295         for (int n = tempMax; n > 0; n--)
296         {
297           String backupfilename = dir + File.separatorChar
298                   + BackupFilenameParts.getBackupFilename(n, basename,
299                           suffix, digits);
300           File backupfile_n = new File(backupfilename);
301
302           if (!backupfile_n.exists())
303           {
304             // no "oldest" file to delete
305             previousFile = backupfile_n;
306             fileToBeDeleted = null;
307             continue;
308           }
309
310           // check the modification time of this (backupfile_n) and the previous
311           // file (fileToBeDeleted) if the previous file is going to be deleted
312           if (fileToBeDeleted != null)
313           {
314             File replacementFile = backupfile_n;
315             long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
316             long replacementFileLMT = replacementFile.lastModified();
317
318             try
319             {
320               File oldestTempFile = nextTempFile(fileToBeDeleted.getName(),
321                       dirFile);
322               
323               if (fileToBeDeletedLMT > replacementFileLMT)
324               {
325                 String fileToBeDeletedLMTString = sdf
326                         .format(fileToBeDeletedLMT);
327                 String replacementFileLMTString = sdf
328                         .format(replacementFileLMT);
329                 System.out.println("WARNING! I am set to delete backupfile "
330                         + fileToBeDeleted.getName()
331                         + " has modification time "
332                         + fileToBeDeletedLMTString
333                         + " which is newer than its replacement "
334                         + replacementFile.getName()
335                         + " with modification time "
336                         + replacementFileLMTString);
337
338                 boolean delete = confirmNewerDeleteFile(fileToBeDeleted,
339                         replacementFile, true);
340
341                 if (delete)
342                 {
343                   // User has confirmed delete -- no need to add it to the list
344                   fileToBeDeleted.delete();
345                 }
346                 else
347                 {
348                   fileToBeDeleted.renameTo(oldestTempFile);
349                 }
350               }
351               else
352               {
353                 fileToBeDeleted.renameTo(oldestTempFile);
354                 addDeleteFile(oldestTempFile);
355               }
356
357             } catch (Exception e)
358             {
359               System.out.println(
360                       "Error occurred, probably making new temp file for '"
361                               + fileToBeDeleted.getName() + "'");
362               e.printStackTrace();
363             }
364
365             // reset
366             fileToBeDeleted = null;
367           }
368
369           if (!noMax && n == tempMax && backupfile_n.exists())
370           {
371             fileToBeDeleted = backupfile_n;
372           }
373           else
374           {
375             if (previousFile != null)
376             {
377               ret = ret && backupfile_n.renameTo(previousFile);
378             }
379           }
380
381           previousFile = backupfile_n;
382         }
383
384         // index to use for the latest backup
385         nextIndexNum = 1;
386       }
387       else
388       {
389         // version style numbering (with earliest file deletion if max files
390         // reached)
391
392         bfTreeMap.values().toArray(backupFiles);
393
394         // noMax == true means keep all backup files
395         if ((!noMax) && bfTreeMap.size() >= max)
396         {
397           // need to delete some files to keep number of backups to designated
398           // max
399           int numToDelete = bfTreeMap.size() - max + 1;
400           // the "replacement" file is the latest backup file being kept (it's
401           // not replacing though)
402           File replacementFile = numToDelete < backupFiles.length
403                   ? backupFiles[numToDelete]
404                   : null;
405           for (int i = 0; i < numToDelete; i++)
406           {
407             // check the deletion files for modification time of the last
408             // backupfile being saved
409             File fileToBeDeleted = backupFiles[i];
410             boolean delete = true;
411
412             boolean newer = false;
413             if (replacementFile != null)
414             {
415               long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
416               long replacementFileLMT = replacementFile != null
417                       ? replacementFile.lastModified()
418                       : Long.MAX_VALUE;
419               if (fileToBeDeletedLMT > replacementFileLMT)
420               {
421                 String fileToBeDeletedLMTString = sdf
422                         .format(fileToBeDeletedLMT);
423                 String replacementFileLMTString = sdf
424                         .format(replacementFileLMT);
425
426                 System.out
427                         .println("WARNING! I am set to delete backupfile '"
428                                 + fileToBeDeleted.getName()
429                                 + "' has modification time "
430                         + fileToBeDeletedLMTString
431                                 + " which is newer than the oldest backupfile being kept '"
432                         + replacementFile.getName()
433                                 + "' with modification time "
434                         + replacementFileLMTString);
435
436                 delete = confirmNewerDeleteFile(fileToBeDeleted,
437                         replacementFile, false);
438                 if (delete)
439                 {
440                   // User has confirmed delete -- no need to add it to the list
441                   fileToBeDeleted.delete();
442                   delete = false;
443                 }
444                 else
445                 {
446                   // keeping file, nothing to do!
447                 }
448               }
449             }
450             if (delete)
451             {
452               addDeleteFile(fileToBeDeleted);
453             }
454
455           }
456
457         }
458
459         nextIndexNum = bfTreeMap.lastKey() + 1;
460       }
461     }
462
463     // Let's make the new backup file!! yay, got there at last!
464     String latestBackupFilename = dir + File.separatorChar
465             + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
466                     suffix, digits);
467     ret |= file.renameTo(new File(latestBackupFilename));
468
469     if (tidyUp)
470     {
471       tidyUpFiles();
472     }
473
474     return ret;
475   }
476
477   private static File nextTempFile(String filename, File dirFile)
478           throws IOException
479   {
480     File temp = null;
481     COUNT: for (int i = 1; i < 1000; i++)
482     {
483       File trythis = new File(dirFile,
484               filename + '~' + Integer.toString(i));
485       if (!trythis.exists())
486       {
487         temp = trythis;
488         break COUNT;
489       }
490
491     }
492     if (temp == null)
493     {
494       temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
495     }
496     return temp;
497   }
498
499   private void tidyUpFiles()
500   {
501     deleteOldFiles();
502   }
503
504   private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
505           File replacementFile, boolean replace)
506   {
507     StringBuilder messageSB = new StringBuilder();
508
509     File ftbd = fileToBeDeleted;
510     String ftbdLMT = sdf.format(ftbd.lastModified());
511     String ftbdSize = Long.toString(ftbd.length());
512
513     File rf = replacementFile;
514     String rfLMT = sdf.format(rf.lastModified());
515     String rfSize = Long.toString(rf.length());
516
517     int confirmButton = JvOptionPane.NO_OPTION;
518     if (replace)
519     {
520       File saveFile = null;
521       try
522       {
523         saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
524       } catch (Exception e)
525       {
526         System.out.println(
527                 "Error when confirming to keep backup file newer than other backup files.");
528         e.printStackTrace();
529       }
530       messageSB.append(MessageManager.formatMessage(
531               "label.newerdelete_replacement_line", new String[]
532               { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
533                   rfSize }));
534       messageSB.append("\n\n");
535       messageSB.append(MessageManager.formatMessage(
536               "label.confirm_deletion_or_rename", new String[]
537               { ftbd.getName(), saveFile.getName() }));
538       String[] options = new String[] {
539           MessageManager.getString("label.delete"),
540           MessageManager.getString("label.rename") };
541
542       confirmButton = JvOptionPane.showOptionDialog(Desktop.desktop,
543               messageSB.toString(),
544               MessageManager.getString("label.backupfiles_confirm_delete"),
545               JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
546               null, options, options[0]);
547     }
548     else
549     {
550       messageSB.append(MessageManager
551               .formatMessage("label.newerdelete_line", new String[]
552               { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
553                   rfSize }));
554       messageSB.append("\n\n");
555       messageSB.append(MessageManager
556               .formatMessage("label.confirm_deletion", new String[]
557               { ftbd.getName() }));
558       String[] options = new String[] {
559           MessageManager.getString("label.delete"),
560           MessageManager.getString("label.keep") };
561
562       confirmButton = JvOptionPane.showOptionDialog(Desktop.desktop,
563               messageSB.toString(),
564               MessageManager.getString("label.backupfiles_confirm_delete"),
565               JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE,
566               null, options, options[0]);
567     }
568
569
570     // return should be TRUE if file is to be deleted
571     return (confirmButton == JvOptionPane.YES_OPTION);
572   }
573
574   private void deleteOldFiles()
575   {
576     if (deleteFiles != null && !deleteFiles.isEmpty())
577     {
578       boolean doDelete = false;
579       StringBuilder messageSB = null;
580       if (confirmDelete && deleteFiles.size() > 0)
581       {
582         messageSB = new StringBuilder();
583         messageSB.append(MessageManager
584                 .getString("label.backupfiles_confirm_delete_old_files"));
585         for (int i = 0; i < deleteFiles.size(); i++)
586         {
587           File df = deleteFiles.get(i);
588           messageSB.append("\n");
589           messageSB.append(df.getName());
590           messageSB.append(" ");
591           messageSB.append(MessageManager.formatMessage("label.file_info",
592                   new String[]
593                   { sdf.format(df.lastModified()),
594                       Long.toString(df.length()) }));
595         }
596
597         int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop,
598                 messageSB.toString(),
599                 MessageManager
600                         .getString("label.backupfiles_confirm_delete"),
601                 JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE);
602
603         doDelete = (confirmButton == JvOptionPane.YES_OPTION);
604       }
605       else
606       {
607         doDelete = true;
608       }
609
610       if (doDelete)
611       {
612         for (int i = 0; i < deleteFiles.size(); i++)
613         {
614           File fileToDelete = deleteFiles.get(i);
615           fileToDelete.delete();
616           System.out.println("DELETING '" + fileToDelete.getName() + "'");
617         }
618       }
619
620     }
621
622     deleteFiles.clear();
623   }
624
625   private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
626           File[] backupFiles,
627           String basename)
628   {
629     // sort the backup files (based on integer found in the suffix) using a
630     // precomputed Hashmap for speed
631     Map<Integer, File> bfHashMap = new HashMap<>();
632     for (int i = 0; i < backupFiles.length; i++)
633     {
634       File f = backupFiles[i];
635       BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
636               digits);
637       bfHashMap.put(bfp.indexNum(), f);
638     }
639     TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
640     bfTreeMap.putAll(bfHashMap);
641     return bfTreeMap;
642   }
643
644   public boolean rollBackupsAndRenameTempFile()
645   {
646     boolean write = this.getWriteSuccess();
647
648     boolean roll = false;
649     boolean rename = false;
650     if (write)
651     {
652       roll = this.rollBackupFiles(false);
653       rename = this.renameTempFile();
654     }
655
656     /*
657      * Not sure that this confirmation is desirable.  By this stage the new file is
658      * already written successfully, but something (e.g. disk full) has happened while 
659      * trying to roll the backup files, and most likely the filename needed will already
660      * be vacant so renaming the temp file is nearly always correct!
661      */
662     boolean okay = roll && rename;
663     if (!okay)
664     {
665       StringBuilder messageSB = new StringBuilder();
666       messageSB.append(MessageManager.getString( "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
667       if (rename)
668       {
669         if (messageSB.length() > 0)
670         {
671           messageSB.append("\n");
672         }
673         messageSB.append(MessageManager.getString(
674                 "label.backupfiles_confirm_save_new_saved_file_ok"));
675       }
676       else
677       {
678         if (messageSB.length() > 0)
679         {
680           messageSB.append("\n");
681         }
682         messageSB.append(MessageManager.getString(
683                 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
684       }
685
686       int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop,
687               messageSB.toString(),
688               MessageManager
689                       .getString("label.backupfiles_confirm_save_file"),
690               JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
691       okay = confirmButton == JvOptionPane.OK_OPTION;
692     }
693     if (okay)
694     {
695       tidyUpFiles();
696     }
697
698     return rename;
699   }
700
701   public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
702           String fileName, String suffix, int digits)
703   {
704     File[] backupFiles = null;
705
706     File file = new File(fileName);
707
708     File dirFile;
709     try
710     {
711       dirFile = file.getParentFile();
712     } catch (Exception e)
713     {
714       System.out.println(
715               "Could not get canonical path for file '" + file + "'");
716       return new TreeMap<>();
717     }
718
719     String filename = file.getName();
720     String basename = filename;
721
722     // find existing backup files
723     BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
724             digits);
725     backupFiles = dirFile.listFiles(bff); // is clone needed?
726
727     // sort the backup files (based on integer found in the suffix) using a
728     // precomputed Hashmap for speed
729     Map<Integer, File> bfHashMap = new HashMap<>();
730     for (int i = 0; i < backupFiles.length; i++)
731     {
732       File f = backupFiles[i];
733       BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
734               digits);
735       bfHashMap.put(bfp.indexNum(), f);
736     }
737     TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
738     bfTreeMap.putAll(bfHashMap);
739
740     return bfTreeMap;
741   }
742
743   /*
744   private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
745           boolean delete, boolean newer)
746   {
747     return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
748   }
749   */
750   private boolean addDeleteFile(File fileToBeDeleted)
751   {
752     boolean ret = false;
753     int pos = deleteFiles.indexOf(fileToBeDeleted);
754     if (pos > -1)
755     {
756       return true;
757     }
758     else
759     {
760       deleteFiles.add(fileToBeDeleted);
761     }
762     return ret;
763   }
764
765 }