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