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