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

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

findbugs - RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE

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