001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.IOException;
007import java.io.InputStream;
008import java.net.SocketException;
009import java.util.Collection;
010import java.util.Collections;
011import java.util.List;
012
013import org.openstreetmap.josm.data.Bounds;
014import org.openstreetmap.josm.data.DataSource;
015import org.openstreetmap.josm.data.gpx.GpxData;
016import org.openstreetmap.josm.data.gpx.IGpxTrack;
017import org.openstreetmap.josm.data.notes.Note;
018import org.openstreetmap.josm.data.osm.DataSet;
019import org.openstreetmap.josm.data.osm.RelationMember;
020import org.openstreetmap.josm.gui.progress.ProgressMonitor;
021import org.openstreetmap.josm.spi.preferences.Config;
022import org.openstreetmap.josm.tools.CheckParameterUtil;
023import org.openstreetmap.josm.tools.JosmRuntimeException;
024import org.openstreetmap.josm.tools.Logging;
025import org.openstreetmap.josm.tools.Utils;
026import org.xml.sax.SAXException;
027
028/**
029 * Read content from OSM server for a given bounding box
030 * @since 627
031 */
032public class BoundingBoxDownloader extends OsmServerReader {
033
034    /**
035     * The boundings of the desired map data.
036     */
037    protected final double lat1;
038    protected final double lon1;
039    protected final double lat2;
040    protected final double lon2;
041    protected final boolean crosses180th;
042
043    /**
044     * Constructs a new {@code BoundingBoxDownloader}.
045     * @param downloadArea The area to download
046     */
047    public BoundingBoxDownloader(Bounds downloadArea) {
048        CheckParameterUtil.ensureParameterNotNull(downloadArea, "downloadArea");
049        this.lat1 = downloadArea.getMinLat();
050        this.lon1 = downloadArea.getMinLon();
051        this.lat2 = downloadArea.getMaxLat();
052        this.lon2 = downloadArea.getMaxLon();
053        this.crosses180th = downloadArea.crosses180thMeridian();
054    }
055
056    private GpxData downloadRawGps(Bounds b, ProgressMonitor progressMonitor) throws IOException, OsmTransferException, SAXException {
057        boolean done = false;
058        GpxData result = null;
059        final int pointsPerPage = 5000; // see https://wiki.openstreetmap.org/wiki/API_v0.6#GPS_traces
060        final String url = getBaseUrl() + "trackpoints?bbox="+b.getMinLon()+','+b.getMinLat()+','+b.getMaxLon()+','+b.getMaxLat()+"&page=";
061        for (int i = 0; !done && !isCanceled(); ++i) {
062            progressMonitor.subTask(tr("Downloading points {0} to {1}...", i * pointsPerPage, (i + 1) * pointsPerPage));
063            try (InputStream in = getInputStream(url+i, progressMonitor.createSubTaskMonitor(1, true))) {
064                if (in == null) {
065                    break;
066                }
067                progressMonitor.setTicks(0);
068                GpxReader reader = new GpxReader(in);
069                gpxParsedProperly = reader.parse(false);
070                GpxData currentGpx = reader.getGpxData();
071
072                // #21538 - Apparently track URLs are no longer complete URLs, but only paths
073                // We'll prefix the browse URL to get something to navigate to again.
074                final String browseUrl = Config.getUrls().getBaseBrowseUrl();
075                for (IGpxTrack track : currentGpx.tracks) {
076                    Object trackUrl = track.get("url");
077                    if (trackUrl instanceof String) {
078                        String sTrackUrl = (String) trackUrl;
079                        if (!Utils.isStripEmpty(sTrackUrl) && !sTrackUrl.startsWith("http")) {
080                            track.put("url", browseUrl + sTrackUrl);
081                        }
082                    }
083                }
084
085                long count = 0;
086                if (currentGpx.hasTrackPoints()) {
087                    count = currentGpx.getTrackPoints().count();
088                }
089                if (count < pointsPerPage)
090                    done = true;
091                Logging.debug("got {0} gpx points", count);
092                if (result == null) {
093                    result = currentGpx;
094                } else {
095                    result.mergeFrom(currentGpx);
096                }
097            } catch (OsmApiException ex) {
098                throw ex; // this avoids infinite loop in case of API error such as bad request (ex: bbox too large, see #12853)
099            } catch (OsmTransferException | SocketException ex) {
100                if (isCanceled()) {
101                    final OsmTransferCanceledException canceledException = new OsmTransferCanceledException("Operation canceled");
102                    canceledException.initCause(ex);
103                    Logging.warn(canceledException);
104                }
105            }
106            activeConnection = null;
107        }
108        if (result != null) {
109            result.fromServer = true;
110            result.dataSources.add(new DataSource(b, "OpenStreetMap server"));
111        }
112        return result;
113    }
114
115    @Override
116    public GpxData parseRawGps(ProgressMonitor progressMonitor) throws OsmTransferException {
117        progressMonitor.beginTask("", 1);
118        try {
119            progressMonitor.indeterminateSubTask(getTaskName());
120            if (crosses180th) {
121                // API 0.6 does not support requests crossing the 180th meridian, so make two requests
122                GpxData result = downloadRawGps(new Bounds(lat1, lon1, lat2, 180.0), progressMonitor);
123                if (result != null)
124                    result.mergeFrom(downloadRawGps(new Bounds(lat1, -180.0, lat2, lon2), progressMonitor));
125                return result;
126            } else {
127                // Simple request
128                return downloadRawGps(new Bounds(lat1, lon1, lat2, lon2), progressMonitor);
129            }
130        } catch (IllegalArgumentException e) {
131            // caused by HttpUrlConnection in case of illegal stuff in the response
132            if (cancel)
133                return null;
134            throw new OsmTransferException("Illegal characters within the HTTP-header response.", e);
135        } catch (IOException e) {
136            if (cancel)
137                return null;
138            throw new OsmTransferException(e);
139        } catch (SAXException e) {
140            throw new OsmTransferException(e);
141        } catch (OsmTransferException e) {
142            throw e;
143        } catch (JosmRuntimeException | IllegalStateException e) {
144            if (cancel)
145                return null;
146            throw e;
147        } finally {
148            progressMonitor.finishTask();
149        }
150    }
151
152    /**
153     * Returns the name of the download task to be displayed in the {@link ProgressMonitor}.
154     * @return task name
155     */
156    protected String getTaskName() {
157        return tr("Contacting OSM Server...");
158    }
159
160    /**
161     * Builds the request part for the bounding box.
162     * @param lon1 left
163     * @param lat1 bottom
164     * @param lon2 right
165     * @param lat2 top
166     * @return "map?bbox=left,bottom,right,top"
167     */
168    protected String getRequestForBbox(double lon1, double lat1, double lon2, double lat2) {
169        return "map?bbox=" + lon1 + ',' + lat1 + ',' + lon2 + ',' + lat2;
170    }
171
172    /**
173     * Parse the given input source and return the dataset.
174     * @param source input stream
175     * @param progressMonitor progress monitor
176     * @return dataset
177     * @throws IllegalDataException if an error was found while parsing the OSM data
178     *
179     * @see OsmReader#parseDataSet(InputStream, ProgressMonitor)
180     */
181    protected DataSet parseDataSet(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {
182        return OsmReader.parseDataSet(source, progressMonitor);
183    }
184
185    @Override
186    public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException {
187        progressMonitor.beginTask(getTaskName(), 10);
188        try {
189            DataSet ds = null;
190            progressMonitor.indeterminateSubTask(null);
191            if (crosses180th) {
192                // API 0.6 does not support requests crossing the 180th meridian, so make two requests
193                DataSet ds2 = null;
194
195                try (InputStream in = getInputStream(getRequestForBbox(lon1, lat1, 180.0, lat2),
196                        progressMonitor.createSubTaskMonitor(9, false))) {
197                    if (in == null)
198                        return null;
199                    ds = parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
200                }
201
202                try (InputStream in = getInputStream(getRequestForBbox(-180.0, lat1, lon2, lat2),
203                        progressMonitor.createSubTaskMonitor(9, false))) {
204                    if (in == null)
205                        return null;
206                    ds2 = parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
207                }
208                if (ds2 == null)
209                    return null;
210                ds.mergeFrom(ds2);
211
212            } else {
213                // Simple request
214                try (InputStream in = getInputStream(getRequestForBbox(lon1, lat1, lon2, lat2),
215                        progressMonitor.createSubTaskMonitor(9, false))) {
216                    if (in == null)
217                        return null;
218                    ds = parseDataSet(in, progressMonitor.createSubTaskMonitor(1, false));
219                }
220            }
221            // From https://wiki.openstreetmap.org/wiki/API_v0.6#Retrieving_map_data_by_bounding_box:_GET_/api/0.6/map,
222            // relations are not recursed up, so they *may* have parent relations.
223            // Nodes inside the download area should have all relations and ways that refer to them.
224            // Ways should have all relations that refer to them and all child nodes, but those child nodes may not
225            //    have their parent referrers.
226            // Relations will have the *first* parent relations downloaded, but those are not split out in the returns.
227            // So we always assume that a relation has referrers that need to be downloaded unless it has no child relations.
228            // Our "full" overpass query doesn't return the same data as a standard download, so we cannot
229            // mark relations with no child relations as fully downloaded *yet*.
230            if (this.considerAsFullDownload()) {
231                final Collection<Bounds> bounds = this.getBounds();
232                // We cannot use OsmPrimitive#isOutsideDownloadArea yet since some download methods haven't added
233                // the download bounds to the dataset yet. This is specifically the case for overpass downloads.
234                ds.getNodes().stream().filter(n -> bounds.stream().anyMatch(b -> b.contains(n)))
235                        .forEach(i -> i.setReferrersDownloaded(true));
236                ds.getWays().forEach(i -> i.setReferrersDownloaded(true));
237                ds.getRelations().stream().filter(r -> r.getMembers().stream().noneMatch(RelationMember::isRelation))
238                        .forEach(i -> i.setReferrersDownloaded(true));
239            }
240            return ds;
241        } catch (OsmTransferException e) {
242            throw e;
243        } catch (IllegalDataException | IOException e) {
244            throw new OsmTransferException(e);
245        } finally {
246            progressMonitor.finishTask();
247            activeConnection = null;
248        }
249    }
250
251    @Override
252    public List<Note> parseNotes(int noteLimit, int daysClosed, ProgressMonitor progressMonitor) throws OsmTransferException {
253        progressMonitor.beginTask(tr("Downloading notes"));
254        CheckParameterUtil.ensureThat(noteLimit > 0, "Requested note limit is less than 1.");
255        // see result_limit in https://github.com/openstreetmap/openstreetmap-website/blob/master/app/controllers/notes_controller.rb
256        CheckParameterUtil.ensureThat(noteLimit <= 10_000, "Requested note limit is over API hard limit of 10000.");
257        CheckParameterUtil.ensureThat(daysClosed >= -1, "Requested note limit is less than -1.");
258        String url = "notes?limit=" + noteLimit + "&closed=" + daysClosed + "&bbox=" + lon1 + ',' + lat1 + ',' + lon2 + ',' + lat2;
259        try (InputStream is = getInputStream(url, progressMonitor.createSubTaskMonitor(1, false))) {
260            final List<Note> notes = new NoteReader(is).parse();
261            if (notes.size() == noteLimit) {
262                throw new MoreNotesException(notes, noteLimit);
263            }
264            return notes;
265        } catch (IOException | SAXException e) {
266            throw new OsmTransferException(e);
267        } finally {
268            progressMonitor.finishTask();
269        }
270    }
271
272    /**
273     * Indicates that the number of fetched notes equals the specified limit. Thus there might be more notes to download.
274     */
275    public static class MoreNotesException extends RuntimeException {
276        /**
277         * The downloaded notes
278         */
279        public final transient List<Note> notes;
280        /**
281         * The download limit sent to the server.
282         */
283        public final int limit;
284
285        /**
286         * Constructs a {@code MoreNotesException}.
287         * @param notes downloaded notes
288         * @param limit download limit sent to the server
289         */
290        public MoreNotesException(List<Note> notes, int limit) {
291            this.notes = notes;
292            this.limit = limit;
293        }
294    }
295
296    /**
297     * Determines if download is complete for the given bounding box.
298     * @return true if download is complete for the given bounding box (not filtered)
299     */
300    public boolean considerAsFullDownload() {
301        return true;
302    }
303
304    /**
305     * Get the bounds for this downloader
306     * @return The bounds for this downloader
307     * @since 19078
308     */
309    protected Collection<Bounds> getBounds() {
310        return Collections.singleton(new Bounds(this.lat1, this.lon1, this.lat2, this.lon2));
311    }
312}