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