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

Last change on this file since 7835 was 7835, checked in by Don-vip, 9 years ago

fix #10026 - migrate preferences and plugins from old ~/.josm directory to new directories on OSX, then delete old directory

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