001/**
002 *
003 */
004package jmri.jmrit.operations.setup;
005
006import java.io.File;
007import java.util.Date;
008
009import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
010
011/**
012 * Represents the set of Operations files that is considered a "Backup" of the
013 * current Operations files.
014 *
015 * It can facilitate the display and selection of backup sets using a GUI.
016 *
017 * This class needs tests.......
018 *
019 * @author Gregory Madsen Copyright (C) 2012
020 *
021 */
022public class BackupSet {
023
024    private String _setName;
025
026    public String getSetName() {
027        return _setName;
028    }
029
030    public Date getLastModifiedDate() {
031        return _lastModifiedDate;
032    }
033
034    private Date _lastModifiedDate;
035    private File _dir;
036
037    public BackupSet(File dir) {
038        _dir = dir;
039        _setName = dir.getName();
040        _lastModifiedDate = new Date(dir.lastModified());
041    }
042
043    public void delete() {
044        deleteDirectoryAndFiles(_dir);
045    }
046
047    @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification = "not possible")
048    private void deleteDirectoryAndFiles(File dir) {
049        // Deletes all of the files in a directory, and then the directory
050        // itself.
051        // This is NOT a general purpose method, as it only handles directories
052        // with only files and no sub directories.
053        // This probably needs to handle failures. delete() returns false if it fails.
054        Boolean ok;
055        for (File f : dir.listFiles()) {
056            // Delete files first
057            if (f.isFile()) {
058                ok = f.delete();
059                if (!ok) {
060                    throw new RuntimeException("Failed to delete file: " + f.getAbsolutePath()); // NOI18N
061                }
062            }
063        }
064
065        ok = dir.delete();
066        if (!ok) {
067            throw new RuntimeException("Failed to delete directory: " + dir.getAbsolutePath()); // NOI18N
068        }
069    }
070
071    @Override
072    public String toString() {
073        return String.format("%s (%s)", _setName, _lastModifiedDate); // NOI18N
074    }
075}