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

Last change on this file since 12620 was 12620, checked in by Don-vip, 4 months ago

see #15182 - deprecate all Main logging methods and introduce suitable replacements in Logging for most of them

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