source: josm/trunk/src/org/openstreetmap/josm/data/cache/JCSCachedTileLoaderJob.java@ 8643

Last change on this file since 8643 was 8643, checked in by wiktorn, 9 years ago

Fix behaviour when exception is thrown during download.

  • fix endless download, when exception is thrown during download
  • draw multiline error text on tile if error string is longer than tile width
  • Property svn:eol-style set to native
File size: 20.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.cache;
3
4import java.io.FileNotFoundException;
5import java.io.IOException;
6import java.net.HttpURLConnection;
7import java.net.URL;
8import java.net.URLConnection;
9import java.util.HashSet;
10import java.util.List;
11import java.util.Map;
12import java.util.Random;
13import java.util.Set;
14import java.util.concurrent.ConcurrentHashMap;
15import java.util.concurrent.ConcurrentMap;
16import java.util.concurrent.LinkedBlockingDeque;
17import java.util.concurrent.ThreadPoolExecutor;
18import java.util.concurrent.TimeUnit;
19import java.util.logging.Level;
20import java.util.logging.Logger;
21
22import org.apache.commons.jcs.access.behavior.ICacheAccess;
23import org.apache.commons.jcs.engine.behavior.ICacheElement;
24import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
25import org.openstreetmap.josm.Main;
26import org.openstreetmap.josm.data.cache.ICachedLoaderListener.LoadResult;
27import org.openstreetmap.josm.data.preferences.IntegerProperty;
28import org.openstreetmap.josm.tools.Utils;
29
30/**
31 * @author Wiktor Niesiobędzki
32 *
33 * @param <K> cache entry key type
34 * @param <V> cache value type
35 *
36 * Generic loader for HTTP based tiles. Uses custom attribute, to check, if entry has expired
37 * according to HTTP headers sent with tile. If so, it tries to verify using Etags
38 * or If-Modified-Since / Last-Modified.
39 *
40 * If the tile is not valid, it will try to download it from remote service and put it
41 * to cache. If remote server will fail it will try to use stale entry.
42 *
43 * This class will keep only one Job running for specified tile. All others will just finish, but
44 * listeners will be gathered and notified, once download job will be finished
45 *
46 * @since 8168
47 */
48public abstract class JCSCachedTileLoaderJob<K, V extends CacheEntry> implements ICachedLoaderJob<K>, Runnable {
49 private static final Logger log = FeatureAdapter.getLogger(JCSCachedTileLoaderJob.class.getCanonicalName());
50 protected static final long DEFAULT_EXPIRE_TIME = 1000L * 60 * 60 * 24 * 7; // 7 days
51 // Limit for the max-age value send by the server.
52 protected static final long EXPIRE_TIME_SERVER_LIMIT = 1000L * 60 * 60 * 24 * 28; // 4 weeks
53 // Absolute expire time limit. Cached tiles that are older will not be used,
54 // even if the refresh from the server fails.
55 protected static final long ABSOLUTE_EXPIRE_TIME_LIMIT = 1000L * 60 * 60 * 24 * 365; // 1 year
56
57 /**
58 * maximum download threads that will be started
59 */
60 public static final IntegerProperty THREAD_LIMIT = new IntegerProperty("cache.jcs.max_threads", 10);
61
62 /*
63 * ThreadPoolExecutor starts new threads, until THREAD_LIMIT is reached. Then it puts tasks into LinkedBlockingDeque.
64 *
65 * The queue works FIFO, so one needs to take care about ordering of the entries submitted
66 *
67 * There is no point in canceling tasks, that are already taken by worker threads (if we made so much effort, we can at least cache
68 * the response, so later it could be used). We could actually cancel what is in LIFOQueue, but this is a tradeoff between simplicity
69 * and performance (we do want to have something to offer to worker threads before tasks will be resubmitted by class consumer)
70 */
71
72 private static ThreadPoolExecutor DEFAULT_DOWNLOAD_JOB_DISPATCHER = new ThreadPoolExecutor(
73 2, // we have a small queue, so threads will be quickly started (threads are started only, when queue is full)
74 THREAD_LIMIT.get().intValue(), // do not this number of threads
75 30, // keepalive for thread
76 TimeUnit.SECONDS,
77 // make queue of LIFO type - so recently requested tiles will be loaded first (assuming that these are which user is waiting to see)
78 new LinkedBlockingDeque<Runnable>(),
79 Utils.getNamedThreadFactory("JCS downloader")
80 );
81
82
83
84 private static ConcurrentMap<String, Set<ICachedLoaderListener>> inProgress = new ConcurrentHashMap<>();
85 private static ConcurrentMap<String, Boolean> useHead = new ConcurrentHashMap<>();
86
87 protected long now; // when the job started
88
89 private ICacheAccess<K, V> cache;
90 private ICacheElement<K, V> cacheElement;
91 protected V cacheData = null;
92 protected CacheEntryAttributes attributes = null;
93
94 // HTTP connection parameters
95 private int connectTimeout;
96 private int readTimeout;
97 private Map<String, String> headers;
98 private ThreadPoolExecutor downloadJobExecutor;
99 private Runnable finishTask;
100 private boolean force = false;
101
102 /**
103 * @param cache cache instance that we will work on
104 * @param headers HTTP headers to be sent together with request
105 * @param readTimeout when connecting to remote resource
106 * @param connectTimeout when connecting to remote resource
107 * @param downloadJobExecutor that will be executing the jobs
108 */
109 public JCSCachedTileLoaderJob(ICacheAccess<K, V> cache,
110 int connectTimeout, int readTimeout,
111 Map<String, String> headers,
112 ThreadPoolExecutor downloadJobExecutor) {
113
114 this.cache = cache;
115 this.now = System.currentTimeMillis();
116 this.connectTimeout = connectTimeout;
117 this.readTimeout = readTimeout;
118 this.headers = headers;
119 this.downloadJobExecutor = downloadJobExecutor;
120 }
121
122 /**
123 * @param cache cache instance that we will work on
124 * @param headers HTTP headers to be sent together with request
125 * @param readTimeout when connecting to remote resource
126 * @param connectTimeout when connecting to remote resource
127 */
128 public JCSCachedTileLoaderJob(ICacheAccess<K, V> cache,
129 int connectTimeout, int readTimeout,
130 Map<String, String> headers) {
131 this(cache, connectTimeout, readTimeout,
132 headers, DEFAULT_DOWNLOAD_JOB_DISPATCHER);
133 }
134
135 private void ensureCacheElement() {
136 if (cacheElement == null && getCacheKey() != null) {
137 cacheElement = cache.getCacheElement(getCacheKey());
138 if (cacheElement != null) {
139 attributes = (CacheEntryAttributes) cacheElement.getElementAttributes();
140 cacheData = cacheElement.getVal();
141 }
142 }
143 }
144
145 public V get() {
146 ensureCacheElement();
147 return cacheData;
148 }
149
150 @Override
151 public void submit(ICachedLoaderListener listener, boolean force) {
152 this.force = force;
153 boolean first = false;
154 URL url = getUrl();
155 String deduplicationKey = null;
156 if (url != null) {
157 // url might be null, for example when Bing Attribution is not loaded yet
158 deduplicationKey = url.toString();
159 }
160 if (deduplicationKey == null) {
161 log.log(Level.WARNING, "No url returned for: {0}, skipping", getCacheKey());
162 return;
163 }
164 synchronized (inProgress) {
165 Set<ICachedLoaderListener> newListeners = inProgress.get(deduplicationKey);
166 if (newListeners == null) {
167 newListeners = new HashSet<>();
168 inProgress.put(deduplicationKey, newListeners);
169 first = true;
170 }
171 newListeners.add(listener);
172 }
173
174 if (first || force) {
175 ensureCacheElement();
176 if (!force && cacheElement != null && isCacheElementValid() && isObjectLoadable()) {
177 // we got something in cache, and it's valid, so lets return it
178 log.log(Level.FINE, "JCS - Returning object from cache: {0}", getCacheKey());
179 finishLoading(LoadResult.SUCCESS);
180 return;
181 }
182 // object not in cache, so submit work to separate thread
183 downloadJobExecutor.execute(this);
184 }
185 }
186
187 /**
188 * This method is run when job has finished
189 */
190 protected void executionFinished() {
191 if (finishTask != null) {
192 finishTask.run();
193 }
194 }
195
196 /**
197 *
198 * @return checks if object from cache has sufficient data to be returned
199 */
200 protected boolean isObjectLoadable() {
201 if (cacheData == null) {
202 return false;
203 }
204 byte[] content = cacheData.getContent();
205 return content != null && content.length > 0;
206 }
207
208 /**
209 * Simple implementation. All errors should be cached as empty. Though some JDK (JDK8 on Windows for example)
210 * doesn't return 4xx error codes, instead they do throw an FileNotFoundException or IOException
211 *
212 * @return true if we should put empty object into cache, regardless of what remote resource has returned
213 */
214 protected boolean cacheAsEmpty() {
215 return attributes.getResponseCode() < 500;
216 }
217
218 /**
219 * @return key under which discovered server settings will be kept
220 */
221 protected String getServerKey() {
222 return getUrl().getHost();
223 }
224
225 @Override
226 public void run() {
227 final Thread currentThread = Thread.currentThread();
228 final String oldName = currentThread.getName();
229 currentThread.setName("JCS Downloading: " + getUrl());
230 try {
231 // try to load object from remote resource
232 if (loadObject()) {
233 finishLoading(LoadResult.SUCCESS);
234 } else {
235 // if loading failed - check if we can return stale entry
236 if (isObjectLoadable()) {
237 // try to get stale entry in cache
238 finishLoading(LoadResult.SUCCESS);
239 log.log(Level.FINE, "JCS - found stale object in cache: {0}", getUrl());
240 } else {
241 // failed completely
242 finishLoading(LoadResult.FAILURE);
243 }
244 }
245 } finally {
246 executionFinished();
247 currentThread.setName(oldName);
248 }
249 }
250
251 private void finishLoading(LoadResult result) {
252 Set<ICachedLoaderListener> listeners = null;
253 synchronized (inProgress) {
254 listeners = inProgress.remove(getUrl().toString());
255 }
256 if (listeners == null) {
257 log.log(Level.WARNING, "Listener not found for URL: {0}. Listener not notified!", getUrl());
258 return;
259 }
260 for (ICachedLoaderListener l: listeners) {
261 l.loadingFinished(cacheData, attributes, result);
262 }
263 }
264
265 protected boolean isCacheElementValid() {
266 long expires = attributes.getExpirationTime();
267
268 // check by expire date set by server
269 if (expires != 0L) {
270 // put a limit to the expire time (some servers send a value
271 // that is too large)
272 expires = Math.min(expires, attributes.getCreateTime() + EXPIRE_TIME_SERVER_LIMIT);
273 if (now > expires) {
274 log.log(Level.FINE, "JCS - Object {0} has expired -> valid to {1}, now is: {2}",
275 new Object[]{getUrl(), Long.toString(expires), Long.toString(now)});
276 return false;
277 }
278 } else if (attributes.getLastModification() > 0 &&
279 now - attributes.getLastModification() > DEFAULT_EXPIRE_TIME) {
280 // check by file modification date
281 log.log(Level.FINE, "JCS - Object has expired, maximum file age reached {0}", getUrl());
282 return false;
283 } else if (now - attributes.getCreateTime() > DEFAULT_EXPIRE_TIME) {
284 log.log(Level.FINE, "JCS - Object has expired, maximum time since object creation reached {0}", getUrl());
285 return false;
286 }
287 return true;
288 }
289
290 /**
291 * @return true if object was successfully downloaded, false, if there was a loading failure
292 */
293
294 private boolean loadObject() {
295 if (attributes == null) {
296 attributes = new CacheEntryAttributes();
297 }
298 try {
299 // if we have object in cache, and host doesn't support If-Modified-Since nor If-None-Match
300 // then just use HEAD request and check returned values
301 if (isObjectLoadable() &&
302 Boolean.TRUE.equals(useHead.get(getServerKey())) &&
303 isCacheValidUsingHead()) {
304 log.log(Level.FINE, "JCS - cache entry verified using HEAD request: {0}", getUrl());
305 return true;
306 }
307
308 HttpURLConnection urlConn = getURLConnection();
309
310 if (isObjectLoadable() &&
311 (now - attributes.getLastModification()) <= ABSOLUTE_EXPIRE_TIME_LIMIT) {
312 urlConn.setIfModifiedSince(attributes.getLastModification());
313 }
314 if (isObjectLoadable() && attributes.getEtag() != null) {
315 urlConn.addRequestProperty("If-None-Match", attributes.getEtag());
316 }
317 if (urlConn.getResponseCode() == 304) {
318 // If isModifiedSince or If-None-Match has been set
319 // and the server answers with a HTTP 304 = "Not Modified"
320 log.log(Level.FINE, "JCS - IfModifiedSince/Etag test: local version is up to date: {0}", getUrl());
321 return true;
322 } else if (isObjectLoadable() // we have an object in cache, but we haven't received 304 resposne code
323 && (
324 (attributes.getEtag() != null && attributes.getEtag().equals(urlConn.getRequestProperty("ETag"))) ||
325 attributes.getLastModification() == urlConn.getLastModified())
326 ) {
327 // we sent ETag or If-Modified-Since, but didn't get 304 response code
328 // for further requests - use HEAD
329 String serverKey = getServerKey();
330 log.log(Level.INFO, "JCS - Host: {0} found not to return 304 codes for If-Modifed-Since or If-None-Match headers",
331 serverKey);
332 useHead.put(serverKey, Boolean.TRUE);
333 }
334
335
336 attributes = parseHeaders(urlConn);
337
338 for (int i = 0; i < 5; ++i) {
339 if (urlConn.getResponseCode() == 503) {
340 Thread.sleep(5000+(new Random()).nextInt(5000));
341 continue;
342 }
343
344 attributes.setResponseCode(urlConn.getResponseCode());
345 byte[] raw;
346 if (urlConn.getResponseCode() == 200) {
347 raw = Utils.readBytesFromStream(urlConn.getInputStream());
348 } else {
349 raw = new byte[]{};
350 }
351
352 if (isResponseLoadable(urlConn.getHeaderFields(), urlConn.getResponseCode(), raw)) {
353 // we need to check cacheEmpty, so for cases, when data is returned, but we want to store
354 // as empty (eg. empty tile images) to save some space
355 cacheData = createCacheEntry(raw);
356 cache.put(getCacheKey(), cacheData, attributes);
357 log.log(Level.FINE, "JCS - downloaded key: {0}, length: {1}, url: {2}",
358 new Object[] {getCacheKey(), raw.length, getUrl()});
359 return true;
360 } else if (cacheAsEmpty()) {
361 cacheData = createCacheEntry(new byte[]{});
362 cache.put(getCacheKey(), cacheData, attributes);
363 log.log(Level.FINE, "JCS - Caching empty object {0}", getUrl());
364 return true;
365 } else {
366 log.log(Level.FINE, "JCS - failure during load - reponse is not loadable nor cached as empty");
367 return false;
368 }
369 }
370 } catch (FileNotFoundException e) {
371 log.log(Level.FINE, "JCS - Caching empty object as server returned 404 for: {0}", getUrl());
372 attributes.setResponseCode(404);
373 attributes.setErrorMessage(e.toString());
374 boolean doCache = isResponseLoadable(null, 404, null) || cacheAsEmpty();
375 if (doCache) {
376 cacheData = createCacheEntry(new byte[]{});
377 cache.put(getCacheKey(), cacheData, attributes);
378 }
379 return doCache;
380 } catch (IOException e) {
381 log.log(Level.FINE, "JCS - IOExecption during communication with server for: {0}", getUrl());
382 attributes.setErrorMessage(e.toString());
383 attributes.setResponseCode(499); // set dummy error code
384 boolean doCache = isResponseLoadable(null, 499, null) || cacheAsEmpty(); //generic 499 error code returned
385 if (doCache) {
386 cacheData = createCacheEntry(new byte[]{});
387 cache.put(getCacheKey(), createCacheEntry(new byte[]{}), attributes);
388 }
389 return doCache;
390 } catch (Exception e) {
391 attributes.setErrorMessage(e.toString());
392 log.log(Level.WARNING, "JCS - Exception during download {0}", getUrl());
393 Main.warn(e);
394 }
395 log.log(Level.WARNING, "JCS - Silent failure during download: {0}", getUrl());
396 return false;
397
398 }
399
400 /**
401 * Check if the object is loadable. This means, if the data will be parsed, and if this response
402 * will finish as successful retrieve.
403 *
404 * This simple implementation doesn't load empty response, nor client (4xx) and server (5xx) errors
405 *
406 * @param headerFields headers sent by server
407 * @param responseCode http status code
408 * @param raw data read from server
409 * @return true if object should be cached and returned to listener
410 */
411 protected boolean isResponseLoadable(Map<String, List<String>> headerFields, int responseCode, byte[] raw) {
412 if (raw == null || raw.length == 0 || responseCode >= 400) {
413 return false;
414 }
415 return true;
416 }
417
418 protected abstract V createCacheEntry(byte[] content);
419
420 protected CacheEntryAttributes parseHeaders(URLConnection urlConn) {
421 CacheEntryAttributes ret = new CacheEntryAttributes();
422
423 Long lng = urlConn.getExpiration();
424 if (lng.equals(0L)) {
425 try {
426 String str = urlConn.getHeaderField("Cache-Control");
427 if (str != null) {
428 for (String token: str.split(",")) {
429 if (token.startsWith("max-age=")) {
430 lng = Long.parseLong(token.substring(8)) * 1000 +
431 System.currentTimeMillis();
432 }
433 }
434 }
435 } catch (NumberFormatException e) {
436 // ignore malformed Cache-Control headers
437 if (Main.isTraceEnabled()) {
438 Main.trace(e.getMessage());
439 }
440 }
441 }
442
443 ret.setExpirationTime(lng);
444 ret.setLastModification(now);
445 ret.setEtag(urlConn.getHeaderField("ETag"));
446 return ret;
447 }
448
449 private HttpURLConnection getURLConnection() throws IOException {
450 HttpURLConnection urlConn = (HttpURLConnection) getUrl().openConnection();
451 urlConn.setRequestProperty("Accept", "text/html, image/png, image/jpeg, image/gif, */*");
452 urlConn.setReadTimeout(readTimeout); // 30 seconds read timeout
453 urlConn.setConnectTimeout(connectTimeout);
454 if (headers != null) {
455 for (Map.Entry<String, String> e: headers.entrySet()) {
456 urlConn.setRequestProperty(e.getKey(), e.getValue());
457 }
458 }
459
460 if (force) {
461 urlConn.setUseCaches(false);
462 }
463 return urlConn;
464 }
465
466 private boolean isCacheValidUsingHead() throws IOException {
467 HttpURLConnection urlConn = getURLConnection();
468 urlConn.setRequestMethod("HEAD");
469 long lastModified = urlConn.getLastModified();
470 return (attributes.getEtag() != null && attributes.getEtag().equals(urlConn.getRequestProperty("ETag"))) ||
471 (lastModified != 0 && lastModified <= attributes.getLastModification());
472 }
473
474 /**
475 * TODO: move to JobFactory
476 * cancels all outstanding tasks in the queue.
477 */
478 public void cancelOutstandingTasks() {
479 for (Runnable r: downloadJobExecutor.getQueue()) {
480 if (downloadJobExecutor.remove(r) && r instanceof JCSCachedTileLoaderJob) {
481 ((JCSCachedTileLoaderJob<?, ?>) r).handleJobCancellation();
482 }
483 }
484 }
485
486 /**
487 * Sets a job, that will be run, when job will finish execution
488 * @param runnable that will be executed
489 */
490 public void setFinishedTask(Runnable runnable) {
491 this.finishTask = runnable;
492
493 }
494
495 /**
496 * Marks this job as canceled
497 */
498 public void handleJobCancellation() {
499 finishLoading(LoadResult.CANCELED);
500 }
501}
Note: See TracBrowser for help on using the repository browser.