source: josm/trunk/src/org/openstreetmap/josm/data/imagery/TMSCachedTileLoaderJob.java@ 11559

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

fix #14361 - WMTS: download only supported image formats

  • Property svn:eol-style set to native
File size: 13.6 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.imagery;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.ByteArrayInputStream;
7import java.io.IOException;
8import java.net.URL;
9import java.util.HashSet;
10import java.util.List;
11import java.util.Map;
12import java.util.Map.Entry;
13import java.util.Optional;
14import java.util.Set;
15import java.util.concurrent.ConcurrentHashMap;
16import java.util.concurrent.ConcurrentMap;
17import java.util.concurrent.ThreadPoolExecutor;
18import java.util.concurrent.TimeUnit;
19import java.util.logging.Level;
20import java.util.logging.Logger;
21
22import org.apache.commons.jcs.access.behavior.ICacheAccess;
23import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
24import org.openstreetmap.gui.jmapviewer.Tile;
25import org.openstreetmap.gui.jmapviewer.interfaces.TileJob;
26import org.openstreetmap.gui.jmapviewer.interfaces.TileLoaderListener;
27import org.openstreetmap.gui.jmapviewer.interfaces.TileSource;
28import org.openstreetmap.gui.jmapviewer.tilesources.AbstractTMSTileSource;
29import org.openstreetmap.josm.Main;
30import org.openstreetmap.josm.data.cache.BufferedImageCacheEntry;
31import org.openstreetmap.josm.data.cache.CacheEntry;
32import org.openstreetmap.josm.data.cache.CacheEntryAttributes;
33import org.openstreetmap.josm.data.cache.ICachedLoaderListener;
34import org.openstreetmap.josm.data.cache.JCSCachedTileLoaderJob;
35import org.openstreetmap.josm.data.preferences.LongProperty;
36import org.openstreetmap.josm.tools.HttpClient;
37
38/**
39 * Class bridging TMS requests to JCS cache requests
40 *
41 * @author Wiktor Niesiobędzki
42 * @since 8168
43 */
44public class TMSCachedTileLoaderJob extends JCSCachedTileLoaderJob<String, BufferedImageCacheEntry> implements TileJob, ICachedLoaderListener {
45 private static final Logger LOG = FeatureAdapter.getLogger(TMSCachedTileLoaderJob.class.getCanonicalName());
46 private static final LongProperty MAXIMUM_EXPIRES = new LongProperty("imagery.generic.maximum_expires", TimeUnit.DAYS.toMillis(30));
47 private static final LongProperty MINIMUM_EXPIRES = new LongProperty("imagery.generic.minimum_expires", TimeUnit.HOURS.toMillis(1));
48 private final Tile tile;
49 private volatile URL url;
50
51 // we need another deduplication of Tile Loader listeners, as for each submit, new TMSCachedTileLoaderJob was created
52 // that way, we reduce calls to tileLoadingFinished, and general CPU load due to surplus Map repaints
53 private static final ConcurrentMap<String, Set<TileLoaderListener>> inProgress = new ConcurrentHashMap<>();
54
55 /**
56 * Constructor for creating a job, to get a specific tile from cache
57 * @param listener Tile loader listener
58 * @param tile to be fetched from cache
59 * @param cache object
60 * @param connectTimeout when connecting to remote resource
61 * @param readTimeout when connecting to remote resource
62 * @param headers HTTP headers to be sent together with request
63 * @param downloadExecutor that will be executing the jobs
64 */
65 public TMSCachedTileLoaderJob(TileLoaderListener listener, Tile tile,
66 ICacheAccess<String, BufferedImageCacheEntry> cache,
67 int connectTimeout, int readTimeout, Map<String, String> headers,
68 ThreadPoolExecutor downloadExecutor) {
69 super(cache, connectTimeout, readTimeout, headers, downloadExecutor);
70 this.tile = tile;
71 if (listener != null) {
72 String deduplicationKey = getCacheKey();
73 synchronized (inProgress) {
74 Set<TileLoaderListener> newListeners = inProgress.get(deduplicationKey);
75 if (newListeners == null) {
76 newListeners = new HashSet<>();
77 inProgress.put(deduplicationKey, newListeners);
78 }
79 newListeners.add(listener);
80 }
81 }
82 }
83
84 @Override
85 public Tile getTile() {
86 return getCachedTile();
87 }
88
89 @Override
90 public String getCacheKey() {
91 if (tile != null) {
92 TileSource tileSource = tile.getTileSource();
93 return Optional.ofNullable(tileSource.getName()).orElse("").replace(':', '_') + ':'
94 + tileSource.getTileId(tile.getZoom(), tile.getXtile(), tile.getYtile());
95 }
96 return null;
97 }
98
99 /*
100 * this doesn't needs to be synchronized, as it's not that costly to keep only one execution
101 * in parallel, but URL creation and Tile.getUrl() are costly and are not needed when fetching
102 * data from cache, that's why URL creation is postponed until it's needed
103 *
104 * We need to have static url value for TileLoaderJob, as for some TileSources we might get different
105 * URL's each call we made (servers switching), and URL's are used below as a key for duplicate detection
106 *
107 */
108 @Override
109 public URL getUrl() throws IOException {
110 if (url == null) {
111 synchronized (this) {
112 if (url == null) {
113 String sUrl = tile.getUrl();
114 if (!"".equals(sUrl)) {
115 url = new URL(sUrl);
116 }
117 }
118 }
119 }
120 return url;
121 }
122
123 @Override
124 public boolean isObjectLoadable() {
125 if (cacheData != null) {
126 byte[] content = cacheData.getContent();
127 try {
128 return content.length > 0 || cacheData.getImage() != null || isNoTileAtZoom();
129 } catch (IOException e) {
130 LOG.log(Level.WARNING, "JCS TMS - error loading from cache for tile {0}: {1}", new Object[] {tile.getKey(), e.getMessage()});
131 Main.warn(e);
132 }
133 }
134 return false;
135 }
136
137 @Override
138 protected boolean isResponseLoadable(Map<String, List<String>> headers, int statusCode, byte[] content) {
139 attributes.setMetadata(tile.getTileSource().getMetadata(headers));
140 if (tile.getTileSource().isNoTileAtZoom(headers, statusCode, content)) {
141 attributes.setNoTileAtZoom(true);
142 return false; // do no try to load data from no-tile at zoom, cache empty object instead
143 }
144 return super.isResponseLoadable(headers, statusCode, content);
145 }
146
147 @Override
148 protected boolean cacheAsEmpty() {
149 return isNoTileAtZoom() || super.cacheAsEmpty();
150 }
151
152 @Override
153 public void submit(boolean force) {
154 tile.initLoading();
155 try {
156 super.submit(this, force);
157 } catch (IOException | IllegalArgumentException e) {
158 // if we fail to submit the job, mark tile as loaded and set error message
159 Main.warn(e, false);
160 tile.finishLoading();
161 tile.setError(e.getMessage());
162 }
163 }
164
165 @Override
166 public void loadingFinished(CacheEntry object, CacheEntryAttributes attributes, LoadResult result) {
167 this.attributes = attributes; // as we might get notification from other object than our selfs, pass attributes along
168 Set<TileLoaderListener> listeners;
169 synchronized (inProgress) {
170 listeners = inProgress.remove(getCacheKey());
171 }
172 boolean status = result.equals(LoadResult.SUCCESS);
173
174 try {
175 tile.finishLoading(); // whatever happened set that loading has finished
176 // set tile metadata
177 if (this.attributes != null) {
178 for (Entry<String, String> e: this.attributes.getMetadata().entrySet()) {
179 tile.putValue(e.getKey(), e.getValue());
180 }
181 }
182
183 switch(result) {
184 case SUCCESS:
185 handleNoTileAtZoom();
186 int httpStatusCode = attributes.getResponseCode();
187 if (httpStatusCode >= 400 && !isNoTileAtZoom()) {
188 if (attributes.getErrorMessage() == null) {
189 tile.setError(tr("HTTP error {0} when loading tiles", httpStatusCode));
190 } else {
191 tile.setError(tr("Error downloading tiles: {0}", attributes.getErrorMessage()));
192 }
193 status = false;
194 }
195 status &= tryLoadTileImage(object); //try to keep returned image as background
196 break;
197 case FAILURE:
198 tile.setError("Problem loading tile");
199 tryLoadTileImage(object);
200 break;
201 case CANCELED:
202 tile.loadingCanceled();
203 // do nothing
204 }
205
206 // always check, if there is some listener interested in fact, that tile has finished loading
207 if (listeners != null) { // listeners might be null, if some other thread notified already about success
208 for (TileLoaderListener l: listeners) {
209 l.tileLoadingFinished(tile, status);
210 }
211 }
212 } catch (IOException e) {
213 LOG.log(Level.WARNING, "JCS TMS - error loading object for tile {0}: {1}", new Object[] {tile.getKey(), e.getMessage()});
214 tile.setError(e);
215 tile.setLoaded(false);
216 if (listeners != null) { // listeners might be null, if some other thread notified already about success
217 for (TileLoaderListener l: listeners) {
218 l.tileLoadingFinished(tile, false);
219 }
220 }
221 }
222 }
223
224 /**
225 * For TMS use BaseURL as settings discovery, so for different paths, we will have different settings (useful for developer servers)
226 *
227 * @return base URL of TMS or server url as defined in super class
228 */
229 @Override
230 protected String getServerKey() {
231 TileSource ts = tile.getSource();
232 if (ts instanceof AbstractTMSTileSource) {
233 return ((AbstractTMSTileSource) ts).getBaseUrl();
234 }
235 return super.getServerKey();
236 }
237
238 @Override
239 protected BufferedImageCacheEntry createCacheEntry(byte[] content) {
240 return new BufferedImageCacheEntry(content);
241 }
242
243 @Override
244 public void submit() {
245 submit(false);
246 }
247
248 @Override
249 protected CacheEntryAttributes parseHeaders(HttpClient.Response urlConn) {
250 CacheEntryAttributes ret = super.parseHeaders(urlConn);
251 // keep the expiration time between MINIMUM_EXPIRES and MAXIMUM_EXPIRES, so we will cache the tiles
252 // at least for some short period of time, but not too long
253 if (ret.getExpirationTime() < now + MINIMUM_EXPIRES.get()) {
254 ret.setExpirationTime(now + MINIMUM_EXPIRES.get());
255 }
256 if (ret.getExpirationTime() > now + MAXIMUM_EXPIRES.get()) {
257 ret.setExpirationTime(now + MAXIMUM_EXPIRES.get());
258 }
259 return ret;
260 }
261
262 /**
263 * Method for getting the tile from cache only, without trying to reach remote resource
264 * @return tile or null, if nothing (useful) was found in cache
265 */
266 public Tile getCachedTile() {
267 BufferedImageCacheEntry data = get();
268 if (isObjectLoadable() && isCacheElementValid()) {
269 try {
270 // set tile metadata
271 if (this.attributes != null) {
272 for (Entry<String, String> e: this.attributes.getMetadata().entrySet()) {
273 tile.putValue(e.getKey(), e.getValue());
274 }
275 }
276
277 if (data != null) {
278 if (data.getImage() != null) {
279 tile.setImage(data.getImage());
280 tile.finishLoading();
281 } else {
282 // we had some data, but we didn't get any image. Malformed image?
283 tile.setError(tr("Could not load image from tile server"));
284 }
285 }
286 if (isNoTileAtZoom()) {
287 handleNoTileAtZoom();
288 tile.finishLoading();
289 }
290 if (attributes != null && attributes.getResponseCode() >= 400) {
291 if (attributes.getErrorMessage() == null) {
292 tile.setError(tr("HTTP error {0} when loading tiles", attributes.getResponseCode()));
293 } else {
294 tile.setError(tr("Error downloading tiles: {0}", attributes.getErrorMessage()));
295 }
296 }
297 return tile;
298 } catch (IOException e) {
299 LOG.log(Level.WARNING, "JCS TMS - error loading object for tile {0}: {1}", new Object[] {tile.getKey(), e.getMessage()});
300 Main.warn(e);
301 return null;
302 }
303
304 } else {
305 return tile;
306 }
307 }
308
309 private boolean handleNoTileAtZoom() {
310 if (isNoTileAtZoom()) {
311 LOG.log(Level.FINE, "JCS TMS - Tile valid, but no file, as no tiles at this level {0}", tile);
312 tile.setError("No tile at this zoom level");
313 tile.putValue("tile-info", "no-tile");
314 return true;
315 }
316 return false;
317 }
318
319 private boolean isNoTileAtZoom() {
320 if (attributes == null) {
321 LOG.warning("Cache attributes are null");
322 }
323 return attributes != null && attributes.isNoTileAtZoom();
324 }
325
326 private boolean tryLoadTileImage(CacheEntry object) throws IOException {
327 if (object != null) {
328 byte[] content = object.getContent();
329 if (content.length > 0) {
330 tile.loadImage(new ByteArrayInputStream(content));
331 if (tile.getImage() == null) {
332 tile.setError(tr("Could not load image from tile server"));
333 return false;
334 }
335 }
336 }
337 return true;
338 }
339}
Note: See TracBrowser for help on using the repository browser.