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