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