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