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