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