Fix SerialTest :
[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;
0988831f
NR
50 this.tooOldChanging = 1000L * 60 * 60 * hoursChanging;
51 this.tooOldStable = 1000L * 60 * 60 * hoursStable;
8816d2f7
NR
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;
0988831f
NR
177 File[] files = cacheDir.listFiles();
178 if (files != null) {
179 for (File file : files) {
180 if (file.isDirectory()) {
181 num += clean(onlyOld, file);
182 } else {
183 if (!onlyOld || isOld(file, true)) {
184 if (file.delete()) {
185 num++;
186 } else {
187 tracer.error("Cannot delete temporary file: "
188 + file.getAbsolutePath());
189 }
8816d2f7
NR
190 }
191 }
192 }
193 }
194
195 return num;
196 }
197
198 /**
199 * Open a resource from the cache if it exists.
200 *
201 * @param uniqueID
202 * the unique ID
203 * @param allowTooOld
204 * allow files even if they are considered too old
205 * @param stable
206 * a stable file (that dones't change too often) -- parameter
207 * used to check if the file is too old to keep or not
208 *
209 * @return the opened resource if found, NULL if not
8816d2f7
NR
210 */
211 public InputStream load(String uniqueID, boolean allowTooOld, boolean stable) {
212 return load(getCached(uniqueID), allowTooOld, stable);
213 }
214
215 /**
216 * Open a resource from the cache if it exists.
217 *
218 * @param url
219 * the resource to open
220 * @param allowTooOld
221 * allow files even if they are considered too old
222 * @param stable
223 * a stable file (that dones't change too often) -- parameter
224 * used to check if the file is too old to keep or not
225 *
226 * @return the opened resource if found, NULL if not
8816d2f7 227 */
2ee6c205 228 public InputStream load(URL url, boolean allowTooOld, boolean stable) {
8816d2f7
NR
229 return load(getCached(url), allowTooOld, stable);
230 }
231
232 /**
233 * Open a resource from the cache if it exists.
234 *
2ee6c205 235 * @param cached
8816d2f7
NR
236 * the resource to open
237 * @param allowTooOld
238 * allow files even if they are considered too old
239 * @param stable
240 * a stable file (that dones't change too often) -- parameter
241 * used to check if the file is too old to keep or not
242 *
243 * @return the opened resource if found, NULL if not
8816d2f7
NR
244 */
245 private InputStream load(File cached, boolean allowTooOld, boolean stable) {
80500544
NR
246 if (cached.exists() && cached.isFile()
247 && (allowTooOld || !isOld(cached, stable))) {
8816d2f7
NR
248 try {
249 return new MarkableFileInputStream(new FileInputStream(cached));
250 } catch (FileNotFoundException e) {
251 return null;
252 }
253 }
254
255 return null;
256 }
257
258 /**
259 * Save the given resource to the cache.
260 *
261 * @param in
262 * the input data
263 * @param uniqueID
264 * a unique ID used to locate the cached resource
265 *
8816d2f7
NR
266 * @throws IOException
267 * in case of I/O error
268 */
e8aa5bf9 269 public void save(InputStream in, String uniqueID) throws IOException {
8816d2f7
NR
270 File cached = getCached(uniqueID);
271 cached.getParentFile().mkdirs();
e8aa5bf9 272 save(in, cached);
8816d2f7
NR
273 }
274
275 /**
276 * Save the given resource to the cache.
277 *
278 * @param in
279 * the input data
280 * @param url
281 * the {@link URL} used to locate the cached resource
282 *
283 * @throws IOException
284 * in case of I/O error
285 */
e8aa5bf9 286 public void save(InputStream in, URL url) throws IOException {
8816d2f7 287 File cached = getCached(url);
e8aa5bf9 288 save(in, cached);
8816d2f7
NR
289 }
290
291 /**
292 * Save the given resource to the cache.
293 *
294 * @param in
295 * the input data
296 * @param cached
297 * the cached {@link File} to save to
298 *
299 * @throws IOException
300 * in case of I/O error
301 */
e8aa5bf9 302 private void save(InputStream in, File cached) throws IOException {
8816d2f7 303 IOUtils.write(in, cached);
8816d2f7
NR
304 }
305
2ee6c205
NR
306 /**
307 * Remove the given resource from the cache.
308 *
309 * @param uniqueID
310 * a unique ID used to locate the cached resource
311 *
312 * @return TRUE if it was removed
313 */
314 public boolean remove(String uniqueID) {
315 File cached = getCached(uniqueID);
316 return cached.delete();
317 }
318
319 /**
320 * Remove the given resource from the cache.
321 *
322 * @param url
323 * the {@link URL} used to locate the cached resource
324 *
325 * @return TRUE if it was removed
326 */
327 public boolean remove(URL url) {
328 File cached = getCached(url);
329 return cached.delete();
330 }
331
8816d2f7
NR
332 /**
333 * Check if the {@link File} is too old according to
334 * {@link Cache#tooOldChanging}.
335 *
336 * @param file
337 * the file to check
338 * @param stable
339 * TRUE to denote stable files, that are not supposed to change
340 * too often
341 *
342 * @return TRUE if it is
343 */
344 private boolean isOld(File file, boolean stable) {
345 long max = tooOldChanging;
346 if (stable) {
347 max = tooOldStable;
348 }
349
350 if (max < 0) {
351 return false;
352 }
353
354 long time = new Date().getTime() - file.lastModified();
355 if (time < 0) {
530d4062
NR
356 tracer.error("Timestamp in the future for file: "
357 + file.getAbsolutePath());
8816d2f7
NR
358 }
359
360 return time < 0 || time > max;
361 }
362
363 /**
364 * Return the associated cache {@link File} from this {@link URL}.
365 *
366 * @param url
367 * the {@link URL}
368 *
369 * @return the cached {@link File} version of this {@link URL}
370 */
371 private File getCached(URL url) {
372 File subdir;
373
374 String name = url.getHost();
375 if (name == null || name.isEmpty()) {
376 // File
377 File file = new File(url.getFile());
d827da2a
NR
378 if (file.getParent() == null) {
379 subdir = new File("+");
380 } else {
381 subdir = new File(file.getParent().replace("..", "__"));
382 }
8816d2f7
NR
383 subdir = new File(dir, allowedChars(subdir.getPath()));
384 name = allowedChars(url.getFile());
385 } else {
386 // URL
387 File subsubDir = new File(dir, allowedChars(url.getHost()));
388 subdir = new File(subsubDir, "_" + allowedChars(url.getPath()));
389 name = allowedChars("_" + url.getQuery());
390 }
391
392 File cacheFile = new File(subdir, name);
393 subdir.mkdirs();
394
395 return cacheFile;
396 }
397
398 /**
399 * Get the basic cache resource file corresponding to this unique ID.
400 * <p>
401 * Note that you may need to add a sub-directory in some cases.
402 *
403 * @param uniqueID
404 * the id
405 *
406 * @return the cached version if present, NULL if not
407 */
408 private File getCached(String uniqueID) {
409 File file = new File(dir, allowedChars(uniqueID));
410 File subdir = new File(file.getParentFile(), "_");
411 return new File(subdir, file.getName());
412 }
413
414 /**
415 * Replace not allowed chars (in a {@link File}) by "_".
416 *
417 * @param raw
418 * the raw {@link String}
419 *
420 * @return the sanitised {@link String}
421 */
422 private String allowedChars(String raw) {
423 return raw.replace('/', '_').replace(':', '_').replace("\\", "_");
424 }
425}