aboutsummaryrefslogtreecommitdiffstats
path: root/AndroidAsync/src/com/koushikdutta/async/util/FileCache.java
blob: d1171083e0b4557c6b8c5f15abf45157c01a1d67 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package com.koushikdutta.async.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

/**
 * Created by koush on 4/12/14.
 */
public class FileCache {
    class CacheEntry {
        final long size;
        public CacheEntry(File file) {
            size = file.length();
        }
    }

    public static class Snapshot {
        FileInputStream[] fins;
        long[] lens;
        Snapshot(FileInputStream[] fins, long[] lens) {
            this.fins = fins;
            this.lens = lens;
        }

        public long getLength(int index) {
            return lens[index];
        }

        public void close() {
            StreamUtility.closeQuietly(fins);
        }
    }

    private static String hashAlgorithm = "MD5";

    private static MessageDigest findAlternativeMessageDigest() {
        if ("MD5".equals(hashAlgorithm)) {
            for (Provider provider : Security.getProviders()) {
                for (Provider.Service service : provider.getServices()) {
                    hashAlgorithm = service.getAlgorithm();
                    try {
                        MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm);
                        if (messageDigest != null)
                            return messageDigest;
                    } catch (NoSuchAlgorithmException ignored) {
                    }
                }
            }
        }
        return null;
    }

    public static String toKeyString(Object... parts) {
        MessageDigest messageDigest;
        synchronized (FileCache.class) {
            try {
                messageDigest = MessageDigest.getInstance(hashAlgorithm);
            } catch (NoSuchAlgorithmException e) {
                messageDigest = findAlternativeMessageDigest();
                if (null == messageDigest)
                    throw new RuntimeException(e);
            }
        }

        for (Object part : parts) {
            messageDigest.update(part.toString().getBytes());
        }
        byte[] md5bytes = messageDigest.digest();
        return new BigInteger(1, md5bytes).toString(16);
    }

    boolean loadAsync;
    Random random = new Random();
    public File getTempFile() {
        File f;
        while ((f = new File(directory, new BigInteger(128, random).toString(16))).exists());
        return f;
    }

    public File[] getTempFiles(int count) {
        File[] ret = new File[count];
        for (int i = 0; i < count; i++) {
            ret[i] = getTempFile();
        }
        return ret;
    }

    public static void removeFiles(File... files) {
        if (files == null)
            return;
        for (File file: files) {
            file.delete();
        }
    }

    public void remove(String key) {
        int i = 0;
        while (cache.remove(getPartName(key, i)) != null) {
            i++;
        }
        removePartFiles(key);
    }

    public boolean exists(String key, int part) {
        return getPartFile(key, part).exists();
    }

    public boolean exists(String key) {
        return getPartFile(key, 0).exists();
    }

    public File touch(File file) {
        cache.get(file.getName());
        file.setLastModified(System.currentTimeMillis());
        return file;
    }

    public FileInputStream get(String key) throws IOException {
        return new FileInputStream(touch(getPartFile(key, 0)));
    }

    public File getFile(String key) {
        return touch(getPartFile(key, 0));
    }

    public FileInputStream[] get(String key, int count) throws IOException {
        FileInputStream[] ret = new FileInputStream[count];
        try {
            for (int i = 0; i < count; i++) {
                ret[i] = new FileInputStream(touch(getPartFile(key, i)));
            }
        }
        catch (IOException e) {
            // if we can't get all the parts, delete everything
            for (FileInputStream fin: ret) {
                StreamUtility.closeQuietly(fin);
            }
            remove(key);
            throw e;
        }

        return ret;
    }

    String getPartName(String key, int part) {
        return key + "." + part;
    }

    public void commitTempFiles(String key, File... tempFiles) {
        removePartFiles(key);

        // try to rename everything
        for (int i = 0; i < tempFiles.length; i++) {
            File tmp = tempFiles[i];
            File partFile = getPartFile(key, i);
            if (!tmp.renameTo(partFile)) {
                // if any rename fails, delete everything
                removeFiles(tempFiles);
                remove(key);
                return;
            }
            remove(tmp.getName());
            cache.put(getPartName(key, i), new CacheEntry(partFile));
        }
    }

    void removePartFiles(String key) {
        int i = 0;
        File f;
        while ((f = getPartFile(key, i)).exists()) {
            f.delete();
            i++;
        }
    }

    File getPartFile(String key, int part) {
        return new File(directory, getPartName(key, part));
    }

    long blockSize = 4096;
    public void setBlockSize(long blockSize) {
        this.blockSize = blockSize;
    }

    class InternalCache extends LruCache<String, CacheEntry> {
        public InternalCache() {
            super(size);
        }

        @Override
        protected long sizeOf(String key, CacheEntry value) {
            return Math.max(blockSize, value.size);
        }

        @Override
        protected void entryRemoved(boolean evicted, String key, CacheEntry oldValue, CacheEntry newValue) {
            super.entryRemoved(evicted, key, oldValue, newValue);
            if (newValue != null)
                return;
            if (loading)
                return;
            new File(directory, key).delete();
        }
    }

    InternalCache cache;
    File directory;
    long size;

    Comparator<File> dateCompare = new Comparator<File>() {
        @Override
        public int compare(File lhs, File rhs) {
            long l = lhs.lastModified();
            long r = rhs.lastModified();
            if (l < r)
                return -1;
            if (r > l)
                return 1;
            return 0;
        }
    };

    boolean loading;
    void load() {
        loading = true;
        try {
            File[] files = directory.listFiles();
            if (files == null)
                return;
            ArrayList<File> list = new ArrayList<File>();
            Collections.addAll(list, files);
            Collections.sort(list, dateCompare);

            for (File file: list) {
                String name = file.getName();
                CacheEntry entry = new CacheEntry(file);
                cache.put(name, entry);
                cache.get(name);
            }
        }
        finally {
            loading = false;
        }
    }

    private void doLoad() {
        if (loadAsync) {
            new Thread() {
                @Override
                public void run() {
                    load();
                }
            }.start();
        }
        else {
            load();
        }
    }

    public FileCache(File directory, long size, boolean loadAsync) {
        this.directory = directory;
        this.size = size;
        this.loadAsync = loadAsync;
        cache = new InternalCache();

        directory.mkdirs();
        doLoad();
    }

    public long size() {
        return cache.size();
    }

    public void clear() {
        removeFiles(directory.listFiles());
        cache.evictAll();
    }

    public Set<String> keySet() {
        HashSet<String> ret = new HashSet<String>();
        File[] files = directory.listFiles();
        if (files == null)
            return ret;
        for (File file: files) {
            String name = file.getName();
            int last = name.lastIndexOf('.');
            if (last != -1)
                ret.add(name.substring(0, last));
        }
        return ret;
    }

    public void setMaxSize(long maxSize) {
        cache.setMaxSize(maxSize);
        doLoad();
    }
}