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

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

partial revert of r12537

  • Property svn:eol-style set to native
File size: 11.7 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 protected 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 String getCacheKey() {
86 if (tile != null) {
87 TileSource tileSource = tile.getTileSource();
88 return Optional.ofNullable(tileSource.getName()).orElse("").replace(':', '_') + ':'
89 + tileSource.getTileId(tile.getZoom(), tile.getXtile(), tile.getYtile());
90 }
91 return null;
92 }
93
94 /*
95 * this doesn't needs to be synchronized, as it's not that costly to keep only one execution
96 * in parallel, but URL creation and Tile.getUrl() are costly and are not needed when fetching
97 * data from cache, that's why URL creation is postponed until it's needed
98 *
99 * We need to have static url value for TileLoaderJob, as for some TileSources we might get different
100 * URL's each call we made (servers switching), and URL's are used below as a key for duplicate detection
101 *
102 */
103 @Override
104 public URL getUrl() throws IOException {
105 if (url == null) {
106 synchronized (this) {
107 if (url == null) {
108 String sUrl = tile.getUrl();
109 if (!"".equals(sUrl)) {
110 url = new URL(sUrl);
111 }
112 }
113 }
114 }
115 return url;
116 }
117
118 @Override
119 public boolean isObjectLoadable() {
120 if (cacheData != null) {
121 byte[] content = cacheData.getContent();
122 try {
123 return content.length > 0 || cacheData.getImage() != null || isNoTileAtZoom();
124 } catch (IOException e) {
125 LOG.log(Level.WARNING, "JCS TMS - error loading from cache for tile {0}: {1}", new Object[] {tile.getKey(), e.getMessage()});
126 Main.warn(e);
127 }
128 }
129 return false;
130 }
131
132 @Override
133 protected boolean isResponseLoadable(Map<String, List<String>> headers, int statusCode, byte[] content) {
134 attributes.setMetadata(tile.getTileSource().getMetadata(headers));
135 if (tile.getTileSource().isNoTileAtZoom(headers, statusCode, content)) {
136 attributes.setNoTileAtZoom(true);
137 return false; // do no try to load data from no-tile at zoom, cache empty object instead
138 }
139 return super.isResponseLoadable(headers, statusCode, content);
140 }
141
142 @Override
143 protected boolean cacheAsEmpty() {
144 return isNoTileAtZoom() || super.cacheAsEmpty();
145 }
146
147 @Override
148 public void submit(boolean force) {
149 tile.initLoading();
150 try {
151 super.submit(this, force);
152 } catch (IOException | IllegalArgumentException e) {
153 // if we fail to submit the job, mark tile as loaded and set error message
154 Main.warn(e, false);
155 tile.finishLoading();
156 tile.setError(e.getMessage());
157 }
158 }
159
160 @Override
161 public void loadingFinished(CacheEntry object, CacheEntryAttributes attributes, LoadResult result) {
162 this.attributes = attributes; // as we might get notification from other object than our selfs, pass attributes along
163 Set<TileLoaderListener> listeners;
164 synchronized (inProgress) {
165 listeners = inProgress.remove(getCacheKey());
166 }
167 boolean status = result.equals(LoadResult.SUCCESS);
168
169 try {
170 tile.finishLoading(); // whatever happened set that loading has finished
171 // set tile metadata
172 if (this.attributes != null) {
173 for (Entry<String, String> e: this.attributes.getMetadata().entrySet()) {
174 tile.putValue(e.getKey(), e.getValue());
175 }
176 }
177
178 switch(result) {
179 case SUCCESS:
180 handleNoTileAtZoom();
181 if (attributes != null) {
182 int httpStatusCode = attributes.getResponseCode();
183 if (httpStatusCode >= 400 && !isNoTileAtZoom()) {
184 if (attributes.getErrorMessage() == null) {
185 tile.setError(tr("HTTP error {0} when loading tiles", httpStatusCode));
186 } else {
187 tile.setError(tr("Error downloading tiles: {0}", attributes.getErrorMessage()));
188 }
189 status = false;
190 }
191 }
192 status &= tryLoadTileImage(object); //try to keep returned image as background
193 break;
194 case FAILURE:
195 tile.setError("Problem loading tile");
196 tryLoadTileImage(object);
197 break;
198 case CANCELED:
199 tile.loadingCanceled();
200 // do nothing
201 }
202
203 // always check, if there is some listener interested in fact, that tile has finished loading
204 if (listeners != null) { // listeners might be null, if some other thread notified already about success
205 for (TileLoaderListener l: listeners) {
206 l.tileLoadingFinished(tile, status);
207 }
208 }
209 } catch (IOException e) {
210 LOG.log(Level.WARNING, "JCS TMS - error loading object for tile {0}: {1}", new Object[] {tile.getKey(), e.getMessage()});
211 tile.setError(e);
212 tile.setLoaded(false);
213 if (listeners != null) { // listeners might be null, if some other thread notified already about success
214 for (TileLoaderListener l: listeners) {
215 l.tileLoadingFinished(tile, false);
216 }
217 }
218 }
219 }
220
221 /**
222 * For TMS use BaseURL as settings discovery, so for different paths, we will have different settings (useful for developer servers)
223 *
224 * @return base URL of TMS or server url as defined in super class
225 */
226 @Override
227 protected String getServerKey() {
228 TileSource ts = tile.getSource();
229 if (ts instanceof AbstractTMSTileSource) {
230 return ((AbstractTMSTileSource) ts).getBaseUrl();
231 }
232 return super.getServerKey();
233 }
234
235 @Override
236 protected BufferedImageCacheEntry createCacheEntry(byte[] content) {
237 return new BufferedImageCacheEntry(content);
238 }
239
240 @Override
241 public void submit() {
242 submit(false);
243 }
244
245 @Override
246 protected CacheEntryAttributes parseHeaders(HttpClient.Response urlConn) {
247 CacheEntryAttributes ret = super.parseHeaders(urlConn);
248 // keep the expiration time between MINIMUM_EXPIRES and MAXIMUM_EXPIRES, so we will cache the tiles
249 // at least for some short period of time, but not too long
250 if (ret.getExpirationTime() < now + MINIMUM_EXPIRES.get()) {
251 ret.setExpirationTime(now + MINIMUM_EXPIRES.get());
252 }
253 if (ret.getExpirationTime() > now + MAXIMUM_EXPIRES.get()) {
254 ret.setExpirationTime(now + MAXIMUM_EXPIRES.get());
255 }
256 return ret;
257 }
258
259 private boolean handleNoTileAtZoom() {
260 if (isNoTileAtZoom()) {
261 LOG.log(Level.FINE, "JCS TMS - Tile valid, but no file, as no tiles at this level {0}", tile);
262 tile.setError("No tile at this zoom level");
263 tile.putValue("tile-info", "no-tile");
264 return true;
265 }
266 return false;
267 }
268
269 private boolean isNoTileAtZoom() {
270 if (attributes == null) {
271 LOG.warning("Cache attributes are null");
272 }
273 return attributes != null && attributes.isNoTileAtZoom();
274 }
275
276 private boolean tryLoadTileImage(CacheEntry object) throws IOException {
277 if (object != null) {
278 byte[] content = object.getContent();
279 if (content.length > 0) {
280 tile.loadImage(new ByteArrayInputStream(content));
281 if (tile.getImage() == null) {
282 tile.setError(tr("Could not load image from tile server"));
283 return false;
284 }
285 }
286 }
287 return true;
288 }
289}
Note: See TracBrowser for help on using the repository browser.