2 // Getdown - application installer, patcher and launcher
3 // Copyright (C) 2004-2018 Getdown authors
4 // https://github.com/threerings/getdown/blob/master/LICENSE
6 package com.threerings.getdown.cache;
9 import java.io.IOException;
11 import com.threerings.getdown.util.FileUtil;
14 * Maintains a cache of code resources. The cache allows multiple application instances of different
15 * versions to open at the same time.
17 public class ResourceCache
19 public ResourceCache (File _cacheDir) throws IOException
21 this._cacheDir = _cacheDir;
22 createDirectoryIfNecessary(_cacheDir);
25 private void createDirectoryIfNecessary (File dir) throws IOException
27 if (!dir.exists() && !dir.mkdirs()) {
28 throw new IOException("unable to create directory: " + dir.getAbsolutePath());
33 * Caches the given file under its {@code digest}.
34 * @param fileToCache file to cache.
35 * @param cacheSubdir the subdirectory of the cache directory in which to store the cached
36 * file. Usually either {@code digest} or a prefix of {@code digest}.
37 * @param digest a crypto digest of the cached files contents.
38 * @return the cached file.
40 public File cacheFile (File fileToCache, String cacheSubdir, String digest) throws IOException
42 File cacheLocation = new File(_cacheDir, cacheSubdir);
43 createDirectoryIfNecessary(cacheLocation);
45 File cachedFile = new File(cacheLocation, digest + getFileSuffix(fileToCache));
46 File lastAccessedFile = new File(
47 cacheLocation, cachedFile.getName() + LAST_ACCESSED_FILE_SUFFIX);
49 if (!cachedFile.exists()) {
50 createNewFile(cachedFile);
51 FileUtil.copy(fileToCache, cachedFile);
54 if (lastAccessedFile.exists()) {
55 lastAccessedFile.setLastModified(System.currentTimeMillis());
57 createNewFile(lastAccessedFile);
63 private void createNewFile (File fileToCreate) throws IOException
65 if (!fileToCreate.exists() && !fileToCreate.createNewFile()) {
66 throw new IOException("unable to create new file: " + fileToCreate.getAbsolutePath());
70 private String getFileSuffix (File fileToCache) {
71 String fileName = fileToCache.getName();
72 int index = fileName.lastIndexOf(".");
74 return index > -1 ? fileName.substring(index) : "";
77 private final File _cacheDir;
79 static final String LAST_ACCESSED_FILE_SUFFIX = ".lastAccessed";