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, 7 years 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
RevLine 
[6380]1// License: GPL. For details, see LICENSE file.
[906]2package org.openstreetmap.josm.io;
3
[2832]4import static org.openstreetmap.josm.tools.I18n.tr;
5
[9411]6import java.io.BufferedReader;
[9995]7import java.io.ByteArrayOutputStream;
[9411]8import java.io.Closeable;
[906]9import java.io.File;
10import java.io.FileInputStream;
[2017]11import java.io.IOException;
[906]12import java.io.InputStream;
[4262]13import java.net.HttpURLConnection;
14import java.net.MalformedURLException;
[906]15import java.net.URL;
[7089]16import java.nio.charset.StandardCharsets;
[9280]17import java.nio.file.Files;
18import java.nio.file.StandardCopyOption;
[4612]19import java.util.ArrayList;
[4022]20import java.util.Arrays;
[2889]21import java.util.Enumeration;
[4612]22import java.util.List;
[8568]23import java.util.Map;
24import java.util.concurrent.ConcurrentHashMap;
[11288]25import java.util.concurrent.TimeUnit;
[2889]26import java.util.zip.ZipEntry;
27import java.util.zip.ZipFile;
[906]28
29import org.openstreetmap.josm.Main;
[9168]30import org.openstreetmap.josm.tools.HttpClient;
[12620]31import org.openstreetmap.josm.tools.Logging;
[6148]32import org.openstreetmap.josm.tools.Pair;
[4812]33import org.openstreetmap.josm.tools.Utils;
[906]34
35/**
[7248]36 * Downloads a file and caches it on disk in order to reduce network load.
[7434]37 *
[7248]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.)
[906]40 * <p>
[7248]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()}.
[906]46 */
[9411]47public class CachedFile implements Closeable {
[7248]48
[7242]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 */
[7434]57 MaxAge,
[7242]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 */
[7434]64 IfModifiedSince
[7242]65 }
[8510]66
[7248]67 protected String name;
68 protected long maxAge;
69 protected String destDir;
70 protected String httpAccept;
71 protected CachingStrategy cachingStrategy;
[7434]72
[9977]73 private boolean fastFail;
74 private HttpClient activeConnection;
[8840]75 protected File cacheFile;
76 protected boolean initialized;
[4262]77
[6889]78 public static final long DEFAULT_MAXTIME = -1L;
[11288]79 public static final long DAYS = TimeUnit.DAYS.toSeconds(1); // factor to get caching time in days
[906]80
[9078]81 private final Map<String, String> httpHeaders = new ConcurrentHashMap<>();
[8568]82
[6867]83 /**
[7248]84 * Constructs a CachedFile object from a given filename, URL or internal resource.
[7089]85 *
[6867]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>
[8401]89 * <li>{@code http://...} a URL. It will be cached on disk.</li>
[6867]90 * <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
[8401]91 * <li>{@code josmdir://SOME/FILE} file inside josm user data directory (since r7058)</li>
[7835]92 * <li>{@code josmplugindir://SOME/FILE} file inside josm plugin directory (since r7834)</li></ul>
[6867]93 */
[7248]94 public CachedFile(String name) {
95 this.name = name;
[1169]96 }
[906]97
[6867]98 /**
[7248]99 * Set the name of the resource.
[6867]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>
[8401]103 * <li>{@code http://...} a URL. It will be cached on disk.</li>
[6867]104 * <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
[8401]105 * <li>{@code josmdir://SOME/FILE} file inside josm user data directory (since r7058)</li>
[7835]106 * <li>{@code josmplugindir://SOME/FILE} file inside josm plugin directory (since r7834)</li></ul>
[7248]107 * @return this object
[6867]108 */
[7248]109 public CachedFile setName(String name) {
110 this.name = name;
111 return this;
[1169]112 }
[7434]113
[7248]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 }
[906]125
[6867]126 /**
[7248]127 * Set the destination directory for the cache file. Only applies to URLs.
128 * @param destDir the destination directory
129 * @return this object
[6867]130 */
[7248]131 public CachedFile setDestDir(String destDir) {
132 this.destDir = destDir;
133 return this;
[1711]134 }
135
[3695]136 /**
[7248]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
[3695]140 */
[7248]141 public CachedFile setHttpAccept(String httpAccept) {
142 this.httpAccept = httpAccept;
143 return this;
[6867]144 }
145
146 /**
[7248]147 * Set the caching strategy. Only applies to URLs.
[8470]148 * @param cachingStrategy caching strategy
[7248]149 * @return this object
[6867]150 */
[7248]151 public CachedFile setCachingStrategy(CachingStrategy cachingStrategy) {
152 this.cachingStrategy = cachingStrategy;
153 return this;
[6867]154 }
155
[8568]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
[9414]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
[7248]175 public String getName() {
176 return name;
177 }
178
[10194]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 */
[7248]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
[6867]201 /**
[7248]202 * Get InputStream to the requested resource.
203 * @return the InputStream
[6867]204 * @throws IOException when the resource with the given name could not be retrieved
205 */
[7248]206 public InputStream getInputStream() throws IOException {
207 File file = getFile();
208 if (file == null) {
[11493]209 if (name != null && name.startsWith("resource://")) {
[7248]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;
[7853]215 } else {
[7890]216 throw new IOException("No file found for: "+name);
[7853]217 }
[7248]218 }
219 return new FileInputStream(file);
[7242]220 }
221
222 /**
[9995]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 /**
[9411]241 * Returns {@link #getInputStream()} wrapped in a buffered reader.
[9545]242 * <p>
[9411]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 /**
[7248]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.
[7242]257 * @throws IOException when the resource with the given name could not be retrieved
258 */
[7853]259 public synchronized File getFile() throws IOException {
[7248]260 if (initialized)
261 return cacheFile;
262 initialized = true;
[1169]263 URL url;
[1523]264 try {
[1169]265 url = new URL(name);
[7012]266 if ("file".equals(url.getProtocol())) {
[8596]267 cacheFile = new File(name.substring("file:/".length() - 1));
[7248]268 if (!cacheFile.exists()) {
[8596]269 cacheFile = new File(name.substring("file://".length() - 1));
[2832]270 }
[1523]271 } else {
[7248]272 cacheFile = checkLocal(url);
[1169]273 }
[7434]274 } catch (MalformedURLException e) {
[11493]275 if (name == null || name.startsWith("resource://")) {
[7248]276 return null;
[7058]277 } else if (name.startsWith("josmdir://")) {
[7834]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()));
[7058]281 } else {
[7248]282 cacheFile = new File(name);
[1169]283 }
284 }
[7248]285 if (cacheFile == null)
[7434]286 throw new IOException("Unable to get cache file for "+name);
[7248]287 return cacheFile;
[1169]288 }
[7434]289
[3007]290 /**
[6148]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>
[3007]296 * is opened.
[3321]297 *
[3007]298 * @param extension the extension of the file we're looking for
299 * @param namepart the name part
[7248]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
[6148]302 * file in the ZIP file.
[3007]303 */
[6148]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.
[7248]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.
[6985]317 * @since 6148
[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) {
[7248]326 File file = null;
327 try {
328 file = getFile();
329 } catch (IOException ex) {
[12620]330 Logging.log(Logging.LEVEL_WARN, ex);
[7248]331 }
[3011]332 if (file == null)
333 return null;
[6148]334 Pair<String, InputStream> res = null;
[2889]335 try {
[7089]336 ZipFile zipFile = new ZipFile(file, StandardCharsets.UTF_8);
[3007]337 ZipEntry resentry = null;
338 Enumeration<? extends ZipEntry> entries = zipFile.entries();
339 while (entries.hasMoreElements()) {
340 ZipEntry entry = entries.nextElement();
[11386]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;
[2889]344 }
345 }
[3007]346 if (resentry != null) {
[6148]347 InputStream is = zipFile.getInputStream(resentry);
348 res = Pair.create(resentry.getName(), is);
[3007]349 } else {
[5874]350 Utils.close(zipFile);
[3007]351 }
[10212]352 } catch (IOException e) {
[6248]353 if (file.getName().endsWith(".zip")) {
[12620]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);
[3041]357 }
[2889]358 }
359 return res;
360 }
361
[7081]362 /**
[7248]363 * Clear the cache for the given resource.
364 * This forces a fresh download.
[7434]365 * @param name the URL
[7081]366 */
[6310]367 public static void cleanup(String name) {
[2832]368 cleanup(name, null);
[1747]369 }
[7089]370
[7248]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 */
[6310]377 public static void cleanup(String name, String destDir) {
[1747]378 URL url;
379 try {
380 url = new URL(name);
[7012]381 if (!"file".equals(url.getProtocol())) {
[3695]382 String prefKey = getPrefKey(url, destDir);
[7005]383 List<String> localPath = new ArrayList<>(Main.pref.getCollection(prefKey));
[4638]384 if (localPath.size() == 2) {
385 File lfile = new File(localPath.get(1));
[8510]386 if (lfile.exists()) {
[9296]387 Utils.deleteFile(lfile);
[2832]388 }
[1747]389 }
[4812]390 Main.pref.putCollection(prefKey, null);
[1747]391 }
[6310]392 } catch (MalformedURLException e) {
[12620]393 Logging.warn(e);
[6310]394 }
[1747]395 }
396
[3695]397 /**
[7248]398 * Get preference key to store the location and age of the cached file.
[3695]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.
[8929]401 * @param url URL
402 * @param destDir destination directory
403 * @return Preference key
[3695]404 */
405 private static String getPrefKey(URL url, String destDir) {
406 StringBuilder prefKey = new StringBuilder("mirror.");
407 if (destDir != null) {
[8390]408 prefKey.append(destDir).append('.');
[3695]409 }
410 prefKey.append(url.toString());
[8510]411 return prefKey.toString().replaceAll("=", "_");
[3695]412 }
413
[7248]414 private File checkLocal(URL url) throws IOException {
[3695]415 String prefKey = getPrefKey(url, destDir);
[7434]416 String urlStr = url.toExternalForm();
[4128]417 long age = 0L;
[11288]418 long maxAgeMillis = maxAge;
[7242]419 Long ifModifiedSince = null;
[4262]420 File localFile = null;
[7005]421 List<String> localPathEntry = new ArrayList<>(Main.pref.getCollection(prefKey));
[7434]422 boolean offline = false;
423 try {
424 checkOfflineAccess(urlStr);
425 } catch (OfflineAccessException e) {
[12620]426 Logging.trace(e);
[7434]427 offline = true;
428 }
[4612]429 if (localPathEntry.size() == 2) {
430 localFile = new File(localPathEntry.get(1));
[7434]431 if (!localFile.exists()) {
[4262]432 localFile = null;
[7434]433 } else {
[8443]434 if (maxAge == DEFAULT_MAXTIME
[7248]435 || maxAge <= 0 // arbitrary value <= 0 is deprecated
[4240]436 ) {
[11288]437 maxAgeMillis = TimeUnit.SECONDS.toMillis(Main.pref.getLong("mirror.maxtime", TimeUnit.DAYS.toSeconds(7)));
[3877]438 }
[4612]439 age = System.currentTimeMillis() - Long.parseLong(localPathEntry.get(0));
[11288]440 if (offline || age < maxAgeMillis) {
[4262]441 return localFile;
[3877]442 }
[7248]443 if (cachingStrategy == CachingStrategy.IfModifiedSince) {
[8390]444 ifModifiedSince = Long.valueOf(localPathEntry.get(0));
[7242]445 }
[1169]446 }
447 }
[4812]448 if (destDir == null) {
449 destDir = Main.pref.getCacheDirectory().getPath();
[2832]450 }
[906]451
[1169]452 File destDirFile = new File(destDir);
[2832]453 if (!destDirFile.exists()) {
[9645]454 Utils.mkDirs(destDirFile);
[2832]455 }
[7434]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_.-]", "_");
[4022]463 String localPath = "mirror_" + a;
[1169]464 destDirFile = new File(destDir, localPath + ".tmp");
[1523]465 try {
[9411]466 activeConnection = HttpClient.create(url)
[9168]467 .setAccept(httpAccept)
468 .setIfModifiedSince(ifModifiedSince == null ? 0L : ifModifiedSince)
[9411]469 .setHeaders(httpHeaders);
[9414]470 if (fastFail) {
471 activeConnection.setReadTimeout(1000);
472 }
[9411]473 final HttpClient.Response con = activeConnection.connect();
[7242]474 if (ifModifiedSince != null && con.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
[12620]475 Logging.debug("304 Not Modified ({0})", urlStr);
[7434]476 if (localFile == null)
477 throw new AssertionError();
478 Main.pref.putCollection(prefKey,
[7242]479 Arrays.asList(Long.toString(System.currentTimeMillis()), localPathEntry.get(1)));
480 return localFile;
[10686]481 } else if (con.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) {
482 throw new IOException(tr("The requested URL {0} was not found", urlStr));
[7434]483 }
[11856]484 try (InputStream is = con.getContent()) {
485 Files.copy(is, destDirFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
[2832]486 }
[9411]487 activeConnection = null;
[4262]488 localFile = new File(destDir, localPath);
[7434]489 if (Main.platform.rename(destDirFile, localFile)) {
490 Main.pref.putCollection(prefKey,
[7242]491 Arrays.asList(Long.toString(System.currentTimeMillis()), localFile.toString()));
[4145]492 } else {
[12620]493 Logging.warn(tr("Failed to rename file {0} to {1}.",
[4262]494 destDirFile.getPath(), localFile.getPath()));
[4145]495 }
[4128]496 } catch (IOException e) {
[11288]497 if (age >= maxAgeMillis && age < maxAgeMillis*2) {
[12620]498 Logging.warn(tr("Failed to load {0}, use cached file and retry next time: {1}", urlStr, e));
[4262]499 return localFile;
[4128]500 } else {
501 throw e;
502 }
[1169]503 }
[906]504
[4262]505 return localFile;
[1169]506 }
[4262]507
[7434]508 private static void checkOfflineAccess(String urlString) {
509 OnlineResource.JOSM_WEBSITE.checkOfflineAccess(urlString, Main.getJOSMWebsite());
[9353]510 OnlineResource.OSM_API.checkOfflineAccess(urlString, OsmApi.getOsmApi().getServerUrl());
[7434]511 }
512
[9411]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 }
[10993]524
525 /**
526 * Clears the cached file
[11009]527 * @throws IOException if any I/O error occurs
[10993]528 * @since 10993
529 */
530 public void clear() throws IOException {
[11195]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 }
[10993]540 File f = getFile();
541 if (f != null && f.exists()) {
542 Utils.deleteFile(f);
543 }
544 }
[906]545}
Note: See TracBrowser for help on using the repository browser.