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