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