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