source: josm/trunk/src/org/openstreetmap/josm/io/OsmServerReader.java@ 13352

Last change on this file since 13352 was 13352, checked in by Don-vip, 6 years ago

fix #15816 - full XZ support

  • Property svn:eol-style set to native
File size: 20.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.IOException;
7import java.io.InputStream;
8import java.net.Authenticator.RequestorType;
9import java.net.HttpURLConnection;
10import java.net.MalformedURLException;
11import java.net.URL;
12import java.util.List;
13
14import javax.xml.parsers.ParserConfigurationException;
15
16import org.openstreetmap.josm.Main;
17import org.openstreetmap.josm.data.gpx.GpxData;
18import org.openstreetmap.josm.data.notes.Note;
19import org.openstreetmap.josm.data.osm.DataSet;
20import org.openstreetmap.josm.gui.progress.ProgressMonitor;
21import org.openstreetmap.josm.io.auth.CredentialsAgentException;
22import org.openstreetmap.josm.io.auth.CredentialsManager;
23import org.openstreetmap.josm.tools.HttpClient;
24import org.openstreetmap.josm.tools.Logging;
25import org.openstreetmap.josm.tools.Utils;
26import org.openstreetmap.josm.tools.XmlParsingException;
27import org.w3c.dom.Document;
28import org.w3c.dom.Node;
29import org.xml.sax.SAXException;
30
31/**
32 * This DataReader reads directly from the REST API of the osm server.
33 *
34 * It supports plain text transfer as well as gzip or deflate encoded transfers;
35 * if compressed transfers are unwanted, set property osm-server.use-compression
36 * to false.
37 *
38 * @author imi
39 */
40public abstract class OsmServerReader extends OsmConnection {
41 private final OsmApi api = OsmApi.getOsmApi();
42 private boolean doAuthenticate;
43 protected boolean gpxParsedProperly;
44
45 /**
46 * Constructs a new {@code OsmServerReader}.
47 */
48 public OsmServerReader() {
49 try {
50 doAuthenticate = OsmApi.isUsingOAuth() && CredentialsManager.getInstance().lookupOAuthAccessToken() != null;
51 } catch (CredentialsAgentException e) {
52 Logging.warn(e);
53 }
54 }
55
56 /**
57 * Open a connection to the given url and return a reader on the input stream
58 * from that connection. In case of user cancel, return <code>null</code>.
59 * Relative URL's are directed to API base URL.
60 * @param urlStr The url to connect to.
61 * @param progressMonitor progress monitoring and abort handler
62 * @return A reader reading the input stream (servers answer) or <code>null</code>.
63 * @throws OsmTransferException if data transfer errors occur
64 */
65 protected InputStream getInputStream(String urlStr, ProgressMonitor progressMonitor) throws OsmTransferException {
66 return getInputStream(urlStr, progressMonitor, null);
67 }
68
69 /**
70 * Open a connection to the given url and return a reader on the input stream
71 * from that connection. In case of user cancel, return <code>null</code>.
72 * Relative URL's are directed to API base URL.
73 * @param urlStr The url to connect to.
74 * @param progressMonitor progress monitoring and abort handler
75 * @param reason The reason to show on console. Can be {@code null} if no reason is given
76 * @return A reader reading the input stream (servers answer) or <code>null</code>.
77 * @throws OsmTransferException if data transfer errors occur
78 */
79 protected InputStream getInputStream(String urlStr, ProgressMonitor progressMonitor, String reason) throws OsmTransferException {
80 try {
81 api.initialize(progressMonitor);
82 String url = urlStr.startsWith("http") ? urlStr : (getBaseUrl() + urlStr);
83 return getInputStreamRaw(url, progressMonitor, reason);
84 } finally {
85 progressMonitor.invalidate();
86 }
87 }
88
89 /**
90 * Return the base URL for relative URL requests
91 * @return base url of API
92 */
93 protected String getBaseUrl() {
94 return api.getBaseUrl();
95 }
96
97 /**
98 * Open a connection to the given url and return a reader on the input stream
99 * from that connection. In case of user cancel, return <code>null</code>.
100 * @param urlStr The exact url to connect to.
101 * @param progressMonitor progress monitoring and abort handler
102 * @return An reader reading the input stream (servers answer) or <code>null</code>.
103 * @throws OsmTransferException if data transfer errors occur
104 */
105 protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor) throws OsmTransferException {
106 return getInputStreamRaw(urlStr, progressMonitor, null);
107 }
108
109 /**
110 * Open a connection to the given url and return a reader on the input stream
111 * from that connection. In case of user cancel, return <code>null</code>.
112 * @param urlStr The exact url to connect to.
113 * @param progressMonitor progress monitoring and abort handler
114 * @param reason The reason to show on console. Can be {@code null} if no reason is given
115 * @return An reader reading the input stream (servers answer) or <code>null</code>.
116 * @throws OsmTransferException if data transfer errors occur
117 */
118 protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason) throws OsmTransferException {
119 return getInputStreamRaw(urlStr, progressMonitor, reason, false);
120 }
121
122 /**
123 * Open a connection to the given url (if HTTP, trough a GET request) and return a reader on the input stream
124 * from that connection. In case of user cancel, return <code>null</code>.
125 * @param urlStr The exact url to connect to.
126 * @param progressMonitor progress monitoring and abort handler
127 * @param reason The reason to show on console. Can be {@code null} if no reason is given
128 * @param uncompressAccordingToContentDisposition Whether to inspect the HTTP header {@code Content-Disposition}
129 * for {@code filename} and uncompress a gzip/bzip2/xz/zip stream.
130 * @return An reader reading the input stream (servers answer) or <code>null</code>.
131 * @throws OsmTransferException if data transfer errors occur
132 */
133 protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason,
134 boolean uncompressAccordingToContentDisposition) throws OsmTransferException {
135 return getInputStreamRaw(urlStr, progressMonitor, reason, uncompressAccordingToContentDisposition, "GET", null);
136 }
137
138 /**
139 * Open a connection to the given url (if HTTP, with the specified method) and return a reader on the input stream
140 * from that connection. In case of user cancel, return <code>null</code>.
141 * @param urlStr The exact url to connect to.
142 * @param progressMonitor progress monitoring and abort handler
143 * @param reason The reason to show on console. Can be {@code null} if no reason is given
144 * @param uncompressAccordingToContentDisposition Whether to inspect the HTTP header {@code Content-Disposition}
145 * for {@code filename} and uncompress a gzip/bzip2/xz/zip stream.
146 * @param httpMethod HTTP method ("GET", "POST" or "PUT")
147 * @param requestBody HTTP request body (for "POST" and "PUT" methods only). Must be null for "GET" method.
148 * @return An reader reading the input stream (servers answer) or <code>null</code>.
149 * @throws OsmTransferException if data transfer errors occur
150 * @since 12596
151 */
152 @SuppressWarnings("resource")
153 protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason,
154 boolean uncompressAccordingToContentDisposition, String httpMethod, byte[] requestBody) throws OsmTransferException {
155 try {
156 OnlineResource.JOSM_WEBSITE.checkOfflineAccess(urlStr, Main.getJOSMWebsite());
157 OnlineResource.OSM_API.checkOfflineAccess(urlStr, OsmApi.getOsmApi().getServerUrl());
158
159 URL url = null;
160 try {
161 url = new URL(urlStr.replace(" ", "%20"));
162 } catch (MalformedURLException e) {
163 throw new OsmTransferException(e);
164 }
165
166 if ("file".equals(url.getProtocol())) {
167 try {
168 return url.openStream();
169 } catch (IOException e) {
170 throw new OsmTransferException(e);
171 }
172 }
173
174 final HttpClient client = HttpClient.create(url, httpMethod)
175 .setFinishOnCloseOutput(false)
176 .setReasonForRequest(reason)
177 .setOutputMessage(tr("Downloading data..."))
178 .setRequestBody(requestBody);
179 activeConnection = client;
180 adaptRequest(client);
181 if (doAuthenticate) {
182 addAuth(client);
183 }
184 if (cancel)
185 throw new OsmTransferCanceledException("Operation canceled");
186
187 final HttpClient.Response response;
188 try {
189 response = client.connect(progressMonitor);
190 } catch (IOException e) {
191 Logging.error(e);
192 OsmTransferException ote = new OsmTransferException(
193 tr("Could not connect to the OSM server. Please check your internet connection."), e);
194 ote.setUrl(url.toString());
195 throw ote;
196 }
197 try {
198 if (response.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
199 CredentialsManager.getInstance().purgeCredentialsCache(RequestorType.SERVER);
200 throw new OsmApiException(HttpURLConnection.HTTP_UNAUTHORIZED, null, null);
201 }
202
203 if (response.getResponseCode() == HttpURLConnection.HTTP_PROXY_AUTH)
204 throw new OsmTransferCanceledException("Proxy Authentication Required");
205
206 if (response.getResponseCode() != HttpURLConnection.HTTP_OK) {
207 String errorHeader = response.getHeaderField("Error");
208 String errorBody = fetchResponseText(response);
209 throw new OsmApiException(response.getResponseCode(), errorHeader, errorBody, url.toString());
210 }
211
212 response.uncompressAccordingToContentDisposition(uncompressAccordingToContentDisposition);
213 return response.getContent();
214 } catch (OsmTransferException e) {
215 throw e;
216 } catch (IOException e) {
217 throw new OsmTransferException(e);
218 }
219 } finally {
220 progressMonitor.invalidate();
221 }
222 }
223
224 private static String fetchResponseText(final HttpClient.Response response) {
225 try {
226 return response.fetchContent();
227 } catch (IOException e) {
228 Logging.error(e);
229 return tr("Reading error text failed.");
230 }
231 }
232
233 /**
234 * Allows subclasses to modify the request.
235 * @param request the prepared request
236 * @since 9308
237 */
238 protected void adaptRequest(HttpClient request) {
239 }
240
241 /**
242 * Download OSM files from somewhere
243 * @param progressMonitor The progress monitor
244 * @return The corresponding dataset
245 * @throws OsmTransferException if any error occurs
246 */
247 public abstract DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException;
248
249 /**
250 * Download compressed OSM files from somewhere
251 * @param progressMonitor The progress monitor
252 * @param compression compression to use
253 * @return The corresponding dataset
254 * @throws OsmTransferException if any error occurs
255 * @since 13352
256 */
257 public DataSet parseOsm(ProgressMonitor progressMonitor, Compression compression) throws OsmTransferException {
258 return null;
259 }
260
261 /**
262 * Download OSM Change uncompressed files from somewhere
263 * @param progressMonitor The progress monitor
264 * @return The corresponding dataset
265 * @throws OsmTransferException if any error occurs
266 */
267 public DataSet parseOsmChange(ProgressMonitor progressMonitor) throws OsmTransferException {
268 return null;
269 }
270
271 /**
272 * Download OSM Change compressed files from somewhere
273 * @param progressMonitor The progress monitor
274 * @param compression compression to use
275 * @return The corresponding dataset
276 * @throws OsmTransferException if any error occurs
277 * @since 13352
278 */
279 public DataSet parseOsmChange(ProgressMonitor progressMonitor, Compression compression) throws OsmTransferException {
280 return null;
281 }
282
283 /**
284 * Download BZip2-compressed OSM Change files from somewhere
285 * @param progressMonitor The progress monitor
286 * @return The corresponding dataset
287 * @throws OsmTransferException if any error occurs
288 * @deprecated use {@link #parseOsmChange(ProgressMonitor, Compression)} instead
289 */
290 @Deprecated
291 public DataSet parseOsmChangeBzip2(ProgressMonitor progressMonitor) throws OsmTransferException {
292 return parseOsmChange(progressMonitor, Compression.BZIP2);
293 }
294
295 /**
296 * Download GZip-compressed OSM Change files from somewhere
297 * @param progressMonitor The progress monitor
298 * @return The corresponding dataset
299 * @throws OsmTransferException if any error occurs
300 * @deprecated use {@link #parseOsmChange(ProgressMonitor, Compression)} instead
301 */
302 @Deprecated
303 public DataSet parseOsmChangeGzip(ProgressMonitor progressMonitor) throws OsmTransferException {
304 return parseOsmChange(progressMonitor, Compression.GZIP);
305 }
306
307 /**
308 * Retrieve raw gps waypoints from the server API.
309 * @param progressMonitor The progress monitor
310 * @return The corresponding GPX tracks
311 * @throws OsmTransferException if any error occurs
312 */
313 public GpxData parseRawGps(ProgressMonitor progressMonitor) throws OsmTransferException {
314 return null;
315 }
316
317 /**
318 * Retrieve compressed GPX files from somewhere.
319 * @param progressMonitor The progress monitor
320 * @param compression compression to use
321 * @return The corresponding GPX tracks
322 * @throws OsmTransferException if any error occurs
323 * @since 13352
324 */
325 public GpxData parseRawGps(ProgressMonitor progressMonitor, Compression compression) throws OsmTransferException {
326 return null;
327 }
328
329 /**
330 * Retrieve BZip2-compressed GPX files from somewhere.
331 * @param progressMonitor The progress monitor
332 * @return The corresponding GPX tracks
333 * @throws OsmTransferException if any error occurs
334 * @deprecated use {@link #parseRawGps(ProgressMonitor, Compression)} instead
335 * @since 6244
336 */
337 @Deprecated
338 public GpxData parseRawGpsBzip2(ProgressMonitor progressMonitor) throws OsmTransferException {
339 return parseRawGps(progressMonitor, Compression.BZIP2);
340 }
341
342 /**
343 * Download BZip2-compressed OSM files from somewhere
344 * @param progressMonitor The progress monitor
345 * @return The corresponding dataset
346 * @throws OsmTransferException if any error occurs
347 * @deprecated use {@link #parseOsm(ProgressMonitor, Compression)} instead
348 */
349 @Deprecated
350 public DataSet parseOsmBzip2(ProgressMonitor progressMonitor) throws OsmTransferException {
351 return parseOsm(progressMonitor, Compression.BZIP2);
352 }
353
354 /**
355 * Download GZip-compressed OSM files from somewhere
356 * @param progressMonitor The progress monitor
357 * @return The corresponding dataset
358 * @throws OsmTransferException if any error occurs
359 * @deprecated use {@link #parseOsm(ProgressMonitor, Compression)} instead
360 */
361 @Deprecated
362 public DataSet parseOsmGzip(ProgressMonitor progressMonitor) throws OsmTransferException {
363 return parseOsm(progressMonitor, Compression.GZIP);
364 }
365
366 /**
367 * Download Zip-compressed OSM files from somewhere
368 * @param progressMonitor The progress monitor
369 * @return The corresponding dataset
370 * @throws OsmTransferException if any error occurs
371 * @deprecated use {@link #parseOsm(ProgressMonitor, Compression)} instead
372 * @since 6882
373 */
374 @Deprecated
375 public DataSet parseOsmZip(final ProgressMonitor progressMonitor) throws OsmTransferException {
376 return parseOsm(progressMonitor, Compression.ZIP);
377 }
378
379 /**
380 * Returns true if this reader is adding authentication credentials to the read
381 * request sent to the server.
382 *
383 * @return true if this reader is adding authentication credentials to the read
384 * request sent to the server
385 */
386 public boolean isDoAuthenticate() {
387 return doAuthenticate;
388 }
389
390 /**
391 * Sets whether this reader adds authentication credentials to the read
392 * request sent to the server.
393 *
394 * @param doAuthenticate true if this reader adds authentication credentials to the read
395 * request sent to the server
396 */
397 public void setDoAuthenticate(boolean doAuthenticate) {
398 this.doAuthenticate = doAuthenticate;
399 }
400
401 /**
402 * Determines if the GPX data has been parsed properly.
403 * @return true if the GPX data has been parsed properly, false otherwise
404 * @see GpxReader#parse
405 */
406 public final boolean isGpxParsedProperly() {
407 return gpxParsedProperly;
408 }
409
410 /**
411 * Downloads notes from the API, given API limit parameters
412 *
413 * @param noteLimit How many notes to download.
414 * @param daysClosed Return notes closed this many days in the past. -1 means all notes, ever. 0 means only unresolved notes.
415 * @param progressMonitor Progress monitor for user feedback
416 * @return List of notes returned by the API
417 * @throws OsmTransferException if any errors happen
418 */
419 public List<Note> parseNotes(int noteLimit, int daysClosed, ProgressMonitor progressMonitor) throws OsmTransferException {
420 return null;
421 }
422
423 /**
424 * Downloads notes from a given raw URL. The URL is assumed to be complete and no API limits are added
425 *
426 * @param progressMonitor progress monitor
427 * @return A list of notes parsed from the URL
428 * @throws OsmTransferException if any error occurs during dialog with OSM API
429 */
430 public List<Note> parseRawNotes(final ProgressMonitor progressMonitor) throws OsmTransferException {
431 return null;
432 }
433
434 /**
435 * Download notes from a URL that contains a compressed notes dump file
436 * @param progressMonitor progress monitor
437 * @param compression compression to use
438 * @return A list of notes parsed from the URL
439 * @throws OsmTransferException if any error occurs during dialog with OSM API
440 * @since 13352
441 */
442 public List<Note> parseRawNotes(ProgressMonitor progressMonitor, Compression compression) throws OsmTransferException {
443 return null;
444 }
445
446 /**
447 * Download notes from a URL that contains a bzip2 compressed notes dump file
448 * @param progressMonitor progress monitor
449 * @return A list of notes parsed from the URL
450 * @throws OsmTransferException if any error occurs during dialog with OSM API
451 * @deprecated Use {@link #parseRawNotes(ProgressMonitor, Compression)} instead
452 */
453 @Deprecated
454 public List<Note> parseRawNotesBzip2(final ProgressMonitor progressMonitor) throws OsmTransferException {
455 return parseRawNotes(progressMonitor, Compression.BZIP2);
456 }
457
458 /**
459 * Returns an attribute from the given DOM node.
460 * @param node DOM node
461 * @param name attribute name
462 * @return attribute value for the given attribute
463 * @since 12510
464 */
465 protected static String getAttribute(Node node, String name) {
466 return node.getAttributes().getNamedItem(name).getNodeValue();
467 }
468
469 /**
470 * DOM document parser.
471 * @param <R> resulting type
472 * @since 12510
473 */
474 @FunctionalInterface
475 protected interface DomParser<R> {
476 /**
477 * Parses a given DOM document.
478 * @param doc DOM document
479 * @return parsed data
480 * @throws XmlParsingException if an XML parsing error occurs
481 */
482 R parse(Document doc) throws XmlParsingException;
483 }
484
485 /**
486 * Fetches generic data from the DOM document resulting an API call.
487 * @param api the OSM API call
488 * @param subtask the subtask translated message
489 * @param parser the parser converting the DOM document (OSM API result)
490 * @param <T> data type
491 * @param monitor The progress monitor
492 * @param reason The reason to show on console. Can be {@code null} if no reason is given
493 * @return The converted data
494 * @throws OsmTransferException if something goes wrong
495 * @since 12510
496 */
497 public <T> T fetchData(String api, String subtask, DomParser<T> parser, ProgressMonitor monitor, String reason)
498 throws OsmTransferException {
499 try {
500 monitor.beginTask("");
501 monitor.indeterminateSubTask(subtask);
502 try (InputStream in = getInputStream(api, monitor.createSubTaskMonitor(1, true), reason)) {
503 return parser.parse(Utils.parseSafeDOM(in));
504 }
505 } catch (OsmTransferException e) {
506 throw e;
507 } catch (IOException | ParserConfigurationException | SAXException e) {
508 throw new OsmTransferException(e);
509 } finally {
510 monitor.finishTask();
511 }
512 }
513}
Note: See TracBrowser for help on using the repository browser.