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

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

code style - A close curly brace should be located at the beginning of a line

File size: 19.2 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 public Thread newThread(Runnable r) {
88 Thread t = Executors.defaultThreadFactory().newThread(r);
89 t.setName(name);
90 return t;
91 }
92 };
93 }
94
95 private static ConcurrentMap<String,Set<ICachedLoaderListener>> inProgress = new ConcurrentHashMap<>();
96 private static ConcurrentMap<String, Boolean> useHead = new ConcurrentHashMap<>();
97
98 private long now; // when the job started
99
100 private ICacheAccess<K, V> cache;
101 private ICacheElement<K, V> cacheElement;
102 protected V cacheData = null;
103 protected CacheEntryAttributes attributes = null;
104
105 // HTTP connection parameters
106 private int connectTimeout;
107 private int readTimeout;
108 private Map<String, String> headers;
109 private ThreadPoolExecutor downloadJobExecutor;
110 private Runnable finishTask;
111
112 /**
113 * @param cache cache instance that we will work on
114 * @param headers
115 * @param readTimeout
116 * @param connectTimeout
117 * @param downloadJobExecutor
118 */
119 public JCSCachedTileLoaderJob(ICacheAccess<K,V> cache,
120 int connectTimeout, int readTimeout,
121 Map<String, String> headers,
122 ThreadPoolExecutor downloadJobExecutor) {
123
124 this.cache = cache;
125 this.now = System.currentTimeMillis();
126 this.connectTimeout = connectTimeout;
127 this.readTimeout = readTimeout;
128 this.headers = headers;
129 this.downloadJobExecutor = downloadJobExecutor;
130 }
131
132 /**
133 * @param cache cache instance that we will work on
134 * @param headers
135 * @param readTimeout
136 * @param connectTimeout
137 */
138 public JCSCachedTileLoaderJob(ICacheAccess<K, V> cache,
139 int connectTimeout, int readTimeout,
140 Map<String, String> headers) {
141 this(cache, connectTimeout, readTimeout,
142 headers, DEFAULT_DOWNLOAD_JOB_DISPATCHER);
143 }
144
145 private void ensureCacheElement() {
146 if (cacheElement == null && getCacheKey() != null) {
147 cacheElement = cache.getCacheElement(getCacheKey());
148 if (cacheElement != null) {
149 attributes = (CacheEntryAttributes) cacheElement.getElementAttributes();
150 cacheData = cacheElement.getVal();
151 }
152 }
153 }
154
155 public V get() {
156 ensureCacheElement();
157 return cacheData;
158 }
159
160 @Override
161 public void submit(ICachedLoaderListener listener) {
162 boolean first = false;
163 URL url = getUrl();
164 String deduplicationKey = null;
165 if (url != null) {
166 // url might be null, for example when Bing Attribution is not loaded yet
167 deduplicationKey = url.toString();
168 }
169 if (deduplicationKey == null) {
170 log.log(Level.WARNING, "No url returned for: {0}, skipping", getCacheKey());
171 return;
172 }
173 synchronized (inProgress) {
174 Set<ICachedLoaderListener> newListeners = inProgress.get(deduplicationKey);
175 if (newListeners == null) {
176 newListeners = new HashSet<>();
177 inProgress.put(deduplicationKey, newListeners);
178 first = true;
179 }
180 newListeners.add(listener);
181 }
182
183 if (first) {
184 ensureCacheElement();
185 if (cacheElement != null && isCacheElementValid() && (isObjectLoadable())) {
186 // we got something in cache, and it's valid, so lets return it
187 log.log(Level.FINE, "JCS - Returning object from cache: {0}", getCacheKey());
188 finishLoading(LoadResult.SUCCESS);
189 return;
190 }
191 // object not in cache, so submit work to separate thread
192 getDownloadExecutor().execute(this);
193 }
194 }
195
196 /**
197 * This method is run when job has finished
198 */
199 protected void executionFinished() {
200 if (finishTask != null) {
201 finishTask.run();
202 }
203 }
204
205 /**
206 *
207 * @return checks if object from cache has sufficient data to be returned
208 */
209 protected boolean isObjectLoadable() {
210 byte[] content = cacheData.getContent();
211 return content != null && content.length > 0;
212 }
213
214 /**
215 *
216 * @return cache object as empty, regardless of what remote resource has returned (ex. based on headers)
217 */
218 protected boolean cacheAsEmpty(Map<String, List<String>> headers, int statusCode, byte[] content) {
219 return false;
220 }
221
222 /**
223 * @return key under which discovered server settings will be kept
224 */
225 protected String getServerKey() {
226 return getUrl().getHost();
227 }
228
229 /**
230 * this needs to be non-static, so it can be overridden by subclasses
231 */
232 protected ThreadPoolExecutor getDownloadExecutor() {
233 return downloadJobExecutor;
234 }
235
236 public void run() {
237 final Thread currentThread = Thread.currentThread();
238 final String oldName = currentThread.getName();
239 currentThread.setName("JCS Downloading: " + getUrl());
240 try {
241 // try to load object from remote resource
242 if (loadObject()) {
243 finishLoading(LoadResult.SUCCESS);
244 } else {
245 // if loading failed - check if we can return stale entry
246 if (isObjectLoadable()) {
247 // try to get stale entry in cache
248 finishLoading(LoadResult.SUCCESS);
249 log.log(Level.FINE, "JCS - found stale object in cache: {0}", getUrl());
250 } else {
251 // failed completely
252 finishLoading(LoadResult.FAILURE);
253 }
254 }
255 } finally {
256 executionFinished();
257 currentThread.setName(oldName);
258 }
259 }
260
261
262 private void finishLoading(LoadResult result) {
263 Set<ICachedLoaderListener> listeners = null;
264 synchronized (inProgress) {
265 listeners = inProgress.remove(getUrl().toString());
266 }
267 if (listeners == null) {
268 log.log(Level.WARNING, "Listener not found for URL: {0}. Listener not notified!", getUrl());
269 return;
270 }
271 try {
272 for (ICachedLoaderListener l: listeners) {
273 l.loadingFinished(cacheData, attributes, result);
274 }
275 } catch (Exception e) {
276 log.log(Level.WARNING, "JCS - Error while loading object from cache: {0}; {1}", new Object[]{e.getMessage(), getUrl()});
277 Main.warn(e);
278 for (ICachedLoaderListener l: listeners) {
279 l.loadingFinished(cacheData, attributes, LoadResult.FAILURE);
280 }
281
282 }
283
284 }
285
286 private boolean isCacheElementValid() {
287 long expires = attributes.getExpirationTime();
288
289 // check by expire date set by server
290 if (expires != 0L) {
291 // put a limit to the expire time (some servers send a value
292 // that is too large)
293 expires = Math.min(expires, attributes.getCreateTime() + EXPIRE_TIME_SERVER_LIMIT);
294 if (now > expires) {
295 log.log(Level.FINE, "JCS - Object {0} has expired -> valid to {1}, now is: {2}", new Object[]{getUrl(), Long.toString(expires), Long.toString(now)});
296 return false;
297 }
298 } else {
299 // check by file modification date
300 if (now - attributes.getLastModification() > DEFAULT_EXPIRE_TIME) {
301 log.log(Level.FINE, "JCS - Object has expired, maximum file age reached {0}", getUrl());
302 return false;
303 }
304 }
305 return true;
306 }
307
308 /**
309 * @return true if object was successfully downloaded, false, if there was a loading failure
310 */
311
312 private boolean loadObject() {
313 try {
314 // if we have object in cache, and host doesn't support If-Modified-Since nor If-None-Match
315 // then just use HEAD request and check returned values
316 if (isObjectLoadable() &&
317 Boolean.TRUE.equals(useHead.get(getServerKey())) &&
318 isCacheValidUsingHead()) {
319 log.log(Level.FINE, "JCS - cache entry verified using HEAD request: {0}", getUrl());
320 return true;
321 }
322
323 HttpURLConnection urlConn = getURLConnection();
324
325 if (isObjectLoadable() &&
326 (now - attributes.getLastModification()) <= ABSOLUTE_EXPIRE_TIME_LIMIT) {
327 urlConn.setIfModifiedSince(attributes.getLastModification());
328 }
329 if (isObjectLoadable() && attributes.getEtag() != null) {
330 urlConn.addRequestProperty("If-None-Match", attributes.getEtag());
331 }
332 if (urlConn.getResponseCode() == 304) {
333 // If isModifiedSince or If-None-Match has been set
334 // and the server answers with a HTTP 304 = "Not Modified"
335 log.log(Level.FINE, "JCS - IfModifiedSince/Etag test: local version is up to date: {0}", getUrl());
336 return true;
337 } else if (isObjectLoadable()) {
338 // we have an object in cache, but we haven't received 304 resposne code
339 // check if we should use HEAD request to verify
340 if((attributes.getEtag() != null && attributes.getEtag().equals(urlConn.getRequestProperty("ETag"))) ||
341 attributes.getLastModification() == urlConn.getLastModified()) {
342 // we sent ETag or If-Modified-Since, but didn't get 304 response code
343 // for further requests - use HEAD
344 String serverKey = getServerKey();
345 log.log(Level.INFO, "JCS - Host: {0} found not to return 304 codes for If-Modifed-Since or If-None-Match headers", serverKey);
346 useHead.put(serverKey, Boolean.TRUE);
347 }
348 }
349
350 attributes = parseHeaders(urlConn);
351
352 for (int i = 0; i < 5; ++i) {
353 if (urlConn.getResponseCode() == 503) {
354 Thread.sleep(5000+(new Random()).nextInt(5000));
355 continue;
356 }
357
358 attributes.setResponseCode(urlConn.getResponseCode());
359 byte[] raw = read(urlConn);
360
361 if (!cacheAsEmpty(urlConn.getHeaderFields(), urlConn.getResponseCode(), raw) &&
362 raw != null && raw.length > 0) {
363 // we need to check cacheEmpty, so for cases, when data is returned, but we want to store
364 // as empty (eg. empty tile images) to save some space
365 cacheData = createCacheEntry(raw);
366 cache.put(getCacheKey(), cacheData, attributes);
367 log.log(Level.FINE, "JCS - downloaded key: {0}, length: {1}, url: {2}",
368 new Object[] {getCacheKey(), raw.length, getUrl()});
369 return true;
370 } else {
371 cacheData = createCacheEntry(new byte[]{});
372 cache.put(getCacheKey(), cacheData, attributes);
373 log.log(Level.FINE, "JCS - Caching empty object {0}", getUrl());
374 return true;
375 }
376 }
377 } catch (FileNotFoundException e) {
378 log.log(Level.FINE, "JCS - Caching empty object as server returned 404 for: {0}", getUrl());
379 cache.put(getCacheKey(), createCacheEntry(new byte[]{}), attributes);
380 return handleNotFound();
381 } catch (Exception e) {
382 log.log(Level.WARNING, "JCS - Exception during download {0}", getUrl());
383 Main.warn(e);
384 }
385 log.log(Level.WARNING, "JCS - Silent failure during download: {0}", getUrl());
386 return false;
387
388 }
389
390 /**
391 * @return if we should treat this object as properly loaded
392 */
393 protected abstract boolean handleNotFound();
394
395 protected abstract V createCacheEntry(byte[] content);
396
397 private CacheEntryAttributes parseHeaders(URLConnection urlConn) {
398 CacheEntryAttributes ret = new CacheEntryAttributes();
399
400 Long lng = urlConn.getExpiration();
401 if (lng.equals(0L)) {
402 try {
403 String str = urlConn.getHeaderField("Cache-Control");
404 if (str != null) {
405 for (String token: str.split(",")) {
406 if (token.startsWith("max-age=")) {
407 lng = Long.parseLong(token.substring(8)) * 1000 +
408 System.currentTimeMillis();
409 }
410 }
411 }
412 } catch (NumberFormatException e) {
413 // ignore malformed Cache-Control headers
414 }
415 }
416
417 ret.setExpirationTime(lng);
418 ret.setLastModification(now);
419 ret.setEtag(urlConn.getHeaderField("ETag"));
420 return ret;
421 }
422
423 private HttpURLConnection getURLConnection() throws IOException {
424 HttpURLConnection urlConn = (HttpURLConnection) getUrl().openConnection();
425 urlConn.setRequestProperty("Accept", "text/html, image/png, image/jpeg, image/gif, */*");
426 urlConn.setReadTimeout(readTimeout); // 30 seconds read timeout
427 urlConn.setConnectTimeout(connectTimeout);
428 for(Map.Entry<String, String> e: headers.entrySet()) {
429 urlConn.setRequestProperty(e.getKey(), e.getValue());
430 }
431 return urlConn;
432 }
433
434 private boolean isCacheValidUsingHead() throws IOException {
435 HttpURLConnection urlConn = (HttpURLConnection) getUrl().openConnection();
436 urlConn.setRequestMethod("HEAD");
437 long lastModified = urlConn.getLastModified();
438 return (attributes.getEtag() != null && attributes.getEtag().equals(urlConn.getRequestProperty("ETag"))) ||
439 (lastModified != 0 && lastModified <= attributes.getLastModification());
440 }
441
442 private static byte[] read(URLConnection urlConn) throws IOException {
443 InputStream input = urlConn.getInputStream();
444 try {
445 ByteArrayOutputStream bout = new ByteArrayOutputStream(input.available());
446 byte[] buffer = new byte[2048];
447 boolean finished = false;
448 do {
449 int read = input.read(buffer);
450 if (read >= 0) {
451 bout.write(buffer, 0, read);
452 } else {
453 finished = true;
454 }
455 } while (!finished);
456 if (bout.size() == 0)
457 return null;
458 return bout.toByteArray();
459 } finally {
460 input.close();
461 }
462 }
463
464 /**
465 * TODO: move to JobFactory
466 * cancels all outstanding tasks in the queue.
467 */
468 public void cancelOutstandingTasks() {
469 ThreadPoolExecutor downloadExecutor = getDownloadExecutor();
470 for(Runnable r: downloadExecutor.getQueue()) {
471 if (downloadExecutor.remove(r)) {
472 if (r instanceof JCSCachedTileLoaderJob) {
473 ((JCSCachedTileLoaderJob<?, ?>) r).handleJobCancellation();
474 }
475 }
476 }
477 }
478
479 /**
480 * Sets a job, that will be run, when job will finish execution
481 * @param runnable that will be executed
482 */
483 public void setFinishedTask(Runnable runnable) {
484 this.finishTask = runnable;
485
486 }
487
488 /**
489 * Marks this job as canceled
490 */
491 public void handleJobCancellation() {
492 finishLoading(LoadResult.CANCELED);
493 }
494}
Note: See TracBrowser for help on using the repository browser.