JAL-3628 Even 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 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               ret = ret && moveFileToFile(backupfile_n, previousFile);
435             }
436           }
437
438           previousFile = backupfile_n;
439         }
440
441         // index to use for the latest backup
442         nextIndexNum = 1;
443       }
444       else // not reverse numbering
445       {
446         // version style numbering (with earliest file deletion if max files
447         // reached)
448
449         bfTreeMap.values().toArray(backupFiles);
450         StringBuilder bfsb = new StringBuilder();
451         for (int i = 0; i < backupFiles.length; i++)
452         {
453           if (bfsb.length() > 0)
454           {
455             bfsb.append(", ");
456           }
457           bfsb.append(backupFiles[i].getName());
458         }
459         Cache.log.debug("BACKUPFILES backupFiles: " + bfsb.toString());
460
461         // noMax == true means keep all backup files
462         if ((!noMax) && bfTreeMap.size() >= max)
463         {
464           Cache.log.debug("BACKUPFILES noMax: " + noMax + ", " + "max: "
465                   + max + ", " + "bfTreeMap.size(): " + bfTreeMap.size());
466           // need to delete some files to keep number of backups to designated
467           // max.
468           // Note that if the suffix is not numbered then do not delete any
469           // backup files later or we'll delete the new backup file (there can
470           // be only one).
471           int numToDelete = suffix.indexOf(NUM_PLACEHOLDER) > -1
472                   ? bfTreeMap.size() - max + 1
473                   : 0;
474           Cache.log.debug("BACKUPFILES numToDelete: " + numToDelete);
475           // the "replacement" file is the latest backup file being kept (it's
476           // not replacing though)
477           File replacementFile = numToDelete < backupFiles.length
478                   ? backupFiles[numToDelete]
479                   : null;
480           for (int i = 0; i < numToDelete; i++)
481           {
482             // check the deletion files for modification time of the last
483             // backupfile being saved
484             File fileToBeDeleted = backupFiles[i];
485             boolean delete = true;
486
487             Cache.log.debug(
488                     "BACKUPFILES fileToBeDeleted: " + fileToBeDeleted);
489
490             boolean newer = false;
491             if (replacementFile != null)
492             {
493               long fileToBeDeletedLMT = fileToBeDeleted.lastModified();
494               long replacementFileLMT = replacementFile != null
495                       ? replacementFile.lastModified()
496                       : Long.MAX_VALUE;
497               if (fileToBeDeletedLMT > replacementFileLMT)
498               {
499                 String fileToBeDeletedLMTString = sdf
500                         .format(fileToBeDeletedLMT);
501                 String replacementFileLMTString = sdf
502                         .format(replacementFileLMT);
503
504                 Cache.log.warn("WARNING! I am set to delete backupfile '"
505                         + fileToBeDeleted.getName()
506                         + "' has modification time "
507                         + fileToBeDeletedLMTString
508                         + " which is newer than the oldest backupfile being kept '"
509                         + replacementFile.getName()
510                         + "' with modification time "
511                         + replacementFileLMTString);
512
513                 delete = confirmNewerDeleteFile(fileToBeDeleted,
514                         replacementFile, false);
515                 if (delete)
516                 {
517                   // User has confirmed delete -- no need to add it to the list
518                   fileToBeDeleted.delete();
519                   Cache.log.debug("BACKUPFILES deleting fileToBeDeleted: "
520                           + fileToBeDeleted);
521                   delete = false;
522                 }
523                 else
524                 {
525                   // keeping file, nothing to do!
526                   Cache.log.debug("BACKUPFILES keeping fileToBeDeleted: "
527                           + fileToBeDeleted);
528                 }
529               }
530             }
531             if (delete)
532             {
533               addDeleteFile(fileToBeDeleted);
534               Cache.log.debug("BACKUPFILES addDeleteFile(fileToBeDeleted): "
535                       + fileToBeDeleted);
536             }
537
538           }
539
540         }
541
542         nextIndexNum = bfTreeMap.lastKey() + 1;
543       }
544     }
545
546     // Let's make the new backup file!! yay, got there at last!
547     String latestBackupFilename = dir + File.separatorChar
548             + BackupFilenameParts.getBackupFilename(nextIndexNum, basename,
549                     suffix, digits);
550     Cache.log.debug("BACKUPFILES Moving old file [" + file
551             + "] to latestBackupFilename [" + latestBackupFilename + "]");
552     ret |= moveFileToFile(file, new File(latestBackupFilename));
553     Cache.log.debug(
554             "BACKUPFILES moving " + file + " to " + latestBackupFilename
555                     + " was " + (ret ? "" : "NOT ") + "successful");
556     if (tidyUp)
557     {
558       Cache.log.debug("BACKUPFILES tidying up files");
559       tidyUpFiles();
560     }
561
562     return ret;
563   }
564
565   private static File nextTempFile(String filename, File dirFile)
566           throws IOException
567   {
568     File temp = null;
569     COUNT: for (int i = 1; i < 1000; i++)
570     {
571       File trythis = new File(dirFile,
572               filename + '~' + Integer.toString(i));
573       if (!trythis.exists())
574       {
575         temp = trythis;
576         break COUNT;
577       }
578
579     }
580     if (temp == null)
581     {
582       temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile);
583     }
584     return temp;
585   }
586
587   private void tidyUpFiles()
588   {
589     deleteOldFiles();
590   }
591
592   private static boolean confirmNewerDeleteFile(File fileToBeDeleted,
593           File replacementFile, boolean replace)
594   {
595     StringBuilder messageSB = new StringBuilder();
596
597     File ftbd = fileToBeDeleted;
598     String ftbdLMT = sdf.format(ftbd.lastModified());
599     String ftbdSize = Long.toString(ftbd.length());
600
601     File rf = replacementFile;
602     String rfLMT = sdf.format(rf.lastModified());
603     String rfSize = Long.toString(rf.length());
604
605     int confirmButton = JvOptionPane.NO_OPTION;
606     if (replace)
607     {
608       File saveFile = null;
609       try
610       {
611         saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile());
612       } catch (Exception e)
613       {
614         Cache.log.error(
615                 "Error when confirming to keep backup file newer than other backup files.");
616         e.printStackTrace();
617       }
618       messageSB.append(MessageManager.formatMessage(
619               "label.newerdelete_replacement_line", new String[]
620               { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
621                   rfSize }));
622       // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted and
623       // replaced by apparently older file \n''{1}''\t(modified {3}, size
624       // {5}).""
625       messageSB.append("\n\n");
626       messageSB.append(MessageManager.formatMessage(
627               "label.confirm_deletion_or_rename", new String[]
628               { ftbd.getName(), saveFile.getName() }));
629       // "Confirm deletion of ''{0}'' or rename to ''{1}''?"
630       String[] options = new String[] {
631           MessageManager.getString("label.delete"),
632           MessageManager.getString("label.rename") };
633
634       confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
635               : JvOptionPane.showOptionDialog(Desktop.desktop,
636                       messageSB.toString(),
637                       MessageManager.getString(
638                               "label.backupfiles_confirm_delete"),
639                       // "Confirm delete"
640                       JvOptionPane.YES_NO_OPTION,
641                       JvOptionPane.WARNING_MESSAGE, null, options,
642                       options[0]);
643     }
644     else
645     {
646       messageSB.append(MessageManager
647               .formatMessage("label.newerdelete_line", new String[]
648               { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize,
649                   rfSize }));
650       // "Backup file\n''{0}''\t(modified {2}, size {4})\nis to be deleted but
651       // is newer than the oldest remaining backup file \n''{1}''\t(modified
652       // {3}, size {5})."
653       messageSB.append("\n\n");
654       messageSB.append(MessageManager
655               .formatMessage("label.confirm_deletion", new String[]
656               { ftbd.getName() }));
657       // "Confirm deletion of ''{0}''?"
658       String[] options = new String[] {
659           MessageManager.getString("label.delete"),
660           MessageManager.getString("label.keep") };
661
662       confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
663               : JvOptionPane.showOptionDialog(Desktop.desktop,
664                       messageSB.toString(),
665                       MessageManager.getString(
666                               "label.backupfiles_confirm_delete"),
667                       // "Confirm delete"
668                       JvOptionPane.YES_NO_OPTION,
669                       JvOptionPane.WARNING_MESSAGE, null, options,
670                       options[0]);
671     }
672
673     // return should be TRUE if file is to be deleted
674     return (confirmButton == JvOptionPane.YES_OPTION);
675   }
676
677   private void deleteOldFiles()
678   {
679     if (deleteFiles != null && !deleteFiles.isEmpty())
680     {
681       boolean doDelete = false;
682       StringBuilder messageSB = null;
683       if (confirmDelete && deleteFiles.size() > 0)
684       {
685         messageSB = new StringBuilder();
686         messageSB.append(MessageManager
687                 .getString("label.backupfiles_confirm_delete_old_files"));
688         // "Delete the following older backup files? (see the Backups tab in
689         // Preferences for more options)"
690         for (int i = 0; i < deleteFiles.size(); i++)
691         {
692           File df = deleteFiles.get(i);
693           messageSB.append("\n");
694           messageSB.append(df.getName());
695           messageSB.append(" ");
696           messageSB.append(MessageManager.formatMessage("label.file_info",
697                   new String[]
698                   { sdf.format(df.lastModified()),
699                       Long.toString(df.length()) }));
700           // "(modified {0}, size {1})"
701         }
702
703         int confirmButton = Platform.isHeadless() ? JvOptionPane.YES_OPTION
704                 : JvOptionPane.showConfirmDialog(Desktop.desktop,
705                         messageSB.toString(),
706                         MessageManager.getString(
707                                 "label.backupfiles_confirm_delete"),
708                         // "Confirm delete"
709                         JvOptionPane.YES_NO_OPTION,
710                         JvOptionPane.WARNING_MESSAGE);
711
712         doDelete = (confirmButton == JvOptionPane.YES_OPTION);
713       }
714       else
715       {
716         doDelete = true;
717       }
718
719       if (doDelete)
720       {
721         for (int i = 0; i < deleteFiles.size(); i++)
722         {
723           File fileToDelete = deleteFiles.get(i);
724           Cache.log.debug(
725                   "BACKUPFILES deleting fileToDelete:" + fileToDelete);
726           fileToDelete.delete();
727           Cache.log.warn("deleting '" + fileToDelete.getName() + "'");
728         }
729       }
730
731     }
732
733     deleteFiles.clear();
734   }
735
736   private TreeMap<Integer, File> sortBackupFilesAsTreeMap(
737           File[] backupFiles, String basename)
738   {
739     // sort the backup files (based on integer found in the suffix) using a
740     // precomputed Hashmap for speed
741     Map<Integer, File> bfHashMap = new HashMap<>();
742     for (int i = 0; i < backupFiles.length; i++)
743     {
744       File f = backupFiles[i];
745       BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
746               digits);
747       bfHashMap.put(bfp.indexNum(), f);
748     }
749     TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
750     bfTreeMap.putAll(bfHashMap);
751     return bfTreeMap;
752   }
753
754   public boolean rollBackupsAndRenameTempFile()
755   {
756     boolean write = this.getWriteSuccess();
757
758     boolean roll = false;
759     boolean rename = false;
760     if (write)
761     {
762       roll = this.rollBackupFiles(false); // tidyUpFiles at the end
763       rename = this.renameTempFile();
764     }
765
766     /*
767      * Not sure that this confirmation is desirable.  By this stage the new file is
768      * already written successfully, but something (e.g. disk full) has happened while 
769      * trying to roll the backup files, and most likely the filename needed will already
770      * be vacant so renaming the temp file is nearly always correct!
771      */
772     boolean okay = roll && rename;
773     if (!okay)
774     {
775       StringBuilder messageSB = new StringBuilder();
776       messageSB.append(MessageManager.getString(
777               "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"));
778       // "Something possibly went wrong with the backups of this file."
779       if (rename)
780       {
781         if (messageSB.length() > 0)
782         {
783           messageSB.append("\n");
784         }
785         messageSB.append(MessageManager.getString(
786                 "label.backupfiles_confirm_save_new_saved_file_ok"));
787         // "The new saved file seems okay."
788       }
789       else
790       {
791         if (messageSB.length() > 0)
792         {
793           messageSB.append("\n");
794         }
795         messageSB.append(MessageManager.getString(
796                 "label.backupfiles_confirm_save_new_saved_file_not_ok"));
797         // "The new saved file might not be okay."
798       }
799
800       int confirmButton = Platform.isHeadless() ? JvOptionPane.OK_OPTION
801               : JvOptionPane.showConfirmDialog(Desktop.desktop,
802                       messageSB.toString(),
803                       MessageManager.getString(
804                               "label.backupfiles_confirm_save_file"),
805                       // "Confirm save file"
806                       JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE);
807       okay = confirmButton == JvOptionPane.OK_OPTION;
808     }
809     if (okay)
810     {
811       tidyUpFiles();
812     }
813
814     return rename;
815   }
816
817   public static TreeMap<Integer, File> getBackupFilesAsTreeMap(
818           String fileName, String suffix, int digits)
819   {
820     File[] backupFiles = null;
821
822     File file = new File(fileName);
823
824     File dirFile;
825     try
826     {
827       dirFile = file.getParentFile();
828     } catch (Exception e)
829     {
830       Cache.log.error(
831               "Could not get canonical path for file '" + file + "'");
832       return new TreeMap<>();
833     }
834
835     String filename = file.getName();
836     String basename = filename;
837
838     // find existing backup files
839     BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix,
840             digits);
841     backupFiles = dirFile.listFiles(bff); // is clone needed?
842
843     // sort the backup files (based on integer found in the suffix) using a
844     // precomputed Hashmap for speed
845     Map<Integer, File> bfHashMap = new HashMap<>();
846     for (int i = 0; i < backupFiles.length; i++)
847     {
848       File f = backupFiles[i];
849       BackupFilenameParts bfp = new BackupFilenameParts(f, basename, suffix,
850               digits);
851       bfHashMap.put(bfp.indexNum(), f);
852     }
853     TreeMap<Integer, File> bfTreeMap = new TreeMap<>();
854     bfTreeMap.putAll(bfHashMap);
855
856     return bfTreeMap;
857   }
858
859   /*
860   private boolean addDeleteFile(File fileToBeDeleted, File originalFile,
861           boolean delete, boolean newer)
862   {
863     return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer);
864   }
865   */
866   private boolean addDeleteFile(File fileToBeDeleted)
867   {
868     boolean ret = false;
869     int pos = deleteFiles.indexOf(fileToBeDeleted);
870     if (pos > -1)
871     {
872       Cache.log.debug("BACKUPFILES not adding file "
873               + fileToBeDeleted.getAbsolutePath()
874               + " to the delete list (already at index" + pos + ")");
875       return true;
876     }
877     else
878     {
879       Cache.log.debug("BACKUPFILES adding file "
880               + fileToBeDeleted.getAbsolutePath() + " to the delete list");
881       deleteFiles.add(fileToBeDeleted);
882     }
883     return ret;
884   }
885
886   public static boolean moveFileToFile(File oldFile, File newFile)
887   {
888     boolean ret = false;
889     Path oldPath = Paths.get(oldFile.getAbsolutePath());
890     Path newPath = Paths.get(newFile.getAbsolutePath());
891     try
892     {
893       // delete destination file - not usually necessary but Just In Case...
894       Cache.log.debug("BACKUPFILES deleting " + newFile.getAbsolutePath());
895       newFile.delete();
896       Cache.log.debug("BACKUPFILES moving " + oldFile.getAbsolutePath()
897               + " to " + newFile.getAbsolutePath());
898       Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING);
899       ret = true;
900       Cache.log.debug("BACKUPFILES move seems to have succeeded");
901     } catch (IOException e)
902     {
903       Cache.log.warn("Could not move file '" + oldPath.toString() + "' to '"
904               + newPath.toString() + "'");
905       Cache.log.error(e.getMessage());
906       Cache.log.debug(e.getStackTrace());
907       ret = false;
908     } catch (Exception e)
909     {
910       Cache.log.error(e.getMessage());
911       Cache.log.debug(e.getStackTrace());
912       ret = false;
913     }
914     return ret;
915   }
916 }