1 package be
.nikiroo
.utils
;
4 import java
.io
.FileInputStream
;
5 import java
.io
.FileNotFoundException
;
6 import java
.io
.IOException
;
7 import java
.io
.InputStream
;
12 * A generic cache system, with special support for {@link URL}s.
14 * This cache also manages timeout information.
20 private long tooOldChanging
;
21 private long tooOldStable
;
22 private TraceHandler tracer
= new TraceHandler();
25 * Only for inheritance.
31 * Create a new {@link Cache} object.
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
40 * the number of hours after which a cached file that is thought
41 * to change rarely is considered too old (or -1 for
45 * in case of I/O error
47 public Cache(File dir
, int hoursChanging
, int hoursStable
)
50 this.tooOldChanging
= 1000L * 60 * 60 * hoursChanging
;
51 this.tooOldStable
= 1000L * 60 * 60 * hoursStable
;
53 if (dir
!= null && !dir
.exists()) {
57 if (dir
== null || !dir
.exists()) {
58 throw new IOException("Cannot create the cache directory: "
59 + (dir
== null ?
"null" : dir
.getAbsolutePath()));
64 * The traces handler for this {@link Cache}.
66 * @return the traces handler
68 public TraceHandler
getTraceHandler() {
73 * The traces handler for this {@link Cache}.
76 * the new traces handler
78 public void setTraceHandler(TraceHandler tracer
) {
80 tracer
= new TraceHandler(false, false, false);
87 * Check the resource to see if it is in the cache.
90 * the resource to check
92 * allow files even if they are considered too old
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
97 * @return TRUE if it is
100 public boolean check(String uniqueID
, boolean allowTooOld
, boolean stable
) {
101 return check(getCached(uniqueID
), allowTooOld
, stable
);
105 * Check the resource to see if it is in the cache.
108 * the resource to check
110 * allow files even if they are considered too old
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
115 * @return TRUE if it is
118 public boolean check(URL url
, boolean allowTooOld
, boolean stable
) {
119 return check(getCached(url
), allowTooOld
, stable
);
123 * Check the resource to see if it is in the cache.
126 * the resource to check
128 * allow files even if they are considered too old
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
133 * @return TRUE if it is
136 private boolean check(File cached
, boolean allowTooOld
, boolean stable
) {
137 if (cached
.exists() && cached
.isFile()) {
138 if (!allowTooOld
&& isOld(cached
, stable
)) {
139 if (!cached
.delete()) {
140 tracer
.error("Cannot delete temporary file: "
141 + cached
.getAbsolutePath());
152 * Clean the cache (delete the cached items).
155 * only clean the files that are considered too old for a stable
158 * @return the number of cleaned items
160 public int clean(boolean onlyOld
) {
161 return clean(onlyOld
, dir
);
165 * Clean the cache (delete the cached items) in the given cache directory.
168 * only clean the files that are considered too old for stable
171 * the cache directory to clean
173 * @return the number of cleaned items
175 private int clean(boolean onlyOld
, File cacheDir
) {
177 File
[] files
= cacheDir
.listFiles();
179 for (File file
: files
) {
180 if (file
.isDirectory()) {
181 num
+= clean(onlyOld
, file
);
183 if (!onlyOld
|| isOld(file
, true)) {
187 tracer
.error("Cannot delete temporary file: "
188 + file
.getAbsolutePath());
199 * Open a resource from the cache if it exists.
204 * allow files even if they are considered too old
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
209 * @return the opened resource if found, NULL if not
211 public InputStream
load(String uniqueID
, boolean allowTooOld
, boolean stable
) {
212 return load(getCached(uniqueID
), allowTooOld
, stable
);
216 * Open a resource from the cache if it exists.
219 * the resource to open
221 * allow files even if they are considered too old
223 * a stable file (that doesn't change too often) -- parameter
224 * used to check if the file is too old to keep or not in the
227 * @return the opened resource if found, NULL if not
229 public InputStream
load(URL url
, boolean allowTooOld
, boolean stable
) {
230 return load(getCached(url
), allowTooOld
, stable
);
234 * Open a resource from the cache if it exists.
237 * the resource to open
239 * allow files even if they are considered too old
241 * a stable file (that dones't change too often) -- parameter
242 * used to check if the file is too old to keep or not
244 * @return the opened resource if found, NULL if not
246 private InputStream
load(File cached
, boolean allowTooOld
, boolean stable
) {
247 if (cached
.exists() && cached
.isFile()
248 && (allowTooOld
|| !isOld(cached
, stable
))) {
250 return new MarkableFileInputStream(new FileInputStream(cached
));
251 } catch (FileNotFoundException e
) {
260 * Save the given resource to the cache.
265 * a unique ID used to locate the cached resource
267 * @throws IOException
268 * in case of I/O error
270 public void save(InputStream in
, String uniqueID
) throws IOException
{
271 File cached
= getCached(uniqueID
);
272 cached
.getParentFile().mkdirs();
277 * Save the given resource to the cache.
282 * the {@link URL} used to locate the cached resource
284 * @throws IOException
285 * in case of I/O error
287 public void save(InputStream in
, URL url
) throws IOException
{
288 File cached
= getCached(url
);
293 * Save the given resource to the cache.
295 * Will also clean the {@link Cache} from old files.
300 * the cached {@link File} to save to
302 * @throws IOException
303 * in case of I/O error
305 private void save(InputStream in
, File cached
) throws IOException
{
307 IOUtils
.write(in
, cached
);
311 * Remove the given resource from the cache.
314 * a unique ID used to locate the cached resource
316 * @return TRUE if it was removed
318 public boolean remove(String uniqueID
) {
319 File cached
= getCached(uniqueID
);
320 return cached
.delete();
324 * Remove the given resource from the cache.
327 * the {@link URL} used to locate the cached resource
329 * @return TRUE if it was removed
331 public boolean remove(URL url
) {
332 File cached
= getCached(url
);
333 return cached
.delete();
337 * Check if the {@link File} is too old according to
338 * {@link Cache#tooOldChanging}.
343 * TRUE to denote stable files, that are not supposed to change
346 * @return TRUE if it is
348 private boolean isOld(File file
, boolean stable
) {
349 long max
= tooOldChanging
;
358 long time
= new Date().getTime() - file
.lastModified();
360 tracer
.error("Timestamp in the future for file: "
361 + file
.getAbsolutePath());
364 return time
< 0 || time
> max
;
368 * Return the associated cache {@link File} from this {@link URL}.
373 * @return the cached {@link File} version of this {@link URL}
375 private File
getCached(URL url
) {
378 String name
= url
.getHost();
379 if (name
== null || name
.isEmpty()) {
381 File file
= new File(url
.getFile());
382 if (file
.getParent() == null) {
383 subdir
= new File("+");
385 subdir
= new File(file
.getParent().replace("..", "__"));
387 subdir
= new File(dir
, allowedChars(subdir
.getPath()));
388 name
= allowedChars(url
.getFile());
391 File subsubDir
= new File(dir
, allowedChars(url
.getHost()));
392 subdir
= new File(subsubDir
, "_" + allowedChars(url
.getPath()));
393 name
= allowedChars("_" + url
.getQuery());
396 File cacheFile
= new File(subdir
, name
);
403 * Get the basic cache resource file corresponding to this unique ID.
405 * Note that you may need to add a sub-directory in some cases.
410 * @return the cached version if present, NULL if not
412 private File
getCached(String uniqueID
) {
413 File file
= new File(dir
, allowedChars(uniqueID
));
414 File subdir
= new File(file
.getParentFile(), "_");
415 return new File(subdir
, file
.getName());
419 * Replace not allowed chars (in a {@link File}) by "_".
422 * the raw {@link String}
424 * @return the sanitised {@link String}
426 private String
allowedChars(String raw
) {
427 return raw
.replace('/', '_').replace(':', '_').replace("\\", "_");