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

Last change on this file since 15969 was 15969, checked in by simon04, 4 years ago

see #18812 - OsmApi, OsmServerReader, NameFinder: specify Accept=application/xml, */*;q=0.8

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