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

Last change on this file since 9615 was 9545, checked in by Don-vip, 8 years ago

fix javadoc errors/warnings

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