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