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     * Creates an OSM primitive on the server. The OsmPrimitive object passed in
343     * is modified by giving it the server-assigned id.
344     *
345     * @param osm the primitive
346     * @param monitor the progress monitor
347     * @throws OsmTransferException if something goes wrong
348     */
349    public void createPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
350        String ret = "";
351        try {
352            ensureValidChangeset();
353            initialize(monitor);
354            ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+"/create", toXml(osm, true), monitor);
355            osm.setOsmId(Long.parseLong(ret.trim()), 1);
356            osm.setChangesetId(getChangeset().getId());
357        } catch (NumberFormatException e) {
358            throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret), e);
359        }
360    }
361
362    /**
363     * Modifies an OSM primitive on the server.
364     *
365     * @param osm the primitive. Must not be null.
366     * @param monitor the progress monitor
367     * @throws OsmTransferException if something goes wrong
368     */
369    public void modifyPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
370        String ret = null;
371        try {
372            ensureValidChangeset();
373            initialize(monitor);
374            // normal mode (0.6 and up) returns new object version.
375            ret = sendRequest("PUT", OsmPrimitiveType.from(osm).getAPIName()+'/' + osm.getId(), toXml(osm, true), monitor);
376            osm.setOsmId(osm.getId(), Integer.parseInt(ret.trim()));
377            osm.setChangesetId(getChangeset().getId());
378            osm.setVisible(true);
379        } catch (NumberFormatException e) {
380            throw new OsmTransferException(tr("Unexpected format of new version of modified primitive ''{0}''. Got ''{1}''.",
381                    osm.getId(), ret), e);
382        }
383    }
384
385    /**
386     * Deletes an OSM primitive on the server.
387     * @param osm the primitive
388     * @param monitor the progress monitor
389     * @throws OsmTransferException if something goes wrong
390     */
391    public void deletePrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
392        ensureValidChangeset();
393        initialize(monitor);
394        // can't use a the individual DELETE method in the 0.6 API. Java doesn't allow
395        // submitting a DELETE request with content, the 0.6 API requires it, however. Falling back
396        // to diff upload.
397        //
398        uploadDiff(Collections.singleton(osm), monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
399    }
400
401    /**
402     * Creates a new changeset based on the keys in <code>changeset</code>. If this
403     * method succeeds, changeset.getId() replies the id the server assigned to the new
404     * changeset
405     *
406     * The changeset must not be null, but its key/value-pairs may be empty.
407     *
408     * @param changeset the changeset toe be created. Must not be null.
409     * @param progressMonitor the progress monitor
410     * @throws OsmTransferException signifying a non-200 return code, or connection errors
411     * @throws IllegalArgumentException if changeset is null
412     */
413    public void openChangeset(Changeset changeset, ProgressMonitor progressMonitor) throws OsmTransferException {
414        CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
415        try {
416            progressMonitor.beginTask(tr("Creating changeset..."));
417            initialize(progressMonitor);
418            String ret = "";
419            try {
420                ret = sendRequest("PUT", "changeset/create", toXml(changeset), progressMonitor);
421                changeset.setId(Integer.parseInt(ret.trim()));
422                changeset.setOpen(true);
423            } catch (NumberFormatException e) {
424                throw new OsmTransferException(tr("Unexpected format of ID replied by the server. Got ''{0}''.", ret), e);
425            }
426            progressMonitor.setCustomText(tr("Successfully opened changeset {0}", changeset.getId()));
427        } finally {
428            progressMonitor.finishTask();
429        }
430    }
431
432    /**
433     * Updates a changeset with the keys in  <code>changesetUpdate</code>. The changeset must not
434     * be null and id &gt; 0 must be true.
435     *
436     * @param changeset the changeset to update. Must not be null.
437     * @param monitor the progress monitor. If null, uses the {@link NullProgressMonitor#INSTANCE}.
438     *
439     * @throws OsmTransferException if something goes wrong.
440     * @throws IllegalArgumentException if changeset is null
441     * @throws IllegalArgumentException if changeset.getId() &lt;= 0
442     *
443     */
444    public void updateChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
445        CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
446        if (monitor == null) {
447            monitor = NullProgressMonitor.INSTANCE;
448        }
449        if (changeset.getId() <= 0)
450            throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
451        try {
452            monitor.beginTask(tr("Updating changeset..."));
453            initialize(monitor);
454            monitor.setCustomText(tr("Updating changeset {0}...", changeset.getId()));
455            sendRequest(
456                    "PUT",
457                    "changeset/" + changeset.getId(),
458                    toXml(changeset),
459                    monitor
460            );
461        } catch (ChangesetClosedException e) {
462            e.setSource(ChangesetClosedException.Source.UPDATE_CHANGESET);
463            throw e;
464        } catch (OsmApiException e) {
465            String errorHeader = e.getErrorHeader();
466            if (e.getResponseCode() == HttpURLConnection.HTTP_CONFLICT && ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
467                throw new ChangesetClosedException(errorHeader, ChangesetClosedException.Source.UPDATE_CHANGESET);
468            throw e;
469        } finally {
470            monitor.finishTask();
471        }
472    }
473
474    /**
475     * Closes a changeset on the server. Sets changeset.setOpen(false) if this operation succeeds.
476     *
477     * @param changeset the changeset to be closed. Must not be null. changeset.getId() &gt; 0 required.
478     * @param monitor the progress monitor. If null, uses {@link NullProgressMonitor#INSTANCE}
479     *
480     * @throws OsmTransferException if something goes wrong.
481     * @throws IllegalArgumentException if changeset is null
482     * @throws IllegalArgumentException if changeset.getId() &lt;= 0
483     */
484    public void closeChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
485        CheckParameterUtil.ensureParameterNotNull(changeset, "changeset");
486        if (monitor == null) {
487            monitor = NullProgressMonitor.INSTANCE;
488        }
489        if (changeset.getId() <= 0)
490            throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
491        try {
492            monitor.beginTask(tr("Closing changeset..."));
493            initialize(monitor);
494            /* send "\r\n" instead of empty string, so we don't send zero payload - works around bugs
495               in proxy software */
496            sendRequest("PUT", "changeset" + "/" + changeset.getId() + "/close", "\r\n", monitor);
497            changeset.setOpen(false);
498        } finally {
499            monitor.finishTask();
500        }
501    }
502
503    /**
504     * Uploads a list of changes in "diff" form to the server.
505     *
506     * @param list the list of changed OSM Primitives
507     * @param  monitor the progress monitor
508     * @return list of processed primitives
509     * @throws OsmTransferException if something is wrong
510     */
511    public Collection<OsmPrimitive> uploadDiff(Collection<? extends OsmPrimitive> list, ProgressMonitor monitor)
512            throws OsmTransferException {
513        try {
514            monitor.beginTask("", list.size() * 2);
515            if (changeset == null)
516                throw new OsmTransferException(tr("No changeset present for diff upload."));
517
518            initialize(monitor);
519
520            // prepare upload request
521            //
522            OsmChangeBuilder changeBuilder = new OsmChangeBuilder(changeset);
523            monitor.subTask(tr("Preparing upload request..."));
524            changeBuilder.start();
525            changeBuilder.append(list);
526            changeBuilder.finish();
527            String diffUploadRequest = changeBuilder.getDocument();
528
529            // Upload to the server
530            //
531            monitor.indeterminateSubTask(
532                    trn("Uploading {0} object...", "Uploading {0} objects...", list.size(), list.size()));
533            String diffUploadResponse = sendRequest("POST", "changeset/" + changeset.getId() + "/upload", diffUploadRequest, monitor);
534
535            // Process the response from the server
536            //
537            DiffResultProcessor reader = new DiffResultProcessor(list);
538            reader.parse(diffUploadResponse, monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));
539            return reader.postProcess(
540                    getChangeset(),
541                    monitor.createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)
542            );
543        } catch (OsmTransferException e) {
544            throw e;
545        } catch (XmlParsingException e) {
546            throw new OsmTransferException(e);
547        } finally {
548            monitor.finishTask();
549        }
550    }
551
552    private void sleepAndListen(int retry, ProgressMonitor monitor) throws OsmTransferCanceledException {
553        Main.info(tr("Waiting 10 seconds ... "));
554        for (int i = 0; i < 10; i++) {
555            if (monitor != null) {
556                monitor.setCustomText(tr("Starting retry {0} of {1} in {2} seconds ...", getMaxRetries() - retry, getMaxRetries(), 10-i));
557            }
558            if (cancel)
559                throw new OsmTransferCanceledException("Operation canceled" + (i > 0 ? " in retry #"+i : ""));
560            try {
561                Thread.sleep(1000);
562            } catch (InterruptedException ex) {
563                Main.warn("InterruptedException in "+getClass().getSimpleName()+" during sleep");
564            }
565        }
566        Main.info(tr("OK - trying again."));
567    }
568
569    /**
570     * Replies the max. number of retries in case of 5XX errors on the server
571     *
572     * @return the max number of retries
573     */
574    protected int getMaxRetries() {
575        int ret = Main.pref.getInteger("osm-server.max-num-retries", DEFAULT_MAX_NUM_RETRIES);
576        return Math.max(ret, 0);
577    }
578
579    /**
580     * Determines if JOSM is configured to access OSM API via OAuth
581     * @return {@code true} if JOSM is configured to access OSM API via OAuth, {@code false} otherwise
582     * @since 6349
583     */
584    public static final boolean isUsingOAuth() {
585        return "oauth".equals(Main.pref.get("osm-server.auth-method", "basic"));
586    }
587
588    protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor)
589            throws OsmTransferException {
590        return sendRequest(requestMethod, urlSuffix, requestBody, monitor, true, false);
591    }
592
593    /**
594     * Generic method for sending requests to the OSM API.
595     *
596     * This method will automatically re-try any requests that are answered with a 5xx
597     * error code, or that resulted in a timeout exception from the TCP layer.
598     *
599     * @param requestMethod The http method used when talking with the server.
600     * @param urlSuffix The suffix to add at the server url, not including the version number,
601     *    but including any object ids (e.g. "/way/1234/history").
602     * @param requestBody the body of the HTTP request, if any.
603     * @param monitor the progress monitor
604     * @param doAuthenticate  set to true, if the request sent to the server shall include authentication
605     * credentials;
606     * @param fastFail true to request a short timeout
607     *
608     * @return the body of the HTTP response, if and only if the response code was "200 OK".
609     * @throws OsmTransferException if the HTTP return code was not 200 (and retries have
610     *    been exhausted), or rewrapping a Java exception.
611     */
612    protected final String sendRequest(String requestMethod, String urlSuffix, String requestBody, ProgressMonitor monitor,
613            boolean doAuthenticate, boolean fastFail) throws OsmTransferException {
614        int retries = fastFail ? 0 : getMaxRetries();
615
616        while (true) { // the retry loop
617            try {
618                url = new URL(new URL(getBaseUrl()), urlSuffix);
619                final HttpClient client = HttpClient.create(url, requestMethod).keepAlive(false);
620                activeConnection = client;
621                if (fastFail) {
622                    client.setConnectTimeout(1000);
623                    client.setReadTimeout(1000);
624                } else {
625                    // use default connect timeout from org.openstreetmap.josm.tools.HttpClient.connectTimeout
626                    client.setReadTimeout(0);
627                }
628                if (doAuthenticate) {
629                    addAuth(client);
630                }
631
632                if ("PUT".equals(requestMethod) || "POST".equals(requestMethod) || "DELETE".equals(requestMethod)) {
633                    client.setHeader("Content-Type", "text/xml");
634                    // It seems that certain bits of the Ruby API are very unhappy upon
635                    // receipt of a PUT/POST message without a Content-length header,
636                    // even if the request has no payload.
637                    // Since Java will not generate a Content-length header unless
638                    // we use the output stream, we create an output stream for PUT/POST
639                    // even if there is no payload.
640                    client.setRequestBody((requestBody != null ? requestBody : "").getBytes(StandardCharsets.UTF_8));
641                }
642
643                final HttpClient.Response response = client.connect();
644                Main.info(response.getResponseMessage());
645                int retCode = response.getResponseCode();
646
647                if (retCode >= 500) {
648                    if (retries-- > 0) {
649                        sleepAndListen(retries, monitor);
650                        Main.info(tr("Starting retry {0} of {1}.", getMaxRetries() - retries, getMaxRetries()));
651                        continue;
652                    }
653                }
654
655                final String responseBody = response.fetchContent();
656
657                String errorHeader = null;
658                // Look for a detailed error message from the server
659                if (response.getHeaderField("Error") != null) {
660                    errorHeader = response.getHeaderField("Error");
661                    Main.error("Error header: " + errorHeader);
662                } else if (retCode != HttpURLConnection.HTTP_OK && responseBody.length() > 0) {
663                    Main.error("Error body: " + responseBody);
664                }
665                activeConnection.disconnect();
666
667                errorHeader = errorHeader == null ? null : errorHeader.trim();
668                String errorBody = responseBody.length() == 0 ? null : responseBody.trim();
669                switch(retCode) {
670                case HttpURLConnection.HTTP_OK:
671                    return responseBody;
672                case HttpURLConnection.HTTP_GONE:
673                    throw new OsmApiPrimitiveGoneException(errorHeader, errorBody);
674                case HttpURLConnection.HTTP_CONFLICT:
675                    if (ChangesetClosedException.errorHeaderMatchesPattern(errorHeader))
676                        throw new ChangesetClosedException(errorBody, ChangesetClosedException.Source.UPLOAD_DATA);
677                    else
678                        throw new OsmApiException(retCode, errorHeader, errorBody);
679                case HttpURLConnection.HTTP_FORBIDDEN:
680                    OsmApiException e = new OsmApiException(retCode, errorHeader, errorBody);
681                    e.setAccessedUrl(activeConnection.getURL().toString());
682                    throw e;
683                default:
684                    throw new OsmApiException(retCode, errorHeader, errorBody);
685                }
686            } catch (SocketTimeoutException | ConnectException e) {
687                if (retries-- > 0) {
688                    continue;
689                }
690                throw new OsmTransferException(e);
691            } catch (IOException e) {
692                throw new OsmTransferException(e);
693            } catch (OsmTransferException e) {
694                throw e;
695            }
696        }
697    }
698
699    /**
700     * Replies the API capabilities.
701     *
702     * @return the API capabilities, or null, if the API is not initialized yet
703     */
704    public synchronized Capabilities getCapabilities() {
705        return capabilities;
706    }
707
708    /**
709     * Ensures that the current changeset can be used for uploading data
710     *
711     * @throws OsmTransferException if the current changeset can't be used for uploading data
712     */
713    protected void ensureValidChangeset() throws OsmTransferException {
714        if (changeset == null)
715            throw new OsmTransferException(tr("Current changeset is null. Cannot upload data."));
716        if (changeset.getId() <= 0)
717            throw new OsmTransferException(tr("ID of current changeset > 0 required. Current ID is {0}.", changeset.getId()));
718    }
719
720    /**
721     * Replies the changeset data uploads are currently directed to
722     *
723     * @return the changeset data uploads are currently directed to
724     */
725    public Changeset getChangeset() {
726        return changeset;
727    }
728
729    /**
730     * Sets the changesets to which further data uploads are directed. The changeset
731     * can be null. If it isn't null it must have been created, i.e. id &gt; 0 is required. Furthermore,
732     * it must be open.
733     *
734     * @param changeset the changeset
735     * @throws IllegalArgumentException if changeset.getId() &lt;= 0
736     * @throws IllegalArgumentException if !changeset.isOpen()
737     */
738    public void setChangeset(Changeset changeset) {
739        if (changeset == null) {
740            this.changeset = null;
741            return;
742        }
743        if (changeset.getId() <= 0)
744            throw new IllegalArgumentException(tr("Changeset ID > 0 expected. Got {0}.", changeset.getId()));
745        if (!changeset.isOpen())
746            throw new IllegalArgumentException(tr("Open changeset expected. Got closed changeset with id {0}.", changeset.getId()));
747        this.changeset = changeset;
748    }
749
750    private static StringBuilder noteStringBuilder(Note note) {
751        return new StringBuilder().append("notes/").append(note.getId());
752    }
753
754    /**
755     * Create a new note on the server.
756     * @param latlon Location of note
757     * @param text Comment entered by user to open the note
758     * @param monitor Progress monitor
759     * @return Note as it exists on the server after creation (ID assigned)
760     * @throws OsmTransferException if any error occurs during dialog with OSM API
761     */
762    public Note createNote(LatLon latlon, String text, ProgressMonitor monitor) throws OsmTransferException {
763        initialize(monitor);
764        String noteUrl = new StringBuilder()
765            .append("notes?lat=")
766            .append(latlon.lat())
767            .append("&lon=")
768            .append(latlon.lon())
769            .append("&text=")
770            .append(Utils.encodeUrl(text)).toString();
771
772        String response = sendRequest("POST", noteUrl, null, monitor, true, false);
773        return parseSingleNote(response);
774    }
775
776    /**
777     * Add a comment to an existing note.
778     * @param note The note to add a comment to
779     * @param comment Text of the comment
780     * @param monitor Progress monitor
781     * @return Note returned by the API after the comment was added
782     * @throws OsmTransferException if any error occurs during dialog with OSM API
783     */
784    public Note addCommentToNote(Note note, String comment, ProgressMonitor monitor) throws OsmTransferException {
785        initialize(monitor);
786        String noteUrl = noteStringBuilder(note)
787            .append("/comment?text=")
788            .append(Utils.encodeUrl(comment)).toString();
789
790        String response = sendRequest("POST", noteUrl, null, monitor, true, false);
791        return parseSingleNote(response);
792    }
793
794    /**
795     * Close a note.
796     * @param note Note to close. Must currently be open
797     * @param closeMessage Optional message supplied by the user when closing the note
798     * @param monitor Progress monitor
799     * @return Note returned by the API after the close operation
800     * @throws OsmTransferException if any error occurs during dialog with OSM API
801     */
802    public Note closeNote(Note note, String closeMessage, ProgressMonitor monitor) throws OsmTransferException {
803        initialize(monitor);
804        String encodedMessage = Utils.encodeUrl(closeMessage);
805        StringBuilder urlBuilder = noteStringBuilder(note)
806            .append("/close");
807        if (encodedMessage != null && !encodedMessage.trim().isEmpty()) {
808            urlBuilder.append("?text=");
809            urlBuilder.append(encodedMessage);
810        }
811
812        String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false);
813        return parseSingleNote(response);
814    }
815
816    /**
817     * Reopen a closed note
818     * @param note Note to reopen. Must currently be closed
819     * @param reactivateMessage Optional message supplied by the user when reopening the note
820     * @param monitor Progress monitor
821     * @return Note returned by the API after the reopen operation
822     * @throws OsmTransferException if any error occurs during dialog with OSM API
823     */
824    public Note reopenNote(Note note, String reactivateMessage, ProgressMonitor monitor) throws OsmTransferException {
825        initialize(monitor);
826        String encodedMessage = Utils.encodeUrl(reactivateMessage);
827        StringBuilder urlBuilder = noteStringBuilder(note)
828            .append("/reopen");
829        if (encodedMessage != null && !encodedMessage.trim().isEmpty()) {
830            urlBuilder.append("?text=");
831            urlBuilder.append(encodedMessage);
832        }
833
834        String response = sendRequest("POST", urlBuilder.toString(), null, monitor, true, false);
835        return parseSingleNote(response);
836    }
837
838    /**
839     * Method for parsing API responses for operations on individual notes
840     * @param xml the API response as XML data
841     * @return the resulting Note
842     * @throws OsmTransferException if the API response cannot be parsed
843     */
844    private Note parseSingleNote(String xml) throws OsmTransferException {
845        try {
846            List<Note> newNotes = new NoteReader(xml).parse();
847            if (newNotes.size() == 1) {
848                return newNotes.get(0);
849            }
850            //Shouldn't ever execute. Server will either respond with an error (caught elsewhere) or one note
851            throw new OsmTransferException(tr("Note upload failed"));
852        } catch (SAXException | IOException e) {
853            Main.error(e, true);
854            throw new OsmTransferException(tr("Error parsing note response from server"), e);
855        }
856    }
857}