001// License: GPL. For details, see Readme.txt file. 002package org.openstreetmap.gui.jmapviewer.tilesources; 003 004import java.awt.Image; 005import java.io.IOException; 006import java.io.InputStream; 007import java.net.MalformedURLException; 008import java.net.URL; 009import java.util.ArrayList; 010import java.util.List; 011import java.util.Locale; 012import java.util.concurrent.Callable; 013import java.util.concurrent.ExecutionException; 014import java.util.concurrent.Future; 015import java.util.concurrent.FutureTask; 016import java.util.concurrent.TimeUnit; 017import java.util.concurrent.TimeoutException; 018import java.util.regex.Pattern; 019 020import javax.imageio.ImageIO; 021import javax.xml.parsers.DocumentBuilder; 022import javax.xml.parsers.DocumentBuilderFactory; 023import javax.xml.parsers.ParserConfigurationException; 024import javax.xml.xpath.XPath; 025import javax.xml.xpath.XPathConstants; 026import javax.xml.xpath.XPathExpression; 027import javax.xml.xpath.XPathExpressionException; 028import javax.xml.xpath.XPathFactory; 029 030import org.openstreetmap.gui.jmapviewer.Coordinate; 031import org.openstreetmap.gui.jmapviewer.JMapViewer; 032import org.openstreetmap.gui.jmapviewer.interfaces.ICoordinate; 033import org.w3c.dom.Document; 034import org.w3c.dom.Node; 035import org.w3c.dom.NodeList; 036import org.xml.sax.InputSource; 037import org.xml.sax.SAXException; 038 039/** 040 * Tile source for the Bing Maps REST Imagery API. 041 * @see <a href="https://msdn.microsoft.com/en-us/library/ff701724.aspx">MSDN</a> 042 */ 043public class BingAerialTileSource extends TMSTileSource { 044 045 private static final String API_KEY = "Arzdiw4nlOJzRwOz__qailc8NiR31Tt51dN2D7cm57NrnceZnCpgOkmJhNpGoppU"; 046 private static volatile Future<List<Attribution>> attributions; // volatile is required for getAttribution(), see below. 047 private static String imageUrlTemplate; 048 private static Integer imageryZoomMax; 049 private static String[] subdomains; 050 051 private static final Pattern subdomainPattern = Pattern.compile("\\{subdomain\\}"); 052 private static final Pattern quadkeyPattern = Pattern.compile("\\{quadkey\\}"); 053 private static final Pattern culturePattern = Pattern.compile("\\{culture\\}"); 054 private String brandLogoUri; 055 056 /** 057 * Constructs a new {@code BingAerialTileSource}. 058 */ 059 public BingAerialTileSource() { 060 super(new TileSourceInfo("Bing", null, null)); 061 } 062 063 /** 064 * Constructs a new {@code BingAerialTileSource}. 065 * @param info imagery info 066 */ 067 public BingAerialTileSource(TileSourceInfo info) { 068 super(info); 069 } 070 071 protected static class Attribution { 072 private String attributionText; 073 private int minZoom; 074 private int maxZoom; 075 private Coordinate min; 076 private Coordinate max; 077 } 078 079 @Override 080 public String getTileUrl(int zoom, int tilex, int tiley) throws IOException { 081 // make sure that attribution is loaded. otherwise subdomains is null. 082 if (getAttribution() == null) 083 throw new IOException("Attribution is not loaded yet"); 084 085 int t = (zoom + tilex + tiley) % subdomains.length; 086 String subdomain = subdomains[t]; 087 088 String url = imageUrlTemplate; 089 url = subdomainPattern.matcher(url).replaceAll(subdomain); 090 url = quadkeyPattern.matcher(url).replaceAll(computeQuadTree(zoom, tilex, tiley)); 091 092 return url; 093 } 094 095 protected URL getAttributionUrl() throws MalformedURLException { 096 return new URL("https://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial?include=ImageryProviders&output=xml&key=" 097 + API_KEY); 098 } 099 100 protected List<Attribution> parseAttributionText(InputSource xml) throws IOException { 101 try { 102 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 103 DocumentBuilder builder = factory.newDocumentBuilder(); 104 Document document = builder.parse(xml); 105 106 XPathFactory xPathFactory = XPathFactory.newInstance(); 107 XPath xpath = xPathFactory.newXPath(); 108 imageUrlTemplate = xpath.compile("//ImageryMetadata/ImageUrl/text()").evaluate(document).replace( 109 "http://ecn.{subdomain}.tiles.virtualearth.net/", 110 "https://ecn.{subdomain}.tiles.virtualearth.net/"); 111 imageUrlTemplate = culturePattern.matcher(imageUrlTemplate).replaceAll(Locale.getDefault().toString()); 112 imageryZoomMax = Integer.valueOf(xpath.compile("//ImageryMetadata/ZoomMax/text()").evaluate(document)); 113 114 NodeList subdomainTxt = (NodeList) xpath.compile("//ImageryMetadata/ImageUrlSubdomains/string/text()") 115 .evaluate(document, XPathConstants.NODESET); 116 subdomains = new String[subdomainTxt.getLength()]; 117 for (int i = 0; i < subdomainTxt.getLength(); i++) { 118 subdomains[i] = subdomainTxt.item(i).getNodeValue(); 119 } 120 121 brandLogoUri = xpath.compile("/Response/BrandLogoUri/text()").evaluate(document); 122 123 XPathExpression attributionXpath = xpath.compile("Attribution/text()"); 124 XPathExpression coverageAreaXpath = xpath.compile("CoverageArea"); 125 XPathExpression zoomMinXpath = xpath.compile("ZoomMin/text()"); 126 XPathExpression zoomMaxXpath = xpath.compile("ZoomMax/text()"); 127 XPathExpression southLatXpath = xpath.compile("BoundingBox/SouthLatitude/text()"); 128 XPathExpression westLonXpath = xpath.compile("BoundingBox/WestLongitude/text()"); 129 XPathExpression northLatXpath = xpath.compile("BoundingBox/NorthLatitude/text()"); 130 XPathExpression eastLonXpath = xpath.compile("BoundingBox/EastLongitude/text()"); 131 132 NodeList imageryProviderNodes = (NodeList) xpath.compile("//ImageryMetadata/ImageryProvider") 133 .evaluate(document, XPathConstants.NODESET); 134 List<Attribution> attributionsList = new ArrayList<>(imageryProviderNodes.getLength()); 135 for (int i = 0; i < imageryProviderNodes.getLength(); i++) { 136 Node providerNode = imageryProviderNodes.item(i); 137 138 String attribution = attributionXpath.evaluate(providerNode); 139 140 NodeList coverageAreaNodes = (NodeList) coverageAreaXpath.evaluate(providerNode, XPathConstants.NODESET); 141 for (int j = 0; j < coverageAreaNodes.getLength(); j++) { 142 Node areaNode = coverageAreaNodes.item(j); 143 Attribution attr = new Attribution(); 144 attr.attributionText = attribution; 145 146 attr.maxZoom = Integer.parseInt(zoomMaxXpath.evaluate(areaNode)); 147 attr.minZoom = Integer.parseInt(zoomMinXpath.evaluate(areaNode)); 148 149 Double southLat = Double.valueOf(southLatXpath.evaluate(areaNode)); 150 Double northLat = Double.valueOf(northLatXpath.evaluate(areaNode)); 151 Double westLon = Double.valueOf(westLonXpath.evaluate(areaNode)); 152 Double eastLon = Double.valueOf(eastLonXpath.evaluate(areaNode)); 153 attr.min = new Coordinate(southLat, westLon); 154 attr.max = new Coordinate(northLat, eastLon); 155 156 attributionsList.add(attr); 157 } 158 } 159 160 return attributionsList; 161 } catch (SAXException e) { 162 System.err.println("Could not parse Bing aerials attribution metadata."); 163 e.printStackTrace(); 164 } catch (ParserConfigurationException | XPathExpressionException | NumberFormatException e) { 165 e.printStackTrace(); 166 } 167 return null; 168 } 169 170 @Override 171 public int getMaxZoom() { 172 if (imageryZoomMax != null) 173 return imageryZoomMax; 174 else 175 return 22; 176 } 177 178 @Override 179 public boolean requiresAttribution() { 180 return true; 181 } 182 183 @Override 184 public String getAttributionLinkURL() { 185 // Terms of Use URL to comply with Bing Terms of Use 186 // (the requirement is that we have such a link at the bottom of the window) 187 return "https://www.microsoft.com/maps/assets/docs/terms.aspx"; 188 } 189 190 @Override 191 public Image getAttributionImage() { 192 try { 193 final InputStream imageResource = JMapViewer.class.getResourceAsStream("images/bing_maps.png"); 194 if (imageResource != null) { 195 return ImageIO.read(imageResource); 196 } else { 197 // Some Linux distributions (like Debian) will remove Bing logo from sources, so get it at runtime 198 for (int i = 0; i < 5 && getAttribution() == null; i++) { 199 // Makes sure attribution is loaded 200 if (JMapViewer.debug) { 201 System.out.println("Bing attribution attempt " + (i+1)); 202 } 203 } 204 if (brandLogoUri != null && !brandLogoUri.isEmpty()) { 205 System.out.println("Reading Bing logo from "+brandLogoUri); 206 return ImageIO.read(new URL(brandLogoUri)); 207 } 208 } 209 } catch (IOException e) { 210 System.err.println("Error while retrieving Bing logo: "+e.getMessage()); 211 } 212 return null; 213 } 214 215 @Override 216 public String getAttributionImageURL() { 217 return "https://opengeodata.org/microsoft-imagery-details"; 218 } 219 220 @Override 221 public String getTermsOfUseText() { 222 return null; 223 } 224 225 @Override 226 public String getTermsOfUseURL() { 227 return "https://opengeodata.org/microsoft-imagery-details"; 228 } 229 230 protected Callable<List<Attribution>> getAttributionLoaderCallable() { 231 return new Callable<List<Attribution>>() { 232 233 @Override 234 public List<Attribution> call() throws Exception { 235 int waitTimeSec = 1; 236 while (true) { 237 try { 238 InputSource xml = new InputSource(getAttributionUrl().openStream()); 239 List<Attribution> r = parseAttributionText(xml); 240 System.out.println("Successfully loaded Bing attribution data."); 241 return r; 242 } catch (IOException ex) { 243 System.err.println("Could not connect to Bing API. Will retry in " + waitTimeSec + " seconds."); 244 Thread.sleep(TimeUnit.SECONDS.toMillis(waitTimeSec)); 245 waitTimeSec *= 2; 246 } 247 } 248 } 249 }; 250 } 251 252 protected List<Attribution> getAttribution() { 253 if (attributions == null) { 254 // see http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html 255 synchronized (BingAerialTileSource.class) { 256 if (attributions == null) { 257 final FutureTask<List<Attribution>> loader = new FutureTask<>(getAttributionLoaderCallable()); 258 new Thread(loader, "bing-attribution-loader").start(); 259 attributions = loader; 260 } 261 } 262 } 263 try { 264 return attributions.get(0, TimeUnit.MILLISECONDS); 265 } catch (TimeoutException ex) { 266 System.err.println("Bing: attribution data is not yet loaded."); 267 } catch (ExecutionException ex) { 268 throw new RuntimeException(ex.getCause()); 269 } catch (InterruptedException ign) { 270 System.err.println("InterruptedException: " + ign.getMessage()); 271 } 272 return null; 273 } 274 275 @Override 276 public String getAttributionText(int zoom, ICoordinate topLeft, ICoordinate botRight) { 277 try { 278 final List<Attribution> data = getAttribution(); 279 if (data == null) 280 return "Error loading Bing attribution data"; 281 StringBuilder a = new StringBuilder(); 282 for (Attribution attr : data) { 283 if (zoom <= attr.maxZoom && zoom >= attr.minZoom) { 284 if (topLeft.getLon() < attr.max.getLon() && botRight.getLon() > attr.min.getLon() 285 && topLeft.getLat() > attr.min.getLat() && botRight.getLat() < attr.max.getLat()) { 286 a.append(attr.attributionText); 287 a.append(' '); 288 } 289 } 290 } 291 return a.toString(); 292 } catch (RuntimeException e) { 293 e.printStackTrace(); 294 } 295 return "Error loading Bing attribution data"; 296 } 297 298 private static String computeQuadTree(int zoom, int tilex, int tiley) { 299 StringBuilder k = new StringBuilder(); 300 for (int i = zoom; i > 0; i--) { 301 char digit = 48; 302 int mask = 1 << (i - 1); 303 if ((tilex & mask) != 0) { 304 digit += (char) 1; 305 } 306 if ((tiley & mask) != 0) { 307 digit += (char) 2; 308 } 309 k.append(digit); 310 } 311 return k.toString(); 312 } 313}