| 1 | // License: GPL. For details, see LICENSE file.
|
|---|
| 2 | package org.openstreetmap.josm.data.cache;
|
|---|
| 3 |
|
|---|
| 4 | import java.io.File;
|
|---|
| 5 | import java.io.FileNotFoundException;
|
|---|
| 6 | import java.io.IOException;
|
|---|
| 7 | import java.io.InputStream;
|
|---|
| 8 | import java.net.HttpURLConnection;
|
|---|
| 9 | import java.net.URL;
|
|---|
| 10 | import java.nio.file.Files;
|
|---|
| 11 | import java.security.SecureRandom;
|
|---|
| 12 | import java.util.Collections;
|
|---|
| 13 | import java.util.List;
|
|---|
| 14 | import java.util.Map;
|
|---|
| 15 | import java.util.Set;
|
|---|
| 16 | import java.util.concurrent.ConcurrentHashMap;
|
|---|
| 17 | import java.util.concurrent.ConcurrentMap;
|
|---|
| 18 | import java.util.concurrent.LinkedBlockingDeque;
|
|---|
| 19 | import java.util.concurrent.ThreadPoolExecutor;
|
|---|
| 20 | import java.util.concurrent.TimeUnit;
|
|---|
| 21 | import java.util.regex.Matcher;
|
|---|
| 22 |
|
|---|
| 23 | import org.openstreetmap.josm.data.cache.ICachedLoaderListener.LoadResult;
|
|---|
| 24 | import org.openstreetmap.josm.data.imagery.TileJobOptions;
|
|---|
| 25 | import org.openstreetmap.josm.data.preferences.IntegerProperty;
|
|---|
| 26 | import org.openstreetmap.josm.tools.CheckParameterUtil;
|
|---|
| 27 | import org.openstreetmap.josm.tools.HttpClient;
|
|---|
| 28 | import org.openstreetmap.josm.tools.Logging;
|
|---|
| 29 | import org.openstreetmap.josm.tools.Utils;
|
|---|
| 30 |
|
|---|
| 31 | import org.apache.commons.jcs3.access.behavior.ICacheAccess;
|
|---|
| 32 | import org.apache.commons.jcs3.engine.behavior.ICacheElement;
|
|---|
| 33 |
|
|---|
| 34 | /**
|
|---|
| 35 | * Generic loader for HTTP based tiles. Uses custom attribute, to check, if entry has expired
|
|---|
| 36 | * according to HTTP headers sent with tile. If so, it tries to verify using Etags
|
|---|
| 37 | * or If-Modified-Since / Last-Modified.
|
|---|
| 38 | *
|
|---|
| 39 | * If the tile is not valid, it will try to download it from remote service and put it
|
|---|
| 40 | * to cache. If remote server will fail it will try to use stale entry.
|
|---|
| 41 | *
|
|---|
| 42 | * This class will keep only one Job running for specified tile. All others will just finish, but
|
|---|
| 43 | * listeners will be gathered and notified, once download job will be finished
|
|---|
| 44 | *
|
|---|
| 45 | * @author Wiktor Niesiobędzki
|
|---|
| 46 | * @param <K> cache entry key type
|
|---|
| 47 | * @param <V> cache value type
|
|---|
| 48 | * @since 8168
|
|---|
| 49 | */
|
|---|
| 50 | public abstract class JCSCachedTileLoaderJob<K, V extends CacheEntry> implements ICachedLoaderJob<K> {
|
|---|
| 51 | protected static final long DEFAULT_EXPIRE_TIME = TimeUnit.DAYS.toMillis(7);
|
|---|
| 52 | // Limit for the max-age value send by the server.
|
|---|
| 53 | protected static final long EXPIRE_TIME_SERVER_LIMIT = TimeUnit.DAYS.toMillis(28);
|
|---|
| 54 | // Absolute expire time limit. Cached tiles that are older will not be used,
|
|---|
| 55 | // even if the refresh from the server fails.
|
|---|
| 56 | protected static final long ABSOLUTE_EXPIRE_TIME_LIMIT = TimeUnit.DAYS.toMillis(365);
|
|---|
| 57 |
|
|---|
| 58 | /**
|
|---|
| 59 | * maximum download threads that will be started
|
|---|
| 60 | */
|
|---|
| 61 | public static final IntegerProperty THREAD_LIMIT = new IntegerProperty("cache.jcs.max_threads", 10);
|
|---|
| 62 |
|
|---|
| 63 | /*
|
|---|
| 64 | * ThreadPoolExecutor starts new threads, until THREAD_LIMIT is reached. Then it puts tasks into LinkedBlockingDeque.
|
|---|
| 65 | *
|
|---|
| 66 | * The queue works FIFO, so one needs to take care about ordering of the entries submitted
|
|---|
| 67 | *
|
|---|
| 68 | * 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
|
|---|
| 69 | * the response, so later it could be used). We could actually cancel what is in LIFOQueue, but this is a tradeoff between simplicity
|
|---|
| 70 | * and performance (we do want to have something to offer to worker threads before tasks will be resubmitted by class consumer)
|
|---|
| 71 | */
|
|---|
| 72 |
|
|---|
| 73 | private static final ThreadPoolExecutor DEFAULT_DOWNLOAD_JOB_DISPATCHER = new ThreadPoolExecutor(
|
|---|
| 74 | 1, // we have a small queue, so threads will be quickly started (threads are started only, when queue is full)
|
|---|
| 75 | THREAD_LIMIT.get(), // do not this number of threads
|
|---|
| 76 | 30, // keepalive for thread
|
|---|
| 77 | TimeUnit.SECONDS,
|
|---|
| 78 | // make queue of LIFO type - so recently requested tiles will be loaded first (assuming that these are which user is waiting to see)
|
|---|
| 79 | new LinkedBlockingDeque<>(),
|
|---|
| 80 | Utils.newThreadFactory("JCS-downloader-%d", Thread.NORM_PRIORITY)
|
|---|
| 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 | protected 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 | private final long minimumExpiryTime;
|
|---|
| 101 |
|
|---|
| 102 | /**
|
|---|
| 103 | * @param cache cache instance that we will work on
|
|---|
| 104 | * @param options options of the request
|
|---|
| 105 | * @param downloadJobExecutor that will be executing the jobs
|
|---|
| 106 | */
|
|---|
| 107 | protected JCSCachedTileLoaderJob(ICacheAccess<K, V> cache,
|
|---|
| 108 | TileJobOptions options,
|
|---|
| 109 | ThreadPoolExecutor downloadJobExecutor) {
|
|---|
| 110 | CheckParameterUtil.ensureParameterNotNull(cache, "cache");
|
|---|
| 111 | this.cache = cache;
|
|---|
| 112 | this.now = System.currentTimeMillis();
|
|---|
| 113 | this.connectTimeout = options.getConnectionTimeout();
|
|---|
| 114 | this.readTimeout = options.getReadTimeout();
|
|---|
| 115 | this.headers = options.getHeaders();
|
|---|
| 116 | this.downloadJobExecutor = downloadJobExecutor;
|
|---|
| 117 | this.minimumExpiryTime = TimeUnit.SECONDS.toMillis(options.getMinimumExpiryTime());
|
|---|
| 118 | }
|
|---|
| 119 |
|
|---|
| 120 | /**
|
|---|
| 121 | * @param cache cache instance that we will work on
|
|---|
| 122 | * @param options of the request
|
|---|
| 123 | */
|
|---|
| 124 | protected JCSCachedTileLoaderJob(ICacheAccess<K, V> cache,
|
|---|
| 125 | TileJobOptions options) {
|
|---|
| 126 | this(cache, options, DEFAULT_DOWNLOAD_JOB_DISPATCHER);
|
|---|
| 127 | }
|
|---|
| 128 |
|
|---|
| 129 | private void ensureCacheElement() {
|
|---|
| 130 | if (cacheElement == null && getCacheKey() != null) {
|
|---|
| 131 | cacheElement = cache.getCacheElement(getCacheKey());
|
|---|
| 132 | if (cacheElement != null) {
|
|---|
| 133 | attributes = (CacheEntryAttributes) cacheElement.getElementAttributes();
|
|---|
| 134 | cacheData = cacheElement.getVal();
|
|---|
| 135 | }
|
|---|
| 136 | }
|
|---|
| 137 | }
|
|---|
| 138 |
|
|---|
| 139 | @Override
|
|---|
| 140 | public V get() {
|
|---|
| 141 | ensureCacheElement();
|
|---|
| 142 | return cacheData;
|
|---|
| 143 | }
|
|---|
| 144 |
|
|---|
| 145 | @Override
|
|---|
| 146 | public void submit(ICachedLoaderListener listener, boolean force) throws IOException {
|
|---|
| 147 | this.force = force;
|
|---|
| 148 | boolean first = false;
|
|---|
| 149 | URL url = getUrl();
|
|---|
| 150 | String deduplicationKey = null;
|
|---|
| 151 | if (url != null) {
|
|---|
| 152 | // url might be null, for example when Bing Attribution is not loaded yet
|
|---|
| 153 | deduplicationKey = url.toString();
|
|---|
| 154 | }
|
|---|
| 155 | if (deduplicationKey == null) {
|
|---|
| 156 | Logging.warn("No url returned for: {0}, skipping", getCacheKey());
|
|---|
| 157 | throw new IllegalArgumentException("No url returned");
|
|---|
| 158 | }
|
|---|
| 159 | synchronized (this) {
|
|---|
| 160 | first = !inProgress.containsKey(deduplicationKey);
|
|---|
| 161 | }
|
|---|
| 162 | inProgress.computeIfAbsent(deduplicationKey, k -> ConcurrentHashMap.newKeySet()).add(listener);
|
|---|
| 163 |
|
|---|
| 164 | if (first || force) {
|
|---|
| 165 | // submit all jobs to separate thread, so calling thread is not blocked with IO when loading from disk
|
|---|
| 166 | Logging.debug("JCS - Submitting job for execution for url: {0}", getUrlNoException());
|
|---|
| 167 | downloadJobExecutor.execute(this);
|
|---|
| 168 | }
|
|---|
| 169 | }
|
|---|
| 170 |
|
|---|
| 171 | /**
|
|---|
| 172 | * This method is run when job has finished
|
|---|
| 173 | */
|
|---|
| 174 | protected void executionFinished() {
|
|---|
| 175 | if (finishTask != null) {
|
|---|
| 176 | finishTask.run();
|
|---|
| 177 | }
|
|---|
| 178 | }
|
|---|
| 179 |
|
|---|
| 180 | /**
|
|---|
| 181 | * Checks if object from cache has sufficient data to be returned.
|
|---|
| 182 | * @return {@code true} if object from cache has sufficient data to be returned
|
|---|
| 183 | */
|
|---|
| 184 | protected boolean isObjectLoadable() {
|
|---|
| 185 | if (cacheData == null) {
|
|---|
| 186 | return false;
|
|---|
| 187 | }
|
|---|
| 188 | return cacheData.getContent().length > 0;
|
|---|
| 189 | }
|
|---|
| 190 |
|
|---|
| 191 | /**
|
|---|
| 192 | * Simple implementation. All errors should be cached as empty. Though some JDK (JDK8 on Windows for example)
|
|---|
| 193 | * doesn't return 4xx error codes, instead they do throw an FileNotFoundException or IOException
|
|---|
| 194 | * @param headerFields headers sent by server
|
|---|
| 195 | * @param responseCode http status code
|
|---|
| 196 | *
|
|---|
| 197 | * @return true if we should put empty object into cache, regardless of what remote resource has returned
|
|---|
| 198 | */
|
|---|
| 199 | protected boolean cacheAsEmpty(Map<String, List<String>> headerFields, int responseCode) {
|
|---|
| 200 | return attributes.getResponseCode() < 500;
|
|---|
| 201 | }
|
|---|
| 202 |
|
|---|
| 203 | /**
|
|---|
| 204 | * Returns key under which discovered server settings will be kept.
|
|---|
| 205 | * @return key under which discovered server settings will be kept
|
|---|
| 206 | */
|
|---|
| 207 | protected String getServerKey() {
|
|---|
| 208 | try {
|
|---|
| 209 | return getUrl().getHost();
|
|---|
| 210 | } catch (IOException e) {
|
|---|
| 211 | Logging.trace(e);
|
|---|
| 212 | return null;
|
|---|
| 213 | }
|
|---|
| 214 | }
|
|---|
| 215 |
|
|---|
| 216 | @Override
|
|---|
| 217 | public void run() {
|
|---|
| 218 | final Thread currentThread = Thread.currentThread();
|
|---|
| 219 | final String oldName = currentThread.getName();
|
|---|
| 220 | currentThread.setName("JCS Downloading: " + getUrlNoException());
|
|---|
| 221 | Logging.debug("JCS - starting fetch of url: {0} ", getUrlNoException());
|
|---|
| 222 | ensureCacheElement();
|
|---|
| 223 | try {
|
|---|
| 224 | // try to fetch from cache
|
|---|
| 225 | if (!force && cacheElement != null && isCacheElementValid() && isObjectLoadable()) {
|
|---|
| 226 | // we got something in cache, and it's valid, so lets return it
|
|---|
| 227 | Logging.debug("JCS - Returning object from cache: {0}", getCacheKey());
|
|---|
| 228 | finishLoading(LoadResult.SUCCESS);
|
|---|
| 229 | return;
|
|---|
| 230 | }
|
|---|
| 231 |
|
|---|
| 232 | // try to load object from remote resource
|
|---|
| 233 | if (loadObject()) {
|
|---|
| 234 | finishLoading(LoadResult.SUCCESS);
|
|---|
| 235 | } else {
|
|---|
| 236 | // if loading failed - check if we can return stale entry
|
|---|
| 237 | if (isObjectLoadable()) {
|
|---|
| 238 | // try to get stale entry in cache
|
|---|
| 239 | finishLoading(LoadResult.SUCCESS);
|
|---|
| 240 | Logging.debug("JCS - found stale object in cache: {0}", getUrlNoException());
|
|---|
| 241 | } else {
|
|---|
| 242 | // failed completely
|
|---|
| 243 | finishLoading(LoadResult.FAILURE);
|
|---|
| 244 | }
|
|---|
| 245 | }
|
|---|
| 246 | } finally {
|
|---|
| 247 | executionFinished();
|
|---|
| 248 | currentThread.setName(oldName);
|
|---|
| 249 | }
|
|---|
| 250 | }
|
|---|
| 251 |
|
|---|
| 252 | private void finishLoading(LoadResult result) {
|
|---|
| 253 | Set<ICachedLoaderListener> listeners;
|
|---|
| 254 | try {
|
|---|
| 255 | listeners = inProgress.remove(getUrl().toString());
|
|---|
| 256 | } catch (IOException e) {
|
|---|
| 257 | listeners = null;
|
|---|
| 258 | Logging.trace(e);
|
|---|
| 259 | }
|
|---|
| 260 | if (listeners == null) {
|
|---|
| 261 | Logging.warn("Listener not found for URL: {0}. Listener not notified!", getUrlNoException());
|
|---|
| 262 | return;
|
|---|
| 263 | }
|
|---|
| 264 | for (ICachedLoaderListener l: listeners) {
|
|---|
| 265 | l.loadingFinished(cacheData, attributes, result);
|
|---|
| 266 | }
|
|---|
| 267 | }
|
|---|
| 268 |
|
|---|
| 269 | protected boolean isCacheElementValid() {
|
|---|
| 270 | long expires = attributes.getExpirationTime();
|
|---|
| 271 |
|
|---|
| 272 | // check by expire date set by server
|
|---|
| 273 | if (expires != 0L) {
|
|---|
| 274 | // put a limit to the expire time (some servers send a value
|
|---|
| 275 | // that is too large)
|
|---|
| 276 | expires = Math.min(expires, attributes.getCreateTime() + Math.max(EXPIRE_TIME_SERVER_LIMIT, minimumExpiryTime));
|
|---|
| 277 | if (now > expires) {
|
|---|
| 278 | Logging.debug("JCS - Object {0} has expired -> valid to {1}, now is: {2}",
|
|---|
| 279 | getUrlNoException(), Long.toString(expires), Long.toString(now));
|
|---|
| 280 | return false;
|
|---|
| 281 | }
|
|---|
| 282 | } else if (attributes.getLastModification() > 0 &&
|
|---|
| 283 | now - attributes.getLastModification() > Math.max(DEFAULT_EXPIRE_TIME, minimumExpiryTime)) {
|
|---|
| 284 | // check by file modification date
|
|---|
| 285 | Logging.debug("JCS - Object has expired, maximum file age reached {0}", getUrlNoException());
|
|---|
| 286 | return false;
|
|---|
| 287 | } else if (now - attributes.getCreateTime() > Math.max(DEFAULT_EXPIRE_TIME, minimumExpiryTime)) {
|
|---|
| 288 | Logging.debug("JCS - Object has expired, maximum time since object creation reached {0}", getUrlNoException());
|
|---|
| 289 | return false;
|
|---|
| 290 | }
|
|---|
| 291 | return true;
|
|---|
| 292 | }
|
|---|
| 293 |
|
|---|
| 294 | /**
|
|---|
| 295 | * Load an cache object
|
|---|
| 296 | * @return {@code true} if object was successfully downloaded, false, if there was a loading failure
|
|---|
| 297 | * @since 18831
|
|---|
| 298 | */
|
|---|
| 299 | protected boolean loadObject() {
|
|---|
| 300 | if (attributes == null) {
|
|---|
| 301 | attributes = new CacheEntryAttributes();
|
|---|
| 302 | }
|
|---|
| 303 | final URL url = this.getUrlNoException();
|
|---|
| 304 | if (url == null) {
|
|---|
| 305 | return false;
|
|---|
| 306 | }
|
|---|
| 307 |
|
|---|
| 308 | if (url.getProtocol().contains("http")) {
|
|---|
| 309 | return loadObjectHttp();
|
|---|
| 310 | }
|
|---|
| 311 | if (url.getProtocol().contains("file")) {
|
|---|
| 312 | return loadObjectFile(url);
|
|---|
| 313 | }
|
|---|
| 314 |
|
|---|
| 315 | return false;
|
|---|
| 316 | }
|
|---|
| 317 |
|
|---|
| 318 | private boolean loadObjectFile(URL url) {
|
|---|
| 319 | String fileName = url.toExternalForm();
|
|---|
| 320 | File file = new File(fileName.substring("file:/".length() - 1));
|
|---|
| 321 | if (!file.exists()) {
|
|---|
| 322 | file = new File(fileName.substring("file://".length() - 1));
|
|---|
| 323 | }
|
|---|
| 324 | try (InputStream fileInputStream = Files.newInputStream(file.toPath())) {
|
|---|
| 325 | cacheData = createCacheEntry(fileInputStream.readAllBytes());
|
|---|
| 326 | cache.put(getCacheKey(), cacheData, attributes);
|
|---|
| 327 | return true;
|
|---|
| 328 | } catch (IOException e) {
|
|---|
| 329 | Logging.error(e);
|
|---|
| 330 | attributes.setError(e);
|
|---|
| 331 | attributes.setException(e);
|
|---|
| 332 | }
|
|---|
| 333 | return false;
|
|---|
| 334 | }
|
|---|
| 335 |
|
|---|
| 336 | /**
|
|---|
| 337 | * Load an cache object via HTTP
|
|---|
| 338 | * @return {@code true} if object was successfully downloaded via http, false, if there was a loading failure
|
|---|
| 339 | */
|
|---|
| 340 | private boolean loadObjectHttp() {
|
|---|
| 341 | try {
|
|---|
| 342 | // if we have object in cache, and host doesn't support If-Modified-Since nor If-None-Match
|
|---|
| 343 | // then just use HEAD request and check returned values
|
|---|
| 344 | if (isObjectLoadable() &&
|
|---|
| 345 | Boolean.TRUE.equals(useHead.get(getServerKey())) &&
|
|---|
| 346 | isCacheValidUsingHead()) {
|
|---|
| 347 | Logging.debug("JCS - cache entry verified using HEAD request: {0}", getUrl());
|
|---|
| 348 | return true;
|
|---|
| 349 | }
|
|---|
| 350 |
|
|---|
| 351 | Logging.debug("JCS - starting HttpClient GET request for URL: {0}", getUrl());
|
|---|
| 352 | final HttpClient request = getRequest("GET");
|
|---|
| 353 |
|
|---|
| 354 | if (isObjectLoadable() &&
|
|---|
| 355 | (now - attributes.getLastModification()) <= ABSOLUTE_EXPIRE_TIME_LIMIT) {
|
|---|
| 356 | request.setIfModifiedSince(attributes.getLastModification());
|
|---|
| 357 | }
|
|---|
| 358 | if (isObjectLoadable() && attributes.getEtag() != null) {
|
|---|
| 359 | request.setHeader("If-None-Match", attributes.getEtag());
|
|---|
| 360 | }
|
|---|
| 361 |
|
|---|
| 362 | final HttpClient.Response urlConn = request.connect();
|
|---|
| 363 |
|
|---|
| 364 | if (urlConn.getResponseCode() == 304) {
|
|---|
| 365 | // If isModifiedSince or If-None-Match has been set
|
|---|
| 366 | // and the server answers with a HTTP 304 = "Not Modified"
|
|---|
| 367 | Logging.debug("JCS - If-Modified-Since/ETag test: local version is up to date: {0}", getUrl());
|
|---|
| 368 | // update cache attributes
|
|---|
| 369 | attributes = parseHeaders(urlConn);
|
|---|
| 370 | cache.put(getCacheKey(), cacheData, attributes);
|
|---|
| 371 | return true;
|
|---|
| 372 | } else if (isObjectLoadable() // we have an object in cache, but we haven't received 304 response code
|
|---|
| 373 | && (
|
|---|
| 374 | (attributes.getEtag() != null && attributes.getEtag().equals(urlConn.getHeaderField("ETag"))) ||
|
|---|
| 375 | attributes.getLastModification() == urlConn.getLastModified())
|
|---|
| 376 | ) {
|
|---|
| 377 | // we sent ETag or If-Modified-Since, but didn't get 304 response code
|
|---|
| 378 | // for further requests - use HEAD
|
|---|
| 379 | String serverKey = getServerKey();
|
|---|
| 380 | Logging.info("JCS - Host: {0} found not to return 304 codes for If-Modified-Since or If-None-Match headers",
|
|---|
| 381 | serverKey);
|
|---|
| 382 | useHead.put(serverKey, Boolean.TRUE);
|
|---|
| 383 | }
|
|---|
| 384 |
|
|---|
| 385 | attributes = parseHeaders(urlConn);
|
|---|
| 386 |
|
|---|
| 387 | for (int i = 0; i < 5; ++i) {
|
|---|
| 388 | if (urlConn.getResponseCode() == HttpURLConnection.HTTP_UNAVAILABLE) {
|
|---|
| 389 | Thread.sleep(5000L+new SecureRandom().nextInt(5000));
|
|---|
| 390 | continue;
|
|---|
| 391 | }
|
|---|
| 392 |
|
|---|
| 393 | attributes.setResponseCode(urlConn.getResponseCode());
|
|---|
| 394 | byte[] raw;
|
|---|
| 395 | if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
|
|---|
| 396 | try (InputStream is = urlConn.getContent()) {
|
|---|
| 397 | raw = is.readAllBytes();
|
|---|
| 398 | }
|
|---|
| 399 | } else {
|
|---|
| 400 | raw = new byte[]{};
|
|---|
| 401 | try {
|
|---|
| 402 | String data = urlConn.fetchContent();
|
|---|
| 403 | if (!data.isEmpty()) {
|
|---|
| 404 | String detectErrorMessage = detectErrorMessage(data);
|
|---|
| 405 | if (detectErrorMessage != null) {
|
|---|
| 406 | attributes.setErrorMessage(detectErrorMessage);
|
|---|
| 407 | }
|
|---|
| 408 | }
|
|---|
| 409 | } catch (IOException e) {
|
|---|
| 410 | Logging.warn(e);
|
|---|
| 411 | }
|
|---|
| 412 | }
|
|---|
| 413 |
|
|---|
| 414 | if (isResponseLoadable(urlConn.getHeaderFields(), urlConn.getResponseCode(), raw)) {
|
|---|
| 415 | // we need to check cacheEmpty, so for cases, when data is returned, but we want to store
|
|---|
| 416 | // as empty (eg. empty tile images) to save some space
|
|---|
| 417 | cacheData = createCacheEntry(raw);
|
|---|
| 418 | cache.put(getCacheKey(), cacheData, attributes);
|
|---|
| 419 | Logging.debug("JCS - downloaded key: {0}, length: {1}, url: {2}",
|
|---|
| 420 | getCacheKey(), raw.length, getUrl());
|
|---|
| 421 | return true;
|
|---|
| 422 | } else if (cacheAsEmpty(urlConn.getHeaderFields(), urlConn.getResponseCode())) {
|
|---|
| 423 | cacheData = createCacheEntry(new byte[]{});
|
|---|
| 424 | cache.put(getCacheKey(), cacheData, attributes);
|
|---|
| 425 | Logging.debug("JCS - Caching empty object {0}", getUrl());
|
|---|
| 426 | return true;
|
|---|
| 427 | } else {
|
|---|
| 428 | Logging.debug("JCS - failure during load - response is not loadable nor cached as empty");
|
|---|
| 429 | return false;
|
|---|
| 430 | }
|
|---|
| 431 | }
|
|---|
| 432 | } catch (FileNotFoundException e) {
|
|---|
| 433 | Logging.debug("JCS - Caching empty object as server returned 404 for: {0}", getUrlNoException());
|
|---|
| 434 | attributes.setResponseCode(404);
|
|---|
| 435 | attributes.setError(e);
|
|---|
| 436 | attributes.setException(e);
|
|---|
| 437 | boolean doCache = isResponseLoadable(null, 404, null) || cacheAsEmpty(Collections.emptyMap(), 404);
|
|---|
| 438 | if (doCache) {
|
|---|
| 439 | cacheData = createCacheEntry(new byte[]{});
|
|---|
| 440 | cache.put(getCacheKey(), cacheData, attributes);
|
|---|
| 441 | }
|
|---|
| 442 | return doCache;
|
|---|
| 443 | } catch (IOException e) {
|
|---|
| 444 | Logging.debug("JCS - IOException during communication with server for: {0}", getUrlNoException());
|
|---|
| 445 | if (isObjectLoadable()) {
|
|---|
| 446 | return true;
|
|---|
| 447 | } else {
|
|---|
| 448 | attributes.setError(e);
|
|---|
| 449 | attributes.setException(e);
|
|---|
| 450 | attributes.setResponseCode(599); // set dummy error code, greater than 500 so it will be not cached
|
|---|
| 451 | return false;
|
|---|
| 452 | }
|
|---|
| 453 |
|
|---|
| 454 | } catch (InterruptedException e) {
|
|---|
| 455 | attributes.setError(e);
|
|---|
| 456 | attributes.setException(e);
|
|---|
| 457 | Logging.logWithStackTrace(Logging.LEVEL_WARN, e, "JCS - Exception during download {0}", getUrlNoException());
|
|---|
| 458 | Thread.currentThread().interrupt();
|
|---|
| 459 | }
|
|---|
| 460 | Logging.warn("JCS - Silent failure during download: {0}", getUrlNoException());
|
|---|
| 461 | return false;
|
|---|
| 462 | }
|
|---|
| 463 |
|
|---|
| 464 | /**
|
|---|
| 465 | * Tries do detect an error message from given string.
|
|---|
| 466 | * @param data string to analyze
|
|---|
| 467 | * @return error message if detected, or null
|
|---|
| 468 | * @since 14535
|
|---|
| 469 | */
|
|---|
| 470 | public String detectErrorMessage(String data) {
|
|---|
| 471 | Matcher m = HttpClient.getTomcatErrorMatcher(data);
|
|---|
| 472 | return m.matches() ? m.group(1).replace("'", "''") : null;
|
|---|
| 473 | }
|
|---|
| 474 |
|
|---|
| 475 | /**
|
|---|
| 476 | * Check if the object is loadable. This means, if the data will be parsed, and if this response
|
|---|
| 477 | * will finish as successful retrieve.
|
|---|
| 478 | * <p>
|
|---|
| 479 | * This simple implementation doesn't load empty response, nor client (4xx) and server (5xx) errors
|
|---|
| 480 | *
|
|---|
| 481 | * @param headerFields headers sent by server
|
|---|
| 482 | * @param responseCode http status code
|
|---|
| 483 | * @param raw data read from server
|
|---|
| 484 | * @return true if object should be cached and returned to listener
|
|---|
| 485 | */
|
|---|
| 486 | protected boolean isResponseLoadable(Map<String, List<String>> headerFields, int responseCode, byte[] raw) {
|
|---|
| 487 | return raw != null && raw.length != 0 && responseCode < 400;
|
|---|
| 488 | }
|
|---|
| 489 |
|
|---|
| 490 | protected abstract V createCacheEntry(byte[] content);
|
|---|
| 491 |
|
|---|
| 492 | protected CacheEntryAttributes parseHeaders(HttpClient.Response urlConn) {
|
|---|
| 493 | CacheEntryAttributes ret = new CacheEntryAttributes();
|
|---|
| 494 |
|
|---|
| 495 | /*
|
|---|
| 496 | * according to https://www.ietf.org/rfc/rfc2616.txt Cache-Control takes precedence over max-age
|
|---|
| 497 | * max-age is for private caches, s-max-age is for shared caches. We take any value that is larger
|
|---|
| 498 | */
|
|---|
| 499 | Long expiration = 0L;
|
|---|
| 500 | String cacheControl = urlConn.getHeaderField("Cache-Control");
|
|---|
| 501 | if (cacheControl != null) {
|
|---|
| 502 | for (String token: cacheControl.split(",", -1)) {
|
|---|
| 503 | try {
|
|---|
| 504 | if (token.startsWith("max-age=")) {
|
|---|
| 505 | expiration = Math.max(expiration,
|
|---|
| 506 | TimeUnit.SECONDS.toMillis(Long.parseLong(token.substring("max-age=".length())))
|
|---|
| 507 | + System.currentTimeMillis()
|
|---|
| 508 | );
|
|---|
| 509 | }
|
|---|
| 510 | if (token.startsWith("s-max-age=")) {
|
|---|
| 511 | expiration = Math.max(expiration,
|
|---|
| 512 | TimeUnit.SECONDS.toMillis(Long.parseLong(token.substring("s-max-age=".length())))
|
|---|
| 513 | + System.currentTimeMillis()
|
|---|
| 514 | );
|
|---|
| 515 | }
|
|---|
| 516 | } catch (NumberFormatException e) {
|
|---|
| 517 | // ignore malformed Cache-Control headers
|
|---|
| 518 | Logging.trace(e);
|
|---|
| 519 | }
|
|---|
| 520 | }
|
|---|
| 521 | }
|
|---|
| 522 |
|
|---|
| 523 | if (expiration.equals(0L)) {
|
|---|
| 524 | expiration = urlConn.getExpiration();
|
|---|
| 525 | }
|
|---|
| 526 |
|
|---|
| 527 | // if nothing is found - set default
|
|---|
| 528 | if (expiration.equals(0L)) {
|
|---|
| 529 | expiration = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME;
|
|---|
| 530 | }
|
|---|
| 531 |
|
|---|
| 532 | ret.setExpirationTime(Math.max(minimumExpiryTime + System.currentTimeMillis(), expiration));
|
|---|
| 533 | ret.setLastModification(now);
|
|---|
| 534 | ret.setEtag(urlConn.getHeaderField("ETag"));
|
|---|
| 535 |
|
|---|
| 536 | return ret;
|
|---|
| 537 | }
|
|---|
| 538 |
|
|---|
| 539 | private HttpClient getRequest(String requestMethod) throws IOException {
|
|---|
| 540 | final HttpClient urlConn = HttpClient.create(getUrl(), requestMethod);
|
|---|
| 541 | urlConn.setAccept("text/html, image/png, image/jpeg, image/gif, */*");
|
|---|
| 542 | urlConn.setReadTimeout(readTimeout); // 30 seconds read timeout
|
|---|
| 543 | urlConn.setConnectTimeout(connectTimeout);
|
|---|
| 544 | if (headers != null) {
|
|---|
| 545 | urlConn.setHeaders(headers);
|
|---|
| 546 | }
|
|---|
| 547 |
|
|---|
| 548 | final boolean noCache = force;
|
|---|
| 549 | urlConn.useCache(!noCache);
|
|---|
| 550 |
|
|---|
| 551 | return urlConn;
|
|---|
| 552 | }
|
|---|
| 553 |
|
|---|
| 554 | private boolean isCacheValidUsingHead() throws IOException {
|
|---|
| 555 | final HttpClient.Response urlConn = getRequest("HEAD").connect();
|
|---|
| 556 | long lastModified = urlConn.getLastModified();
|
|---|
| 557 | boolean ret = (attributes.getEtag() != null && attributes.getEtag().equals(urlConn.getHeaderField("ETag"))) ||
|
|---|
| 558 | (lastModified != 0 && lastModified <= attributes.getLastModification());
|
|---|
| 559 | if (ret) {
|
|---|
| 560 | // update attributes
|
|---|
| 561 | attributes = parseHeaders(urlConn);
|
|---|
| 562 | cache.put(getCacheKey(), cacheData, attributes);
|
|---|
| 563 | }
|
|---|
| 564 | return ret;
|
|---|
| 565 | }
|
|---|
| 566 |
|
|---|
| 567 | /**
|
|---|
| 568 | * TODO: move to JobFactory
|
|---|
| 569 | * cancels all outstanding tasks in the queue.
|
|---|
| 570 | */
|
|---|
| 571 | public void cancelOutstandingTasks() {
|
|---|
| 572 | for (Runnable r: downloadJobExecutor.getQueue()) {
|
|---|
| 573 | if (downloadJobExecutor.remove(r) && r instanceof JCSCachedTileLoaderJob) {
|
|---|
| 574 | ((JCSCachedTileLoaderJob<?, ?>) r).handleJobCancellation();
|
|---|
| 575 | }
|
|---|
| 576 | }
|
|---|
| 577 | }
|
|---|
| 578 |
|
|---|
| 579 | /**
|
|---|
| 580 | * Sets a job, that will be run, when job will finish execution
|
|---|
| 581 | * @param runnable that will be executed
|
|---|
| 582 | */
|
|---|
| 583 | public void setFinishedTask(Runnable runnable) {
|
|---|
| 584 | this.finishTask = runnable;
|
|---|
| 585 |
|
|---|
| 586 | }
|
|---|
| 587 |
|
|---|
| 588 | /**
|
|---|
| 589 | * Marks this job as canceled
|
|---|
| 590 | */
|
|---|
| 591 | public void handleJobCancellation() {
|
|---|
| 592 | finishLoading(LoadResult.CANCELED);
|
|---|
| 593 | }
|
|---|
| 594 |
|
|---|
| 595 | private URL getUrlNoException() {
|
|---|
| 596 | try {
|
|---|
| 597 | return getUrl();
|
|---|
| 598 | } catch (IOException e) {
|
|---|
| 599 | Logging.trace(e);
|
|---|
| 600 | return null;
|
|---|
| 601 | }
|
|---|
| 602 | }
|
|---|
| 603 | }
|
|---|