summaryrefslogtreecommitdiff
path: root/src/main/java/com/keuin/kbackupfabric/ui/BackupManager.java
blob: abd7d5b075b7d024a85a00c943b596bcb920bea4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.keuin.kbackupfabric.ui;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;

/**
 * Holding all types of backups for the user interaction logic.
 */
public class BackupManager {

    private final File backupStorageDirectory;

    public BackupManager(File backupStorageDirectory) {
        this.backupStorageDirectory = backupStorageDirectory;
    }

    public BackupManager(String backupStorageDirectory) {
        this.backupStorageDirectory = new File(backupStorageDirectory);
    }

    /**
     * Get available backups in the disk.
     *
     * @return all backups.
     */
    public Iterable<BackupInfo> getAllBackups() {
        return new Iterable<BackupInfo>() {
            @NotNull
            @Override
            public Iterator<BackupInfo> iterator() {
                return new Iterator<BackupInfo>() {
                    private final Iterator<File> fileIterator = Arrays.stream(backupStorageDirectory.listFiles()).filter(file -> {
                        String name = file.getName().toLowerCase();
                        return name.endsWith(".zip") || name.endsWith(".kbi");
                    }).iterator();

                    @Override
                    public boolean hasNext() {
                        return fileIterator.hasNext();
                    }

                    @Override
                    public BackupInfo next() {
                        try {
                            File backupFile = fileIterator.next();
                            String fileName = backupFile.getName().toLowerCase();
                            if (fileName.endsWith(".zip"))
                                return PrimitiveBackupInfo.fromFile(backupFile);
                            if (fileName.endsWith(".kbi"))
                                return IncrementalBackupInfo.fromFile(backupFile);
                            throw new RuntimeException("Invalid backup file extname");
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                };
            }
        };
    }
}