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
039public class BingAerialTileSource extends AbstractTMSTileSource {
040
041    private static final String API_KEY = "Arzdiw4nlOJzRwOz__qailc8NiR31Tt51dN2D7cm57NrnceZnCpgOkmJhNpGoppU";
042    private static volatile Future<List<Attribution>> attributions; // volatile is required for getAttribution(), see below.
043    private static String imageUrlTemplate;
044    private static Integer imageryZoomMax;
045    private static String[] subdomains;
046
047    private static final Pattern subdomainPattern = Pattern.compile("\\{subdomain\\}");
048    private static final Pattern quadkeyPattern = Pattern.compile("\\{quadkey\\}");
049    private static final Pattern culturePattern = Pattern.compile("\\{culture\\}");
050    private String brandLogoUri;
051
052    /**
053     * Constructs a new {@code BingAerialTileSource}.
054     */
055    public BingAerialTileSource() {
056        super(new TileSourceInfo("Bing", null, null));
057    }
058
059    /**
060     * Constructs a new {@code BingAerialTileSource}.
061     * @param info imagery info
062     */
063    public BingAerialTileSource(TileSourceInfo info) {
064        super(info);
065    }
066
067    protected static class Attribution {
068        private String attribution;
069        private int minZoom;
070        private int maxZoom;
071        private Coordinate min;
072        private Coordinate max;
073    }
074
075    @Override
076    public String getTileUrl(int zoom, int tilex, int tiley) throws IOException {
077        // make sure that attribution is loaded. otherwise subdomains is null.
078        if (getAttribution() == null)
079            throw new IOException("Attribution is not loaded yet");
080
081        int t = (zoom + tilex + tiley) % subdomains.length;
082        String subdomain = subdomains[t];
083
084        String url = imageUrlTemplate;
085        url = subdomainPattern.matcher(url).replaceAll(subdomain);
086        url = quadkeyPattern.matcher(url).replaceAll(computeQuadTree(zoom, tilex, tiley));
087
088        return url;
089    }
090
091    protected URL getAttributionUrl() throws MalformedURLException {
092        return new URL("https://dev.virtualearth.net/REST/v1/Imagery/Metadata/Aerial?include=ImageryProviders&output=xml&key="
093                + API_KEY);
094    }
095
096    protected List<Attribution> parseAttributionText(InputSource xml) throws IOException {
097        try {
098            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
099            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 = imageUrlTemplate.replace(
106                    "http://ecn.{subdomain}.tiles.virtualearth.net/",
107                    "https://ecn.{subdomain}.tiles.virtualearth.net/");
108            imageUrlTemplate = culturePattern.matcher(imageUrlTemplate).replaceAll(Locale.getDefault().toString());
109            imageryZoomMax = Integer.valueOf(xpath.compile("//ImageryMetadata/ZoomMax/text()").evaluate(document));
110
111            NodeList subdomainTxt = (NodeList) xpath.compile("//ImageryMetadata/ImageUrlSubdomains/string/text()")
112                    .evaluate(document, XPathConstants.NODESET);
113            subdomains = new String[subdomainTxt.getLength()];
114            for (int i = 0; i < subdomainTxt.getLength(); i++) {
115                subdomains[i] = subdomainTxt.item(i).getNodeValue();
116            }
117
118            brandLogoUri = xpath.compile("/Response/BrandLogoUri/text()").evaluate(document);
119
120            XPathExpression attributionXpath = xpath.compile("Attribution/text()");
121            XPathExpression coverageAreaXpath = xpath.compile("CoverageArea");
122            XPathExpression zoomMinXpath = xpath.compile("ZoomMin/text()");
123            XPathExpression zoomMaxXpath = xpath.compile("ZoomMax/text()");
124            XPathExpression southLatXpath = xpath.compile("BoundingBox/SouthLatitude/text()");
125            XPathExpression westLonXpath = xpath.compile("BoundingBox/WestLongitude/text()");
126            XPathExpression northLatXpath = xpath.compile("BoundingBox/NorthLatitude/text()");
127            XPathExpression eastLonXpath = xpath.compile("BoundingBox/EastLongitude/text()");
128
129            NodeList imageryProviderNodes = (NodeList) xpath.compile("//ImageryMetadata/ImageryProvider")
130                    .evaluate(document, XPathConstants.NODESET);
131            List<Attribution> attributions = new ArrayList<>(imageryProviderNodes.getLength());
132            for (int i = 0; i < imageryProviderNodes.getLength(); i++) {
133                Node providerNode = imageryProviderNodes.item(i);
134
135                String attribution = attributionXpath.evaluate(providerNode);
136
137                NodeList coverageAreaNodes = (NodeList) coverageAreaXpath.evaluate(providerNode, XPathConstants.NODESET);
138                for (int j = 0; j < coverageAreaNodes.getLength(); j++) {
139                    Node areaNode = coverageAreaNodes.item(j);
140                    Attribution attr = new Attribution();
141                    attr.attribution = attribution;
142
143                    attr.maxZoom = Integer.parseInt(zoomMaxXpath.evaluate(areaNode));
144                    attr.minZoom = Integer.parseInt(zoomMinXpath.evaluate(areaNode));
145
146                    Double southLat = Double.valueOf(southLatXpath.evaluate(areaNode));
147                    Double northLat = Double.valueOf(northLatXpath.evaluate(areaNode));
148                    Double westLon = Double.valueOf(westLonXpath.evaluate(areaNode));
149                    Double eastLon = Double.valueOf(eastLonXpath.evaluate(areaNode));
150                    attr.min = new Coordinate(southLat, westLon);
151                    attr.max = new Coordinate(northLat, eastLon);
152
153                    attributions.add(attr);
154                }
155            }
156
157            return attributions;
158        } catch (SAXException e) {
159            System.err.println("Could not parse Bing aerials attribution metadata.");
160            e.printStackTrace();
161        } catch (ParserConfigurationException e) {
162            e.printStackTrace();
163        } catch (XPathExpressionException 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        //return "http://bing.com/maps"
185        // FIXME: I've set attributionLinkURL temporarily to ToU URL to comply with bing ToU
186        // (the requirement is that we have such a link at the bottom of the window)
187        return "http://go.microsoft.com/?linkid=9710837";
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 "http://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 "http://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(waitTimeSec * 1000L);
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.attribution);
287                        a.append(' ');
288                    }
289                }
290            }
291            return a.toString();
292        } catch (Exception 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 += 1;
305            }
306            if ((tiley & mask) != 0) {
307                digit += 2;
308            }
309            k.append(digit);
310        }
311        return k.toString();
312    }
313}