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.Authenticator.RequestorType;
009import java.net.HttpURLConnection;
010import java.net.MalformedURLException;
011import java.net.URL;
012import java.util.List;
013import java.util.Objects;
014
015import javax.xml.parsers.ParserConfigurationException;
016
017import org.openstreetmap.josm.data.gpx.GpxData;
018import org.openstreetmap.josm.data.notes.Note;
019import org.openstreetmap.josm.data.osm.DataSet;
020import org.openstreetmap.josm.gui.progress.ProgressMonitor;
021import org.openstreetmap.josm.io.auth.CredentialsManager;
022import org.openstreetmap.josm.tools.HttpClient;
023import org.openstreetmap.josm.tools.Logging;
024import org.openstreetmap.josm.tools.Utils;
025import org.openstreetmap.josm.tools.XmlParsingException;
026import org.openstreetmap.josm.tools.XmlUtils;
027import org.w3c.dom.Document;
028import org.w3c.dom.Node;
029import org.xml.sax.SAXException;
030
031/**
032 * This DataReader reads directly from the REST API of the osm server.
033 *
034 * It supports plain text transfer as well as gzip or deflate encoded transfers;
035 * if compressed transfers are unwanted, set property osm-server.use-compression
036 * to false.
037 *
038 * @author imi
039 */
040public abstract class OsmServerReader extends OsmConnection {
041    private final OsmApi api;
042    private boolean doAuthenticate;
043    protected boolean gpxParsedProperly;
044    protected String contentType;
045
046    /**
047     * Constructs a new {@code OsmServerReader}.
048     */
049    protected OsmServerReader() {
050        this(OsmApi.getOsmApi());
051    }
052
053    /**
054     * Constructs a new {@code OsmServerReader}.
055     * @param osmApi The API to use for this call
056     * @since 18650
057     */
058    protected OsmServerReader(OsmApi osmApi) {
059        this.api = osmApi;
060        this.doAuthenticate = OsmApi.isUsingOAuthAndOAuthSetUp(osmApi) && OsmApi.USE_OAUTH_FOR_ALL_REQUESTS.get();
061    }
062
063    /**
064     * Open a connection to the given url and return a reader on the input stream
065     * from that connection. In case of user cancel, return <code>null</code>.
066     * Relative URL's are directed to API base URL.
067     * @param urlStr The url to connect to.
068     * @param progressMonitor progress monitoring and abort handler
069     * @return A reader reading the input stream (servers answer) or <code>null</code>.
070     * @throws OsmTransferException if data transfer errors occur
071     */
072    protected InputStream getInputStream(String urlStr, ProgressMonitor progressMonitor) throws OsmTransferException {
073        return getInputStream(urlStr, progressMonitor, null);
074    }
075
076    /**
077     * Open a connection to the given url and return a reader on the input stream
078     * from that connection. In case of user cancel, return <code>null</code>.
079     * Relative URL's are directed to API base URL.
080     * @param urlStr The url to connect to.
081     * @param progressMonitor progress monitoring and abort handler
082     * @param reason The reason to show on console. Can be {@code null} if no reason is given
083     * @return A reader reading the input stream (servers answer) or <code>null</code>.
084     * @throws OsmTransferException if data transfer errors occur
085     */
086    protected InputStream getInputStream(String urlStr, ProgressMonitor progressMonitor, String reason) throws OsmTransferException {
087        try {
088            api.initialize(progressMonitor);
089            String url = urlStr.startsWith("http") ? urlStr : (getBaseUrl() + urlStr);
090            return getInputStreamRaw(url, progressMonitor, reason);
091        } finally {
092            progressMonitor.invalidate();
093        }
094    }
095
096    /**
097     * Return the base URL for relative URL requests
098     * @return base url of API
099     */
100    protected String getBaseUrl() {
101        return api.getBaseUrl();
102    }
103
104    /**
105     * Open a connection to the given url and return a reader on the input stream
106     * from that connection. In case of user cancel, return <code>null</code>.
107     * @param urlStr The exact url to connect to.
108     * @param progressMonitor progress monitoring and abort handler
109     * @return An reader reading the input stream (servers answer) or <code>null</code>.
110     * @throws OsmTransferException if data transfer errors occur
111     */
112    protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor) throws OsmTransferException {
113        return getInputStreamRaw(urlStr, progressMonitor, null);
114    }
115
116    /**
117     * Open a connection to the given url and return a reader on the input stream
118     * from that connection. In case of user cancel, return <code>null</code>.
119     * @param urlStr The exact url to connect to.
120     * @param progressMonitor progress monitoring and abort handler
121     * @param reason The reason to show on console. Can be {@code null} if no reason is given
122     * @return An reader reading the input stream (servers answer) or <code>null</code>.
123     * @throws OsmTransferException if data transfer errors occur
124     */
125    protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason) throws OsmTransferException {
126        return getInputStreamRaw(urlStr, progressMonitor, reason, false);
127    }
128
129    /**
130     * Open a connection to the given url (if HTTP, trough a GET request) and return a reader on the input stream
131     * from that connection. In case of user cancel, return <code>null</code>.
132     * @param urlStr The exact url to connect to.
133     * @param progressMonitor progress monitoring and abort handler
134     * @param reason The reason to show on console. Can be {@code null} if no reason is given
135     * @param uncompressAccordingToContentDisposition Whether to inspect the HTTP header {@code Content-Disposition}
136     *                                                for {@code filename} and uncompress a gzip/bzip2/xz/zip stream.
137     * @return An reader reading the input stream (servers answer) or <code>null</code>.
138     * @throws OsmTransferException if data transfer errors occur
139     */
140    protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason,
141            boolean uncompressAccordingToContentDisposition) throws OsmTransferException {
142        return getInputStreamRaw(urlStr, progressMonitor, reason, uncompressAccordingToContentDisposition, "GET", null);
143    }
144
145    /**
146     * Open a connection to the given url (if HTTP, with the specified method) and return a reader on the input stream
147     * from that connection. In case of user cancel, return <code>null</code>.
148     * @param urlStr The exact url to connect to.
149     * @param progressMonitor progress monitoring and abort handler
150     * @param reason The reason to show on console. Can be {@code null} if no reason is given
151     * @param uncompressAccordingToContentDisposition Whether to inspect the HTTP header {@code Content-Disposition}
152     *                                                for {@code filename} and uncompress a gzip/bzip2/xz/zip stream.
153     * @param httpMethod HTTP method ("GET", "POST" or "PUT")
154     * @param requestBody HTTP request body (for "POST" and "PUT" methods only). Must be null for "GET" method.
155     * @return An reader reading the input stream (servers answer) or <code>null</code>.
156     * @throws OsmTransferException if data transfer errors occur
157     * @since 12596
158     */
159    @SuppressWarnings("resource")
160    protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason,
161            boolean uncompressAccordingToContentDisposition, String httpMethod, byte[] requestBody) throws OsmTransferException {
162        try {
163            if (NetworkManager.isOffline(urlStr)) {
164                throw new OsmApiException(OfflineAccessException.forResource(urlStr));
165            }
166
167            URL url = null;
168            try {
169                url = new URL(urlStr.replace(" ", "%20"));
170            } catch (MalformedURLException e) {
171                throw new OsmTransferException(e);
172            }
173
174            String protocol = url.getProtocol();
175            if ("file".equals(protocol) || "jar".equals(protocol)) {
176                try {
177                    return Utils.openStream(url);
178                } catch (IOException e) {
179                    throw new OsmTransferException(e);
180                }
181            }
182
183            final HttpClient client = HttpClient.create(url, httpMethod)
184                    .setAccept("application/xml, */*;q=0.8")
185                    .setFinishOnCloseOutput(false)
186                    .setReasonForRequest(reason)
187                    .setOutputMessage(tr("Downloading data..."))
188                    .setRequestBody(requestBody);
189            activeConnection = client;
190            adaptRequest(client);
191            if (doAuthenticate && Objects.equals(this.api.getHost(), client.getURL().getHost())) {
192                addAuth(client);
193            }
194            if (cancel)
195                throw new OsmTransferCanceledException("Operation canceled");
196
197            final HttpClient.Response response;
198            try {
199                response = client.connect(progressMonitor);
200                contentType = response.getContentType();
201            } catch (IOException e) {
202                Logging.error(e);
203                OsmTransferException ote = new OsmTransferException(
204                        tr("Could not connect to the OSM server. Please check your internet connection."), e);
205                ote.setUrl(url.toString());
206                throw ote;
207            }
208            try {
209                if (response.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
210                    CredentialsManager.getInstance().purgeCredentialsCache(RequestorType.SERVER, OsmApi.getOsmApi().getHost());
211                    throw new OsmApiException(HttpURLConnection.HTTP_UNAUTHORIZED, null, null);
212                }
213
214                if (response.getResponseCode() == HttpURLConnection.HTTP_PROXY_AUTH)
215                    throw new OsmTransferCanceledException("Proxy Authentication Required");
216
217                if (response.getResponseCode() != HttpURLConnection.HTTP_OK) {
218                    String errorHeader = response.getHeaderField("Error");
219                    String errorBody = fetchResponseText(response);
220                    throw new OsmApiException(response.getResponseCode(), errorHeader, errorBody, url.toString(), null,
221                            contentType);
222                }
223
224                response.uncompressAccordingToContentDisposition(uncompressAccordingToContentDisposition);
225                return response.getContent();
226            } catch (OsmTransferException e) {
227                throw e;
228            } catch (IOException e) {
229                throw new OsmTransferException(e);
230            }
231        } finally {
232            progressMonitor.invalidate();
233        }
234    }
235
236    private static String fetchResponseText(final HttpClient.Response response) {
237        try {
238            return response.fetchContent();
239        } catch (IOException e) {
240            Logging.error(e);
241            return tr("Reading error text failed.");
242        }
243    }
244
245    /**
246     * Allows subclasses to modify the request.
247     * @param request the prepared request
248     * @since 9308
249     */
250    protected void adaptRequest(HttpClient request) {
251    }
252
253    /**
254     * Download OSM files from somewhere
255     * @param progressMonitor The progress monitor
256     * @return The corresponding dataset
257     * @throws OsmTransferException if any error occurs
258     */
259    public abstract DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException;
260
261    /**
262     * Download compressed OSM files from somewhere
263     * @param progressMonitor The progress monitor
264     * @param compression compression to use
265     * @return The corresponding dataset
266     * @throws OsmTransferException if any error occurs
267     * @since 13352
268     */
269    public DataSet parseOsm(ProgressMonitor progressMonitor, Compression compression) throws OsmTransferException {
270        throw new UnsupportedOperationException();
271    }
272
273    /**
274     * Download OSM Change uncompressed files from somewhere
275     * @param progressMonitor The progress monitor
276     * @return The corresponding dataset
277     * @throws OsmTransferException if any error occurs
278     */
279    public DataSet parseOsmChange(ProgressMonitor progressMonitor) throws OsmTransferException {
280        return null;
281    }
282
283    /**
284     * Download OSM Change compressed files from somewhere
285     * @param progressMonitor The progress monitor
286     * @param compression compression to use
287     * @return The corresponding dataset
288     * @throws OsmTransferException if any error occurs
289     * @since 13352
290     */
291    public DataSet parseOsmChange(ProgressMonitor progressMonitor, Compression compression) throws OsmTransferException {
292        throw new UnsupportedOperationException();
293    }
294
295    /**
296     * Retrieve raw gps waypoints from the server API.
297     * @param progressMonitor The progress monitor
298     * @return The corresponding GPX tracks
299     * @throws OsmTransferException if any error occurs
300     */
301    public GpxData parseRawGps(ProgressMonitor progressMonitor) throws OsmTransferException {
302        return null;
303    }
304
305    /**
306     * Retrieve compressed GPX files from somewhere.
307     * @param progressMonitor The progress monitor
308     * @param compression compression to use
309     * @return The corresponding GPX tracks
310     * @throws OsmTransferException if any error occurs
311     * @since 13352
312     */
313    public GpxData parseRawGps(ProgressMonitor progressMonitor, Compression compression) throws OsmTransferException {
314        throw new UnsupportedOperationException();
315    }
316
317    /**
318     * Returns true if this reader is adding authentication credentials to the read
319     * request sent to the server.
320     *
321     * @return true if this reader is adding authentication credentials to the read
322     * request sent to the server
323     */
324    public boolean isDoAuthenticate() {
325        return doAuthenticate;
326    }
327
328    /**
329     * Sets whether this reader adds authentication credentials to the read
330     * request sent to the server.
331     *
332     * @param doAuthenticate  true if  this reader adds authentication credentials to the read
333     * request sent to the server
334     */
335    public void setDoAuthenticate(boolean doAuthenticate) {
336        this.doAuthenticate = doAuthenticate;
337    }
338
339    /**
340     * Determines if the GPX data has been parsed properly.
341     * @return true if the GPX data has been parsed properly, false otherwise
342     * @see GpxReader#parse
343     */
344    public final boolean isGpxParsedProperly() {
345        return gpxParsedProperly;
346    }
347
348    /**
349     * Downloads notes from the API, given API limit parameters
350     *
351     * @param noteLimit How many notes to download.
352     * @param daysClosed Return notes closed this many days in the past. -1 means all notes, ever. 0 means only unresolved notes.
353     * @param progressMonitor Progress monitor for user feedback
354     * @return List of notes returned by the API
355     * @throws OsmTransferException if any errors happen
356     */
357    public List<Note> parseNotes(int noteLimit, int daysClosed, ProgressMonitor progressMonitor) throws OsmTransferException {
358        return null;
359    }
360
361    /**
362     * Downloads notes from a given raw URL. The URL is assumed to be complete and no API limits are added
363     *
364     * @param progressMonitor progress monitor
365     * @return A list of notes parsed from the URL
366     * @throws OsmTransferException if any error occurs during dialog with OSM API
367     */
368    public List<Note> parseRawNotes(final ProgressMonitor progressMonitor) throws OsmTransferException {
369        return null;
370    }
371
372    /**
373     * Download notes from a URL that contains a compressed notes dump file
374     * @param progressMonitor progress monitor
375     * @param compression compression to use
376     * @return A list of notes parsed from the URL
377     * @throws OsmTransferException if any error occurs during dialog with OSM API
378     * @since 13352
379     */
380    public List<Note> parseRawNotes(ProgressMonitor progressMonitor, Compression compression) throws OsmTransferException {
381        throw new UnsupportedOperationException();
382    }
383
384    /**
385     * Returns an attribute from the given DOM node.
386     * @param node DOM node
387     * @param name attribute name
388     * @return attribute value for the given attribute
389     * @since 12510
390     */
391    protected static String getAttribute(Node node, String name) {
392        return node.getAttributes().getNamedItem(name).getNodeValue();
393    }
394
395    /**
396     * DOM document parser.
397     * @param <R> resulting type
398     * @since 12510
399     */
400    @FunctionalInterface
401    protected interface DomParser<R> {
402        /**
403         * Parses a given DOM document.
404         * @param doc DOM document
405         * @return parsed data
406         * @throws XmlParsingException if an XML parsing error occurs
407         */
408        R parse(Document doc) throws XmlParsingException;
409    }
410
411    /**
412     * Fetches generic data from the DOM document resulting an API call.
413     * @param api the OSM API call
414     * @param subtask the subtask translated message
415     * @param parser the parser converting the DOM document (OSM API result)
416     * @param <T> data type
417     * @param monitor The progress monitor
418     * @param reason The reason to show on console. Can be {@code null} if no reason is given
419     * @return The converted data
420     * @throws OsmTransferException if something goes wrong
421     * @since 12510
422     */
423    public <T> T fetchData(String api, String subtask, DomParser<T> parser, ProgressMonitor monitor, String reason)
424            throws OsmTransferException {
425        try {
426            monitor.beginTask("");
427            monitor.indeterminateSubTask(subtask);
428            try (InputStream in = getInputStream(api, monitor.createSubTaskMonitor(1, true), reason)) {
429                return parser.parse(XmlUtils.parseSafeDOM(in));
430            }
431        } catch (OsmTransferException e) {
432            throw e;
433        } catch (IOException | ParserConfigurationException | SAXException e) {
434            throw new OsmTransferException(e);
435        } finally {
436            monitor.finishTask();
437        }
438    }
439}