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

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

see #20129 - Fix typos and misspellings in the code (patch by gaben)

  • Property svn:eol-style set to native
File size: 37.0 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 = sendRequest("PUT", "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 sendRequest(
496 "PUT",
497 "changeset/" + changeset.getId(),
498 toXml(changeset),
499 monitor
500 );
501 } catch (ChangesetClosedException e) {
502 e.setSource(ChangesetClosedException.Source.UPDATE_CHANGESET);
503 throw e;
504 } catch (OsmApiException e) {
505 String errorHeader = e.getErrorHeader();
506 if (e.getResponseCode() == HttpURLConnection.HTTP_CONFLICT && ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
507 throw new ChangesetClosedException(errorHeader, ChangesetClosedException.Source.UPDATE_CHANGESET, e);
508 throw e;
509 } finally {
510 monitor.finishTask();
511 }
512 }
513
514 /**
515 * Closes a changeset on the server. Sets changeset.setOpen(false) if this operation succeeds.
516 *
517 * @param changeset the changeset to be closed. Must not be null. changeset.getId() &gt; 0 required.
518 * @param monitor the progress monitor. If null, uses {@link NullProgressMonitor#INSTANCE}
519 *
520 * @throws OsmTransferException if something goes wrong.
521 * @throws IllegalArgumentException if changeset is null
522 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
523 */
524 public void closeChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
525 CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
526 if (monitor == null) {
527 monitor = NullProgressMonitor.INSTANCE;
528 }
529 if (changeset.getId() <= 0)
530 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
531 try {
532 monitor.beginTask(tr("Closing changeset..."));
533 initialize(monitor);
534 /* send "\r\n" instead of empty string, so we don't send zero payload - works around bugs
535 in proxy software */
536 sendRequest("PUT", "changeset" + "/" + changeset.getId() + "/close", "\r\n", monitor);
537 changeset.setOpen(false);
538 } finally {
539 monitor.finishTask();
540 }
541 }
542
543 /**
544 * Uploads a list of changes in "diff" form to the server.
545 *
546 * @param list the list of changed OSM Primitives
547 * @param monitor the progress monitor
548 * @return list of processed primitives
549 * @throws OsmTransferException if something is wrong
550 */
551 public Collection<OsmPrimitive> uploadDiff(Collection<? extends OsmPrimitive> list, ProgressMonitor monitor)
552 throws OsmTransferException {
553 try {
554 monitor.beginTask("", list.size() * 2);
555 if (changeset == null)
556 throw new OsmTransferException(tr("No changeset present for diff upload."));
557
558 initialize(monitor);
559
560 // prepare upload request
561 //
562 OsmChangeBuilder changeBuilder = new OsmChangeBuilder(changeset);
563 monitor.subTask(tr("Preparing upload request..."));
564 changeBuilder.start();
565 changeBuilder.append(list);
566 changeBuilder.finish();
567 String diffUploadRequest = changeBuilder.getDocument();
568
569 // Upload to the server
570 //
571 monitor.indeterminateSubTask(
572 trn("Uploading {0} object...", "Uploading {0} objects...", list.size(), list.size()));
573 String diffUploadResponse = sendRequest("POST", "changeset/" + changeset.getId() + "/upload", diffUploadRequest, monitor);
574
575 // Process the response from the server
576 //
577 DiffResultProcessor reader = new DiffResultProcessor(list);
578 reader.parse(diffUploadResponse, monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
579 return reader.postProcess(
580 getChangeset(),
581 monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)
582 );
583 } catch (OsmTransferException e) {
584 throw e;
585 } catch (XmlParsingException e) {
586 throw new OsmTransferException(e);
587 } finally {
588 monitor.finishTask();
589 }
590 }
591
592 private void sleepAndListen(int retry, ProgressMonitor monitor) throws OsmTransferCanceledException {
593 Logging.info(tr("Waiting 10 seconds ... "));
594 for (int i = 0; i < 10; i++) {
595 if (monitor != null) {
596 monitor.setCustomText(tr("Starting retry {0} of {1} in {2} seconds ...", getMaxRetries() - retry, getMaxRetries(), 10-i));
597 }
598 if (cancel)
599 throw new OsmTransferCanceledException("Operation canceled" + (i > 0 ? " in retry #"+i : ""));
600 try {
601 Thread.sleep(1000);
602 } catch (InterruptedException ex) {
603 Logging.warn("InterruptedException in "+getClass().getSimpleName()+" during sleep");
604 Thread.currentThread().interrupt();
605 }
606 }
607 Logging.info(tr("OK - trying again."));
608 }
609
610 /**
611 * Replies the max. number of retries in case of 5XX errors on the server
612 *
613 * @return the max number of retries
614 */
615 protected int getMaxRetries() {
616 int ret = Config.getPref().getInt("osm-server.max-num-retries", DEFAULT_MAX_NUM_RETRIES);
617 return Math.max(ret, 0);
618 }
619
620 /**
621 * Determines if JOSM is configured to access OSM API via OAuth
622 * @return {@code true} if JOSM is configured to access OSM API via OAuth, {@code false} otherwise
623 * @since 6349
624 */
625 public static boolean isUsingOAuth() {
626 return "oauth".equals(getAuthMethod());
627 }
628
629 /**
630 * Returns the authentication method set in the preferences
631 * @return the authentication method
632 */
633 public static String getAuthMethod() {
634 return Config.getPref().get("osm-server.auth-method", "oauth");
635 }
636
637 protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor)
638 throws OsmTransferException {
639 return sendRequest(requestMethod, urlSuffix, requestBody, monitor, true, false);
640 }
641
642 /**
643 * Generic method for sending requests to the OSM API.
644 *
645 * This method will automatically re-try any requests that are answered with a 5xx
646 * error code, or that resulted in a timeout exception from the TCP layer.
647 *
648 * @param requestMethod The http method used when talking with the server.
649 * @param urlSuffix The suffix to add at the server url, not including the version number,
650 * but including any object ids (e.g. "/way/1234/history").
651 * @param requestBody the body of the HTTP request, if any.
652 * @param monitor the progress monitor
653 * @param doAuthenticate set to true, if the request sent to the server shall include authentication
654 * credentials;
655 * @param fastFail true to request a short timeout
656 *
657 * @return the body of the HTTP response, if and only if the response code was "200 OK".
658 * @throws OsmTransferException if the HTTP return code was not 200 (and retries have
659 * been exhausted), or rewrapping a Java exception.
660 */
661 protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor,
662 boolean doAuthenticate, boolean fastFail) throws OsmTransferException {
663 int retries = fastFail ? 0 : getMaxRetries();
664
665 while (true) { // the retry loop
666 try {
667 url = new URL(new URL(getBaseUrl()), urlSuffix);
668 final HttpClient client = HttpClient.create(url, requestMethod)
669 .keepAlive(false)
670 .setAccept("application/xml, */*;q=0.8");
671 activeConnection = client;
672 if (fastFail) {
673 client.setConnectTimeout(1000);
674 client.setReadTimeout(1000);
675 } else {
676 // use default connect timeout from org.openstreetmap.josm.tools.HttpClient.connectTimeout
677 client.setReadTimeout(0);
678 }
679 if (doAuthenticate) {
680 addAuth(client);
681 }
682
683 if ("PUT".equals(requestMethod) || "POST".equals(requestMethod) || "DELETE".equals(requestMethod)) {
684 client.setHeader("Content-Type", "text/xml");
685 // It seems that certain bits of the Ruby API are very unhappy upon
686 // receipt of a PUT/POST message without a Content-length header,
687 // even if the request has no payload.
688 // Since Java will not generate a Content-length header unless
689 // we use the output stream, we create an output stream for PUT/POST
690 // even if there is no payload.
691 client.setRequestBody((requestBody != null ? requestBody : "").getBytes(StandardCharsets.UTF_8));
692 }
693
694 final HttpClient.Response response = client.connect();
695 Logging.info(response.getResponseMessage());
696 int retCode = response.getResponseCode();
697
698 if (retCode >= 500 && retries-- > 0) {
699 sleepAndListen(retries, monitor);
700 Logging.info(tr("Starting retry {0} of {1}.", getMaxRetries() - retries, getMaxRetries()));
701 continue;
702 }
703
704 final String responseBody = response.fetchContent();
705
706 String errorHeader = null;
707 // Look for a detailed error message from the server
708 if (response.getHeaderField("Error") != null) {
709 errorHeader = response.getHeaderField("Error");
710 Logging.error("Error header: " + errorHeader);
711 } else if (retCode != HttpURLConnection.HTTP_OK && responseBody.length() > 0) {
712 Logging.error("Error body: " + responseBody);
713 }
714 activeConnection.disconnect();
715
716 errorHeader = errorHeader == null ? null : errorHeader.trim();
717 String errorBody = responseBody.length() == 0 ? null : responseBody.trim();
718 switch(retCode) {
719 case HttpURLConnection.HTTP_OK:
720 return responseBody;
721 case HttpURLConnection.HTTP_GONE:
722 throw new OsmApiPrimitiveGoneException(errorHeader, errorBody);
723 case HttpURLConnection.HTTP_CONFLICT:
724 if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
725 throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA);
726 else
727 throw new OsmApiException(retCode, errorHeader, errorBody);
728 case HttpURLConnection.HTTP_UNAUTHORIZED:
729 case HttpURLConnection.HTTP_FORBIDDEN:
730 CredentialsManager.getInstance().purgeCredentialsCache(RequestorType.SERVER);
731 throw new OsmApiException(retCode, errorHeader, errorBody, activeConnection.getURL().toString(),
732 doAuthenticate ? retrieveBasicAuthorizationLogin(client) : null, response.getContentType());
733 default:
734 throw new OsmApiException(retCode, errorHeader, errorBody);
735 }
736 } catch (SocketTimeoutException | ConnectException e) {
737 if (retries-- > 0) {
738 continue;
739 }
740 throw new OsmTransferException(e);
741 } catch (IOException e) {
742 throw new OsmTransferException(e);
743 } catch (OsmTransferException e) {
744 throw e;
745 }
746 }
747 }
748
749 /**
750 * Replies the API capabilities.
751 *
752 * @return the API capabilities, or null, if the API is not initialized yet
753 */
754 public synchronized Capabilities getCapabilities() {
755 return capabilities;
756 }
757
758 /**
759 * Ensures that the current changeset can be used for uploading data
760 *
761 * @throws OsmTransferException if the current changeset can't be used for uploading data
762 */
763 protected void ensureValidChangeset() throws OsmTransferException {
764 if (changeset == null)
765 throw new OsmTransferException(tr("Current changeset is null. Cannot upload data."));
766 if (changeset.getId() <= 0)
767 throw new OsmTransferException(tr("ID of current changeset > 0 required. Current ID is {0}.", changeset.getId()));
768 }
769
770 /**
771 * Replies the changeset data uploads are currently directed to
772 *
773 * @return the changeset data uploads are currently directed to
774 */
775 public Changeset getChangeset() {
776 return changeset;
777 }
778
779 /**
780 * Sets the changesets to which further data uploads are directed. The changeset
781 * can be null. If it isn't null it must have been created, i.e. id &gt; 0 is required. Furthermore,
782 * it must be open.
783 *
784 * @param changeset the changeset
785 * @throws IllegalArgumentException if changeset.getId() &lt;= 0
786 * @throws IllegalArgumentException if !changeset.isOpen()
787 */
788 public void setChangeset(Changeset changeset) {
789 if (changeset == null) {
790 this.changeset = null;
791 return;
792 }
793 if (changeset.getId() <= 0)
794 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
795 if (!changeset.isOpen())
796 throw new IllegalArgumentException(tr("Open changeset expected. Got closed changeset with id {0}.", changeset.getId()));
797 this.changeset = changeset;
798 }
799
800 private static StringBuilder noteStringBuilder(Note note) {
801 return new StringBuilder().append("notes/").append(note.getId());
802 }
803
804 /**
805 * Create a new note on the server.
806 * @param latlon Location of note
807 * @param text Comment entered by user to open the note
808 * @param monitor Progress monitor
809 * @return Note as it exists on the server after creation (ID assigned)
810 * @throws OsmTransferException if any error occurs during dialog with OSM API
811 */
812 public Note createNote(LatLon latlon, String text, ProgressMonitor monitor) throws OsmTransferException {
813 initialize(monitor);
814 String noteUrl = new StringBuilder()
815 .append("notes?lat=")
816 .append(latlon.lat())
817 .append("&lon=")
818 .append(latlon.lon())
819 .append("&text=")
820 .append(Utils.encodeUrl(text)).toString();
821
822 String response = sendRequest("POST", noteUrl, null, monitor, true, false);
823 return parseSingleNote(response);
824 }
825
826 /**
827 * Add a comment to an existing note.
828 * @param note The note to add a comment to
829 * @param comment Text of the comment
830 * @param monitor Progress monitor
831 * @return Note returned by the API after the comment was added
832 * @throws OsmTransferException if any error occurs during dialog with OSM API
833 */
834 public Note addCommentToNote(Note note, String comment, ProgressMonitor monitor) throws OsmTransferException {
835 initialize(monitor);
836 String noteUrl = noteStringBuilder(note)
837 .append("/comment?text=")
838 .append(Utils.encodeUrl(comment)).toString();
839
840 String response = sendRequest("POST", noteUrl, null, monitor, true, false);
841 return parseSingleNote(response);
842 }
843
844 /**
845 * Close a note.
846 * @param note Note to close. Must currently be open
847 * @param closeMessage Optional message supplied by the user when closing the note
848 * @param monitor Progress monitor
849 * @return Note returned by the API after the close operation
850 * @throws OsmTransferException if any error occurs during dialog with OSM API
851 */
852 public Note closeNote(Note note, String closeMessage, ProgressMonitor monitor) throws OsmTransferException {
853 initialize(monitor);
854 String encodedMessage = Utils.encodeUrl(closeMessage);
855 StringBuilder urlBuilder = noteStringBuilder(note)
856 .append("/close");
857 if (!encodedMessage.trim().isEmpty()) {
858 urlBuilder.append("?text=");
859 urlBuilder.append(encodedMessage);
860 }
861
862 String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false);
863 return parseSingleNote(response);
864 }
865
866 /**
867 * Reopen a closed note
868 * @param note Note to reopen. Must currently be closed
869 * @param reactivateMessage Optional message supplied by the user when reopening the note
870 * @param monitor Progress monitor
871 * @return Note returned by the API after the reopen operation
872 * @throws OsmTransferException if any error occurs during dialog with OSM API
873 */
874 public Note reopenNote(Note note, String reactivateMessage, ProgressMonitor monitor) throws OsmTransferException {
875 initialize(monitor);
876 String encodedMessage = Utils.encodeUrl(reactivateMessage);
877 StringBuilder urlBuilder = noteStringBuilder(note)
878 .append("/reopen");
879 if (!encodedMessage.trim().isEmpty()) {
880 urlBuilder.append("?text=");
881 urlBuilder.append(encodedMessage);
882 }
883
884 String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false);
885 return parseSingleNote(response);
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.