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

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

fix sonar squid:S1444 - "public static" fields should always be constant

File size: 17.1 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.MalformedURLException;
10import java.net.URL;
11import java.net.URLConnection;
12import java.util.HashSet;
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.Executor;
19import java.util.concurrent.LinkedBlockingDeque;
20import java.util.concurrent.RejectedExecutionException;
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.data.cache.ICachedLoaderListener.LoadResult;
30import org.openstreetmap.josm.data.preferences.IntegerProperty;
31
32/**
33 * @author Wiktor Niesiobędzki
34 *
35 * @param <K> cache entry key type
36 *
37 * Generic loader for HTTP based tiles. Uses custom attribute, to check, if entry has expired
38 * according to HTTP headers sent with tile. If so, it tries to verify using Etags
39 * or If-Modified-Since / Last-Modified.
40 *
41 * If the tile is not valid, it will try to download it from remote service and put it
42 * to cache. If remote server will fail it will try to use stale entry.
43 *
44 * This class will keep only one Job running for specified tile. All others will just finish, but
45 * listeners will be gathered and notified, once download job will be finished
46 */
47public abstract class JCSCachedTileLoaderJob<K, V extends CacheEntry> implements ICachedLoaderJob<K>, Runnable {
48 private static final Logger log = FeatureAdapter.getLogger(JCSCachedTileLoaderJob.class.getCanonicalName());
49 protected static final long DEFAULT_EXPIRE_TIME = 1000L * 60 * 60 * 24 * 7; // 7 days
50 // Limit for the max-age value send by the server.
51 protected static final long EXPIRE_TIME_SERVER_LIMIT = 1000L * 60 * 60 * 24 * 28; // 4 weeks
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 = Long.MAX_VALUE; // unlimited
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 private static Executor DOWNLOAD_JOB_DISPATCHER = new ThreadPoolExecutor(
61 2, // we have a small queue, so threads will be quickly started (threads are started only, when queue is full)
62 THREAD_LIMIT.get().intValue(), // do not this number of threads
63 30, // keepalive for thread
64 TimeUnit.SECONDS,
65 // make queue of LIFO type - so recently requested tiles will be loaded first (assuming that these are which user is waiting to see)
66 new LinkedBlockingDeque<Runnable>(5) {
67 /* keep the queue size fairly small, we do not want to
68 download a lot of tiles, that user is not seeing anyway */
69 @Override
70 public boolean offer(Runnable t) {
71 return super.offerFirst(t);
72 }
73
74 @Override
75 public Runnable remove() {
76 return super.removeFirst();
77 }
78 }
79 );
80 private static ConcurrentMap<String,Set<ICachedLoaderListener>> inProgress = new ConcurrentHashMap<>();
81 private static ConcurrentMap<String, Boolean> useHead = new ConcurrentHashMap<>();
82
83 private long now; // when the job started
84
85 private ICacheAccess<K, V> cache;
86 private ICacheElement<K, V> cacheElement;
87 protected V cacheData = null;
88 protected CacheEntryAttributes attributes = null;
89
90 // HTTP connection parameters
91 private int connectTimeout;
92 private int readTimeout;
93 private Map<String, String> headers;
94
95 /**
96 * @param cache cache instance that we will work on
97 * @param headers
98 * @param readTimeout
99 * @param connectTimeout
100 */
101 public JCSCachedTileLoaderJob(ICacheAccess<K,V> cache,
102 int connectTimeout, int readTimeout,
103 Map<String, String> headers) {
104
105 this.cache = cache;
106 this.now = System.currentTimeMillis();
107 this.connectTimeout = connectTimeout;
108 this.readTimeout = readTimeout;
109 this.headers = headers;
110 }
111
112 private void ensureCacheElement() {
113 if (cacheElement == null && getCacheKey() != null) {
114 cacheElement = cache.getCacheElement(getCacheKey());
115 if (cacheElement != null) {
116 attributes = (CacheEntryAttributes) cacheElement.getElementAttributes();
117 cacheData = cacheElement.getVal();
118 }
119 }
120 }
121
122 public V get() {
123 ensureCacheElement();
124 return cacheData;
125 }
126
127 @Override
128 public void submit(ICachedLoaderListener listener) {
129 boolean first = false;
130 URL url = getUrl();
131 String deduplicationKey = null;
132 if (url != null) {
133 // url might be null, for example when Bing Attribution is not loaded yet
134 deduplicationKey = url.toString();
135 }
136 if (deduplicationKey == null) {
137 log.log(Level.WARNING, "No url returned for: {0}, skipping", getCacheKey());
138 return;
139 }
140 synchronized (inProgress) {
141 Set<ICachedLoaderListener> newListeners = inProgress.get(deduplicationKey);
142 if (newListeners == null) {
143 newListeners = new HashSet<>();
144 inProgress.put(deduplicationKey, newListeners);
145 first = true;
146 }
147 newListeners.add(listener);
148 }
149
150 if (first) {
151 ensureCacheElement();
152 if (cacheElement != null && isCacheElementValid() && (isObjectLoadable())) {
153 // we got something in cache, and it's valid, so lets return it
154 log.log(Level.FINE, "JCS - Returning object from cache: {0}", getCacheKey());
155 finishLoading(LoadResult.SUCCESS);
156 return;
157 }
158 // object not in cache, so submit work to separate thread
159 try {
160 // use getter method, so subclasses may override executors, to get separate thread pool
161 getDownloadExecutor().execute(JCSCachedTileLoaderJob.this);
162 } catch (RejectedExecutionException e) {
163 // queue was full, try again later
164 log.log(Level.FINE, "JCS - rejected job for: {0}", getCacheKey());
165 finishLoading(LoadResult.REJECTED);
166 }
167 }
168 }
169
170 /**
171 *
172 * @return checks if object from cache has sufficient data to be returned
173 */
174 protected boolean isObjectLoadable() {
175 byte[] content = cacheData.getContent();
176 return content != null && content.length > 0;
177 }
178
179 /**
180 *
181 * @return cache object as empty, regardless of what remote resource has returned (ex. based on headers)
182 */
183 protected boolean cacheAsEmpty() {
184 return false;
185 }
186
187 /**
188 * @return key under which discovered server settings will be kept
189 */
190 protected String getServerKey() {
191 return getUrl().getHost();
192 }
193
194 /**
195 * this needs to be non-static, so it can be overridden by subclasses
196 */
197 protected Executor getDownloadExecutor() {
198 return DOWNLOAD_JOB_DISPATCHER;
199 }
200
201
202 public void run() {
203 final Thread currentThread = Thread.currentThread();
204 final String oldName = currentThread.getName();
205 currentThread.setName("JCS Downloading: " + getUrl());
206 try {
207 // try to load object from remote resource
208 if (loadObject()) {
209 finishLoading(LoadResult.SUCCESS);
210 } else {
211 // if loading failed - check if we can return stale entry
212 if (isObjectLoadable()) {
213 // try to get stale entry in cache
214 finishLoading(LoadResult.SUCCESS);
215 log.log(Level.FINE, "JCS - found stale object in cache: {0}", getUrl());
216 } else {
217 // failed completely
218 finishLoading(LoadResult.FAILURE);
219 }
220 }
221 } finally {
222 currentThread.setName(oldName);
223 }
224 }
225
226
227 private void finishLoading(LoadResult result) {
228 Set<ICachedLoaderListener> listeners = null;
229 synchronized (inProgress) {
230 listeners = inProgress.remove(getUrl().toString());
231 }
232 if (listeners == null) {
233 log.log(Level.WARNING, "Listener not found for URL: {0}. Listener not notified!", getUrl());
234 return;
235 }
236 try {
237 for (ICachedLoaderListener l: listeners) {
238 l.loadingFinished(cacheData, result);
239 }
240 } catch (Exception e) {
241 log.log(Level.WARNING, "JCS - Error while loading object from cache: {0}; {1}", new Object[]{e.getMessage(), getUrl()});
242 log.log(Level.FINE, "Stacktrace", e);
243 for (ICachedLoaderListener l: listeners) {
244 l.loadingFinished(cacheData, LoadResult.FAILURE);
245 }
246
247 }
248
249 }
250
251 private boolean isCacheElementValid() {
252 long expires = attributes.getExpirationTime();
253
254 // check by expire date set by server
255 if (expires != 0L) {
256 // put a limit to the expire time (some servers send a value
257 // that is too large)
258 expires = Math.min(expires, attributes.getCreateTime() + EXPIRE_TIME_SERVER_LIMIT);
259 if (now > expires) {
260 log.log(Level.FINE, "JCS - Object {0} has expired -> valid to {1}, now is: {2}", new Object[]{getUrl(), Long.toString(expires), Long.toString(now)});
261 return false;
262 }
263 } else {
264 // check by file modification date
265 if (now - attributes.getLastModification() > DEFAULT_EXPIRE_TIME) {
266 log.log(Level.FINE, "JCS - Object has expired, maximum file age reached {0}", getUrl());
267 return false;
268 }
269 }
270 return true;
271 }
272
273 /**
274 * @return true if object was successfully downloaded, false, if there was a loading failure
275 */
276
277 private boolean loadObject() {
278 try {
279 // if we have object in cache, and host doesn't support If-Modified-Since nor If-None-Match
280 // then just use HEAD request and check returned values
281 if (isObjectLoadable() &&
282 Boolean.TRUE.equals(useHead.get(getServerKey())) &&
283 isCacheValidUsingHead()) {
284 log.log(Level.FINE, "JCS - cache entry verified using HEAD request: {0}", getUrl());
285 return true;
286 }
287 URLConnection urlConn = getURLConnection();
288
289 if (isObjectLoadable() &&
290 (now - attributes.getLastModification()) <= ABSOLUTE_EXPIRE_TIME_LIMIT) {
291 urlConn.setIfModifiedSince(attributes.getLastModification());
292 }
293 if (isObjectLoadable() && attributes.getEtag() != null) {
294 urlConn.addRequestProperty("If-None-Match", attributes.getEtag());
295 }
296 if (urlConn instanceof HttpURLConnection && ((HttpURLConnection)urlConn).getResponseCode() == 304) {
297 // If isModifiedSince or If-None-Match has been set
298 // and the server answers with a HTTP 304 = "Not Modified"
299 log.log(Level.FINE, "JCS - IfModifiedSince/Etag test: local version is up to date: {0}", getUrl());
300 return true;
301 } else if (isObjectLoadable()) {
302 // we have an object in cache, but we haven't received 304 resposne code
303 // check if we should use HEAD request to verify
304 if((attributes.getEtag() != null && attributes.getEtag().equals(urlConn.getRequestProperty("ETag"))) ||
305 attributes.getLastModification() == urlConn.getLastModified()) {
306 // we sent ETag or If-Modified-Since, but didn't get 304 response code
307 // for further requests - use HEAD
308 String serverKey = getServerKey();
309 log.log(Level.INFO, "JCS - Host: {0} found not to return 304 codes for If-Modifed-Since or If-None-Match headers", serverKey);
310 useHead.put(serverKey, Boolean.TRUE);
311 }
312 }
313
314 attributes = parseHeaders(urlConn);
315
316 for (int i = 0; i < 5; ++i) {
317 if (urlConn instanceof HttpURLConnection && ((HttpURLConnection)urlConn).getResponseCode() == 503) {
318 Thread.sleep(5000+(new Random()).nextInt(5000));
319 continue;
320 }
321 byte[] raw = read(urlConn);
322
323 if (!cacheAsEmpty() && raw != null && raw.length > 0) {
324 cacheData = createCacheEntry(raw);
325 cache.put(getCacheKey(), cacheData, attributes);
326 log.log(Level.FINE, "JCS - downloaded key: {0}, length: {1}, url: {2}",
327 new Object[] {getCacheKey(), raw.length, getUrl()});
328 return true;
329 } else {
330 cacheData = createCacheEntry(new byte[]{});
331 cache.put(getCacheKey(), cacheData, attributes);
332 log.log(Level.FINE, "JCS - Caching empty object {0}", getUrl());
333 return true;
334 }
335 }
336 } catch (FileNotFoundException e) {
337 log.log(Level.FINE, "JCS - Caching empty object as server returned 404 for: {0}", getUrl());
338 cache.put(getCacheKey(), createCacheEntry(new byte[]{}), attributes);
339 return handleNotFound();
340 } catch (Exception e) {
341 log.log(Level.WARNING, "JCS - Exception during download " + getUrl(), e);
342 }
343 log.log(Level.WARNING, "JCS - Silent failure during download: {0}", getUrl());
344 return false;
345
346 }
347
348 /**
349 * @return if we should treat this object as properly loaded
350 */
351 protected abstract boolean handleNotFound();
352
353 protected abstract V createCacheEntry(byte[] content);
354
355 private CacheEntryAttributes parseHeaders(URLConnection urlConn) {
356 CacheEntryAttributes ret = new CacheEntryAttributes();
357 ret.setNoTileAtZoom("no-tile".equals(urlConn.getHeaderField("X-VE-Tile-Info")));
358
359 Long lng = urlConn.getExpiration();
360 if (lng.equals(0L)) {
361 try {
362 String str = urlConn.getHeaderField("Cache-Control");
363 if (str != null) {
364 for (String token: str.split(",")) {
365 if (token.startsWith("max-age=")) {
366 lng = Long.parseLong(token.substring(8)) * 1000 +
367 System.currentTimeMillis();
368 }
369 }
370 }
371 } catch (NumberFormatException e) {} //ignore malformed Cache-Control headers
372 }
373
374 ret.setExpirationTime(lng);
375 ret.setLastModification(now);
376 ret.setEtag(urlConn.getHeaderField("ETag"));
377 return ret;
378 }
379
380 private HttpURLConnection getURLConnection() throws IOException, MalformedURLException {
381 HttpURLConnection urlConn = (HttpURLConnection) getUrl().openConnection();
382 urlConn.setRequestProperty("Accept", "text/html, image/png, image/jpeg, image/gif, */*");
383 urlConn.setReadTimeout(readTimeout); // 30 seconds read timeout
384 urlConn.setConnectTimeout(connectTimeout);
385 for(Map.Entry<String, String> e: headers.entrySet()) {
386 urlConn.setRequestProperty(e.getKey(), e.getValue());
387 }
388 return urlConn;
389 }
390
391 private boolean isCacheValidUsingHead() throws IOException {
392 HttpURLConnection urlConn = (HttpURLConnection) getUrl().openConnection();
393 urlConn.setRequestMethod("HEAD");
394 long lastModified = urlConn.getLastModified();
395 return (
396 (attributes.getEtag() != null && attributes.getEtag().equals(urlConn.getRequestProperty("ETag"))) ||
397 (lastModified != 0 && lastModified <= attributes.getLastModification())
398 );
399 }
400
401 private static byte[] read(URLConnection urlConn) throws IOException {
402 InputStream input = urlConn.getInputStream();
403 try {
404 ByteArrayOutputStream bout = new ByteArrayOutputStream(input.available());
405 byte[] buffer = new byte[2048];
406 boolean finished = false;
407 do {
408 int read = input.read(buffer);
409 if (read >= 0) {
410 bout.write(buffer, 0, read);
411 } else {
412 finished = true;
413 }
414 } while (!finished);
415 if (bout.size() == 0)
416 return null;
417 return bout.toByteArray();
418 } finally {
419 input.close();
420 }
421 }
422}
Note: See TracBrowser for help on using the repository browser.