001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.imagery;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.IOException;
007import java.io.StringReader;
008import java.net.MalformedURLException;
009import java.net.URL;
010import java.nio.charset.StandardCharsets;
011import java.util.List;
012import java.util.Objects;
013import java.util.Timer;
014import java.util.TimerTask;
015import java.util.concurrent.Callable;
016import java.util.concurrent.CountDownLatch;
017import java.util.concurrent.TimeUnit;
018import java.util.concurrent.atomic.AtomicReference;
019
020import org.openstreetmap.gui.jmapviewer.tilesources.BingAerialTileSource;
021import org.openstreetmap.gui.jmapviewer.tilesources.TileSourceInfo;
022import org.openstreetmap.josm.gui.progress.ProgressMonitor;
023import org.openstreetmap.josm.gui.progress.swing.PleaseWaitProgressMonitor;
024import org.openstreetmap.josm.gui.util.GuiHelper;
025import org.openstreetmap.josm.io.CacheCustomContent;
026import org.openstreetmap.josm.io.NetworkManager;
027import org.openstreetmap.josm.tools.HttpClient;
028import org.openstreetmap.josm.tools.Logging;
029import org.xml.sax.InputSource;
030
031/**
032 * Bing TileSource with cached attribution
033 *
034 * @author Wiktor Niesiobędzki
035 * @since 8526
036 */
037public class CachedAttributionBingAerialTileSource extends BingAerialTileSource {
038    private Runnable attributionDownloadedTask;
039
040    /**
041     * Creates tile source
042     * @param info ImageryInfo description of this tile source
043     */
044    public CachedAttributionBingAerialTileSource(ImageryInfo info) {
045        this(info, null);
046    }
047
048    /**
049     * Creates tile source
050     * @param info ImageryInfo description of this tile source
051     * @param attributionDownloadedTask runnable to be executed once attribution is loaded
052     */
053
054    public CachedAttributionBingAerialTileSource(TileSourceInfo info, Runnable attributionDownloadedTask) {
055        super(info);
056        this.attributionDownloadedTask = attributionDownloadedTask;
057        // See #23227 and https://github.com/openstreetmap/iD/issues/9153#issuecomment-1781569820
058        // Of specific note:
059        // > Due to increased usage of Bing Maps imagery APIs, we decided to separate the free usage of the API
060        // > (for OSM editors) from the paid usage of the API.
061        // We aren't paying for access, so we should solely use the AerialOSM layer.
062        super.setLayer("AerialOSM");
063    }
064
065    class BingAttributionData extends CacheCustomContent<IOException> {
066
067        BingAttributionData() {
068            super("bing.attribution.xml", CacheCustomContent.INTERVAL_HOURLY);
069        }
070
071        @Override
072        protected byte[] updateData() throws IOException {
073            URL u = getAttributionUrl();
074            final String r = HttpClient.create(u).connect().fetchContent();
075            Logging.info("Successfully loaded Bing attribution data.");
076            return r.getBytes(StandardCharsets.UTF_8);
077        }
078
079        @Override
080        protected boolean isOffline() {
081            try {
082                return NetworkManager.isOffline(getAttributionUrl().toExternalForm());
083            } catch (MalformedURLException e) {
084                Logging.error(e);
085                return false;
086            }
087        }
088    }
089
090    @Override
091    protected Callable<List<Attribution>> getAttributionLoaderCallable() {
092        final AtomicReference<List<Attribution>> attributions = new AtomicReference<>();
093        final CountDownLatch finished = new CountDownLatch(1);
094        return () -> {
095            final PleaseWaitProgressMonitor monitor = new PleaseWaitProgressMonitor();
096            monitor.beginTask(tr("Attempting to fetch Bing attribution information"), ProgressMonitor.ALL_TICKS);
097            final Timer timer = new Timer(Thread.currentThread().getName() + "-timer", true);
098            timer.schedule(new AttributionTimerTask(monitor, timer, 1, attributions, finished), 0);
099            try {
100                while (!monitor.isCanceled() && !finished.await(1, TimeUnit.SECONDS)) {
101                    // Do nothing; we are waiting on the CountDownLatch to hit zero.
102                }
103            } finally {
104                monitor.finishTask();
105                monitor.close();
106            }
107            return attributions.get();
108        };
109    }
110
111    /**
112     * A timer task for fetching Bing attribution information
113     */
114    private class AttributionTimerTask extends TimerTask {
115        private final ProgressMonitor monitor;
116        private final Timer timer;
117        private final int waitTimeSec;
118        private final AtomicReference<List<Attribution>> attributions;
119        private final CountDownLatch finished;
120
121        /**
122         * Create a new task for fetching Bing attribution data
123         * @param monitor The monitor to update and use for cancellations
124         * @param timer The timer thread to add the next task to, if this task failed to fetch the attribution data
125         * @param waitTimeSec The time this task is waiting in seconds prior to execution
126         * @param attributions The reference to put attributions in
127         * @param finished Set to {@code true} when we have successfully fetched attributions <i>or</i> fetching has been cancelled.
128         */
129        AttributionTimerTask(ProgressMonitor monitor, Timer timer, int waitTimeSec,
130                             AtomicReference<List<Attribution>> attributions, CountDownLatch finished) {
131            this.monitor = monitor;
132            this.timer = timer;
133            this.waitTimeSec = waitTimeSec;
134            this.attributions = attributions;
135            this.finished = finished;
136        }
137
138        @Override
139        public void run() {
140            BingAttributionData attributionLoader = new BingAttributionData();
141            try {
142                String xml = attributionLoader.updateIfRequiredString();
143                Objects.requireNonNull(xml);
144                List<Attribution> ret;
145                try (StringReader sr = new StringReader(xml)) {
146                    ret = parseAttributionText(new InputSource(sr));
147                }
148                if (attributionDownloadedTask != null) {
149                    GuiHelper.runInEDT(attributionDownloadedTask);
150                    attributionDownloadedTask = null;
151                }
152                this.attributions.set(ret);
153                this.finished.countDown();
154            } catch (IOException ex) {
155                final String message = tr("Could not connect to Bing API. Will retry in {0} seconds.", waitTimeSec);
156                Logging.log(Logging.LEVEL_WARN, message, ex);
157                if (this.monitor.isCanceled()) {
158                    this.finished.countDown();
159                    return;
160                }
161                this.monitor.setCustomText(message);
162                this.monitor.worked(1);
163                final int newWaitTimeSec = 2 * this.waitTimeSec;
164                this.timer.schedule(new AttributionTimerTask(this.monitor, this.timer, newWaitTimeSec, this.attributions, this.finished),
165                        newWaitTimeSec * 1000L);
166            }
167        }
168    }
169}