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

Last change on this file since 10134 was 9995, checked in by bastiK, 8 years ago

fixed #12264 - Add own CA's to Java cert-store

  • Property svn:eol-style set to native
File size: 18.6 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 = 24*60*60; // 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 public long getMaxAge() {
179 return maxAge;
180 }
181
182 public String getDestDir() {
183 return destDir;
184 }
185
186 public String getHttpAccept() {
187 return httpAccept;
188 }
189
190 public CachingStrategy getCachingStrategy() {
191 return cachingStrategy;
192 }
193
194 /**
195 * Get InputStream to the requested resource.
196 * @return the InputStream
197 * @throws IOException when the resource with the given name could not be retrieved
198 */
199 public InputStream getInputStream() throws IOException {
200 File file = getFile();
201 if (file == null) {
202 if (name.startsWith("resource://")) {
203 InputStream is = getClass().getResourceAsStream(
204 name.substring("resource:/".length()));
205 if (is == null)
206 throw new IOException(tr("Failed to open input stream for resource ''{0}''", name));
207 return is;
208 } else {
209 throw new IOException("No file found for: "+name);
210 }
211 }
212 return new FileInputStream(file);
213 }
214
215 /**
216 * Get the full content of the requested resource as a byte array.
217 * @return the full content of the requested resource as byte array
218 * @throws IOException in case of an I/O error
219 */
220 public byte[] getByteContent() throws IOException {
221 try (InputStream is = getInputStream()) {
222 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
223 int nRead;
224 byte[] data = new byte[8192];
225 while ((nRead = is.read(data, 0, data.length)) != -1) {
226 buffer.write(data, 0, nRead);
227 }
228 buffer.flush();
229 return buffer.toByteArray();
230 }
231 }
232
233 /**
234 * Returns {@link #getInputStream()} wrapped in a buffered reader.
235 * <p>
236 * Detects Unicode charset in use utilizing {@link UTFInputStreamReader}.
237 *
238 * @return buffered reader
239 * @throws IOException if any I/O error occurs
240 * @since 9411
241 */
242 public BufferedReader getContentReader() throws IOException {
243 return new BufferedReader(UTFInputStreamReader.create(getInputStream()));
244 }
245
246 /**
247 * Get local file for the requested resource.
248 * @return The local cache file for URLs. If the resource is a local file,
249 * returns just that file.
250 * @throws IOException when the resource with the given name could not be retrieved
251 */
252 public synchronized File getFile() throws IOException {
253 if (initialized)
254 return cacheFile;
255 initialized = true;
256 URL url;
257 try {
258 url = new URL(name);
259 if ("file".equals(url.getProtocol())) {
260 cacheFile = new File(name.substring("file:/".length() - 1));
261 if (!cacheFile.exists()) {
262 cacheFile = new File(name.substring("file://".length() - 1));
263 }
264 } else {
265 cacheFile = checkLocal(url);
266 }
267 } catch (MalformedURLException e) {
268 if (name.startsWith("resource://")) {
269 return null;
270 } else if (name.startsWith("josmdir://")) {
271 cacheFile = new File(Main.pref.getUserDataDirectory(), name.substring("josmdir://".length()));
272 } else if (name.startsWith("josmplugindir://")) {
273 cacheFile = new File(Main.pref.getPluginsDirectory(), name.substring("josmplugindir://".length()));
274 } else {
275 cacheFile = new File(name);
276 }
277 }
278 if (cacheFile == null)
279 throw new IOException("Unable to get cache file for "+name);
280 return cacheFile;
281 }
282
283 /**
284 * Looks for a certain entry inside a zip file and returns the entry path.
285 *
286 * Replies a file in the top level directory of the ZIP file which has an
287 * extension <code>extension</code>. If more than one files have this
288 * extension, the last file whose name includes <code>namepart</code>
289 * is opened.
290 *
291 * @param extension the extension of the file we're looking for
292 * @param namepart the name part
293 * @return The zip entry path of the matching file. Null if this cached file
294 * doesn't represent a zip file or if there was no matching
295 * file in the ZIP file.
296 */
297 public String findZipEntryPath(String extension, String namepart) {
298 Pair<String, InputStream> ze = findZipEntryImpl(extension, namepart);
299 if (ze == null) return null;
300 return ze.a;
301 }
302
303 /**
304 * Like {@link #findZipEntryPath}, but returns the corresponding InputStream.
305 * @param extension the extension of the file we're looking for
306 * @param namepart the name part
307 * @return InputStream to the matching file. Null if this cached file
308 * doesn't represent a zip file or if there was no matching
309 * file in the ZIP file.
310 * @since 6148
311 */
312 public InputStream findZipEntryInputStream(String extension, String namepart) {
313 Pair<String, InputStream> ze = findZipEntryImpl(extension, namepart);
314 if (ze == null) return null;
315 return ze.b;
316 }
317
318 private Pair<String, InputStream> findZipEntryImpl(String extension, String namepart) {
319 File file = null;
320 try {
321 file = getFile();
322 } catch (IOException ex) {
323 Main.warn(ex, false);
324 }
325 if (file == null)
326 return null;
327 Pair<String, InputStream> res = null;
328 try {
329 ZipFile zipFile = new ZipFile(file, StandardCharsets.UTF_8);
330 ZipEntry resentry = null;
331 Enumeration<? extends ZipEntry> entries = zipFile.entries();
332 while (entries.hasMoreElements()) {
333 ZipEntry entry = entries.nextElement();
334 if (entry.getName().endsWith('.' + extension)) {
335 /* choose any file with correct extension. When more than
336 one file, prefer the one which matches namepart */
337 if (resentry == null || entry.getName().indexOf(namepart) >= 0) {
338 resentry = entry;
339 }
340 }
341 }
342 if (resentry != null) {
343 InputStream is = zipFile.getInputStream(resentry);
344 res = Pair.create(resentry.getName(), is);
345 } else {
346 Utils.close(zipFile);
347 }
348 } catch (Exception e) {
349 if (file.getName().endsWith(".zip")) {
350 Main.warn(tr("Failed to open file with extension ''{2}'' and namepart ''{3}'' in zip file ''{0}''. Exception was: {1}",
351 file.getName(), e.toString(), extension, namepart));
352 }
353 }
354 return res;
355 }
356
357 /**
358 * Clear the cache for the given resource.
359 * This forces a fresh download.
360 * @param name the URL
361 */
362 public static void cleanup(String name) {
363 cleanup(name, null);
364 }
365
366 /**
367 * Clear the cache for the given resource.
368 * This forces a fresh download.
369 * @param name the URL
370 * @param destDir the destination directory (see {@link #setDestDir(java.lang.String)})
371 */
372 public static void cleanup(String name, String destDir) {
373 URL url;
374 try {
375 url = new URL(name);
376 if (!"file".equals(url.getProtocol())) {
377 String prefKey = getPrefKey(url, destDir);
378 List<String> localPath = new ArrayList<>(Main.pref.getCollection(prefKey));
379 if (localPath.size() == 2) {
380 File lfile = new File(localPath.get(1));
381 if (lfile.exists()) {
382 Utils.deleteFile(lfile);
383 }
384 }
385 Main.pref.putCollection(prefKey, null);
386 }
387 } catch (MalformedURLException e) {
388 Main.warn(e);
389 }
390 }
391
392 /**
393 * Get preference key to store the location and age of the cached file.
394 * 2 resources that point to the same url, but that are to be stored in different
395 * directories will not share a cache file.
396 * @param url URL
397 * @param destDir destination directory
398 * @return Preference key
399 */
400 private static String getPrefKey(URL url, String destDir) {
401 StringBuilder prefKey = new StringBuilder("mirror.");
402 if (destDir != null) {
403 prefKey.append(destDir).append('.');
404 }
405 prefKey.append(url.toString());
406 return prefKey.toString().replaceAll("=", "_");
407 }
408
409 private File checkLocal(URL url) throws IOException {
410 String prefKey = getPrefKey(url, destDir);
411 String urlStr = url.toExternalForm();
412 long age = 0L;
413 long lMaxAge = maxAge;
414 Long ifModifiedSince = null;
415 File localFile = null;
416 List<String> localPathEntry = new ArrayList<>(Main.pref.getCollection(prefKey));
417 boolean offline = false;
418 try {
419 checkOfflineAccess(urlStr);
420 } catch (OfflineAccessException e) {
421 offline = true;
422 }
423 if (localPathEntry.size() == 2) {
424 localFile = new File(localPathEntry.get(1));
425 if (!localFile.exists()) {
426 localFile = null;
427 } else {
428 if (maxAge == DEFAULT_MAXTIME
429 || maxAge <= 0 // arbitrary value <= 0 is deprecated
430 ) {
431 lMaxAge = Main.pref.getInteger("mirror.maxtime", 7*24*60*60); // one week
432 }
433 age = System.currentTimeMillis() - Long.parseLong(localPathEntry.get(0));
434 if (offline || age < lMaxAge*1000) {
435 return localFile;
436 }
437 if (cachingStrategy == CachingStrategy.IfModifiedSince) {
438 ifModifiedSince = Long.valueOf(localPathEntry.get(0));
439 }
440 }
441 }
442 if (destDir == null) {
443 destDir = Main.pref.getCacheDirectory().getPath();
444 }
445
446 File destDirFile = new File(destDir);
447 if (!destDirFile.exists()) {
448 Utils.mkDirs(destDirFile);
449 }
450
451 // No local file + offline => nothing to do
452 if (offline) {
453 return null;
454 }
455
456 String a = urlStr.replaceAll("[^A-Za-z0-9_.-]", "_");
457 String localPath = "mirror_" + a;
458 destDirFile = new File(destDir, localPath + ".tmp");
459 try {
460 activeConnection = HttpClient.create(url)
461 .setAccept(httpAccept)
462 .setIfModifiedSince(ifModifiedSince == null ? 0L : ifModifiedSince)
463 .setHeaders(httpHeaders);
464 if (fastFail) {
465 activeConnection.setReadTimeout(1000);
466 }
467 final HttpClient.Response con = activeConnection.connect();
468 if (ifModifiedSince != null && con.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
469 if (Main.isDebugEnabled()) {
470 Main.debug("304 Not Modified ("+urlStr+')');
471 }
472 if (localFile == null)
473 throw new AssertionError();
474 Main.pref.putCollection(prefKey,
475 Arrays.asList(Long.toString(System.currentTimeMillis()), localPathEntry.get(1)));
476 return localFile;
477 }
478 try (InputStream bis = new BufferedInputStream(con.getContent())) {
479 Files.copy(bis, destDirFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
480 }
481 activeConnection = null;
482 localFile = new File(destDir, localPath);
483 if (Main.platform.rename(destDirFile, localFile)) {
484 Main.pref.putCollection(prefKey,
485 Arrays.asList(Long.toString(System.currentTimeMillis()), localFile.toString()));
486 } else {
487 Main.warn(tr("Failed to rename file {0} to {1}.",
488 destDirFile.getPath(), localFile.getPath()));
489 }
490 } catch (IOException e) {
491 if (age >= lMaxAge*1000 && age < lMaxAge*1000*2) {
492 Main.warn(tr("Failed to load {0}, use cached file and retry next time: {1}", urlStr, e));
493 return localFile;
494 } else {
495 throw e;
496 }
497 }
498
499 return localFile;
500 }
501
502 private static void checkOfflineAccess(String urlString) {
503 OnlineResource.JOSM_WEBSITE.checkOfflineAccess(urlString, Main.getJOSMWebsite());
504 OnlineResource.OSM_API.checkOfflineAccess(urlString, OsmApi.getOsmApi().getServerUrl());
505 }
506
507 /**
508 * Attempts to disconnect an URL connection.
509 * @see HttpClient#disconnect()
510 * @since 9411
511 */
512 @Override
513 public void close() {
514 if (activeConnection != null) {
515 activeConnection.disconnect();
516 }
517 }
518}
Note: See TracBrowser for help on using the repository browser.