JAL-3754 Fixed jar task creating strange dir because of outputs.file()
[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.text.SimpleDateFormat;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.Map;
35 import java.util.TreeMap;
36
37 /*
38  * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved.
39  * User configurable options are:
40  * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved.
41  * The rest of the options are now saved as BACKUPFILES_PRESET, BACKUPFILES_SAVED and BACKUPFILES_CUSTOM
42  * (see BackupFilesPresetEntry)
43  */
44
45 public class BackupFiles
46 {
47
48   // labels for saved params in Cache and .jalview_properties
49   public static final String NS = "BACKUPFILES";
50
51   public static final String ENABLED = NS + "_ENABLED";
52
53   public static final String NUM_PLACEHOLDER = "%n";
54
55   private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS;
56
57   private static final String TEMP_FILE_EXT = ".tmp";
58
59   // file - File object to be backed up and then updated (written over)
60   private File file;
61
62   // enabled - default flag as to whether to do the backup file roll (if not
63   // defined in preferences)
64   private static boolean enabled;
65
66   // confirmDelete - default flag as to whether to confirm with the user before
67   // deleting old backup/version files
68   private static boolean confirmDelete;
69
70   // defaultSuffix - default template to use to append to basename of file
71   private String suffix;
72
73   // noMax - flag to turn off a maximum number of files
74   private boolean noMax;
75
76   // defaultMax - default max number of backup files
77   private int max;
78
79   // defaultDigits - number of zero-led digits to use in the filename
80   private int digits;
81
82   // reverseOrder - set to true to make newest (latest) files lowest number
83   // (like rolled log files)
84   private boolean reverseOrder;
85
86   // temp saved file to become new saved file
87   private File tempFile;
88
89   // flag set to see if file save to temp file was successful
90   private boolean tempFileWriteSuccess;
91
92   // array of files to be deleted, with extra information
93   private ArrayList<File> deleteFiles = new ArrayList<>();
94
95   // date formatting for modification times
96   private static final SimpleDateFormat sdf = new SimpleDateFormat(
97           "yyyy-MM-dd HH:mm:ss");
98
99   public BackupFiles(String filename)
100   {
101     this(new File(filename));
102   }
103
104   // first time defaults for SUFFIX, NO_MAX, ROLL_MAX, SUFFIX_DIGITS and
105   // REVERSE_ORDER
106   public BackupFiles(File file)
107   {
108     classInit();
109     this.file = file;
110     BackupFilesPresetEntry bfpe = BackupFilesPresetEntry.getSavedBackupEntry();
111     this.suffix = bfpe.suffix;
112     this.noMax = bfpe.keepAll;
113     this.max = bfpe.rollMax;
114     this.digits = bfpe.digits;
115     this.reverseOrder = bfpe.reverse;
116
117     // create a temp file to save new data in
118     File temp = null;
119     try
120     {
121       if (file != null)
122       {
123         String tempfilename = file.getName();
124         File tempdir = file.getParentFile();
125         temp = File.createTempFile(tempfilename, TEMP_FILE_EXT + "_newfile",
126                 tempdir);
127       }
128       else
129       {
130         temp = File.createTempFile(DEFAULT_TEMP_FILE, TEMP_FILE_EXT);
131       }
132     } catch (IOException e)
133     {
134       System.out.println(
135               "Could not create temp file to save into (IOException)");
136     } catch (Exception e)
137     {
138       System.out.println("Exception ctreating temp file for saving");
139     }
140     this.setTempFile(temp);
141   }
142
143   public static void classInit()
144   {
145     setEnabled(Cache.getDefault(ENABLED, !Platform.isJS()));
146     BackupFilesPresetEntry bfpe = BackupFilesPresetEntry
147             .getSavedBackupEntry();
148     setConfirmDelete(bfpe.confirmDelete);
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 }