source: osm/applications/viewer/jmapviewer/src/org/openstreetmap/gui/jmapviewer/tilesources/BingAerialTileSource.java@ 34760

Last change on this file since 34760 was 34760, checked in by donvip, 6 years ago

see #josm16937 - make sure images are loaded using JOSM bullet-proof engine

  • Property svn:eol-style set to native
File size: 12.7 KB
Line 
1// License: GPL. For details, see Readme.txt file.
2package org.openstreetmap.gui.jmapviewer.tilesources;
3
4import java.awt.Image;
5import java.io.IOException;
6import java.net.MalformedURLException;
7import java.net.URL;
8import java.util.ArrayList;
9import java.util.List;
10import java.util.Locale;
11import java.util.concurrent.Callable;
12import java.util.concurrent.ExecutionException;
13import java.util.concurrent.Future;
14import java.util.concurrent.FutureTask;
15import java.util.concurrent.TimeUnit;
16import java.util.concurrent.TimeoutException;
17import java.util.regex.Pattern;
18
19import javax.xml.parsers.DocumentBuilder;
20import javax.xml.parsers.DocumentBuilderFactory;
21import javax.xml.parsers.ParserConfigurationException;
22import javax.xml.xpath.XPath;
23import javax.xml.xpath.XPathConstants;
24import javax.xml.xpath.XPathExpression;
25import javax.xml.xpath.XPathExpressionException;
26import javax.xml.xpath.XPathFactory;
27
28import org.openstreetmap.gui.jmapviewer.Coordinate;
29import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
30import org.openstreetmap.gui.jmapviewer.JMapViewer;
31import org.openstreetmap.gui.jmapviewer.interfaces.ICoordinate;
32import org.w3c.dom.Document;
33import org.w3c.dom.Node;
34import org.w3c.dom.NodeList;
35import org.xml.sax.InputSource;
36import org.xml.sax.SAXException;
37
38/**
39 * Tile source for the Bing Maps REST Imagery API.
40 * @see <a href="https://msdn.microsoft.com/en-us/library/ff701724.aspx">MSDN</a>
41 */
42public class BingAerialTileSource extends TMSTileSource {
43
44 private static final String API_KEY = "Arzdiw4nlOJzRwOz__qailc8NiR31Tt51dN2D7cm57NrnceZnCpgOkmJhNpGoppU";
45 private static volatile Future<List<Attribution>> attributions; // volatile is required for getAttribution(), see below.
46 private static String imageUrlTemplate;
47 private static Integer imageryZoomMax;
48 private static String[] subdomains;
49
50 private static final Pattern subdomainPattern = Pattern.compile("\\{subdomain\\}");
51 private static final Pattern quadkeyPattern = Pattern.compile("\\{quadkey\\}");
52 private static final Pattern culturePattern = Pattern.compile("\\{culture\\}");
53 private String brandLogoUri;
54
55 /**
56 * Constructs a new {@code BingAerialTileSource}.
57 */
58 public BingAerialTileSource() {
59 super(new TileSourceInfo("Bing", null, null));
60 }
61
62 /**
63 * Constructs a new {@code BingAerialTileSource}.
64 * @param info imagery info
65 */
66 public BingAerialTileSource(TileSourceInfo info) {
67 super(info);
68 }
69
70 protected static class Attribution {
71 private String attributionText;
72 private int minZoom;
73 private int maxZoom;
74 private Coordinate min;
75 private Coordinate max;
76 }
77
78 @Override
79 public String getTileUrl(int zoom, int tilex, int tiley) throws IOException {
80 // make sure that attribution is loaded. otherwise subdomains is null.
81 if (getAttribution() == null)
82 throw new IOException("Attribution is not loaded yet");
83
84 int t = (zoom + tilex + tiley) % subdomains.length;
85 String subdomain = subdomains[t];
86
87 String url = imageUrlTemplate;
88 url = subdomainPattern.matcher(url).replaceAll(subdomain);
89 url = quadkeyPattern.matcher(url).replaceAll(computeQuadTree(zoom, tilex, tiley));
90
91 return url;
92 }
93
94 protected URL getAttributionUrl() throws MalformedURLException {
95 return new URL("https://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial?include=ImageryProviders&output=xml&key="
96 + API_KEY);
97 }
98
99 protected List<Attribution> parseAttributionText(InputSource xml) throws IOException {
100 try {
101 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
102 DocumentBuilder builder = factory.newDocumentBuilder();
103 Document document = builder.parse(xml);
104
105 XPathFactory xPathFactory = XPathFactory.newInstance();
106 XPath xpath = xPathFactory.newXPath();
107 imageUrlTemplate = xpath.compile("//ImageryMetadata/ImageUrl/text()").evaluate(document).replace(
108 "http://ecn.{subdomain}.tiles.virtualearth.net/",
109 "https://ecn.{subdomain}.tiles.virtualearth.net/");
110 imageUrlTemplate = culturePattern.matcher(imageUrlTemplate).replaceAll(Locale.getDefault().toString());
111 imageryZoomMax = Integer.valueOf(xpath.compile("//ImageryMetadata/ZoomMax/text()").evaluate(document));
112
113 NodeList subdomainTxt = (NodeList) xpath.compile("//ImageryMetadata/ImageUrlSubdomains/string/text()")
114 .evaluate(document, XPathConstants.NODESET);
115 subdomains = new String[subdomainTxt.getLength()];
116 for (int i = 0; i < subdomainTxt.getLength(); i++) {
117 subdomains[i] = subdomainTxt.item(i).getNodeValue();
118 }
119
120 brandLogoUri = xpath.compile("/Response/BrandLogoUri/text()").evaluate(document);
121
122 XPathExpression attributionXpath = xpath.compile("Attribution/text()");
123 XPathExpression coverageAreaXpath = xpath.compile("CoverageArea");
124 XPathExpression zoomMinXpath = xpath.compile("ZoomMin/text()");
125 XPathExpression zoomMaxXpath = xpath.compile("ZoomMax/text()");
126 XPathExpression southLatXpath = xpath.compile("BoundingBox/SouthLatitude/text()");
127 XPathExpression westLonXpath = xpath.compile("BoundingBox/WestLongitude/text()");
128 XPathExpression northLatXpath = xpath.compile("BoundingBox/NorthLatitude/text()");
129 XPathExpression eastLonXpath = xpath.compile("BoundingBox/EastLongitude/text()");
130
131 NodeList imageryProviderNodes = (NodeList) xpath.compile("//ImageryMetadata/ImageryProvider")
132 .evaluate(document, XPathConstants.NODESET);
133 List<Attribution> attributionsList = new ArrayList<>(imageryProviderNodes.getLength());
134 for (int i = 0; i < imageryProviderNodes.getLength(); i++) {
135 Node providerNode = imageryProviderNodes.item(i);
136
137 String attribution = attributionXpath.evaluate(providerNode);
138
139 NodeList coverageAreaNodes = (NodeList) coverageAreaXpath.evaluate(providerNode, XPathConstants.NODESET);
140 for (int j = 0; j < coverageAreaNodes.getLength(); j++) {
141 Node areaNode = coverageAreaNodes.item(j);
142 Attribution attr = new Attribution();
143 attr.attributionText = attribution;
144
145 attr.maxZoom = Integer.parseInt(zoomMaxXpath.evaluate(areaNode));
146 attr.minZoom = Integer.parseInt(zoomMinXpath.evaluate(areaNode));
147
148 Double southLat = Double.valueOf(southLatXpath.evaluate(areaNode));
149 Double northLat = Double.valueOf(northLatXpath.evaluate(areaNode));
150 Double westLon = Double.valueOf(westLonXpath.evaluate(areaNode));
151 Double eastLon = Double.valueOf(eastLonXpath.evaluate(areaNode));
152 attr.min = new Coordinate(southLat, westLon);
153 attr.max = new Coordinate(northLat, eastLon);
154
155 attributionsList.add(attr);
156 }
157 }
158
159 return attributionsList;
160 } catch (SAXException e) {
161 System.err.println("Could not parse Bing aerials attribution metadata.");
162 e.printStackTrace();
163 } catch (ParserConfigurationException | XPathExpressionException | NumberFormatException e) {
164 e.printStackTrace();
165 }
166 return null;
167 }
168
169 @Override
170 public int getMaxZoom() {
171 if (imageryZoomMax != null)
172 return imageryZoomMax;
173 else
174 return 22;
175 }
176
177 @Override
178 public boolean requiresAttribution() {
179 return true;
180 }
181
182 @Override
183 public String getAttributionLinkURL() {
184 // Terms of Use URL to comply with Bing Terms of Use
185 // (the requirement is that we have such a link at the bottom of the window)
186 return "https://www.microsoft.com/maps/assets/docs/terms.aspx";
187 }
188
189 @Override
190 public Image getAttributionImage() {
191 try {
192 final URL imageResource = JMapViewer.class.getResource("images/bing_maps.png");
193 if (imageResource != null) {
194 return FeatureAdapter.readImage(imageResource);
195 } else {
196 // Some Linux distributions (like Debian) will remove Bing logo from sources, so get it at runtime
197 for (int i = 0; i < 5 && getAttribution() == null; i++) {
198 // Makes sure attribution is loaded
199 if (JMapViewer.debug) {
200 System.out.println("Bing attribution attempt " + (i+1));
201 }
202 }
203 if (brandLogoUri != null && !brandLogoUri.isEmpty()) {
204 System.out.println("Reading Bing logo from "+brandLogoUri);
205 return FeatureAdapter.readImage(new URL(brandLogoUri));
206 }
207 }
208 } catch (IOException e) {
209 System.err.println("Error while retrieving Bing logo: "+e.getMessage());
210 }
211 return null;
212 }
213
214 @Override
215 public String getAttributionImageURL() {
216 return "https://opengeodata.org/microsoft-imagery-details";
217 }
218
219 @Override
220 public String getTermsOfUseText() {
221 return null;
222 }
223
224 @Override
225 public String getTermsOfUseURL() {
226 return "https://opengeodata.org/microsoft-imagery-details";
227 }
228
229 protected Callable<List<Attribution>> getAttributionLoaderCallable() {
230 return new Callable<List<Attribution>>() {
231
232 @Override
233 public List<Attribution> call() throws Exception {
234 int waitTimeSec = 1;
235 while (true) {
236 try {
237 InputSource xml = new InputSource(getAttributionUrl().openStream());
238 List<Attribution> r = parseAttributionText(xml);
239 System.out.println("Successfully loaded Bing attribution data.");
240 return r;
241 } catch (IOException ex) {
242 System.err.println("Could not connect to Bing API. Will retry in " + waitTimeSec + " seconds.");
243 Thread.sleep(TimeUnit.SECONDS.toMillis(waitTimeSec));
244 waitTimeSec *= 2;
245 }
246 }
247 }
248 };
249 }
250
251 protected List<Attribution> getAttribution() {
252 if (attributions == null) {
253 // see http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
254 synchronized (BingAerialTileSource.class) {
255 if (attributions == null) {
256 final FutureTask<List<Attribution>> loader = new FutureTask<>(getAttributionLoaderCallable());
257 new Thread(loader, "bing-attribution-loader").start();
258 attributions = loader;
259 }
260 }
261 }
262 try {
263 return attributions.get(0, TimeUnit.MILLISECONDS);
264 } catch (TimeoutException ex) {
265 System.err.println("Bing: attribution data is not yet loaded.");
266 } catch (ExecutionException ex) {
267 throw new RuntimeException(ex.getCause());
268 } catch (InterruptedException ign) {
269 System.err.println("InterruptedException: " + ign.getMessage());
270 }
271 return null;
272 }
273
274 @Override
275 public String getAttributionText(int zoom, ICoordinate topLeft, ICoordinate botRight) {
276 try {
277 final List<Attribution> data = getAttribution();
278 if (data == null)
279 return "Error loading Bing attribution data";
280 StringBuilder a = new StringBuilder();
281 for (Attribution attr : data) {
282 if (zoom <= attr.maxZoom && zoom >= attr.minZoom) {
283 if (topLeft.getLon() < attr.max.getLon() && botRight.getLon() > attr.min.getLon()
284 && topLeft.getLat() > attr.min.getLat() && botRight.getLat() < attr.max.getLat()) {
285 a.append(attr.attributionText);
286 a.append(' ');
287 }
288 }
289 }
290 return a.toString();
291 } catch (RuntimeException e) {
292 e.printStackTrace();
293 }
294 return "Error loading Bing attribution data";
295 }
296
297 private static String computeQuadTree(int zoom, int tilex, int tiley) {
298 StringBuilder k = new StringBuilder();
299 for (int i = zoom; i > 0; i--) {
300 char digit = 48;
301 int mask = 1 << (i - 1);
302 if ((tilex & mask) != 0) {
303 digit += (char) 1;
304 }
305 if ((tiley & mask) != 0) {
306 digit += (char) 2;
307 }
308 k.append(digit);
309 }
310 return k.toString();
311 }
312}
Note: See TracBrowser for help on using the repository browser.