New TempFiles and Image now uses it instead of mem
[fanfix.git] / src / be / nikiroo / utils / Cache.java
CommitLineData
8816d2f7
NR
1package be.nikiroo.utils;
2
3import java.io.File;
4import java.io.FileInputStream;
5import java.io.FileNotFoundException;
6import java.io.IOException;
7import java.io.InputStream;
8import java.net.URL;
9import java.util.Date;
10
11/**
12 * A generic cache system, with special support for {@link URL}s.
13 * <p>
14 * This cache also manages timeout information.
15 *
16 * @author niki
17 */
18public class Cache {
19 private File dir;
20 private long tooOldChanging;
21 private long tooOldStable;
530d4062 22 private TraceHandler tracer = new TraceHandler();
8816d2f7 23
e8aa5bf9
NR
24 /**
25 * Only for inheritance.
26 */
27 protected Cache() {
28 }
29
8816d2f7
NR
30 /**
31 * Create a new {@link Cache} object.
32 *
33 * @param dir
34 * the directory to use as cache
35 * @param hoursChanging
36 * the number of hours after which a cached file that is thought
37 * to change ~often is considered too old (or -1 for
38 * "never too old")
39 * @param hoursStable
40 * the number of hours after which a cached file that is thought
41 * to change rarely is considered too old (or -1 for
42 * "never too old")
43 *
44 * @throws IOException
45 * in case of I/O error
46 */
47 public Cache(File dir, int hoursChanging, int hoursStable)
48 throws IOException {
49 this.dir = dir;
50 this.tooOldChanging = 1000 * 60 * 60 * hoursChanging;
51 this.tooOldStable = 1000 * 60 * 60 * hoursStable;
52
53 if (dir != null && !dir.exists()) {
54 dir.mkdirs();
55 }
56
57 if (dir == null || !dir.exists()) {
58 throw new IOException("Cannot create the cache directory: "
59 + (dir == null ? "null" : dir.getAbsolutePath()));
60 }
61 }
62
530d4062
NR
63 /**
64 * The traces handler for this {@link Cache}.
65 *
66 * @return the traces handler
67 */
68 public TraceHandler getTraceHandler() {
69 return tracer;
70 }
71
72 /**
73 * The traces handler for this {@link Cache}.
74 *
75 * @param tracer
76 * the new traces handler
77 */
78 public void setTraceHandler(TraceHandler tracer) {
80500544
NR
79 if (tracer == null) {
80 tracer = new TraceHandler(false, false, false);
81 }
82
530d4062
NR
83 this.tracer = tracer;
84 }
85
e8aa5bf9
NR
86 /**
87 * Check the resource to see if it is in the cache.
88 *
89 * @param uniqueID
90 * the resource to check
91 * @param allowTooOld
92 * allow files even if they are considered too old
93 * @param stable
94 * a stable file (that dones't change too often) -- parameter
95 * used to check if the file is too old to keep or not
96 *
97 * @return TRUE if it is
98 *
99 */
100 public boolean check(String uniqueID, boolean allowTooOld, boolean stable) {
101 return check(getCached(uniqueID), allowTooOld, stable);
102 }
103
8816d2f7
NR
104 /**
105 * Check the resource to see if it is in the cache.
106 *
107 * @param url
108 * the resource to check
109 * @param allowTooOld
110 * allow files even if they are considered too old
111 * @param stable
112 * a stable file (that dones't change too often) -- parameter
113 * used to check if the file is too old to keep or not
114 *
115 * @return TRUE if it is
116 *
117 */
118 public boolean check(URL url, boolean allowTooOld, boolean stable) {
e8aa5bf9
NR
119 return check(getCached(url), allowTooOld, stable);
120 }
121
122 /**
123 * Check the resource to see if it is in the cache.
124 *
125 * @param cached
126 * the resource to check
127 * @param allowTooOld
128 * allow files even if they are considered too old
129 * @param stable
130 * a stable file (that dones't change too often) -- parameter
131 * used to check if the file is too old to keep or not
132 *
133 * @return TRUE if it is
134 *
135 */
136 private boolean check(File cached, boolean allowTooOld, boolean stable) {
137 if (cached.exists() && cached.isFile()) {
e704a414
NR
138 if (!allowTooOld && isOld(cached, stable)) {
139 if (!cached.delete()) {
140 tracer.error("Cannot delete temporary file: "
141 + cached.getAbsolutePath());
142 }
143 } else {
8816d2f7
NR
144 return true;
145 }
146 }
147
148 return false;
149 }
150
151 /**
152 * Clean the cache (delete the cached items).
153 *
154 * @param onlyOld
155 * only clean the files that are considered too old for a stable
156 * resource
157 *
158 * @return the number of cleaned items
159 */
160 public int clean(boolean onlyOld) {
161 return clean(onlyOld, dir);
162 }
163
8816d2f7
NR
164 /**
165 * Clean the cache (delete the cached items) in the given cache directory.
166 *
167 * @param onlyOld
168 * only clean the files that are considered too old for stable
169 * resources
170 * @param cacheDir
171 * the cache directory to clean
172 *
173 * @return the number of cleaned items
174 */
175 private int clean(boolean onlyOld, File cacheDir) {
176 int num = 0;
177 for (File file : cacheDir.listFiles()) {
178 if (file.isDirectory()) {
179 num += clean(onlyOld, file);
180 } else {
181 if (!onlyOld || isOld(file, true)) {
182 if (file.delete()) {
183 num++;
184 } else {
530d4062
NR
185 tracer.error("Cannot delete temporary file: "
186 + file.getAbsolutePath());
8816d2f7
NR
187 }
188 }
189 }
190 }
191
192 return num;
193 }
194
195 /**
196 * Open a resource from the cache if it exists.
197 *
198 * @param uniqueID
199 * the unique ID
200 * @param allowTooOld
201 * allow files even if they are considered too old
202 * @param stable
203 * a stable file (that dones't change too often) -- parameter
204 * used to check if the file is too old to keep or not
205 *
206 * @return the opened resource if found, NULL if not
8816d2f7
NR
207 */
208 public InputStream load(String uniqueID, boolean allowTooOld, boolean stable) {
209 return load(getCached(uniqueID), allowTooOld, stable);
210 }
211
212 /**
213 * Open a resource from the cache if it exists.
214 *
215 * @param url
216 * the resource to open
217 * @param allowTooOld
218 * allow files even if they are considered too old
219 * @param stable
220 * a stable file (that dones't change too often) -- parameter
221 * used to check if the file is too old to keep or not
222 *
223 * @return the opened resource if found, NULL if not
8816d2f7 224 */
2ee6c205 225 public InputStream load(URL url, boolean allowTooOld, boolean stable) {
8816d2f7
NR
226 return load(getCached(url), allowTooOld, stable);
227 }
228
229 /**
230 * Open a resource from the cache if it exists.
231 *
2ee6c205 232 * @param cached
8816d2f7
NR
233 * the resource to open
234 * @param allowTooOld
235 * allow files even if they are considered too old
236 * @param stable
237 * a stable file (that dones't change too often) -- parameter
238 * used to check if the file is too old to keep or not
239 *
240 * @return the opened resource if found, NULL if not
8816d2f7
NR
241 */
242 private InputStream load(File cached, boolean allowTooOld, boolean stable) {
80500544
NR
243 if (cached.exists() && cached.isFile()
244 && (allowTooOld || !isOld(cached, stable))) {
8816d2f7
NR
245 try {
246 return new MarkableFileInputStream(new FileInputStream(cached));
247 } catch (FileNotFoundException e) {
248 return null;
249 }
250 }
251
252 return null;
253 }
254
255 /**
256 * Save the given resource to the cache.
257 *
258 * @param in
259 * the input data
260 * @param uniqueID
261 * a unique ID used to locate the cached resource
262 *
8816d2f7
NR
263 * @throws IOException
264 * in case of I/O error
265 */
e8aa5bf9 266 public void save(InputStream in, String uniqueID) throws IOException {
8816d2f7
NR
267 File cached = getCached(uniqueID);
268 cached.getParentFile().mkdirs();
e8aa5bf9 269 save(in, cached);
8816d2f7
NR
270 }
271
272 /**
273 * Save the given resource to the cache.
274 *
275 * @param in
276 * the input data
277 * @param url
278 * the {@link URL} used to locate the cached resource
279 *
280 * @throws IOException
281 * in case of I/O error
282 */
e8aa5bf9 283 public void save(InputStream in, URL url) throws IOException {
8816d2f7 284 File cached = getCached(url);
e8aa5bf9 285 save(in, cached);
8816d2f7
NR
286 }
287
288 /**
289 * Save the given resource to the cache.
290 *
291 * @param in
292 * the input data
293 * @param cached
294 * the cached {@link File} to save to
295 *
296 * @throws IOException
297 * in case of I/O error
298 */
e8aa5bf9 299 private void save(InputStream in, File cached) throws IOException {
8816d2f7 300 IOUtils.write(in, cached);
8816d2f7
NR
301 }
302
2ee6c205
NR
303 /**
304 * Remove the given resource from the cache.
305 *
306 * @param uniqueID
307 * a unique ID used to locate the cached resource
308 *
309 * @return TRUE if it was removed
310 */
311 public boolean remove(String uniqueID) {
312 File cached = getCached(uniqueID);
313 return cached.delete();
314 }
315
316 /**
317 * Remove the given resource from the cache.
318 *
319 * @param url
320 * the {@link URL} used to locate the cached resource
321 *
322 * @return TRUE if it was removed
323 */
324 public boolean remove(URL url) {
325 File cached = getCached(url);
326 return cached.delete();
327 }
328
8816d2f7
NR
329 /**
330 * Check if the {@link File} is too old according to
331 * {@link Cache#tooOldChanging}.
332 *
333 * @param file
334 * the file to check
335 * @param stable
336 * TRUE to denote stable files, that are not supposed to change
337 * too often
338 *
339 * @return TRUE if it is
340 */
341 private boolean isOld(File file, boolean stable) {
342 long max = tooOldChanging;
343 if (stable) {
344 max = tooOldStable;
345 }
346
347 if (max < 0) {
348 return false;
349 }
350
351 long time = new Date().getTime() - file.lastModified();
352 if (time < 0) {
530d4062
NR
353 tracer.error("Timestamp in the future for file: "
354 + file.getAbsolutePath());
8816d2f7
NR
355 }
356
357 return time < 0 || time > max;
358 }
359
360 /**
361 * Return the associated cache {@link File} from this {@link URL}.
362 *
363 * @param url
364 * the {@link URL}
365 *
366 * @return the cached {@link File} version of this {@link URL}
367 */
368 private File getCached(URL url) {
369 File subdir;
370
371 String name = url.getHost();
372 if (name == null || name.isEmpty()) {
373 // File
374 File file = new File(url.getFile());
d827da2a
NR
375 if (file.getParent() == null) {
376 subdir = new File("+");
377 } else {
378 subdir = new File(file.getParent().replace("..", "__"));
379 }
8816d2f7
NR
380 subdir = new File(dir, allowedChars(subdir.getPath()));
381 name = allowedChars(url.getFile());
382 } else {
383 // URL
384 File subsubDir = new File(dir, allowedChars(url.getHost()));
385 subdir = new File(subsubDir, "_" + allowedChars(url.getPath()));
386 name = allowedChars("_" + url.getQuery());
387 }
388
389 File cacheFile = new File(subdir, name);
390 subdir.mkdirs();
391
392 return cacheFile;
393 }
394
395 /**
396 * Get the basic cache resource file corresponding to this unique ID.
397 * <p>
398 * Note that you may need to add a sub-directory in some cases.
399 *
400 * @param uniqueID
401 * the id
402 *
403 * @return the cached version if present, NULL if not
404 */
405 private File getCached(String uniqueID) {
406 File file = new File(dir, allowedChars(uniqueID));
407 File subdir = new File(file.getParentFile(), "_");
408 return new File(subdir, file.getName());
409 }
410
411 /**
412 * Replace not allowed chars (in a {@link File}) by "_".
413 *
414 * @param raw
415 * the raw {@link String}
416 *
417 * @return the sanitised {@link String}
418 */
419 private String allowedChars(String raw) {
420 return raw.replace('/', '_').replace(':', '_').replace("\\", "_");
421 }
422}