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 e) {
165            e.printStackTrace();
166        } catch (XPathExpressionException e) {
167            e.printStackTrace();
168        }
169        return null;
170    }
171
172    @Override
173    public int getMaxZoom() {
174        if (imageryZoomMax != null)
175            return imageryZoomMax;
176        else
177            return 22;
178    }
179
180    @Override
181    public boolean requiresAttribution() {
182        return true;
183    }
184
185    @Override
186    public String getAttributionLinkURL() {
187        // Terms of Use URL to comply with Bing Terms of Use
188        // (the requirement is that we have such a link at the bottom of the window)
189        return "https://www.microsoft.com/maps/assets/docs/terms.aspx";
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(0, 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.attributionText);
289                        a.append(' ');
290                    }
291                }
292            }
293            return a.toString();
294        } catch (RuntimeException 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}