source: josm/trunk/src/org/openstreetmap/josm/io/OsmApi.java@ 17498

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

code refactoring

  • Property svn:eol-style set to native
File size: 37.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.io.IOException;
8import java.io.PrintWriter;
9import java.io.StringReader;
10import java.io.StringWriter;
11import java.net.Authenticator.RequestorType;
12import java.net.ConnectException;
13import java.net.HttpURLConnection;
14import java.net.MalformedURLException;
15import java.net.SocketTimeoutException;
16import java.net.URL;
17import java.nio.charset.StandardCharsets;
18import java.util.Collection;
19import java.util.HashMap;
20import java.util.List;
21import java.util.Map;
22import java.util.function.Consumer;
23import java.util.function.UnaryOperator;
24
25import javax.xml.parsers.ParserConfigurationException;
26
27import org.openstreetmap.josm.data.coor.LatLon;
28import org.openstreetmap.josm.data.notes.Note;
29import org.openstreetmap.josm.data.osm.Changeset;
30import org.openstreetmap.josm.data.osm.IPrimitive;
31import org.openstreetmap.josm.data.osm.OsmPrimitive;
32import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
33import org.openstreetmap.josm.data.preferences.BooleanProperty;
34import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
35import org.openstreetmap.josm.gui.progress.ProgressMonitor;
36import org.openstreetmap.josm.io.Capabilities.CapabilitiesParser;
37import org.openstreetmap.josm.io.auth.CredentialsManager;
38import org.openstreetmap.josm.spi.preferences.Config;
39import org.openstreetmap.josm.tools.CheckParameterUtil;
40import org.openstreetmap.josm.tools.HttpClient;
41import org.openstreetmap.josm.tools.ListenerList;
42import org.openstreetmap.josm.tools.Logging;
43import org.openstreetmap.josm.tools.Utils;
44import org.openstreetmap.josm.tools.XmlParsingException;
45import org.xml.sax.InputSource;
46import org.xml.sax.SAXException;
47import org.xml.sax.SAXParseException;
48
49/**
50 * Class that encapsulates the communications with the <a href="http://wiki.openstreetmap.org/wiki/API_v0.6">OSM API</a>.<br><br>
51 *
52 * All interaction with the server-side OSM API should go through this class.<br><br>
53 *
54 * It is conceivable to extract this into an interface later and create various
55 * classes implementing the interface, to be able to talk to various kinds of servers.
56 * @since 1523
57 */
58public class OsmApi extends OsmConnection {
59
60 /**
61 * Maximum number of retries to send a request in case of HTTP 500 errors or timeouts
62 */
63 public static final int DEFAULT_MAX_NUM_RETRIES = 5;
64
65 /**
66 * Maximum number of concurrent download threads, imposed by
67 * <a href="http://wiki.openstreetmap.org/wiki/API_usage_policy#Technical_Usage_Requirements">
68 * OSM API usage policy.</a>
69 * @since 5386
70 */
71 public static final int MAX_DOWNLOAD_THREADS = 2;
72
73 /**
74 * Defines whether all OSM API requests should be signed with an OAuth token (user-based bandwidth limit instead of IP-based one)
75 */
76 public static final BooleanProperty USE_OAUTH_FOR_ALL_REQUESTS = new BooleanProperty("oauth.use-for-all-requests", true);
77
78 // The collection of instantiated OSM APIs
79 private static final Map<String, OsmApi> instances = new HashMap<>();
80
81 private static final ListenerList<OsmApiInitializationListener> listeners = ListenerList.create();
82
83 private URL url;
84
85 /**
86 * OSM API initialization listener.
87 * @since 12804
88 */
89 public interface OsmApiInitializationListener {
90 /**
91 * Called when an OSM API instance has been successfully initialized.
92 * @param instance the initialized OSM API instance
93 */
94 void apiInitialized(OsmApi instance);
95 }
96
97 /**
98 * Adds a new OSM API initialization listener.
99 * @param listener OSM API initialization listener to add
100 * @since 12804
101 */
102 public static void addOsmApiInitializationListener(OsmApiInitializationListener listener) {
103 listeners.addListener(listener);
104 }
105
106 /**
107 * Removes an OSM API initialization listener.
108 * @param listener OSM API initialization listener to remove
109 * @since 12804
110 */
111 public static void removeOsmApiInitializationListener(OsmApiInitializationListener listener) {
112 listeners.removeListener(listener);
113 }
114
115 /**
116 * Replies the {@link OsmApi} for a given server URL
117 *
118 * @param serverUrl the server URL
119 * @return the OsmApi
120 * @throws IllegalArgumentException if serverUrl is null
121 *
122 */
123 public static OsmApi getOsmApi(String serverUrl) {
124 OsmApi api = instances.get(serverUrl);
125 if (api == null) {
126 api = new OsmApi(serverUrl);
127 cacheInstance(api);
128 }
129 return api;
130 }
131
132 protected static void cacheInstance(OsmApi api) {
133 instances.put(api.getServerUrl(), api);
134 }
135
136 private static String getServerUrlFromPref() {
137 return Config.getPref().get("osm-server.url", Config.getUrls().getDefaultOsmApiUrl());
138 }
139
140 /**
141 * Replies the {@link OsmApi} for the URL given by the preference <code>osm-server.url</code>
142 *
143 * @return the OsmApi
144 */
145 public static OsmApi getOsmApi() {
146 return getOsmApi(getServerUrlFromPref());
147 }
148
149 /** Server URL */
150 private final String serverUrl;
151
152 /** Object describing current changeset */
153 private Changeset changeset;
154
155 /** API version used for server communications */
156 private String version;
157
158 /** API capabilities */
159 private Capabilities capabilities;
160
161 /** true if successfully initialized */
162 private boolean initialized;
163
164 /**
165 * Constructs a new {@code OsmApi} for a specific server URL.
166 *
167 * @param serverUrl the server URL. Must not be null
168 * @throws IllegalArgumentException if serverUrl is null
169 */
170 protected OsmApi(String serverUrl) {
171 CheckParameterUtil.ensureParameterNotNull(serverUrl, "serverUrl");
172 this.serverUrl = serverUrl;
173 }
174
175 /**
176 * Replies the OSM protocol version we use to talk to the server.
177 * @return protocol version, or null if not yet negotiated.
178 */
179 public String getVersion() {
180 return version;
181 }
182
183 /**
184 * Replies the host name of the server URL.
185 * @return the host name of the server URL, or null if the server URL is malformed.
186 */
187 public String getHost() {
188 String host = null;
189 try {
190 host = new URL(serverUrl).getHost();
191 } catch (MalformedURLException e) {
192 Logging.warn(e);
193 }
194 return host;
195 }
196
197 private class CapabilitiesCache extends CacheCustomContent<OsmTransferException> {
198
199 private static final String CAPABILITIES = "capabilities";
200
201 private final ProgressMonitor monitor;
202 private final boolean fastFail;
203
204 CapabilitiesCache(ProgressMonitor monitor, boolean fastFail) {
205 super(CAPABILITIES + getBaseUrl().hashCode(), CacheCustomContent.INTERVAL_WEEKLY);
206 this.monitor = monitor;
207 this.fastFail = fastFail;
208 }
209
210 @Override
211 protected boolean isOffline() {
212 return NetworkManager.isOffline(OnlineResource.OSM_API);
213 }
214
215 @Override
216 protected byte[] updateData() throws OsmTransferException {
217 return sendRequest("GET", CAPABILITIES, null, monitor, false, fastFail).getBytes(StandardCharsets.UTF_8);
218 }
219 }
220
221 /**
222 * Initializes this component by negotiating a protocol version with the server.
223 *
224 * @param monitor the progress monitor
225 * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
226 * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
227 */
228 public void initialize(ProgressMonitor monitor) throws OsmTransferCanceledException, OsmApiInitializationException {
229 initialize(monitor, false);
230 }
231
232 /**
233 * Initializes this component by negotiating a protocol version with the server, with the ability to control the timeout.
234 *
235 * @param monitor the progress monitor
236 * @param fastFail true to request quick initialisation with a small timeout (more likely to throw exception)
237 * @throws OsmTransferCanceledException If the initialisation has been cancelled by user.
238 * @throws OsmApiInitializationException If any other exception occurs. Use getCause() to get the original exception.
239 */
240 public void initialize(ProgressMonitor monitor, boolean fastFail) throws OsmTransferCanceledException, OsmApiInitializationException {
241 if (initialized)
242 return;
243 cancel = false;
244 try {
245 CapabilitiesCache cache = new CapabilitiesCache(monitor, fastFail);
246 try {
247 initializeCapabilities(cache.updateIfRequiredString());
248 } catch (SAXParseException parseException) {
249 Logging.trace(parseException);
250 // XML parsing may fail if JOSM previously stored a corrupted capabilities document (see #8278)
251 // In that case, force update and try again
252 initializeCapabilities(cache.updateForceString());
253 } catch (SecurityException e) {
254 Logging.log(Logging.LEVEL_ERROR, "Unable to initialize OSM API", e);
255 }
256 if (capabilities == null) {
257 if (NetworkManager.isOffline(OnlineResource.OSM_API)) {
258 Logging.warn(OfflineAccessException.forResource(tr("")).getMessage());
259 } else {
260 Logging.error(tr("Unable to initialize OSM API."));
261 }
262 return;
263 } else if (!capabilities.supportsVersion("0.6")) {
264 Logging.error(tr("This version of JOSM is incompatible with the configured server."));
265 Logging.error(tr("It supports protocol version 0.6, while the server says it supports {0} to {1}.",
266 capabilities.get("version", "minimum"), capabilities.get("version", "maximum")));
267 return;
268 } else {
269 version = "0.6";
270 initialized = true;
271 }
272
273 listeners.fireEvent(l -> l.apiInitialized(this));
274 } catch (OsmTransferCanceledException e) {
275 throw e;
276 } catch (OsmTransferException e) {
277 initialized = false;
278 NetworkManager.addNetworkError(url, Utils.getRootCause(e));
279 throw new OsmApiInitializationException(e);
280 } catch (SAXException | IOException | ParserConfigurationException e) {
281 initialized = false;
282 throw new OsmApiInitializationException(e);
283 }
284 }
285
286 private synchronized void initializeCapabilities(String xml) throws SAXException, IOException, ParserConfigurationException {
287 if (xml != null) {
288 capabilities = CapabilitiesParser.parse(new InputSource(new StringReader(xml)));
289 }
290 }
291
292 /**
293 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
294 * @param o the OSM primitive
295 * @param addBody true to generate the full XML, false to only generate the encapsulating tag
296 * @return XML string
297 */
298 protected final String toXml(IPrimitive o, boolean addBody) {
299 StringWriter swriter = new StringWriter();
300 try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
301 swriter.getBuffer().setLength(0);
302 osmWriter.setWithBody(addBody);
303 osmWriter.setChangeset(changeset);
304 osmWriter.header();
305 o.accept(osmWriter);
306 osmWriter.footer();
307 osmWriter.flush();
308 } catch (IOException e) {
309 Logging.warn(e);
310 }
311 return swriter.toString();
312 }
313
314 /**
315 * Makes an XML string from an OSM primitive. Uses the OsmWriter class.
316 * @param s the changeset
317 * @return XML string
318 */
319 protected final String toXml(Changeset s) {
320 StringWriter swriter = new StringWriter();
321 try (OsmWriter osmWriter = OsmWriterFactory.createOsmWriter(new PrintWriter(swriter), true, version)) {
322 swriter.getBuffer().setLength(0);
323 osmWriter.header();
324 osmWriter.visit(s);
325 osmWriter.footer();
326 osmWriter.flush();
327 } catch (IOException e) {
328 Logging.warn(e);
329 }
330 return swriter.toString();
331 }
332
333 private static String getBaseUrl(String serverUrl, String version) {
334 StringBuilder rv = new StringBuilder(serverUrl);
335 if (version != null) {
336 rv.append('/').append(version);
337 }
338 rv.append('/');
339 // this works around a ruby (or lighttpd) bug where two consecutive slashes in
340 // an URL will cause a "404 not found" response.
341 int p;
342 while ((p = rv.indexOf("//", rv.indexOf("://")+2)) > -1) {
343 rv.delete(p, p + 1);
344 }
345 return rv.toString();
346 }
347
348 /**
349 * Returns the base URL for API requests, including the negotiated version number.
350 * @return base URL string
351 */
352 public String getBaseUrl() {
353 return getBaseUrl(serverUrl, version);
354 }
355
356 /**
357 * Returns the server URL
358 * @return the server URL
359 * @since 9353
360 */
361 public String getServerUrl() {
362 return serverUrl;
363 }
364
365 private void individualPrimitiveModification(String method, String verb, IPrimitive osm, ProgressMonitor monitor,
366 Consumer<String> consumer, UnaryOperator<String> errHandler) throws OsmTransferException {
367 String ret = "";
368 try {
369 ensureValidChangeset();
370 initialize(monitor);
371 // Perform request
372 ret = sendRequest(method, OsmPrimitiveType.from(osm).getAPIName() + '/' + verb, toXml(osm, true), monitor);
373 // Unlock dataset if needed
374 boolean locked = false;
375 if (osm instanceof OsmPrimitive) {
376 locked = ((OsmPrimitive) osm).getDataSet().isLocked();
377 if (locked) {
378 ((OsmPrimitive) osm).getDataSet().unlock();
379 }
380 }
381 try {
382 // Update local primitive
383 consumer.accept(ret);
384 } finally {
385 // Lock dataset back if needed
386 if (locked) {
387 ((OsmPrimitive) osm).getDataSet().lock();
388 }
389 }
390 } catch (NumberFormatException e) {
391 throw new OsmTransferException(errHandler.apply(ret), e);
392 }
393 }
394
395 /**
396 * Creates an OSM primitive on the server. The OsmPrimitive object passed in
397 * is modified by giving it the server-assigned id.
398 *
399 * @param osm the primitive
400 * @param monitor the progress monitor
401 * @throws OsmTransferException if something goes wrong
402 */
403 public void createPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
404 individualPrimitiveModification("PUT", "create", osm, monitor, ret -> {
405 osm.setOsmId(Long.parseLong(ret.trim()), 1);
406 osm.setChangesetId(getChangeset().getId());
407 }, ret -> tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret));
408 }
409
410 /**
411 * Modifies an OSM primitive on the server.
412 *
413 * @param osm the primitive. Must not be null.
414 * @param monitor the progress monitor
415 * @throws OsmTransferException if something goes wrong
416 */
417 public void modifyPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
418 individualPrimitiveModification("PUT", Long.toString(osm.getId()), osm, monitor, ret -> {
419 // API returns new object version
420 osm.setOsmId(osm.getId(), Integer.parseInt(ret.trim()));
421 osm.setChangesetId(getChangeset().getId());
422 osm.setVisible(true);
423 }, ret -> tr("Unexpected format of new version of modified primitive ''{0}''. Got ''{1}''.", osm.getId(), ret));
424 }
425
426 /**
427 * Deletes an OSM primitive on the server.
428 *
429 * @param osm the primitive
430 * @param monitor the progress monitor
431 * @throws OsmTransferException if something goes wrong
432 */
433 public void deletePrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
434 individualPrimitiveModification("DELETE", Long.toString(osm.getId()), osm, monitor, ret -> {
435 // API returns new object version
436 osm.setOsmId(osm.getId(), Integer.parseInt(ret.trim()));
437 osm.setChangesetId(getChangeset().getId());
438 osm.setVisible(false);
439 }, ret -> tr("Unexpected format of new version of deleted primitive ''{0}''. Got ''{1}''.", osm.getId(), ret));
440 }
441
442 /**
443 * Creates a new changeset based on the keys in <code>changeset</code>. If this
444 * method succeeds, changeset.getId() replies the id the server assigned to the new changeset
445 *
446 * The changeset must not be null, but its key/value-pairs may be empty.
447 *
448 * @param changeset the changeset toe be created. Must not be null.
449 * @param progressMonitor the progress monitor
450 * @throws OsmTransferException signifying a non-200 return code, or connection errors
451 * @throws IllegalArgumentException if changeset is null
452 */
453 public void openChangeset(Changeset changeset, ProgressMonitor progressMonitor) throws OsmTransferException {
454 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
455 try {
456 progressMonitor.beginTask(tr("Creating changeset..."));
457 initialize(progressMonitor);
458 String ret = "";
459 try {
460 ret = sendPutRequest("changeset/create", toXml(changeset), progressMonitor);
461 changeset.setId(Integer.parseInt(ret.trim()));
462 changeset.setOpen(true);
463 } catch (NumberFormatException e) {
464 throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret), e);
465 }
466 progressMonitor.setCustomText(tr("Successfully opened changeset {0}", changeset.getId()));
467 } finally {
468 progressMonitor.finishTask();
469 }
470 }
471
472 /**
473 * Updates a changeset with the keys in <code>changesetUpdate</code>. The changeset must not
474 * be null and id &gt; 0 must be true.
475 *
476 * @param changeset the changeset to update. Must not be null.
477 * @param monitor the progress monitor. If null, uses the {@link NullProgressMonitor#INSTANCE}.
478 *
479 * @throws OsmTransferException if something goes wrong.
480 * @throws IllegalArgumentException if changeset is null
481 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
482 *
483 */
484 public void updateChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
485 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
486 if (monitor == null) {
487 monitor = NullProgressMonitor.INSTANCE;
488 }
489 if (changeset.getId() <= 0)
490 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
491 try {
492 monitor.beginTask(tr("Updating changeset..."));
493 initialize(monitor);
494 monitor.setCustomText(tr("Updating changeset {0}...", changeset.getId()));
495 sendPutRequest("changeset/" + changeset.getId(), toXml(changeset), monitor);
496 } catch (ChangesetClosedException e) {
497 e.setSource(ChangesetClosedException.Source.UPDATE_CHANGESET);
498 throw e;
499 } catch (OsmApiException e) {
500 String errorHeader = e.getErrorHeader();
501 if (e.getResponseCode() == HttpURLConnection.HTTP_CONFLICT && ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
502 throw new ChangesetClosedException(errorHeader, ChangesetClosedException.Source.UPDATE_CHANGESET, e);
503 throw e;
504 } finally {
505 monitor.finishTask();
506 }
507 }
508
509 /**
510 * Closes a changeset on the server. Sets changeset.setOpen(false) if this operation succeeds.
511 *
512 * @param changeset the changeset to be closed. Must not be null. changeset.getId() &gt; 0 required.
513 * @param monitor the progress monitor. If null, uses {@link NullProgressMonitor#INSTANCE}
514 *
515 * @throws OsmTransferException if something goes wrong.
516 * @throws IllegalArgumentException if changeset is null
517 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
518 */
519 public void closeChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
520 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
521 if (monitor == null) {
522 monitor = NullProgressMonitor.INSTANCE;
523 }
524 if (changeset.getId() <= 0)
525 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
526 try {
527 monitor.beginTask(tr("Closing changeset..."));
528 initialize(monitor);
529 // send "\r\n" instead of empty string, so we don't send zero payload - workaround bugs in proxy software
530 sendPutRequest("changeset/" + changeset.getId() + "/close", "\r\n", monitor);
531 changeset.setOpen(false);
532 } finally {
533 monitor.finishTask();
534 }
535 }
536
537 /**
538 * Uploads a list of changes in "diff" form to the server.
539 *
540 * @param list the list of changed OSM Primitives
541 * @param monitor the progress monitor
542 * @return list of processed primitives
543 * @throws OsmTransferException if something is wrong
544 */
545 public Collection<OsmPrimitive> uploadDiff(Collection<? extends OsmPrimitive> list, ProgressMonitor monitor)
546 throws OsmTransferException {
547 try {
548 monitor.beginTask("", list.size() * 2);
549 if (changeset == null)
550 throw new OsmTransferException(tr("No changeset present for diff upload."));
551
552 initialize(monitor);
553
554 // prepare upload request
555 //
556 OsmChangeBuilder changeBuilder = new OsmChangeBuilder(changeset);
557 monitor.subTask(tr("Preparing upload request..."));
558 changeBuilder.start();
559 changeBuilder.append(list);
560 changeBuilder.finish();
561 String diffUploadRequest = changeBuilder.getDocument();
562
563 // Upload to the server
564 //
565 monitor.indeterminateSubTask(
566 trn("Uploading {0} object...", "Uploading {0} objects...", list.size(), list.size()));
567 String diffUploadResponse = sendPostRequest("changeset/" + changeset.getId() + "/upload", diffUploadRequest, monitor);
568
569 // Process the response from the server
570 //
571 DiffResultProcessor reader = new DiffResultProcessor(list);
572 reader.parse(diffUploadResponse, monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
573 return reader.postProcess(
574 getChangeset(),
575 monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)
576 );
577 } catch (OsmTransferException e) {
578 throw e;
579 } catch (XmlParsingException e) {
580 throw new OsmTransferException(e);
581 } finally {
582 monitor.finishTask();
583 }
584 }
585
586 private void sleepAndListen(int retry, ProgressMonitor monitor) throws OsmTransferCanceledException {
587 Logging.info(tr("Waiting 10 seconds ... "));
588 for (int i = 0; i < 10; i++) {
589 if (monitor != null) {
590 monitor.setCustomText(tr("Starting retry {0} of {1} in {2} seconds ...", getMaxRetries() - retry, getMaxRetries(), 10-i));
591 }
592 if (cancel)
593 throw new OsmTransferCanceledException("Operation canceled" + (i > 0 ? " in retry #"+i : ""));
594 try {
595 Thread.sleep(1000);
596 } catch (InterruptedException ex) {
597 Logging.warn("InterruptedException in "+getClass().getSimpleName()+" during sleep");
598 Thread.currentThread().interrupt();
599 }
600 }
601 Logging.info(tr("OK - trying again."));
602 }
603
604 /**
605 * Replies the max. number of retries in case of 5XX errors on the server
606 *
607 * @return the max number of retries
608 */
609 protected int getMaxRetries() {
610 int ret = Config.getPref().getInt("osm-server.max-num-retries", DEFAULT_MAX_NUM_RETRIES);
611 return Math.max(ret, 0);
612 }
613
614 /**
615 * Determines if JOSM is configured to access OSM API via OAuth
616 * @return {@code true} if JOSM is configured to access OSM API via OAuth, {@code false} otherwise
617 * @since 6349
618 */
619 public static boolean isUsingOAuth() {
620 return "oauth".equals(getAuthMethod());
621 }
622
623 /**
624 * Returns the authentication method set in the preferences
625 * @return the authentication method
626 */
627 public static String getAuthMethod() {
628 return Config.getPref().get("osm-server.auth-method", "oauth");
629 }
630
631 protected final String sendPostRequest(String urlSuffix, String requestBody, ProgressMonitor monitor) throws OsmTransferException {
632 // Send a POST request that includes authentication credentials
633 return sendRequest("POST", urlSuffix, requestBody, monitor);
634 }
635
636 protected final String sendPutRequest(String urlSuffix, String requestBody, ProgressMonitor monitor) throws OsmTransferException {
637 // Send a PUT request that includes authentication credentials
638 return sendRequest("PUT", urlSuffix, requestBody, monitor);
639 }
640
641 protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor)
642 throws OsmTransferException {
643 return sendRequest(requestMethod, urlSuffix, requestBody, monitor, true, false);
644 }
645
646 /**
647 * Generic method for sending requests to the OSM API.
648 *
649 * This method will automatically re-try any requests that are answered with a 5xx
650 * error code, or that resulted in a timeout exception from the TCP layer.
651 *
652 * @param requestMethod The http method used when talking with the server.
653 * @param urlSuffix The suffix to add at the server url, not including the version number,
654 * but including any object ids (e.g. "/way/1234/history").
655 * @param requestBody the body of the HTTP request, if any.
656 * @param monitor the progress monitor
657 * @param doAuthenticate set to true, if the request sent to the server shall include authentication
658 * credentials;
659 * @param fastFail true to request a short timeout
660 *
661 * @return the body of the HTTP response, if and only if the response code was "200 OK".
662 * @throws OsmTransferException if the HTTP return code was not 200 (and retries have
663 * been exhausted), or rewrapping a Java exception.
664 */
665 protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor,
666 boolean doAuthenticate, boolean fastFail) throws OsmTransferException {
667 int retries = fastFail ? 0 : getMaxRetries();
668
669 while (true) { // the retry loop
670 try {
671 url = new URL(new URL(getBaseUrl()), urlSuffix);
672 final HttpClient client = HttpClient.create(url, requestMethod)
673 .keepAlive(false)
674 .setAccept("application/xml, */*;q=0.8");
675 activeConnection = client;
676 if (fastFail) {
677 client.setConnectTimeout(1000);
678 client.setReadTimeout(1000);
679 } else {
680 // use default connect timeout from org.openstreetmap.josm.tools.HttpClient.connectTimeout
681 client.setReadTimeout(0);
682 }
683 if (doAuthenticate) {
684 addAuth(client);
685 }
686
687 if ("PUT".equals(requestMethod) || "POST".equals(requestMethod) || "DELETE".equals(requestMethod)) {
688 client.setHeader("Content-Type", "text/xml");
689 // It seems that certain bits of the Ruby API are very unhappy upon
690 // receipt of a PUT/POST message without a Content-length header,
691 // even if the request has no payload.
692 // Since Java will not generate a Content-length header unless
693 // we use the output stream, we create an output stream for PUT/POST
694 // even if there is no payload.
695 client.setRequestBody((requestBody != null ? requestBody : "").getBytes(StandardCharsets.UTF_8));
696 }
697
698 final HttpClient.Response response = client.connect();
699 Logging.info(response.getResponseMessage());
700 int retCode = response.getResponseCode();
701
702 if (retCode >= 500 && retries-- > 0) {
703 sleepAndListen(retries, monitor);
704 Logging.info(tr("Starting retry {0} of {1}.", getMaxRetries() - retries, getMaxRetries()));
705 continue;
706 }
707
708 final String responseBody = response.fetchContent();
709
710 String errorHeader = null;
711 // Look for a detailed error message from the server
712 if (response.getHeaderField("Error") != null) {
713 errorHeader = response.getHeaderField("Error");
714 Logging.error("Error header: " + errorHeader);
715 } else if (retCode != HttpURLConnection.HTTP_OK && responseBody.length() > 0) {
716 Logging.error("Error body: " + responseBody);
717 }
718 activeConnection.disconnect();
719
720 errorHeader = errorHeader == null ? null : errorHeader.trim();
721 String errorBody = responseBody.length() == 0 ? null : responseBody.trim();
722 switch(retCode) {
723 case HttpURLConnection.HTTP_OK:
724 return responseBody;
725 case HttpURLConnection.HTTP_GONE:
726 throw new OsmApiPrimitiveGoneException(errorHeader, errorBody);
727 case HttpURLConnection.HTTP_CONFLICT:
728 if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
729 throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA);
730 else
731 throw new OsmApiException(retCode, errorHeader, errorBody);
732 case HttpURLConnection.HTTP_UNAUTHORIZED:
733 case HttpURLConnection.HTTP_FORBIDDEN:
734 CredentialsManager.getInstance().purgeCredentialsCache(RequestorType.SERVER);
735 throw new OsmApiException(retCode, errorHeader, errorBody, activeConnection.getURL().toString(),
736 doAuthenticate ? retrieveBasicAuthorizationLogin(client) : null, response.getContentType());
737 default:
738 throw new OsmApiException(retCode, errorHeader, errorBody);
739 }
740 } catch (SocketTimeoutException | ConnectException e) {
741 if (retries-- > 0) {
742 continue;
743 }
744 throw new OsmTransferException(e);
745 } catch (IOException e) {
746 throw new OsmTransferException(e);
747 } catch (OsmTransferException e) {
748 throw e;
749 }
750 }
751 }
752
753 /**
754 * Replies the API capabilities.
755 *
756 * @return the API capabilities, or null, if the API is not initialized yet
757 */
758 public synchronized Capabilities getCapabilities() {
759 return capabilities;
760 }
761
762 /**
763 * Ensures that the current changeset can be used for uploading data
764 *
765 * @throws OsmTransferException if the current changeset can't be used for uploading data
766 */
767 protected void ensureValidChangeset() throws OsmTransferException {
768 if (changeset == null)
769 throw new OsmTransferException(tr("Current changeset is null. Cannot upload data."));
770 if (changeset.getId() <= 0)
771 throw new OsmTransferException(tr("ID of current changeset > 0 required. Current ID is {0}.", changeset.getId()));
772 }
773
774 /**
775 * Replies the changeset data uploads are currently directed to
776 *
777 * @return the changeset data uploads are currently directed to
778 */
779 public Changeset getChangeset() {
780 return changeset;
781 }
782
783 /**
784 * Sets the changesets to which further data uploads are directed. The changeset
785 * can be null. If it isn't null it must have been created, i.e. id &gt; 0 is required. Furthermore,
786 * it must be open.
787 *
788 * @param changeset the changeset
789 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
790 * @throws IllegalArgumentException if !changeset.isOpen()
791 */
792 public void setChangeset(Changeset changeset) {
793 if (changeset == null) {
794 this.changeset = null;
795 return;
796 }
797 if (changeset.getId() <= 0)
798 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
799 if (!changeset.isOpen())
800 throw new IllegalArgumentException(tr("Open changeset expected. Got closed changeset with id {0}.", changeset.getId()));
801 this.changeset = changeset;
802 }
803
804 private static StringBuilder noteStringBuilder(Note note) {
805 return new StringBuilder().append("notes/").append(note.getId());
806 }
807
808 /**
809 * Create a new note on the server.
810 * @param latlon Location of note
811 * @param text Comment entered by user to open the note
812 * @param monitor Progress monitor
813 * @return Note as it exists on the server after creation (ID assigned)
814 * @throws OsmTransferException if any error occurs during dialog with OSM API
815 */
816 public Note createNote(LatLon latlon, String text, ProgressMonitor monitor) throws OsmTransferException {
817 initialize(monitor);
818 String noteUrl = new StringBuilder()
819 .append("notes?lat=")
820 .append(latlon.lat())
821 .append("&lon=")
822 .append(latlon.lon())
823 .append("&text=")
824 .append(Utils.encodeUrl(text)).toString();
825
826 return parseSingleNote(sendPostRequest(noteUrl, null, monitor));
827 }
828
829 /**
830 * Add a comment to an existing note.
831 * @param note The note to add a comment to
832 * @param comment Text of the comment
833 * @param monitor Progress monitor
834 * @return Note returned by the API after the comment was added
835 * @throws OsmTransferException if any error occurs during dialog with OSM API
836 */
837 public Note addCommentToNote(Note note, String comment, ProgressMonitor monitor) throws OsmTransferException {
838 initialize(monitor);
839 String noteUrl = noteStringBuilder(note)
840 .append("/comment?text=")
841 .append(Utils.encodeUrl(comment)).toString();
842
843 return parseSingleNote(sendPostRequest(noteUrl, null, monitor));
844 }
845
846 /**
847 * Close a note.
848 * @param note Note to close. Must currently be open
849 * @param closeMessage Optional message supplied by the user when closing the note
850 * @param monitor Progress monitor
851 * @return Note returned by the API after the close operation
852 * @throws OsmTransferException if any error occurs during dialog with OSM API
853 */
854 public Note closeNote(Note note, String closeMessage, ProgressMonitor monitor) throws OsmTransferException {
855 initialize(monitor);
856 String encodedMessage = Utils.encodeUrl(closeMessage);
857 StringBuilder urlBuilder = noteStringBuilder(note)
858 .append("/close");
859 if (!encodedMessage.trim().isEmpty()) {
860 urlBuilder.append("?text=");
861 urlBuilder.append(encodedMessage);
862 }
863
864 return parseSingleNote(sendPostRequest(urlBuilder.toString(), null, monitor));
865 }
866
867 /**
868 * Reopen a closed note
869 * @param note Note to reopen. Must currently be closed
870 * @param reactivateMessage Optional message supplied by the user when reopening the note
871 * @param monitor Progress monitor
872 * @return Note returned by the API after the reopen operation
873 * @throws OsmTransferException if any error occurs during dialog with OSM API
874 */
875 public Note reopenNote(Note note, String reactivateMessage, ProgressMonitor monitor) throws OsmTransferException {
876 initialize(monitor);
877 String encodedMessage = Utils.encodeUrl(reactivateMessage);
878 StringBuilder urlBuilder = noteStringBuilder(note)
879 .append("/reopen");
880 if (!encodedMessage.trim().isEmpty()) {
881 urlBuilder.append("?text=");
882 urlBuilder.append(encodedMessage);
883 }
884
885 return parseSingleNote(sendPostRequest(urlBuilder.toString(), null, monitor));
886 }
887
888 /**
889 * Method for parsing API responses for operations on individual notes
890 * @param xml the API response as XML data
891 * @return the resulting Note
892 * @throws OsmTransferException if the API response cannot be parsed
893 */
894 private static Note parseSingleNote(String xml) throws OsmTransferException {
895 try {
896 List<Note> newNotes = new NoteReader(xml).parse();
897 if (newNotes.size() == 1) {
898 return newNotes.get(0);
899 }
900 // Shouldn't ever execute. Server will either respond with an error (caught elsewhere) or one note
901 throw new OsmTransferException(tr("Note upload failed"));
902 } catch (SAXException | IOException e) {
903 Logging.error(e);
904 throw new OsmTransferException(tr("Error parsing note response from server"), e);
905 }
906 }
907}
Note: See TracBrowser for help on using the repository browser.