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

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

sonar - squid:S1191 - Classes from "sun.*" packages should not be used

  • 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.HttpClient;
28import org.openstreetmap.josm.tools.Utils;
29
30/**
31 * Generic loader for HTTP based tiles. Uses custom attribute, to check, if entry has expired
32 * according to HTTP headers sent with tile. If so, it tries to verify using Etags
33 * or If-Modified-Since / Last-Modified.
34 *
35 * If the tile is not valid, it will try to download it from remote service and put it
36 * to cache. If remote server will fail it will try to use stale entry.
37 *
38 * This class will keep only one Job running for specified tile. All others will just finish, but
39 * listeners will be gathered and notified, once download job will be finished
40 *
41 * @author Wiktor Niesiobędzki
42 * @param <K> cache entry key type
43 * @param <V> cache value type
44 * @since 8168
45 */
46public abstract class JCSCachedTileLoaderJob<K, V extends CacheEntry> implements ICachedLoaderJob<K> {
47 private static final Logger LOG = FeatureAdapter.getLogger(JCSCachedTileLoaderJob.class.getCanonicalName());
48 protected static final long DEFAULT_EXPIRE_TIME = 1000L * 60 * 60 * 24 * 7; // 7 days
49 // Limit for the max-age value send by the server.
50 protected static final long EXPIRE_TIME_SERVER_LIMIT = 1000L * 60 * 60 * 24 * 28; // 4 weeks
51 // Absolute expire time limit. Cached tiles that are older will not be used,
52 // even if the refresh from the server fails.
53 protected static final long ABSOLUTE_EXPIRE_TIME_LIMIT = 1000L * 60 * 60 * 24 * 365; // 1 year
54
55 /**
56 * maximum download threads that will be started
57 */
58 public static final IntegerProperty THREAD_LIMIT = new IntegerProperty("cache.jcs.max_threads", 10);
59
60 /*
61 * ThreadPoolExecutor starts new threads, until THREAD_LIMIT is reached. Then it puts tasks into LinkedBlockingDeque.
62 *
63 * The queue works FIFO, so one needs to take care about ordering of the entries submitted
64 *
65 * 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
66 * the response, so later it could be used). We could actually cancel what is in LIFOQueue, but this is a tradeoff between simplicity
67 * and performance (we do want to have something to offer to worker threads before tasks will be resubmitted by class consumer)
68 */
69
70 private static final ThreadPoolExecutor DEFAULT_DOWNLOAD_JOB_DISPATCHER = new ThreadPoolExecutor(
71 1, // we have a small queue, so threads will be quickly started (threads are started only, when queue is full)
72 THREAD_LIMIT.get(), // do not this number of threads
73 30, // keepalive for thread
74 TimeUnit.SECONDS,
75 // make queue of LIFO type - so recently requested tiles will be loaded first (assuming that these are which user is waiting to see)
76 new LinkedBlockingDeque<Runnable>(),
77 Utils.newThreadFactory("JCS-downloader-%d", Thread.NORM_PRIORITY)
78 );
79
80
81
82 private static final ConcurrentMap<String, Set<ICachedLoaderListener>> inProgress = new ConcurrentHashMap<>();
83 private static final ConcurrentMap<String, Boolean> useHead = new ConcurrentHashMap<>();
84
85 protected final long now; // when the job started
86
87 private final ICacheAccess<K, V> cache;
88 private ICacheElement<K, V> cacheElement;
89 protected V cacheData;
90 protected CacheEntryAttributes attributes;
91
92 // HTTP connection parameters
93 private final int connectTimeout;
94 private final int readTimeout;
95 private final Map<String, String> headers;
96 private final ThreadPoolExecutor downloadJobExecutor;
97 private Runnable finishTask;
98 private boolean force;
99
100 /**
101 * @param cache cache instance that we will work on
102 * @param headers HTTP headers to be sent together with request
103 * @param readTimeout when connecting to remote resource
104 * @param connectTimeout when connecting to remote resource
105 * @param downloadJobExecutor that will be executing the jobs
106 */
107 public JCSCachedTileLoaderJob(ICacheAccess<K, V> cache,
108 int connectTimeout, int readTimeout,
109 Map<String, String> headers,
110 ThreadPoolExecutor downloadJobExecutor) {
111
112 this.cache = cache;
113 this.now = System.currentTimeMillis();
114 this.connectTimeout = connectTimeout;
115 this.readTimeout = readTimeout;
116 this.headers = headers;
117 this.downloadJobExecutor = downloadJobExecutor;
118 }
119
120 /**
121 * @param cache cache instance that we will work on
122 * @param headers HTTP headers to be sent together with request
123 * @param readTimeout when connecting to remote resource
124 * @param connectTimeout when connecting to remote resource
125 */
126 public JCSCachedTileLoaderJob(ICacheAccess<K, V> cache,
127 int connectTimeout, int readTimeout,
128 Map<String, String> headers) {
129 this(cache, connectTimeout, readTimeout,
130 headers, DEFAULT_DOWNLOAD_JOB_DISPATCHER);
131 }
132
133 private void ensureCacheElement() {
134 if (cacheElement == null && getCacheKey() != null) {
135 cacheElement = cache.getCacheElement(getCacheKey());
136 if (cacheElement != null) {
137 attributes = (CacheEntryAttributes) cacheElement.getElementAttributes();
138 cacheData = cacheElement.getVal();
139 }
140 }
141 }
142
143 @Override
144 public V get() {
145 ensureCacheElement();
146 return cacheData;
147 }
148
149 @Override
150 public void submit(ICachedLoaderListener listener, boolean force) throws IOException {
151 this.force = force;
152 boolean first = false;
153 URL url = getUrl();
154 String deduplicationKey = null;
155 if (url != null) {
156 // url might be null, for example when Bing Attribution is not loaded yet
157 deduplicationKey = url.toString();
158 }
159 if (deduplicationKey == null) {
160 LOG.log(Level.WARNING, "No url returned for: {0}, skipping", getCacheKey());
161 throw new IllegalArgumentException("No url returned");
162 }
163 synchronized (inProgress) {
164 Set<ICachedLoaderListener> newListeners = inProgress.get(deduplicationKey);
165 if (newListeners == null) {
166 newListeners = new HashSet<>();
167 inProgress.put(deduplicationKey, newListeners);
168 first = true;
169 }
170 newListeners.add(listener);
171 }
172
173 if (first || force) {
174 // submit all jobs to separate thread, so calling thread is not blocked with IO when loading from disk
175 LOG.log(Level.FINE, "JCS - Submitting job for execution for url: {0}", getUrlNoException());
176 downloadJobExecutor.execute(this);
177 }
178 }
179
180 /**
181 * This method is run when job has finished
182 */
183 protected void executionFinished() {
184 if (finishTask != null) {
185 finishTask.run();
186 }
187 }
188
189 /**
190 *
191 * @return checks if object from cache has sufficient data to be returned
192 */
193 protected boolean isObjectLoadable() {
194 if (cacheData == null) {
195 return false;
196 }
197 byte[] content = cacheData.getContent();
198 return content != null && content.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 = Long.parseLong(token.substring(8)) * 1000 +
434 System.currentTimeMillis();
435 }
436 }
437 }
438 } catch (NumberFormatException e) {
439 // ignore malformed Cache-Control headers
440 Main.trace(e);
441 }
442 }
443
444 ret.setExpirationTime(lng);
445 ret.setLastModification(now);
446 ret.setEtag(urlConn.getHeaderField("ETag"));
447
448 return ret;
449 }
450
451 private HttpClient getRequest(String requestMethod, boolean noCache) throws IOException {
452 final HttpClient urlConn = HttpClient.create(getUrl(), requestMethod);
453 urlConn.setAccept("text/html, image/png, image/jpeg, image/gif, */*");
454 urlConn.setReadTimeout(readTimeout); // 30 seconds read timeout
455 urlConn.setConnectTimeout(connectTimeout);
456 if (headers != null) {
457 urlConn.setHeaders(headers);
458 }
459
460 if (force || noCache) {
461 urlConn.useCache(false);
462 }
463 return urlConn;
464 }
465
466 private boolean isCacheValidUsingHead() throws IOException {
467 final HttpClient.Response urlConn = getRequest("HEAD", false).connect();
468 long lastModified = urlConn.getLastModified();
469 return (attributes.getEtag() != null && attributes.getEtag().equals(urlConn.getHeaderField("ETag"))) ||
470 (lastModified != 0 && lastModified <= attributes.getLastModification());
471 }
472
473 /**
474 * TODO: move to JobFactory
475 * cancels all outstanding tasks in the queue.
476 */
477 public void cancelOutstandingTasks() {
478 for (Runnable r: downloadJobExecutor.getQueue()) {
479 if (downloadJobExecutor.remove(r) && r instanceof JCSCachedTileLoaderJob) {
480 ((JCSCachedTileLoaderJob<?, ?>) r).handleJobCancellation();
481 }
482 }
483 }
484
485 /**
486 * Sets a job, that will be run, when job will finish execution
487 * @param runnable that will be executed
488 */
489 public void setFinishedTask(Runnable runnable) {
490 this.finishTask = runnable;
491
492 }
493
494 /**
495 * Marks this job as canceled
496 */
497 public void handleJobCancellation() {
498 finishLoading(LoadResult.CANCELED);
499 }
500
501 private URL getUrlNoException() {
502 try {
503 return getUrl();
504 } catch (IOException e) {
505 return null;
506 }
507 }
508}
Note: See TracBrowser for help on using the repository browser.