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