source: josm/trunk/src/org/openstreetmap/josm/io/CachedFile.java@ 12856

Last change on this file since 12856 was 12856, checked in by bastiK, 7 years ago

see #15229 - add parameter to base directory methods

  • Property svn:eol-style set to native
File size: 19.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.BufferedReader;
7import java.io.ByteArrayOutputStream;
8import java.io.Closeable;
9import java.io.File;
10import java.io.FileInputStream;
11import java.io.IOException;
12import java.io.InputStream;
13import java.net.HttpURLConnection;
14import java.net.MalformedURLException;
15import java.net.URL;
16import java.nio.charset.StandardCharsets;
17import java.nio.file.Files;
18import java.nio.file.StandardCopyOption;
19import java.util.ArrayList;
20import java.util.Arrays;
21import java.util.Enumeration;
22import java.util.List;
23import java.util.Map;
24import java.util.concurrent.ConcurrentHashMap;
25import java.util.concurrent.TimeUnit;
26import java.util.zip.ZipEntry;
27import java.util.zip.ZipFile;
28
29import org.openstreetmap.josm.Main;
30import org.openstreetmap.josm.spi.preferences.Config;
31import org.openstreetmap.josm.tools.HttpClient;
32import org.openstreetmap.josm.tools.Logging;
33import org.openstreetmap.josm.tools.Pair;
34import org.openstreetmap.josm.tools.Utils;
35
36/**
37 * Downloads a file and caches it on disk in order to reduce network load.
38 *
39 * Supports URLs, local files, and a custom scheme (<code>resource:</code>) to get
40 * resources from the current *.jar file. (Local caching is only done for URLs.)
41 * <p>
42 * The mirrored file is only downloaded if it has been more than 7 days since
43 * last download. (Time can be configured.)
44 * <p>
45 * The file content is normally accessed with {@link #getInputStream()}, but
46 * you can also get the mirrored copy with {@link #getFile()}.
47 */
48public class CachedFile implements Closeable {
49
50 /**
51 * Caching strategy.
52 */
53 public enum CachingStrategy {
54 /**
55 * If cached file on disk is older than a certain time (7 days by default),
56 * consider the cache stale and try to download the file again.
57 */
58 MaxAge,
59 /**
60 * Similar to MaxAge, considers the cache stale when a certain age is
61 * exceeded. In addition, a If-Modified-Since HTTP header is added.
62 * When the server replies "304 Not Modified", this is considered the same
63 * as a full download.
64 */
65 IfModifiedSince
66 }
67
68 protected String name;
69 protected long maxAge;
70 protected String destDir;
71 protected String httpAccept;
72 protected CachingStrategy cachingStrategy;
73
74 private boolean fastFail;
75 private HttpClient activeConnection;
76 protected File cacheFile;
77 protected boolean initialized;
78
79 public static final long DEFAULT_MAXTIME = -1L;
80 public static final long DAYS = TimeUnit.DAYS.toSeconds(1); // factor to get caching time in days
81
82 private final Map<String, String> httpHeaders = new ConcurrentHashMap<>();
83
84 /**
85 * Constructs a CachedFile object from a given filename, URL or internal resource.
86 *
87 * @param name can be:<ul>
88 * <li>relative or absolute file name</li>
89 * <li>{@code file:///SOME/FILE} the same as above</li>
90 * <li>{@code http://...} a URL. It will be cached on disk.</li>
91 * <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
92 * <li>{@code josmdir://SOME/FILE} file inside josm user data directory (since r7058)</li>
93 * <li>{@code josmplugindir://SOME/FILE} file inside josm plugin directory (since r7834)</li></ul>
94 */
95 public CachedFile(String name) {
96 this.name = name;
97 }
98
99 /**
100 * Set the name of the resource.
101 * @param name can be:<ul>
102 * <li>relative or absolute file name</li>
103 * <li>{@code file:///SOME/FILE} the same as above</li>
104 * <li>{@code http://...} a URL. It will be cached on disk.</li>
105 * <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
106 * <li>{@code josmdir://SOME/FILE} file inside josm user data directory (since r7058)</li>
107 * <li>{@code josmplugindir://SOME/FILE} file inside josm plugin directory (since r7834)</li></ul>
108 * @return this object
109 */
110 public CachedFile setName(String name) {
111 this.name = name;
112 return this;
113 }
114
115 /**
116 * Set maximum age of cache file. Only applies to URLs.
117 * When this time has passed after the last download of the file, the
118 * cache is considered stale and a new download will be attempted.
119 * @param maxAge the maximum cache age in seconds
120 * @return this object
121 */
122 public CachedFile setMaxAge(long maxAge) {
123 this.maxAge = maxAge;
124 return this;
125 }
126
127 /**
128 * Set the destination directory for the cache file. Only applies to URLs.
129 * @param destDir the destination directory
130 * @return this object
131 */
132 public CachedFile setDestDir(String destDir) {
133 this.destDir = destDir;
134 return this;
135 }
136
137 /**
138 * Set the accepted MIME types sent in the HTTP Accept header. Only applies to URLs.
139 * @param httpAccept the accepted MIME types
140 * @return this object
141 */
142 public CachedFile setHttpAccept(String httpAccept) {
143 this.httpAccept = httpAccept;
144 return this;
145 }
146
147 /**
148 * Set the caching strategy. Only applies to URLs.
149 * @param cachingStrategy caching strategy
150 * @return this object
151 */
152 public CachedFile setCachingStrategy(CachingStrategy cachingStrategy) {
153 this.cachingStrategy = cachingStrategy;
154 return this;
155 }
156
157 /**
158 * Sets the http headers. Only applies to URL pointing to http or https resources
159 * @param headers that should be sent together with request
160 * @return this object
161 */
162 public CachedFile setHttpHeaders(Map<String, String> headers) {
163 this.httpHeaders.putAll(headers);
164 return this;
165 }
166
167 /**
168 * Sets whether opening HTTP connections should fail fast, i.e., whether a
169 * {@link HttpClient#setConnectTimeout(int) low connect timeout} should be used.
170 * @param fastFail whether opening HTTP connections should fail fast
171 */
172 public void setFastFail(boolean fastFail) {
173 this.fastFail = fastFail;
174 }
175
176 public String getName() {
177 return name;
178 }
179
180 /**
181 * Returns maximum age of cache file. Only applies to URLs.
182 * When this time has passed after the last download of the file, the
183 * cache is considered stale and a new download will be attempted.
184 * @return the maximum cache age in seconds
185 */
186 public long getMaxAge() {
187 return maxAge;
188 }
189
190 public String getDestDir() {
191 return destDir;
192 }
193
194 public String getHttpAccept() {
195 return httpAccept;
196 }
197
198 public CachingStrategy getCachingStrategy() {
199 return cachingStrategy;
200 }
201
202 /**
203 * Get InputStream to the requested resource.
204 * @return the InputStream
205 * @throws IOException when the resource with the given name could not be retrieved
206 */
207 public InputStream getInputStream() throws IOException {
208 File file = getFile();
209 if (file == null) {
210 if (name != null && name.startsWith("resource://")) {
211 InputStream is = getClass().getResourceAsStream(
212 name.substring("resource:/".length()));
213 if (is == null)
214 throw new IOException(tr("Failed to open input stream for resource ''{0}''", name));
215 return is;
216 } else {
217 throw new IOException("No file found for: "+name);
218 }
219 }
220 return new FileInputStream(file);
221 }
222
223 /**
224 * Get the full content of the requested resource as a byte array.
225 * @return the full content of the requested resource as byte array
226 * @throws IOException in case of an I/O error
227 */
228 public byte[] getByteContent() throws IOException {
229 try (InputStream is = getInputStream()) {
230 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
231 int nRead;
232 byte[] data = new byte[8192];
233 while ((nRead = is.read(data, 0, data.length)) != -1) {
234 buffer.write(data, 0, nRead);
235 }
236 buffer.flush();
237 return buffer.toByteArray();
238 }
239 }
240
241 /**
242 * Returns {@link #getInputStream()} wrapped in a buffered reader.
243 * <p>
244 * Detects Unicode charset in use utilizing {@link UTFInputStreamReader}.
245 *
246 * @return buffered reader
247 * @throws IOException if any I/O error occurs
248 * @since 9411
249 */
250 public BufferedReader getContentReader() throws IOException {
251 return new BufferedReader(UTFInputStreamReader.create(getInputStream()));
252 }
253
254 /**
255 * Get local file for the requested resource.
256 * @return The local cache file for URLs. If the resource is a local file,
257 * returns just that file.
258 * @throws IOException when the resource with the given name could not be retrieved
259 */
260 public synchronized File getFile() throws IOException {
261 if (initialized)
262 return cacheFile;
263 initialized = true;
264 URL url;
265 try {
266 url = new URL(name);
267 if ("file".equals(url.getProtocol())) {
268 cacheFile = new File(name.substring("file:/".length() - 1));
269 if (!cacheFile.exists()) {
270 cacheFile = new File(name.substring("file://".length() - 1));
271 }
272 } else {
273 cacheFile = checkLocal(url);
274 }
275 } catch (MalformedURLException e) {
276 if (name == null || name.startsWith("resource://")) {
277 return null;
278 } else if (name.startsWith("josmdir://")) {
279 cacheFile = new File(Config.getDirs().getUserDataDirectory(false), name.substring("josmdir://".length()));
280 } else if (name.startsWith("josmplugindir://")) {
281 cacheFile = new File(Main.pref.getPluginsDirectory(), name.substring("josmplugindir://".length()));
282 } else {
283 cacheFile = new File(name);
284 }
285 }
286 if (cacheFile == null)
287 throw new IOException("Unable to get cache file for "+name);
288 return cacheFile;
289 }
290
291 /**
292 * Looks for a certain entry inside a zip file and returns the entry path.
293 *
294 * Replies a file in the top level directory of the ZIP file which has an
295 * extension <code>extension</code>. If more than one files have this
296 * extension, the last file whose name includes <code>namepart</code>
297 * is opened.
298 *
299 * @param extension the extension of the file we're looking for
300 * @param namepart the name part
301 * @return The zip entry path of the matching file. Null if this cached file
302 * doesn't represent a zip file or if there was no matching
303 * file in the ZIP file.
304 */
305 public String findZipEntryPath(String extension, String namepart) {
306 Pair<String, InputStream> ze = findZipEntryImpl(extension, namepart);
307 if (ze == null) return null;
308 return ze.a;
309 }
310
311 /**
312 * Like {@link #findZipEntryPath}, but returns the corresponding InputStream.
313 * @param extension the extension of the file we're looking for
314 * @param namepart the name part
315 * @return InputStream to the matching file. Null if this cached file
316 * doesn't represent a zip file or if there was no matching
317 * file in the ZIP file.
318 * @since 6148
319 */
320 public InputStream findZipEntryInputStream(String extension, String namepart) {
321 Pair<String, InputStream> ze = findZipEntryImpl(extension, namepart);
322 if (ze == null) return null;
323 return ze.b;
324 }
325
326 private Pair<String, InputStream> findZipEntryImpl(String extension, String namepart) {
327 File file = null;
328 try {
329 file = getFile();
330 } catch (IOException ex) {
331 Logging.log(Logging.LEVEL_WARN, ex);
332 }
333 if (file == null)
334 return null;
335 Pair<String, InputStream> res = null;
336 try {
337 ZipFile zipFile = new ZipFile(file, StandardCharsets.UTF_8);
338 ZipEntry resentry = null;
339 Enumeration<? extends ZipEntry> entries = zipFile.entries();
340 while (entries.hasMoreElements()) {
341 ZipEntry entry = entries.nextElement();
342 // choose any file with correct extension. When more than one file, prefer the one which matches namepart
343 if (entry.getName().endsWith('.' + extension) && (resentry == null || entry.getName().indexOf(namepart) >= 0)) {
344 resentry = entry;
345 }
346 }
347 if (resentry != null) {
348 InputStream is = zipFile.getInputStream(resentry);
349 res = Pair.create(resentry.getName(), is);
350 } else {
351 Utils.close(zipFile);
352 }
353 } catch (IOException e) {
354 if (file.getName().endsWith(".zip")) {
355 Logging.log(Logging.LEVEL_WARN,
356 tr("Failed to open file with extension ''{2}'' and namepart ''{3}'' in zip file ''{0}''. Exception was: {1}",
357 file.getName(), e.toString(), extension, namepart), e);
358 }
359 }
360 return res;
361 }
362
363 /**
364 * Clear the cache for the given resource.
365 * This forces a fresh download.
366 * @param name the URL
367 */
368 public static void cleanup(String name) {
369 cleanup(name, null);
370 }
371
372 /**
373 * Clear the cache for the given resource.
374 * This forces a fresh download.
375 * @param name the URL
376 * @param destDir the destination directory (see {@link #setDestDir(java.lang.String)})
377 */
378 public static void cleanup(String name, String destDir) {
379 URL url;
380 try {
381 url = new URL(name);
382 if (!"file".equals(url.getProtocol())) {
383 String prefKey = getPrefKey(url, destDir);
384 List<String> localPath = new ArrayList<>(Config.getPref().getList(prefKey));
385 if (localPath.size() == 2) {
386 File lfile = new File(localPath.get(1));
387 if (lfile.exists()) {
388 Utils.deleteFile(lfile);
389 }
390 }
391 Config.getPref().putList(prefKey, null);
392 }
393 } catch (MalformedURLException e) {
394 Logging.warn(e);
395 }
396 }
397
398 /**
399 * Get preference key to store the location and age of the cached file.
400 * 2 resources that point to the same url, but that are to be stored in different
401 * directories will not share a cache file.
402 * @param url URL
403 * @param destDir destination directory
404 * @return Preference key
405 */
406 private static String getPrefKey(URL url, String destDir) {
407 StringBuilder prefKey = new StringBuilder("mirror.");
408 if (destDir != null) {
409 prefKey.append(destDir).append('.');
410 }
411 prefKey.append(url.toString());
412 return prefKey.toString().replaceAll("=", "_");
413 }
414
415 private File checkLocal(URL url) throws IOException {
416 String prefKey = getPrefKey(url, destDir);
417 String urlStr = url.toExternalForm();
418 long age = 0L;
419 long maxAgeMillis = maxAge;
420 Long ifModifiedSince = null;
421 File localFile = null;
422 List<String> localPathEntry = new ArrayList<>(Config.getPref().getList(prefKey));
423 boolean offline = false;
424 try {
425 checkOfflineAccess(urlStr);
426 } catch (OfflineAccessException e) {
427 Logging.trace(e);
428 offline = true;
429 }
430 if (localPathEntry.size() == 2) {
431 localFile = new File(localPathEntry.get(1));
432 if (!localFile.exists()) {
433 localFile = null;
434 } else {
435 if (maxAge == DEFAULT_MAXTIME
436 || maxAge <= 0 // arbitrary value <= 0 is deprecated
437 ) {
438 maxAgeMillis = TimeUnit.SECONDS.toMillis(Config.getPref().getLong("mirror.maxtime", TimeUnit.DAYS.toSeconds(7)));
439 }
440 age = System.currentTimeMillis() - Long.parseLong(localPathEntry.get(0));
441 if (offline || age < maxAgeMillis) {
442 return localFile;
443 }
444 if (cachingStrategy == CachingStrategy.IfModifiedSince) {
445 ifModifiedSince = Long.valueOf(localPathEntry.get(0));
446 }
447 }
448 }
449 if (destDir == null) {
450 destDir = Config.getDirs().getCacheDirectory(true).getPath();
451 }
452
453 File destDirFile = new File(destDir);
454 if (!destDirFile.exists()) {
455 Utils.mkDirs(destDirFile);
456 }
457
458 // No local file + offline => nothing to do
459 if (offline) {
460 return null;
461 }
462
463 String a = urlStr.replaceAll("[^A-Za-z0-9_.-]", "_");
464 String localPath = "mirror_" + a;
465 destDirFile = new File(destDir, localPath + ".tmp");
466 try {
467 activeConnection = HttpClient.create(url)
468 .setAccept(httpAccept)
469 .setIfModifiedSince(ifModifiedSince == null ? 0L : ifModifiedSince)
470 .setHeaders(httpHeaders);
471 if (fastFail) {
472 activeConnection.setReadTimeout(1000);
473 }
474 final HttpClient.Response con = activeConnection.connect();
475 if (ifModifiedSince != null && con.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
476 Logging.debug("304 Not Modified ({0})", urlStr);
477 if (localFile == null)
478 throw new AssertionError();
479 Config.getPref().putList(prefKey,
480 Arrays.asList(Long.toString(System.currentTimeMillis()), localPathEntry.get(1)));
481 return localFile;
482 } else if (con.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
483 throw new IOException(tr("The requested URL {0} was not found", urlStr));
484 }
485 try (InputStream is = con.getContent()) {
486 Files.copy(is, destDirFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
487 }
488 activeConnection = null;
489 localFile = new File(destDir, localPath);
490 if (Main.platform.rename(destDirFile, localFile)) {
491 Config.getPref().putList(prefKey,
492 Arrays.asList(Long.toString(System.currentTimeMillis()), localFile.toString()));
493 } else {
494 Logging.warn(tr("Failed to rename file {0} to {1}.",
495 destDirFile.getPath(), localFile.getPath()));
496 }
497 } catch (IOException e) {
498 if (age >= maxAgeMillis && age < maxAgeMillis*2) {
499 Logging.warn(tr("Failed to load {0}, use cached file and retry next time: {1}", urlStr, e));
500 return localFile;
501 } else {
502 throw e;
503 }
504 }
505
506 return localFile;
507 }
508
509 private static void checkOfflineAccess(String urlString) {
510 OnlineResource.JOSM_WEBSITE.checkOfflineAccess(urlString, Main.getJOSMWebsite());
511 OnlineResource.OSM_API.checkOfflineAccess(urlString, OsmApi.getOsmApi().getServerUrl());
512 }
513
514 /**
515 * Attempts to disconnect an URL connection.
516 * @see HttpClient#disconnect()
517 * @since 9411
518 */
519 @Override
520 public void close() {
521 if (activeConnection != null) {
522 activeConnection.disconnect();
523 }
524 }
525
526 /**
527 * Clears the cached file
528 * @throws IOException if any I/O error occurs
529 * @since 10993
530 */
531 public void clear() throws IOException {
532 URL url;
533 try {
534 url = new URL(name);
535 if ("file".equals(url.getProtocol())) {
536 return; // this is local file - do not delete it
537 }
538 } catch (MalformedURLException e) {
539 return; // if it's not a URL, then it still might be a local file - better not to delete
540 }
541 File f = getFile();
542 if (f != null && f.exists()) {
543 Utils.deleteFile(f);
544 }
545 }
546}
Note: See TracBrowser for help on using the repository browser.