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