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

Last change on this file since 12698 was 12620, checked in by Don-vip, 7 years ago

see #15182 - deprecate all Main logging methods and introduce suitable replacements in Logging for most of them

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