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