/
MapTileDownloader.java
393 lines (326 loc) · 13.1 KB
/
MapTileDownloader.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package org.osmdroid.tileprovider.modules;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import org.osmdroid.api.IMapView;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.BitmapPool;
import org.osmdroid.tileprovider.MapTileRequestState;
import org.osmdroid.tileprovider.constants.OpenStreetMapTileProviderConstants;
import org.osmdroid.tileprovider.tilesource.BitmapTileSourceBase.LowMemoryException;
import org.osmdroid.tileprovider.tilesource.ITileSource;
import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase;
import org.osmdroid.tileprovider.util.Counters;
import org.osmdroid.tileprovider.util.StreamUtils;
import org.osmdroid.util.MapTileIndex;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
/**
* The {@link MapTileDownloader} loads tiles from an HTTP server. It saves downloaded tiles to an
* IFilesystemCache if available.
*
* @author Marc Kurtz
* @author Nicolas Gramlich
* @author Manuel Stahl
*
*/
public class MapTileDownloader extends MapTileModuleProviderBase {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final IFilesystemCache mFilesystemCache;
private final AtomicReference<OnlineTileSourceBase> mTileSource = new AtomicReference<>();
private final INetworkAvailablityCheck mNetworkAvailablityCheck;
/**
* @since 6.0.2
*/
private final TileLoader mTileLoader = new TileLoader();
// ===========================================================
// Constructors
// ===========================================================
public MapTileDownloader(final ITileSource pTileSource) {
this(pTileSource, null, null);
}
public MapTileDownloader(final ITileSource pTileSource, final IFilesystemCache pFilesystemCache) {
this(pTileSource, pFilesystemCache, null);
}
public MapTileDownloader(final ITileSource pTileSource,
final IFilesystemCache pFilesystemCache,
final INetworkAvailablityCheck pNetworkAvailablityCheck) {
this(pTileSource, pFilesystemCache, pNetworkAvailablityCheck,
Configuration.getInstance().getTileDownloadThreads(),
Configuration.getInstance().getTileDownloadMaxQueueSize());
}
public MapTileDownloader(final ITileSource pTileSource,
final IFilesystemCache pFilesystemCache,
final INetworkAvailablityCheck pNetworkAvailablityCheck, int pThreadPoolSize,
int pPendingQueueSize) {
super(pThreadPoolSize, pPendingQueueSize);
mFilesystemCache = pFilesystemCache;
mNetworkAvailablityCheck = pNetworkAvailablityCheck;
setTileSource(pTileSource);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public ITileSource getTileSource() {
return mTileSource.get();
}
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
@Override
public boolean getUsesDataConnection() {
return true;
}
@Override
protected String getName() {
return "Online Tile Download Provider";
}
@Override
protected String getThreadGroupName() {
return "downloader";
}
@Override
public TileLoader getTileLoader() {
return mTileLoader;
}
@Override
public void detach() {
super.detach();
if (this.mFilesystemCache!=null)
this.mFilesystemCache.onDetach();
}
@Override
public int getMinimumZoomLevel() {
OnlineTileSourceBase tileSource = mTileSource.get();
return (tileSource != null ? tileSource.getMinimumZoomLevel() : OpenStreetMapTileProviderConstants.MINIMUM_ZOOMLEVEL);
}
@Override
public int getMaximumZoomLevel() {
OnlineTileSourceBase tileSource = mTileSource.get();
return (tileSource != null ? tileSource.getMaximumZoomLevel()
: org.osmdroid.util.TileSystem.getMaximumZoomLevel());
}
@Override
public void setTileSource(final ITileSource tileSource) {
// We are only interested in OnlineTileSourceBase tile sources
if (tileSource instanceof OnlineTileSourceBase) {
mTileSource.set((OnlineTileSourceBase) tileSource);
} else {
// Otherwise shut down the tile downloader
mTileSource.set(null);
}
}
/**
* @since 6.0.2
*/
private long computeExpirationTime(final String pHttpExpiresHeader) {
Long httpExpirationTime = null;
if (pHttpExpiresHeader != null && pHttpExpiresHeader.length() > 0) {
try {
final Date dateExpires = Configuration.getInstance().getHttpHeaderDateTimeFormat().parse(pHttpExpiresHeader);
httpExpirationTime = dateExpires.getTime();
} catch (final Exception ex) {
if (Configuration.getInstance().isDebugMapTileDownloader())
Log.d(IMapView.LOGTAG, "Unable to parse expiration tag for tile, using default, server returned " + pHttpExpiresHeader, ex);
}
}
return computeExpirationTime(httpExpirationTime);
}
/**
* @since 6.0.2
*/
protected long computeExpirationTime(final Long pHttpExpiresTime) {
final Long override=Configuration.getInstance().getExpirationOverrideDuration();
final long now = System.currentTimeMillis();
if (override != null) {
return now + override;
}
final long extension = Configuration.getInstance().getExpirationExtendedDuration();
if (pHttpExpiresTime != null) {
return pHttpExpiresTime + extension;
}
return now + OpenStreetMapTileProviderConstants.DEFAULT_MAXIMUM_CACHED_FILE_AGE + extension;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
protected class TileLoader extends MapTileModuleProviderBase.TileLoader {
/**
* downloads a tile and follows http redirects
* @param pMapTileIndex
* @param redirectCount
* @param targetUrl
* @return
* @throws CantContinueException
*/
protected Drawable downloadTile(final long pMapTileIndex, final int redirectCount, final String targetUrl) throws CantContinueException {
//prevent infinite looping of redirects, rare but very possible for misconfigured servers
if (redirectCount>3)
return null;
OnlineTileSourceBase tileSource = mTileSource.get();
if (tileSource == null) {
return null;
}
InputStream in = null;
OutputStream out = null;
HttpURLConnection c=null;
ByteArrayInputStream byteStream = null;
ByteArrayOutputStream dataStream = null;
try {
final String tileURLString = targetUrl;
if (Configuration.getInstance().isDebugMode()) {
Log.d(IMapView.LOGTAG,"Downloading Maptile from url: " + tileURLString);
}
if (TextUtils.isEmpty(tileURLString)) {
return null;
}
//TODO in the future, it may be necessary to allow app's using this library to override the SSL socket factory. It would here somewhere
if (Configuration.getInstance().getHttpProxy() != null) {
c = (HttpURLConnection) new URL(tileURLString).openConnection(Configuration.getInstance().getHttpProxy());
} else {
c = (HttpURLConnection) new URL(tileURLString).openConnection();
}
c.setUseCaches(true);
c.setRequestProperty(Configuration.getInstance().getUserAgentHttpHeader(),Configuration.getInstance().getUserAgentValue());
for (final Map.Entry<String, String> entry : Configuration.getInstance().getAdditionalHttpRequestProperties().entrySet()) {
c.setRequestProperty(entry.getKey(), entry.getValue());
}
c.connect();
// Check to see if we got success
if (c.getResponseCode() != 200) {
switch (c.getResponseCode()) {
case 301:
case 302:
case 307:
case 308:
if (Configuration.getInstance().isMapTileDownloaderFollowRedirects()) {
//this is a redirect, check the header for a 'Location' header
String redirectUrl = c.getHeaderField("Location");
if (redirectUrl != null) {
if (redirectUrl.startsWith("/")) {
//in this case we need to stitch together a full url
URL old = new URL(targetUrl);
int port = old.getPort();
boolean secure = targetUrl.toLowerCase().startsWith("https://");
if (port == -1)
if (targetUrl.toLowerCase().startsWith("http://")) {
port = 80;
} else {
port = 443;
}
redirectUrl = (secure ? "https://" : "http") + old.getHost() + ":" + port + redirectUrl;
}
Log.i(IMapView.LOGTAG, "Http redirect for MapTile: " + MapTileIndex.toString(pMapTileIndex) + " HTTP response: " + c.getResponseMessage() + " to url " + redirectUrl);
return downloadTile(pMapTileIndex, redirectCount + 1, redirectUrl);
}
break;
} //else follow through the normal path of aborting the download
default: {
Log.w(IMapView.LOGTAG, "Problem downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " HTTP response: " + c.getResponseMessage());
if (Configuration.getInstance().isDebugMapTileDownloader()) {
Log.d(IMapView.LOGTAG, tileURLString);
}
Counters.tileDownloadErrors++;
in = c.getErrorStream(); // in order to have the error stream purged by the finally block
return null;
}
}
}
String mime = c.getHeaderField("Content-Type");
if (Configuration.getInstance().isDebugMapTileDownloader()) {
Log.d(IMapView.LOGTAG, tileURLString + " success, mime is " + mime );
}
if (mime!=null && !mime.toLowerCase().contains("image")) {
Log.w(IMapView.LOGTAG, tileURLString + " success, however the mime type does not appear to be an image " + mime );
}
in = c.getInputStream();
dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, StreamUtils.IO_BUFFER_SIZE);
final long expirationTime = computeExpirationTime(
c.getHeaderField(OpenStreetMapTileProviderConstants.HTTP_EXPIRES_HEADER));
StreamUtils.copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
byteStream = new ByteArrayInputStream(data);
// Save the data to the cache
//this is the only point in which we insert tiles to the db or local file system.
if (mFilesystemCache != null) {
mFilesystemCache.saveFile(tileSource, pMapTileIndex, byteStream, expirationTime);
byteStream.reset();
}
return tileSource.getDrawable(byteStream);
} catch (final UnknownHostException e) {
Log.w(IMapView.LOGTAG,"UnknownHostException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
Counters.tileDownloadErrors++;
} catch (final LowMemoryException e) {
// low memory so empty the queue
Counters.countOOM++;
Log.w(IMapView.LOGTAG,"LowMemoryException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
throw new CantContinueException(e);
} catch (final FileNotFoundException e) {
Counters.tileDownloadErrors++;
Log.w(IMapView.LOGTAG,"Tile not found: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
} catch (final IOException e) {
Counters.tileDownloadErrors++;
Log.w(IMapView.LOGTAG,"IOException downloading MapTile: " + MapTileIndex.toString(pMapTileIndex) + " : " + e);
} catch (final Throwable e) {
Counters.tileDownloadErrors++;
Log.e(IMapView.LOGTAG,"Error downloading MapTile: " + MapTileIndex.toString(pMapTileIndex), e);
} finally {
StreamUtils.closeStream(in);
StreamUtils.closeStream(out);
StreamUtils.closeStream(byteStream);
StreamUtils.closeStream(dataStream);
try{
c.disconnect();
} catch (Exception ex){}
}
return null;
}
@Override
public Drawable loadTile(final long pMapTileIndex) throws CantContinueException {
OnlineTileSourceBase tileSource = mTileSource.get();
if (tileSource == null) {
return null;
}
if (mNetworkAvailablityCheck != null
&& !mNetworkAvailablityCheck.getNetworkAvailable()) {
if (Configuration.getInstance().isDebugMode()) {
Log.d(IMapView.LOGTAG, "Skipping " + getName() + " due to NetworkAvailabliltyCheck.");
}
return null;
}
final String tileURLString = tileSource.getTileURLString(pMapTileIndex);
if (TextUtils.isEmpty(tileURLString)) {
return null; //unlikely but just in case
}
return downloadTile(pMapTileIndex, 0, tileURLString);
}
@Override
protected void tileLoaded(final MapTileRequestState pState, final Drawable pDrawable) {
removeTileFromQueues(pState.getMapTile());
// don't return the tile because we'll wait for the fs provider to ask for it
// this prevent flickering when a load of delayed downloads complete for tiles
// that we might not even be interested in any more
pState.getCallback().mapTileRequestCompleted(pState, null);
// We want to return the Bitmap to the BitmapPool if applicable
BitmapPool.getInstance().asyncRecycle(pDrawable);
}
}
}