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

Last change on this file since 14180 was 14149, checked in by Don-vip, 6 years ago

see #15229 - deprecate Main.pref

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