import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
+import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
-import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
}
/**
- * Open a resource (will load it from the cache if possible, or save it into
- * the cache after downloading if not) as an Image, then save it where
- * requested.
- * <p>
- * This version will not always work properly if the original file was not
- * downloaded before.
+ * Save the given resource as an image on disk using the default image
+ * format for content.
*
* @param url
- * the resource to open
- *
- * @return the opened resource image
+ * the resource
+ * @param target
+ * the target file
*
* @throws IOException
* in case of I/O error
* in case of I/O error
*/
public File addToCache(InputStream in, String uniqueID) throws IOException {
- File file = getCached(new File(uniqueID).toURI().toURL());
+ File file = getCached(uniqueID);
IOUtils.write(in, file);
return file;
}
+ /**
+ * Return the {@link InputStream} corresponding to the given unique ID, or
+ * NULL if none found.
+ *
+ * @param uniqueID
+ * the unique ID
+ *
+ * @return the content or NULL
+ */
+ public InputStream getFromCache(String uniqueID) {
+ File file = getCached(uniqueID);
+ if (file.exists()) {
+ try {
+ return new MarkableFileInputStream(new FileInputStream(file));
+ } catch (FileNotFoundException e) {
+ }
+ }
+
+ return null;
+ }
+
/**
* Clean the cache (delete the cached items).
*
*
* @throws IOException
* in case of I/O error
- * @throws URISyntaxException
*/
private void save(URL url, BasicSupport support, URL originalUrl)
throws IOException {
*
* @param url
* the url
+ *
* @return the cached version if present, NULL if not
*/
private File getCached(URL url) {
String name = url.getHost();
- if (name == null || name.length() == 0) {
+ if (name == null || name.isEmpty()) {
name = url.getFile();
} else {
name = url.toString();
}
- name = name.replace('/', '_').replace(':', '_');
+ return getCached(name);
+ }
+
+ /**
+ * Get the cache resource from the cache if it is present for this unique
+ * ID.
+ *
+ * @param uniqueID
+ * the id
+ *
+ * @return the cached version if present, NULL if not
+ */
+ private File getCached(String uniqueID) {
+ uniqueID = uniqueID.replace('/', '_').replace(':', '_')
+ .replace("\\", "_");
- return new File(dir, name);
+ return new File(dir, uniqueID);
}
/**