X-Git-Url: http://source.jalview.org/gitweb/?a=blobdiff_plain;f=src%2Fjalview%2Fio%2FBackupFiles.java;h=1c8525b2de5987b135c6972da80620522470c718;hb=31df3f13e3ab1ac158ec576d691fa860e9f6dd4b;hp=65232fd16cde68a349d682d2b100337d67decb64;hpb=db80eb8e1acf352e72a33e1e3825d40f7c6e4046;p=jalview.git diff --git a/src/jalview/io/BackupFiles.java b/src/jalview/io/BackupFiles.java index 65232fd..1c8525b 100644 --- a/src/jalview/io/BackupFiles.java +++ b/src/jalview/io/BackupFiles.java @@ -1,27 +1,54 @@ +/* + * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$) + * Copyright (C) $$Year-Rel$$ The Jalview Authors + * + * This file is part of Jalview. + * + * Jalview is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation, either version 3 + * of the License, or (at your option) any later version. + * + * Jalview is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty + * of MERCHANTABILITY or FITNESS FOR A PARTICULAR + * PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Jalview. If not, see . + * The Jalview Authors are detailed in the 'AUTHORS' file. + */ package jalview.io; import jalview.bin.Cache; import jalview.gui.Desktop; import jalview.gui.JvOptionPane; import jalview.util.MessageManager; +import jalview.util.Platform; import java.io.File; import java.io.IOException; -import java.util.Arrays; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; +import jalview.bin.Cache; +import jalview.gui.Desktop; +import jalview.gui.JvOptionPane; +import jalview.util.MessageManager; + /* * BackupFiles used for manipulating (naming rolling/deleting) backup/version files when an alignment or project file is saved. * User configurable options are: * BACKUPFILES_ENABLED - boolean flag as to whether to use this mechanism or act as before, including overwriting files as saved. - * BACKUPFILES_SUFFIX - a template to insert after the file extension. Use '%n' to be replaced by a 0-led SUFFIX_DIGITS long integer. - * BACKUPFILES_NO_MAX - flag to turn off setting a maximum number of backup files to keep. - * BACKUPFILES_ROLL_MAX - the maximum number of backupfiles to keep for any one alignment or project file. - * BACKUPFILES_SUFFIX_DIGITS - the number of digits to insert replace %n with (e.g. BACKUPFILES_SUFFIX_DIGITS = 3 would make "001", "002", etc) - * BACKUPFILES_REVERSE_ORDER - if true then "logfile" style numbering and file rolling will occur. If false then ever-increasing version numbering will occur, but old files will still be deleted if there are more than ROLL_MAX backup files. - * BACKUPFILES_CONFIRM_DELETE_OLD - if true then prompt/confirm with the user when deleting older backup/version files. + * The rest of the options are now saved as BACKUPFILES_PRESET, BACKUPFILES_SAVED and BACKUPFILES_CUSTOM + * (see BackupFilesPresetEntry) */ public class BackupFiles @@ -32,21 +59,8 @@ public class BackupFiles public static final String ENABLED = NS + "_ENABLED"; - public static final String SUFFIX = NS + "_SUFFIX"; - - public static final String NO_MAX = NS + "_NO_MAX"; - - public static final String ROLL_MAX = NS + "_ROLL_MAX"; - - public static final String SUFFIX_DIGITS = NS + "_SUFFIX_DIGITS"; - public static final String NUM_PLACEHOLDER = "%n"; - public static final String REVERSE_ORDER = NS + "_REVERSE_ORDER"; - - public static final String CONFIRM_DELETE_OLD = NS - + "_CONFIRM_DELETE_OLD"; - private static final String DEFAULT_TEMP_FILE = "jalview_temp_file_" + NS; private static final String TEMP_FILE_EXT = ".tmp"; @@ -84,6 +98,17 @@ public class BackupFiles // flag set to see if file save to temp file was successful private boolean tempFileWriteSuccess; + // array of files to be deleted, with extra information + private ArrayList deleteFiles = new ArrayList<>(); + + // date formatting for modification times + private static final SimpleDateFormat sdf = new SimpleDateFormat( + "yyyy-MM-dd HH:mm:ss"); + + private static final String newTempFileSuffix = "_newfile"; + + private static final String oldTempFileSuffix = "_oldfile_tobedeleted"; + public BackupFiles(String filename) { this(new File(filename)); @@ -93,20 +118,15 @@ public class BackupFiles // REVERSE_ORDER public BackupFiles(File file) { - this(file, ".bak" + NUM_PLACEHOLDER, false, 3, 3, false); - } - - public BackupFiles(File file, String defaultSuffix, boolean defaultNoMax, - int defaultMax, int defaultDigits, boolean defaultReverseOrder) - { classInit(); this.file = file; - this.suffix = Cache.getDefault(SUFFIX, defaultSuffix); - this.noMax = Cache.getDefault(NO_MAX, defaultNoMax); - this.max = Cache.getDefault(ROLL_MAX, defaultMax); - this.digits = Cache.getDefault(SUFFIX_DIGITS, defaultDigits); - this.reverseOrder = Cache.getDefault(REVERSE_ORDER, - defaultReverseOrder); + BackupFilesPresetEntry bfpe = BackupFilesPresetEntry + .getSavedBackupEntry(); + this.suffix = bfpe.suffix; + this.noMax = bfpe.keepAll; + this.max = bfpe.rollMax; + this.digits = bfpe.digits; + this.reverseOrder = bfpe.reverse; // create a temp file to save new data in File temp = null; @@ -116,7 +136,8 @@ public class BackupFiles { String tempfilename = file.getName(); File tempdir = file.getParentFile(); - temp = File.createTempFile(tempfilename, TEMP_FILE_EXT, tempdir); + temp = File.createTempFile(tempfilename, + TEMP_FILE_EXT + newTempFileSuffix, tempdir); } else { @@ -135,8 +156,10 @@ public class BackupFiles public static void classInit() { - setEnabled(Cache.getDefault(ENABLED, true)); - setConfirmDelete(Cache.getDefault(CONFIRM_DELETE_OLD, true)); + setEnabled(Cache.getDefault(ENABLED, !Platform.isJS())); + BackupFilesPresetEntry bfpe = BackupFilesPresetEntry + .getSavedBackupEntry(); + setConfirmDelete(bfpe.confirmDelete); } public static void setEnabled(boolean flag) @@ -201,13 +224,17 @@ public class BackupFiles public boolean renameTempFile() { - return tempFile.renameTo(file); + return moveFileToFile(tempFile, file); } // roll the backupfiles public boolean rollBackupFiles() { + return this.rollBackupFiles(true); + } + public boolean rollBackupFiles(boolean tidyUp) + { // file doesn't yet exist or backups are not enabled or template is null or // empty if ((!file.exists()) || (!enabled) || max < 0 || suffix == null @@ -235,14 +262,13 @@ public class BackupFiles boolean ret = true; // Create/move backups up one - File[] oldFilesToDelete = null; + deleteFiles.clear(); // find existing backup files BackupFilenameFilter bff = new BackupFilenameFilter(basename, suffix, digits); File[] backupFiles = dirFile.listFiles(bff); int nextIndexNum = 0; - String confirmDeleteExtraInfo = null; if (backupFiles.length == 0) { @@ -253,12 +279,13 @@ public class BackupFiles { TreeMap bfTreeMap = sortBackupFilesAsTreeMap( backupFiles, basename); + // bfTreeMap now a sorted list of , + // mappings if (reverseOrder) { // backup style numbering - File lastfile = null; int tempMax = noMax ? -1 : max; // noMax == true means no limits // look for first "gap" in backupFiles @@ -275,10 +302,10 @@ public class BackupFiles } } - // for (int m = 0; m < tempMax; m++) + File previousFile = null; + File fileToBeDeleted = null; for (int n = tempMax; n > 0; n--) { - // int n = tempMax - m; String backupfilename = dir + File.separatorChar + BackupFilenameParts.getBackupFilename(n, basename, suffix, digits); @@ -286,40 +313,84 @@ public class BackupFiles if (!backupfile_n.exists()) { - lastfile = backupfile_n; + // no "oldest" file to delete + previousFile = backupfile_n; + fileToBeDeleted = null; continue; } - // if (m == 0 && backupfile_n.exists()) - if ((!noMax) && n == tempMax && backupfile_n.exists()) + // check the modification time of this (backupfile_n) and the previous + // file (fileToBeDeleted) if the previous file is going to be deleted + if (fileToBeDeleted != null) { - // move the largest (max) rolled file to a temp file and add to the - // delete list + File replacementFile = backupfile_n; + long fileToBeDeletedLMT = fileToBeDeleted.lastModified(); + long replacementFileLMT = replacementFile.lastModified(); + try { - File temp = File.createTempFile(backupfilename, TEMP_FILE_EXT, + File oldestTempFile = nextTempFile(fileToBeDeleted.getName(), dirFile); - backupfile_n.renameTo(temp); - oldFilesToDelete = new File[] { temp }; - confirmDeleteExtraInfo = "(was " + backupfile_n.getName() - + ")"; - } catch (IOException e) + if (fileToBeDeletedLMT > replacementFileLMT) + { + String fileToBeDeletedLMTString = sdf + .format(fileToBeDeletedLMT); + String replacementFileLMTString = sdf + .format(replacementFileLMT); + System.out.println("WARNING! I am set to delete backupfile " + + fileToBeDeleted.getName() + + " has modification time " + + fileToBeDeletedLMTString + + " which is newer than its replacement " + + replacementFile.getName() + + " with modification time " + + replacementFileLMTString); + + boolean delete = confirmNewerDeleteFile(fileToBeDeleted, + replacementFile, true); + + if (delete) + { + // User has confirmed delete -- no need to add it to the list + fileToBeDeleted.delete(); + } + else + { + moveFileToFile(fileToBeDeleted, oldestTempFile); + } + } + else + { + moveFileToFile(fileToBeDeleted, oldestTempFile); + addDeleteFile(oldestTempFile); + } + + } catch (Exception e) { System.out.println( - "IOException when creating temporary file for backupfilename"); + "Error occurred, probably making new temp file for '" + + fileToBeDeleted.getName() + "'"); + e.printStackTrace(); } + + // reset + fileToBeDeleted = null; + } + + if (!noMax && n == tempMax && backupfile_n.exists()) + { + fileToBeDeleted = backupfile_n; } else { - // Just In Case - if (lastfile != null) + if (previousFile != null) { - ret = ret && backupfile_n.renameTo(lastfile); + ret = ret && moveFileToFile(backupfile_n, previousFile); } } - lastfile = backupfile_n; + previousFile = backupfile_n; } // index to use for the latest backup @@ -338,82 +409,232 @@ public class BackupFiles // need to delete some files to keep number of backups to designated // max int numToDelete = bfTreeMap.size() - max + 1; - oldFilesToDelete = Arrays.copyOfRange(backupFiles, 0, - numToDelete); + // the "replacement" file is the latest backup file being kept (it's + // not replacing though) + File replacementFile = numToDelete < backupFiles.length + ? backupFiles[numToDelete] + : null; + for (int i = 0; i < numToDelete; i++) + { + // check the deletion files for modification time of the last + // backupfile being saved + File fileToBeDeleted = backupFiles[i]; + boolean delete = true; + + boolean newer = false; + if (replacementFile != null) + { + long fileToBeDeletedLMT = fileToBeDeleted.lastModified(); + long replacementFileLMT = replacementFile != null + ? replacementFile.lastModified() + : Long.MAX_VALUE; + if (fileToBeDeletedLMT > replacementFileLMT) + { + String fileToBeDeletedLMTString = sdf + .format(fileToBeDeletedLMT); + String replacementFileLMTString = sdf + .format(replacementFileLMT); + + System.out + .println("WARNING! I am set to delete backupfile '" + + fileToBeDeleted.getName() + + "' has modification time " + + fileToBeDeletedLMTString + + " which is newer than the oldest backupfile being kept '" + + replacementFile.getName() + + "' with modification time " + + replacementFileLMTString); + + delete = confirmNewerDeleteFile(fileToBeDeleted, + replacementFile, false); + if (delete) + { + // User has confirmed delete -- no need to add it to the list + fileToBeDeleted.delete(); + delete = false; + } + else + { + // keeping file, nothing to do! + } + } + } + if (delete) + { + addDeleteFile(fileToBeDeleted); + } + + } } nextIndexNum = bfTreeMap.lastKey() + 1; - } } - deleteOldFiles(oldFilesToDelete, confirmDeleteExtraInfo); - // Let's make the new backup file!! yay, got there at last! String latestBackupFilename = dir + File.separatorChar + BackupFilenameParts.getBackupFilename(nextIndexNum, basename, suffix, digits); - File latestBackupFile = new File(latestBackupFilename); - ret = ret && file.renameTo(latestBackupFile); + ret |= moveFileToFile(file, new File(latestBackupFilename)); + + if (tidyUp) + { + tidyUpFiles(); + } return ret; } - private void deleteOldFiles(File[] oldFilesToDelete, - String confirmDeleteExtraInfo) + private static File nextTempFile(String filename, File dirFile) + throws IOException { - if (oldFilesToDelete != null && oldFilesToDelete.length > 0) + File temp = null; + COUNT: for (int i = 1; i < 1000; i++) + { + File trythis = new File(dirFile, + filename + '~' + Integer.toString(i)); + if (!trythis.exists()) + { + temp = trythis; + break COUNT; + } + + } + if (temp == null) + { + temp = File.createTempFile(filename, TEMP_FILE_EXT, dirFile); + } + return temp; + } + + private void tidyUpFiles() + { + deleteOldFiles(); + } + + private static boolean confirmNewerDeleteFile(File fileToBeDeleted, + File replacementFile, boolean replace) + { + StringBuilder messageSB = new StringBuilder(); + + File ftbd = fileToBeDeleted; + String ftbdLMT = sdf.format(ftbd.lastModified()); + String ftbdSize = Long.toString(ftbd.length()); + + File rf = replacementFile; + String rfLMT = sdf.format(rf.lastModified()); + String rfSize = Long.toString(rf.length()); + + int confirmButton = JvOptionPane.NO_OPTION; + if (replace) + { + File saveFile = null; + try + { + saveFile = nextTempFile(ftbd.getName(), ftbd.getParentFile()); + } catch (Exception e) + { + System.out.println( + "Error when confirming to keep backup file newer than other backup files."); + e.printStackTrace(); + } + messageSB.append(MessageManager.formatMessage( + "label.newerdelete_replacement_line", new String[] + { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize, + rfSize })); + messageSB.append("\n\n"); + messageSB.append(MessageManager.formatMessage( + "label.confirm_deletion_or_rename", new String[] + { ftbd.getName(), saveFile.getName() })); + String[] options = new String[] { + MessageManager.getString("label.delete"), + MessageManager.getString("label.rename") }; + + confirmButton = JvOptionPane.showOptionDialog(Desktop.desktop, + messageSB.toString(), + MessageManager.getString("label.backupfiles_confirm_delete"), + JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE, + null, options, options[0]); + } + else { - // delete old backup/version files + messageSB.append(MessageManager + .formatMessage("label.newerdelete_line", new String[] + { ftbd.getName(), rf.getName(), ftbdLMT, rfLMT, ftbdSize, + rfSize })); + messageSB.append("\n\n"); + messageSB.append(MessageManager + .formatMessage("label.confirm_deletion", new String[] + { ftbd.getName() })); + String[] options = new String[] { + MessageManager.getString("label.delete"), + MessageManager.getString("label.keep") }; + + confirmButton = JvOptionPane.showOptionDialog(Desktop.desktop, + messageSB.toString(), + MessageManager.getString("label.backupfiles_confirm_delete"), + JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE, + null, options, options[0]); + } + + // return should be TRUE if file is to be deleted + return (confirmButton == JvOptionPane.YES_OPTION); + } - boolean delete = false; - if (confirmDelete) + private void deleteOldFiles() + { + if (deleteFiles != null && !deleteFiles.isEmpty()) + { + boolean doDelete = false; + StringBuilder messageSB = null; + if (confirmDelete && deleteFiles.size() > 0) { - // Object[] confirmMessageArray = {}; - StringBuilder confirmMessage = new StringBuilder(); - confirmMessage.append(MessageManager + messageSB = new StringBuilder(); + messageSB.append(MessageManager .getString("label.backupfiles_confirm_delete_old_files")); - for (File f : oldFilesToDelete) - { - confirmMessage.append("\n"); - confirmMessage.append(f.getName()); - } - if (confirmDeleteExtraInfo != null - && confirmDeleteExtraInfo.length() > 0) + for (int i = 0; i < deleteFiles.size(); i++) { - confirmMessage.append("\n"); - confirmMessage.append(confirmDeleteExtraInfo); + File df = deleteFiles.get(i); + messageSB.append("\n"); + messageSB.append(df.getName()); + messageSB.append(" "); + messageSB.append(MessageManager.formatMessage("label.file_info", + new String[] + { sdf.format(df.lastModified()), + Long.toString(df.length()) })); } - int confirm = JvOptionPane.showConfirmDialog(Desktop.desktop, - confirmMessage.toString(), + + int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop, + messageSB.toString(), MessageManager .getString("label.backupfiles_confirm_delete"), JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE); - delete = (confirm == JvOptionPane.YES_OPTION); + doDelete = (confirmButton == JvOptionPane.YES_OPTION); } else { - delete = true; + doDelete = true; } - if (delete) + if (doDelete) { - for (int i = 0; i < oldFilesToDelete.length; i++) + for (int i = 0; i < deleteFiles.size(); i++) { - File fileToDelete = oldFilesToDelete[i]; + File fileToDelete = deleteFiles.get(i); fileToDelete.delete(); - // System.out.println("DELETING '" + fileToDelete.getName() + - // "'"); + System.out.println("DELETING '" + fileToDelete.getName() + "'"); } } } + + deleteFiles.clear(); } - private TreeMap sortBackupFilesAsTreeMap(File[] backupFiles, - String basename) + private TreeMap sortBackupFilesAsTreeMap( + File[] backupFiles, String basename) { // sort the backup files (based on integer found in the suffix) using a // precomputed Hashmap for speed @@ -435,13 +656,11 @@ public class BackupFiles boolean write = this.getWriteSuccess(); boolean roll = false; + boolean rename = false; if (write) { - roll = this.rollBackupFiles(); - } - else - { - return false; + roll = this.rollBackupFiles(false); + rename = this.renameTempFile(); } /* @@ -450,25 +669,41 @@ public class BackupFiles * trying to roll the backup files, and most likely the filename needed will already * be vacant so renaming the temp file is nearly always correct! */ - if (!roll) + boolean okay = roll && rename; + if (!okay) { - int confirm = JvOptionPane.showConfirmDialog(Desktop.desktop, - MessageManager.getString( - "label.backupfiles_confirm_save_file_backupfiles_roll_wrong"), - MessageManager - .getString("label.backupfiles_confirm_save_file"), - JvOptionPane.YES_NO_OPTION, JvOptionPane.WARNING_MESSAGE); - - if (confirm == JvOptionPane.YES_OPTION) + StringBuilder messageSB = new StringBuilder(); + messageSB.append(MessageManager.getString( + "label.backupfiles_confirm_save_file_backupfiles_roll_wrong")); + if (rename) { - roll = true; + if (messageSB.length() > 0) + { + messageSB.append("\n"); + } + messageSB.append(MessageManager.getString( + "label.backupfiles_confirm_save_new_saved_file_ok")); + } + else + { + if (messageSB.length() > 0) + { + messageSB.append("\n"); + } + messageSB.append(MessageManager.getString( + "label.backupfiles_confirm_save_new_saved_file_not_ok")); } - } - boolean rename = false; - if (roll) + int confirmButton = JvOptionPane.showConfirmDialog(Desktop.desktop, + messageSB.toString(), + MessageManager + .getString("label.backupfiles_confirm_save_file"), + JvOptionPane.OK_OPTION, JvOptionPane.WARNING_MESSAGE); + okay = confirmButton == JvOptionPane.OK_OPTION; + } + if (okay) { - rename = this.renameTempFile(); + tidyUpFiles(); } return rename; @@ -481,12 +716,10 @@ public class BackupFiles File file = new File(fileName); - String dir = ""; File dirFile; try { dirFile = file.getParentFile(); - dir = dirFile.getCanonicalPath(); } catch (Exception e) { System.out.println( @@ -518,4 +751,43 @@ public class BackupFiles return bfTreeMap; } + /* + private boolean addDeleteFile(File fileToBeDeleted, File originalFile, + boolean delete, boolean newer) + { + return addDeleteFile(fileToBeDeleted, originalFile, null, delete, newer); + } + */ + private boolean addDeleteFile(File fileToBeDeleted) + { + boolean ret = false; + int pos = deleteFiles.indexOf(fileToBeDeleted); + if (pos > -1) + { + return true; + } + else + { + deleteFiles.add(fileToBeDeleted); + } + return ret; + } + + public static boolean moveFileToFile(File oldFile, File newFile) + { + boolean ret = false; + Path oldPath = Paths.get(oldFile.getAbsolutePath()); + Path newPath = Paths.get(newFile.getAbsolutePath()); + try + { + Files.move(oldPath, newPath, StandardCopyOption.REPLACE_EXISTING); + ret = true; + } catch (IOException e) + { + Cache.log.warn("Could not move file '" + oldPath.toString() + "' to '" + + newPath.toString() + "'"); + ret = false; + } + return ret; + } }