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

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

fix recent sonar/checkstyle issues

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