Copyright (c) 2012 Johan Brook, Robin Andersson, Lisa Stenberg, Mattias Henriksson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documen...
If you think the Android project watchme listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
Java Source Code
/**
* ImageCache.java//www.java2s.com
*
* <p>A default implementation of a ResponseCache.</p>
*
* @author Johan Brook
* @copyright (c) 2012 Johan Brook, Robin Andersson, Lisa Stenberg, Mattias Henriksson
* @license MIT
*/package se.chalmers.watchme.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.CacheRequest;
import java.net.CacheResponse;
import java.net.ResponseCache;
import java.net.URI;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
publicclass ImageCache extends ResponseCache {
privateFile cacheDir;
/**
* Create a new cache in a specified location.
*
* @param cacheDir The directory to store the cached files
*/public ImageCache(File cacheDir) {
this.cacheDir = cacheDir;
}
@Override
public CacheResponse get(URI uri, String s, Map<String, List<String>> headers) throws IOException {
// Fetch the file we're looking for
finalFile file = newFile(cacheDir, escape(uri.getPath()));
if (file.exists()) {
returnnew CacheResponse() {
@Override
public Map<String, List<String>> getHeaders() throws IOException {
return null;
}
@Override
public InputStream getBody() throws IOException {
// Construct a stream from our cached file
returnnew FileInputStream(file);
}
};
} else {
return null;
}
}
@Override
public CacheRequest put(URI uri, URLConnection urlConnection) throws IOException {
finalFile file = newFile(cacheDir, escape(urlConnection.getURL().getPath()));
returnnew CacheRequest() {
@Override
public OutputStream getBody() throws IOException {
returnnew FileOutputStream(file);
}
@Override
publicvoid abort() {
file.delete();
}
};
}
private String escape(String url) {
return url.replace("/", "-").replace(".", "-");
}
}