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

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

fix remaining checkstyle issues

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