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.tools.CheckParameterUtil; 039import org.openstreetmap.josm.tools.HttpClient; 040import org.openstreetmap.josm.tools.ListenerList; 041import org.openstreetmap.josm.tools.Logging; 042import org.openstreetmap.josm.tools.Utils; 043import org.openstreetmap.josm.tools.XmlParsingException; 044import org.xml.sax.InputSource; 045import org.xml.sax.SAXException; 046import org.xml.sax.SAXParseException; 047 048/** 049 * Class that encapsulates the communications with the <a href="http://wiki.openstreetmap.org/wiki/API_v0.6">OSM API</a>.<br><br> 050 * 051 * All interaction with the server-side OSM API should go through this class.<br><br> 052 * 053 * It is conceivable to extract this into an interface later and create various 054 * classes implementing the interface, to be able to talk to various kinds of servers. 055 * @since 1523 056 */ 057public class OsmApi extends OsmConnection { 058 059 /** 060 * Maximum number of retries to send a request in case of HTTP 500 errors or timeouts 061 */ 062 public static final int DEFAULT_MAX_NUM_RETRIES = 5; 063 064 /** 065 * Maximum number of concurrent download threads, imposed by 066 * <a href="http://wiki.openstreetmap.org/wiki/API_usage_policy#Technical_Usage_Requirements"> 067 * OSM API usage policy.</a> 068 * @since 5386 069 */ 070 public static final int MAX_DOWNLOAD_THREADS = 2; 071 072 // The collection of instantiated OSM APIs 073 private static final Map<String, OsmApi> instances = new HashMap<>(); 074 075 private static final ListenerList<OsmApiInitializationListener> listeners = ListenerList.create(); 076 077 private URL url; 078 079 /** 080 * OSM API initialization listener. 081 * @since 12804 082 */ 083 public interface OsmApiInitializationListener { 084 /** 085 * Called when an OSM API instance has been successfully initialized. 086 * @param instance the initialized OSM API instance 087 */ 088 void apiInitialized(OsmApi instance); 089 } 090 091 /** 092 * Adds a new OSM API initialization listener. 093 * @param listener OSM API initialization listener to add 094 * @since 12804 095 */ 096 public static void addOsmApiInitializationListener(OsmApiInitializationListener listener) { 097 listeners.addListener(listener); 098 } 099 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 > 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() <= 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() > 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() <= 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).keepAlive(false); 663 activeConnection = client; 664 if (fastFail) { 665 client.setConnectTimeout(1000); 666 client.setReadTimeout(1000); 667 } else { 668 // use default connect timeout from org.openstreetmap.josm.tools.HttpClient.connectTimeout 669 client.setReadTimeout(0); 670 } 671 if (doAuthenticate) { 672 addAuth(client); 673 } 674 675 if ("PUT".equals(requestMethod) || "POST".equals(requestMethod) || "DELETE".equals(requestMethod)) { 676 client.setHeader("Content-Type", "text/xml"); 677 // It seems that certain bits of the Ruby API are very unhappy upon 678 // receipt of a PUT/POST message without a Content-length header, 679 // even if the request has no payload. 680 // Since Java will not generate a Content-length header unless 681 // we use the output stream, we create an output stream for PUT/POST 682 // even if there is no payload. 683 client.setRequestBody((requestBody != null ? requestBody : "").getBytes(StandardCharsets.UTF_8)); 684 } 685 686 final HttpClient.Response response = client.connect(); 687 Logging.info(response.getResponseMessage()); 688 int retCode = response.getResponseCode(); 689 690 if (retCode >= 500 && retries-- > 0) { 691 sleepAndListen(retries, monitor); 692 Logging.info(tr("Starting retry {0} of {1}.", getMaxRetries() - retries, getMaxRetries())); 693 continue; 694 } 695 696 final String responseBody = response.fetchContent(); 697 698 String errorHeader = null; 699 // Look for a detailed error message from the server 700 if (response.getHeaderField("Error") != null) { 701 errorHeader = response.getHeaderField("Error"); 702 Logging.error("Error header: " + errorHeader); 703 } else if (retCode != HttpURLConnection.HTTP_OK && responseBody.length() > 0) { 704 Logging.error("Error body: " + responseBody); 705 } 706 activeConnection.disconnect(); 707 708 errorHeader = errorHeader == null ? null : errorHeader.trim(); 709 String errorBody = responseBody.length() == 0 ? null : responseBody.trim(); 710 switch(retCode) { 711 case HttpURLConnection.HTTP_OK: 712 return responseBody; 713 case HttpURLConnection.HTTP_GONE: 714 throw new OsmApiPrimitiveGoneException(errorHeader, errorBody); 715 case HttpURLConnection.HTTP_CONFLICT: 716 if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader)) 717 throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA); 718 else 719 throw new OsmApiException(retCode, errorHeader, errorBody); 720 case HttpURLConnection.HTTP_UNAUTHORIZED: 721 case HttpURLConnection.HTTP_FORBIDDEN: 722 CredentialsManager.getInstance().purgeCredentialsCache(RequestorType.SERVER); 723 throw new OsmApiException(retCode, errorHeader, errorBody, activeConnection.getURL().toString(), 724 doAuthenticate ? retrieveBasicAuthorizationLogin(client) : null, response.getContentType()); 725 default: 726 throw new OsmApiException(retCode, errorHeader, errorBody); 727 } 728 } catch (SocketTimeoutException | ConnectException e) { 729 if (retries-- > 0) { 730 continue; 731 } 732 throw new OsmTransferException(e); 733 } catch (IOException e) { 734 throw new OsmTransferException(e); 735 } catch (OsmTransferException e) { 736 throw e; 737 } 738 } 739 } 740 741 /** 742 * Replies the API capabilities. 743 * 744 * @return the API capabilities, or null, if the API is not initialized yet 745 */ 746 public synchronized Capabilities getCapabilities() { 747 return capabilities; 748 } 749 750 /** 751 * Ensures that the current changeset can be used for uploading data 752 * 753 * @throws OsmTransferException if the current changeset can't be used for uploading data 754 */ 755 protected void ensureValidChangeset() throws OsmTransferException { 756 if (changeset == null) 757 throw new OsmTransferException(tr("Current changeset is null. Cannot upload data.")); 758 if (changeset.getId() <= 0) 759 throw new OsmTransferException(tr("ID of current changeset > 0 required. Current ID is {0}.", changeset.getId())); 760 } 761 762 /** 763 * Replies the changeset data uploads are currently directed to 764 * 765 * @return the changeset data uploads are currently directed to 766 */ 767 public Changeset getChangeset() { 768 return changeset; 769 } 770 771 /** 772 * Sets the changesets to which further data uploads are directed. The changeset 773 * can be null. If it isn't null it must have been created, i.e. id > 0 is required. Furthermore, 774 * it must be open. 775 * 776 * @param changeset the changeset 777 * @throws IllegalArgumentException if changeset.getId() <= 0 778 * @throws IllegalArgumentException if !changeset.isOpen() 779 */ 780 public void setChangeset(Changeset changeset) { 781 if (changeset == null) { 782 this.changeset = null; 783 return; 784 } 785 if (changeset.getId() <= 0) 786 throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId())); 787 if (!changeset.isOpen()) 788 throw new IllegalArgumentException(tr("Open changeset expected. Got closed changeset with id {0}.", changeset.getId())); 789 this.changeset = changeset; 790 } 791 792 private static StringBuilder noteStringBuilder(Note note) { 793 return new StringBuilder().append("notes/").append(note.getId()); 794 } 795 796 /** 797 * Create a new note on the server. 798 * @param latlon Location of note 799 * @param text Comment entered by user to open the note 800 * @param monitor Progress monitor 801 * @return Note as it exists on the server after creation (ID assigned) 802 * @throws OsmTransferException if any error occurs during dialog with OSM API 803 */ 804 public Note createNote(LatLon latlon, String text, ProgressMonitor monitor) throws OsmTransferException { 805 initialize(monitor); 806 String noteUrl = new StringBuilder() 807 .append("notes?lat=") 808 .append(latlon.lat()) 809 .append("&lon=") 810 .append(latlon.lon()) 811 .append("&text=") 812 .append(Utils.encodeUrl(text)).toString(); 813 814 String response = sendRequest("POST", noteUrl, null, monitor, true, false); 815 return parseSingleNote(response); 816 } 817 818 /** 819 * Add a comment to an existing note. 820 * @param note The note to add a comment to 821 * @param comment Text of the comment 822 * @param monitor Progress monitor 823 * @return Note returned by the API after the comment was added 824 * @throws OsmTransferException if any error occurs during dialog with OSM API 825 */ 826 public Note addCommentToNote(Note note, String comment, ProgressMonitor monitor) throws OsmTransferException { 827 initialize(monitor); 828 String noteUrl = noteStringBuilder(note) 829 .append("/comment?text=") 830 .append(Utils.encodeUrl(comment)).toString(); 831 832 String response = sendRequest("POST", noteUrl, null, monitor, true, false); 833 return parseSingleNote(response); 834 } 835 836 /** 837 * Close a note. 838 * @param note Note to close. Must currently be open 839 * @param closeMessage Optional message supplied by the user when closing the note 840 * @param monitor Progress monitor 841 * @return Note returned by the API after the close operation 842 * @throws OsmTransferException if any error occurs during dialog with OSM API 843 */ 844 public Note closeNote(Note note, String closeMessage, ProgressMonitor monitor) throws OsmTransferException { 845 initialize(monitor); 846 String encodedMessage = Utils.encodeUrl(closeMessage); 847 StringBuilder urlBuilder = noteStringBuilder(note) 848 .append("/close"); 849 if (!encodedMessage.trim().isEmpty()) { 850 urlBuilder.append("?text="); 851 urlBuilder.append(encodedMessage); 852 } 853 854 String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false); 855 return parseSingleNote(response); 856 } 857 858 /** 859 * Reopen a closed note 860 * @param note Note to reopen. Must currently be closed 861 * @param reactivateMessage Optional message supplied by the user when reopening the note 862 * @param monitor Progress monitor 863 * @return Note returned by the API after the reopen operation 864 * @throws OsmTransferException if any error occurs during dialog with OSM API 865 */ 866 public Note reopenNote(Note note, String reactivateMessage, ProgressMonitor monitor) throws OsmTransferException { 867 initialize(monitor); 868 String encodedMessage = Utils.encodeUrl(reactivateMessage); 869 StringBuilder urlBuilder = noteStringBuilder(note) 870 .append("/reopen"); 871 if (!encodedMessage.trim().isEmpty()) { 872 urlBuilder.append("?text="); 873 urlBuilder.append(encodedMessage); 874 } 875 876 String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false); 877 return parseSingleNote(response); 878 } 879 880 /** 881 * Method for parsing API responses for operations on individual notes 882 * @param xml the API response as XML data 883 * @return the resulting Note 884 * @throws OsmTransferException if the API response cannot be parsed 885 */ 886 private static Note parseSingleNote(String xml) throws OsmTransferException { 887 try { 888 List<Note> newNotes = new NoteReader(xml).parse(); 889 if (newNotes.size() == 1) { 890 return newNotes.get(0); 891 } 892 // Shouldn't ever execute. Server will either respond with an error (caught elsewhere) or one note 893 throw new OsmTransferException(tr("Note upload failed")); 894 } catch (SAXException | IOException e) { 895 Logging.error(e); 896 throw new OsmTransferException(tr("Error parsing note response from server"), e); 897 } 898 } 899}