Fixed failing to download file when cached entry was removed by user

This commit is contained in:
huanghongxun 2018-10-14 19:04:21 +08:00
parent eaa6790013
commit 16ea88a659
3 changed files with 28 additions and 6 deletions

View File

@ -222,8 +222,14 @@ public class FileDownloadTask extends Task {
if (con.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
// Handle cache
Path cache = repository.getCachedRemoteFile(con);
FileUtils.copyFile(cache.toFile(), file);
try {
Path cache = repository.getCachedRemoteFile(con);
FileUtils.copyFile(cache.toFile(), file);
return;
} catch (IOException e) {
Logging.LOG.log(Level.WARNING, "Unable to use cached file, redownload it", e);
repository.removeRemoteEntry(con);
}
} else if (con.getResponseCode() / 100 != 2) {
throw new IOException("Server error, response code: " + con.getResponseCode());
}

View File

@ -96,11 +96,17 @@ public final class GetTask extends TaskResult<String> {
if (checkETag) repository.injectConnection(conn);
conn.connect();
if (conn.getResponseCode() == 304) {
if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
// Handle cache
Path cache = repository.getCachedRemoteFile(conn);
setResult(FileUtils.readText(cache));
return;
try {
Path cache = repository.getCachedRemoteFile(conn);
setResult(FileUtils.readText(cache));
return;
} catch (IOException e) {
Logging.LOG.log(Level.WARNING, "Unable to use cached file, redownload it", e);
repository.removeRemoteEntry(conn);
continue;
}
} else if (conn.getResponseCode() / 100 != 2) {
throw new IOException("Server error, response code: " + conn.getResponseCode());
}

View File

@ -164,6 +164,16 @@ public class CacheRepository {
return file;
}
public void removeRemoteEntry(URLConnection conn) {
String url = conn.getURL().toString();
lock.readLock().lock();
try {
index.remove(url);
} finally {
lock.readLock().unlock();
}
}
public void injectConnection(URLConnection conn) {
String url = conn.getURL().toString();
lock.readLock().lock();