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

Last change on this file since 31432 was 31432, checked in by donvip, 9 years ago

proper JOSM/JMapViewer integration

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